CURRENT REQUEST-9 SOURCE AND EXTRACTION EVIDENCE Date: 2026-10-09. This section supersedes predecessor identity records below. No GOAL classification or source correctness is inferred from these excerpts. Source/package configuration: modeling-input/SETUP.md and manifest.json. Transparent extraction scope and all 24 external bindings were inspected with python3 .trellis/scripts/pv_modeling.py inspect-native . and checked with python3 .trellis/scripts/pv_modeling.py compose-native . --check. Composition reports matches=true, changed=false, no mismatched files, 170 frozen extracted modules, 24 bindings, raw extraction SHA-256 438af8398703b81aa311d7885dfb34f1909125bee48b096dacc93baefcc4bcf9. This is a composition identity result, not a Lean closure certificate. COMMAND: sha256sum generated.lean GOAL.md modeling-input/manifest.json upstream/dec2flt/parse.rs crate/dec2flt/parse.rs upstream/dec2flt/decimal_seq.rs crate/dec2flt/decimal_seq.rs upstream/dec2flt/mod.rs crate/dec2flt/mod.rs 438af8398703b81aa311d7885dfb34f1909125bee48b096dacc93baefcc4bcf9 generated.lean 0f19c63a168623bd805c17b753dff6f74a695ff283680c22d356fb623fbb4771 GOAL.md 4b71c7166d09bafef194283156edd10e58f25ffd1a498d785e0af04a600c5b32 modeling-input/manifest.json a9303bac61a5e8e7b610632925bb0d04483374a91f9ec38a7305fd4a1ca0b5f3 upstream/dec2flt/parse.rs fb5f09bf0bc9742dae352ae0c3bf6706e8855ff22079765f6233fd16f975b669 crate/dec2flt/parse.rs 7b1b28b8c439afb4628411af12920b7c0ecd19036fa530dc74c6a356ec6e351d upstream/dec2flt/decimal_seq.rs 193ca485206899f913a3da75b6ac6484ee90b35c3a5d1c7059ae3d5c61110ad9 crate/dec2flt/decimal_seq.rs 7198e238c554b692405537a446b3526ad66805ec2900cd0e299f10c51402a44a upstream/dec2flt/mod.rs 6ce998fb79493021a6b7af183ba03934fa699ddb6f9c2bfafcea17d26e5c608a crate/dec2flt/mod.rs COMMAND: nl -ba upstream/dec2flt/parse.rs 1 //! Functions to parse floating-point numbers. 2 3 use dec2flt::common::{ByteSlice, is_8digits}; 4 use dec2flt::decimal::Decimal; 5 6 use crate::num::imp::{Float, dec2flt}; 7 8 const MIN_19DIGIT_INT: u64 = 100_0000_0000_0000_0000; 9 10 /// Parse 8 digits, loaded as bytes in little-endian order. 11 /// 12 /// This uses the trick where every digit is in [0x030, 0x39], 13 /// and therefore can be parsed in 3 multiplications, much 14 /// faster than the normal 8. 15 /// 16 /// This is based off the algorithm described in "Fast numeric string to 17 /// int", available here: . 18 fn parse_8digits(mut v: u64) -> u64 { 19 const MASK: u64 = 0x0000_00FF_0000_00FF; 20 const MUL1: u64 = 0x000F_4240_0000_0064; 21 const MUL2: u64 = 0x0000_2710_0000_0001; 22 v -= 0x3030_3030_3030_3030; 23 v = (v * 10) + (v >> 8); // will not overflow, fits in 63 bits 24 let v1 = (v & MASK).wrapping_mul(MUL1); 25 let v2 = ((v >> 16) & MASK).wrapping_mul(MUL2); 26 ((v1.wrapping_add(v2) >> 32) as u32) as u64 27 } 28 29 /// Parse digits until a non-digit character is found. 30 fn try_parse_digits(mut s: &[u8], mut x: u64) -> (&[u8], u64) { 31 // may cause overflows, to be handled later 32 33 while s.len() >= 8 { 34 let num = s.read_u64(); 35 if is_8digits(num) { 36 x = x.wrapping_mul(1_0000_0000).wrapping_add(parse_8digits(num)); 37 s = &s[8..]; 38 } else { 39 break; 40 } 41 } 42 43 s = s.parse_digits(|digit| { 44 x = x.wrapping_mul(10).wrapping_add(digit as _); 45 }); 46 47 (s, x) 48 } 49 50 /// Parse up to 19 digits (the max that can be stored in a 64-bit integer). 51 fn try_parse_19digits(s_ref: &mut &[u8], x: &mut u64) { 52 let mut s = *s_ref; 53 54 while *x < MIN_19DIGIT_INT { 55 if let Some((c, s_next)) = s.split_first() { 56 let digit = c.wrapping_sub(b'0'); 57 58 if digit < 10 { 59 *x = (*x * 10) + digit as u64; // no overflows here 60 s = s_next; 61 } else { 62 break; 63 } 64 } else { 65 break; 66 } 67 } 68 69 *s_ref = s; 70 } 71 72 /// Parse the scientific notation component of a float. 73 pub(super) fn parse_scientific(s_ref: &mut &[u8]) -> Option { 74 let mut exponent = 0i64; 75 let mut negative = false; 76 77 let mut s = *s_ref; 78 79 if let Some((&c, s_next)) = s.split_first() { 80 negative = c == b'-'; 81 if c == b'-' || c == b'+' { 82 s = s_next; 83 } 84 } 85 86 if matches!(s.first(), Some(&x) if x.is_ascii_digit()) { 87 *s_ref = s.parse_digits(|digit| { 88 // The exponent is at most 10 * 2^59 - 1, which fits in i64. 89 if exponent < (1_i64 << 59) { 90 exponent = 10 * exponent + digit as i64; 91 } 92 }); 93 if negative { Some(-exponent) } else { Some(exponent) } 94 } else { 95 *s_ref = s; 96 None 97 } 98 } 99 100 /// Parse a partial, non-special floating point number. 101 /// 102 /// This creates a representation of the float as the 103 /// significant digits and the decimal exponent. 104 fn parse_partial_number(mut s: &[u8]) -> Option<(Decimal, usize)> { 105 debug_assert!(!s.is_empty()); 106 107 // parse initial digits before dot 108 let mut mantissa = 0_u64; 109 let start = s; 110 let tmp = try_parse_digits(s, mantissa); 111 s = tmp.0; 112 mantissa = tmp.1; 113 let mut n_digits = s.offset_from(start); 114 115 // handle dot with the following digits 116 let mut n_after_dot = 0; 117 let mut exponent = 0_i64; 118 let int_end = s; 119 120 if let Some((&b'.', s_next)) = s.split_first() { 121 s = s_next; 122 let before = s; 123 let tmp = try_parse_digits(s, mantissa); 124 s = tmp.0; 125 mantissa = tmp.1; 126 n_after_dot = s.offset_from(before); 127 exponent = -n_after_dot as i64; 128 } 129 130 n_digits += n_after_dot; 131 if n_digits == 0 { 132 return None; 133 } 134 135 // handle scientific format 136 let mut exp_number = 0_i64; 137 if let Some((&c, s_next)) = s.split_first() { 138 if c == b'e' || c == b'E' { 139 s = s_next; 140 // If None, we have no trailing digits after exponent, or an invalid float. 141 exp_number = parse_scientific(&mut s)?; 142 exponent += exp_number; 143 } 144 } 145 146 let len = s.offset_from(start) as _; 147 148 // handle uncommon case with many digits 149 if n_digits <= 19 { 150 return Some((Decimal { exponent, mantissa, negative: false, many_digits: false }, len)); 151 } 152 153 n_digits -= 19; 154 let mut many_digits = false; 155 let mut p = start; 156 while let Some((&c, p_next)) = p.split_first() { 157 if c == b'.' || c == b'0' { 158 n_digits -= c.saturating_sub(b'0' - 1) as isize; 159 p = p_next; 160 } else { 161 break; 162 } 163 } 164 if n_digits > 0 { 165 // at this point we have more than 19 significant digits, let's try again 166 many_digits = true; 167 mantissa = 0; 168 let mut s = start; 169 try_parse_19digits(&mut s, &mut mantissa); 170 exponent = if mantissa >= MIN_19DIGIT_INT { 171 // big int 172 int_end.offset_from(s) 173 } else { 174 s = &s[1..]; 175 let before = s; 176 try_parse_19digits(&mut s, &mut mantissa); 177 -s.offset_from(before) 178 } as i64; 179 // add back the explicit part 180 exponent += exp_number; 181 } 182 183 Some((Decimal { exponent, mantissa, negative: false, many_digits }, len)) 184 } 185 186 /// Try to parse a non-special floating point number, 187 /// as well as two slices with integer and fractional parts 188 /// and the parsed exponent. 189 pub fn parse_number(s: &[u8]) -> Option { 190 if let Some((float, rest)) = parse_partial_number(s) { 191 if rest == s.len() { 192 return Some(float); 193 } 194 } 195 None 196 } 197 198 /// Try to parse a special, non-finite float. 199 pub(crate) fn parse_inf_nan(s: &[u8], negative: bool) -> Option { 200 // Since a valid string has at most the length 8, we can load 201 // all relevant characters into a u64 and work from there. 202 // This also generates much better code. 203 204 let mut register; 205 let len: usize; 206 207 // All valid strings are either of length 8 or 3. 208 if s.len() == 8 { 209 register = s.read_u64(); 210 len = 8; 211 } else if s.len() == 3 { 212 let a = s[0] as u64; 213 let b = s[1] as u64; 214 let c = s[2] as u64; 215 register = (c << 16) | (b << 8) | a; 216 len = 3; 217 } else { 218 return None; 219 } 220 221 // Clear out the bits which turn ASCII uppercase characters into 222 // lowercase characters. The resulting string is all uppercase. 223 // What happens to other characters is irrelevant. 224 register &= 0xDFDFDFDFDFDFDFDF; 225 226 // u64 values corresponding to relevant cases 227 const INF_3: u64 = 0x464E49; // "INF" 228 const INF_8: u64 = 0x5954494E49464E49; // "INFINITY" 229 const NAN: u64 = 0x4E414E; // "NAN" 230 231 // Match register value to constant to parse string. 232 // Also match on the string length to catch edge cases 233 // like "inf\0\0\0\0\0". 234 let float = match (register, len) { 235 (INF_3, 3) => F::INFINITY, 236 (INF_8, 8) => F::INFINITY, 237 (NAN, 3) => F::NAN, 238 _ => return None, 239 }; 240 241 if negative { Some(-float) } else { Some(float) } 242 } COMMAND: nl -ba upstream/dec2flt/decimal_seq.rs 1 //! Arbitrary-precision decimal type used by fallback algorithms. 2 //! 3 //! This is only used if the fast-path (native floats) and 4 //! the Eisel-Lemire algorithm are unable to unambiguously 5 //! determine the float. 6 //! 7 //! The technique used is "Simple Decimal Conversion", developed 8 //! by Nigel Tao and Ken Thompson. A detailed description of the 9 //! algorithm can be found in "ParseNumberF64 by Simple Decimal Conversion", 10 //! available online: . 11 12 use dec2flt::common::{ByteSlice, is_8digits}; 13 use dec2flt::parse::parse_scientific; 14 15 use crate::num::imp::dec2flt; 16 17 /// A decimal floating-point number, represented as a sequence of decimal digits. 18 #[derive(Clone, Debug, PartialEq)] 19 pub struct DecimalSeq { 20 /// The number of significant digits in the decimal. 21 pub num_digits: usize, 22 /// The offset of the decimal point in the significant digits. 23 pub decimal_point: i32, 24 /// If the number of significant digits stored in the decimal is truncated. 25 pub truncated: bool, 26 /// Buffer of the raw digits, in the range [0, 9]. 27 pub digits: [u8; Self::MAX_DIGITS], 28 } 29 30 impl Default for DecimalSeq { 31 fn default() -> Self { 32 Self { num_digits: 0, decimal_point: 0, truncated: false, digits: [0; Self::MAX_DIGITS] } 33 } 34 } 35 36 impl DecimalSeq { 37 /// The maximum number of digits required to unambiguously round up to a 64-bit float. 38 /// 39 /// For an IEEE 754 binary64 float, this required 767 digits. So we store the max digits + 1. 40 /// 41 /// We can exactly represent a float in radix `b` from radix 2 if 42 /// `b` is divisible by 2. This function calculates the exact number of 43 /// digits required to exactly represent that float. 44 /// 45 /// According to the "Handbook of Floating Point Arithmetic", 46 /// for IEEE754, with `emin` being the min exponent, `p2` being the 47 /// precision, and `b` being the radix, the number of digits follows as: 48 /// 49 /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` 50 /// 51 /// For f32, this follows as: 52 /// emin = -126 53 /// p2 = 24 54 /// 55 /// For f64, this follows as: 56 /// emin = -1022 57 /// p2 = 53 58 /// 59 /// In Python: 60 /// `-emin + p2 + math.floor((emin+ 1)*math.log(2, b)-math.log(1-2**(-p2), b))` 61 pub const MAX_DIGITS: usize = 768; 62 63 /// The max decimal digits that can be exactly represented in a 64-bit integer. 64 pub(super) const MAX_DIGITS_WITHOUT_OVERFLOW: usize = 19; 65 pub(super) const DECIMAL_POINT_RANGE: i32 = 2047; 66 67 /// Append a digit to the buffer if it fits. 68 // FIXME(tgross35): it may be better for this to return an option 69 // FIXME(tgross35): incrementing the digit counter even if we don't push anything 70 // seems incorrect. 71 pub(super) fn try_add_digit(&mut self, digit: u8) { 72 if self.num_digits < Self::MAX_DIGITS { 73 self.digits[self.num_digits] = digit; 74 } 75 self.num_digits += 1; 76 } 77 78 /// Trim trailing zeros from the buffer. 79 // FIXME(tgross35): this could be `.rev().position()` if perf is okay 80 pub fn trim(&mut self) { 81 // All of the following calls to `DecimalSeq::trim` can't panic because: 82 // 83 // 1. `parse_decimal` sets `num_digits` to a max of `DecimalSeq::MAX_DIGITS`. 84 // 2. `right_shift` sets `num_digits` to `write_index`, which is bounded by `num_digits`. 85 // 3. `left_shift` `num_digits` to a max of `DecimalSeq::MAX_DIGITS`. 86 // 87 // Trim is only called in `right_shift` and `left_shift`. 88 debug_assert!(self.num_digits <= Self::MAX_DIGITS); 89 while self.num_digits != 0 && self.digits[self.num_digits - 1] == 0 { 90 self.num_digits -= 1; 91 } 92 } 93 94 pub(super) fn round(&self) -> u64 { 95 if self.num_digits == 0 || self.decimal_point < 0 { 96 return 0; 97 } else if self.decimal_point >= Self::MAX_DIGITS_WITHOUT_OVERFLOW as i32 { 98 return 0xFFFF_FFFF_FFFF_FFFF_u64; 99 } 100 101 let dp = self.decimal_point as usize; 102 let mut n = 0_u64; 103 104 for i in 0..dp { 105 n *= 10; 106 if i < self.num_digits { 107 n += self.digits[i] as u64; 108 } 109 } 110 111 let mut round_up = false; 112 113 if dp < self.num_digits { 114 round_up = self.digits[dp] >= 5; 115 if self.digits[dp] == 5 && dp + 1 == self.num_digits { 116 round_up = self.truncated || ((dp != 0) && (1 & self.digits[dp - 1] != 0)) 117 } 118 } 119 120 if round_up { 121 n += 1; 122 } 123 n 124 } 125 126 /// Computes decimal * 2^shift. 127 pub(super) fn left_shift(&mut self, shift: usize) { 128 if self.num_digits == 0 { 129 return; 130 } 131 let num_new_digits = number_of_digits_decimal_left_shift(self, shift); 132 let mut read_index = self.num_digits; 133 let mut write_index = self.num_digits + num_new_digits; 134 let mut n = 0_u64; 135 136 while read_index != 0 { 137 read_index -= 1; 138 write_index -= 1; 139 n += (self.digits[read_index] as u64) << shift; 140 let quotient = n / 10; 141 let remainder = n - (10 * quotient); 142 if write_index < Self::MAX_DIGITS { 143 self.digits[write_index] = remainder as u8; 144 } else if remainder > 0 { 145 self.truncated = true; 146 } 147 n = quotient; 148 } 149 150 while n > 0 { 151 write_index -= 1; 152 let quotient = n / 10; 153 let remainder = n - (10 * quotient); 154 if write_index < Self::MAX_DIGITS { 155 self.digits[write_index] = remainder as u8; 156 } else if remainder > 0 { 157 self.truncated = true; 158 } 159 n = quotient; 160 } 161 162 self.num_digits += num_new_digits; 163 164 if self.num_digits > Self::MAX_DIGITS { 165 self.num_digits = Self::MAX_DIGITS; 166 } 167 168 self.decimal_point += num_new_digits as i32; 169 self.trim(); 170 } 171 172 /// Computes decimal * 2^-shift. 173 pub(super) fn right_shift(&mut self, shift: usize) { 174 let mut read_index = 0; 175 let mut write_index = 0; 176 let mut n = 0_u64; 177 while (n >> shift) == 0 { 178 if read_index < self.num_digits { 179 n = (10 * n) + self.digits[read_index] as u64; 180 read_index += 1; 181 } else if n == 0 { 182 return; 183 } else { 184 while (n >> shift) == 0 { 185 n *= 10; 186 read_index += 1; 187 } 188 break; 189 } 190 } 191 self.decimal_point -= read_index as i32 - 1; 192 if self.decimal_point < -Self::DECIMAL_POINT_RANGE { 193 // `self = Self::Default()`, but without the overhead of clearing `digits`. 194 self.num_digits = 0; 195 self.decimal_point = 0; 196 self.truncated = false; 197 return; 198 } 199 let mask = (1_u64 << shift) - 1; 200 while read_index < self.num_digits { 201 let new_digit = (n >> shift) as u8; 202 n = (10 * (n & mask)) + self.digits[read_index] as u64; 203 read_index += 1; 204 self.digits[write_index] = new_digit; 205 write_index += 1; 206 } 207 while n > 0 { 208 let new_digit = (n >> shift) as u8; 209 n = 10 * (n & mask); 210 if write_index < Self::MAX_DIGITS { 211 self.digits[write_index] = new_digit; 212 write_index += 1; 213 } else if new_digit > 0 { 214 self.truncated = true; 215 } 216 } 217 self.num_digits = write_index; 218 self.trim(); 219 } 220 } 221 222 /// Combine counts in i64 and clamp before casting to i32. 223 #[inline] 224 pub(super) fn final_decimal_point( 225 significant_count: usize, 226 fractional_count: usize, 227 explicit: i64, 228 ) -> i32 { 229 if significant_count == 0 { 230 return 0; 231 } 232 let base = significant_count as i64 - fractional_count as i64; 233 base.saturating_add(explicit) 234 .clamp(-(DecimalSeq::DECIMAL_POINT_RANGE as i64), DecimalSeq::DECIMAL_POINT_RANGE as i64) 235 as i32 236 } 237 238 /// Parse a big integer representation of the float as a decimal. 239 pub fn parse_decimal_seq(mut s: &[u8]) -> DecimalSeq { 240 let mut d = DecimalSeq::default(); 241 let start = s; 242 let mut fractional_count = 0; 243 244 while let Some((&b'0', s_next)) = s.split_first() { 245 s = s_next; 246 } 247 248 s = s.parse_digits(|digit| d.try_add_digit(digit)); 249 250 if let Some((b'.', s_next)) = s.split_first() { 251 s = s_next; 252 let first = s; 253 // Skip leading zeros. 254 if d.num_digits == 0 { 255 while let Some((&b'0', s_next)) = s.split_first() { 256 s = s_next; 257 } 258 } 259 while s.len() >= 8 && d.num_digits + 8 < DecimalSeq::MAX_DIGITS { 260 let v = s.read_u64(); 261 if !is_8digits(v) { 262 break; 263 } 264 d.digits[d.num_digits..].write_u64(v - 0x3030_3030_3030_3030); 265 d.num_digits += 8; 266 s = &s[8..]; 267 } 268 s = s.parse_digits(|digit| d.try_add_digit(digit)); 269 fractional_count = first.len() - s.len(); 270 } 271 272 let significant_count = d.num_digits; 273 if d.num_digits != 0 { 274 // Ignore the trailing zeros if there are any 275 let mut n_trailing_zeros = 0; 276 for &c in start[..(start.len() - s.len())].iter().rev() { 277 if c == b'0' { 278 n_trailing_zeros += 1; 279 } else if c != b'.' { 280 break; 281 } 282 } 283 d.num_digits -= n_trailing_zeros; 284 if d.num_digits > DecimalSeq::MAX_DIGITS { 285 d.truncated = true; 286 d.num_digits = DecimalSeq::MAX_DIGITS; 287 } 288 } 289 290 let mut explicit = 0; 291 if let Some((&ch, s_next)) = s.split_first() { 292 if ch == b'e' || ch == b'E' { 293 s = s_next; 294 explicit = parse_scientific(&mut s).unwrap_or(0); 295 } 296 } 297 d.decimal_point = final_decimal_point(significant_count, fractional_count, explicit); 298 299 for i in d.num_digits..DecimalSeq::MAX_DIGITS_WITHOUT_OVERFLOW { 300 d.digits[i] = 0; 301 } 302 303 d 304 } 305 306 fn number_of_digits_decimal_left_shift(d: &DecimalSeq, mut shift: usize) -> usize { 307 #[rustfmt::skip] 308 const TABLE: [u16; 65] = [ 309 0x0000, 0x0800, 0x0801, 0x0803, 0x1006, 0x1009, 0x100D, 0x1812, 0x1817, 0x181D, 0x2024, 310 0x202B, 0x2033, 0x203C, 0x2846, 0x2850, 0x285B, 0x3067, 0x3073, 0x3080, 0x388E, 0x389C, 311 0x38AB, 0x38BB, 0x40CC, 0x40DD, 0x40EF, 0x4902, 0x4915, 0x4929, 0x513E, 0x5153, 0x5169, 312 0x5180, 0x5998, 0x59B0, 0x59C9, 0x61E3, 0x61FD, 0x6218, 0x6A34, 0x6A50, 0x6A6D, 0x6A8B, 313 0x72AA, 0x72C9, 0x72E9, 0x7B0A, 0x7B2B, 0x7B4D, 0x8370, 0x8393, 0x83B7, 0x83DC, 0x8C02, 314 0x8C28, 0x8C4F, 0x9477, 0x949F, 0x94C8, 0x9CF2, 0x051C, 0x051C, 0x051C, 0x051C, 315 ]; 316 #[rustfmt::skip] 317 const TABLE_POW5: [u8; 0x051C] = [ 318 5, 2, 5, 1, 2, 5, 6, 2, 5, 3, 1, 2, 5, 1, 5, 6, 2, 5, 7, 8, 1, 2, 5, 3, 9, 0, 6, 2, 5, 1, 319 9, 5, 3, 1, 2, 5, 9, 7, 6, 5, 6, 2, 5, 4, 8, 8, 2, 8, 1, 2, 5, 2, 4, 4, 1, 4, 0, 6, 2, 5, 320 1, 2, 2, 0, 7, 0, 3, 1, 2, 5, 6, 1, 0, 3, 5, 1, 5, 6, 2, 5, 3, 0, 5, 1, 7, 5, 7, 8, 1, 2, 321 5, 1, 5, 2, 5, 8, 7, 8, 9, 0, 6, 2, 5, 7, 6, 2, 9, 3, 9, 4, 5, 3, 1, 2, 5, 3, 8, 1, 4, 6, 322 9, 7, 2, 6, 5, 6, 2, 5, 1, 9, 0, 7, 3, 4, 8, 6, 3, 2, 8, 1, 2, 5, 9, 5, 3, 6, 7, 4, 3, 1, 323 6, 4, 0, 6, 2, 5, 4, 7, 6, 8, 3, 7, 1, 5, 8, 2, 0, 3, 1, 2, 5, 2, 3, 8, 4, 1, 8, 5, 7, 9, 324 1, 0, 1, 5, 6, 2, 5, 1, 1, 9, 2, 0, 9, 2, 8, 9, 5, 5, 0, 7, 8, 1, 2, 5, 5, 9, 6, 0, 4, 6, 325 4, 4, 7, 7, 5, 3, 9, 0, 6, 2, 5, 2, 9, 8, 0, 2, 3, 2, 2, 3, 8, 7, 6, 9, 5, 3, 1, 2, 5, 1, 326 4, 9, 0, 1, 1, 6, 1, 1, 9, 3, 8, 4, 7, 6, 5, 6, 2, 5, 7, 4, 5, 0, 5, 8, 0, 5, 9, 6, 9, 2, 327 3, 8, 2, 8, 1, 2, 5, 3, 7, 2, 5, 2, 9, 0, 2, 9, 8, 4, 6, 1, 9, 1, 4, 0, 6, 2, 5, 1, 8, 6, 328 2, 6, 4, 5, 1, 4, 9, 2, 3, 0, 9, 5, 7, 0, 3, 1, 2, 5, 9, 3, 1, 3, 2, 2, 5, 7, 4, 6, 1, 5, 329 4, 7, 8, 5, 1, 5, 6, 2, 5, 4, 6, 5, 6, 6, 1, 2, 8, 7, 3, 0, 7, 7, 3, 9, 2, 5, 7, 8, 1, 2, 330 5, 2, 3, 2, 8, 3, 0, 6, 4, 3, 6, 5, 3, 8, 6, 9, 6, 2, 8, 9, 0, 6, 2, 5, 1, 1, 6, 4, 1, 5, 331 3, 2, 1, 8, 2, 6, 9, 3, 4, 8, 1, 4, 4, 5, 3, 1, 2, 5, 5, 8, 2, 0, 7, 6, 6, 0, 9, 1, 3, 4, 332 6, 7, 4, 0, 7, 2, 2, 6, 5, 6, 2, 5, 2, 9, 1, 0, 3, 8, 3, 0, 4, 5, 6, 7, 3, 3, 7, 0, 3, 6, 333 1, 3, 2, 8, 1, 2, 5, 1, 4, 5, 5, 1, 9, 1, 5, 2, 2, 8, 3, 6, 6, 8, 5, 1, 8, 0, 6, 6, 4, 0, 334 6, 2, 5, 7, 2, 7, 5, 9, 5, 7, 6, 1, 4, 1, 8, 3, 4, 2, 5, 9, 0, 3, 3, 2, 0, 3, 1, 2, 5, 3, 335 6, 3, 7, 9, 7, 8, 8, 0, 7, 0, 9, 1, 7, 1, 2, 9, 5, 1, 6, 6, 0, 1, 5, 6, 2, 5, 1, 8, 1, 8, 336 9, 8, 9, 4, 0, 3, 5, 4, 5, 8, 5, 6, 4, 7, 5, 8, 3, 0, 0, 7, 8, 1, 2, 5, 9, 0, 9, 4, 9, 4, 337 7, 0, 1, 7, 7, 2, 9, 2, 8, 2, 3, 7, 9, 1, 5, 0, 3, 9, 0, 6, 2, 5, 4, 5, 4, 7, 4, 7, 3, 5, 338 0, 8, 8, 6, 4, 6, 4, 1, 1, 8, 9, 5, 7, 5, 1, 9, 5, 3, 1, 2, 5, 2, 2, 7, 3, 7, 3, 6, 7, 5, 339 4, 4, 3, 2, 3, 2, 0, 5, 9, 4, 7, 8, 7, 5, 9, 7, 6, 5, 6, 2, 5, 1, 1, 3, 6, 8, 6, 8, 3, 7, 340 7, 2, 1, 6, 1, 6, 0, 2, 9, 7, 3, 9, 3, 7, 9, 8, 8, 2, 8, 1, 2, 5, 5, 6, 8, 4, 3, 4, 1, 8, 341 8, 6, 0, 8, 0, 8, 0, 1, 4, 8, 6, 9, 6, 8, 9, 9, 4, 1, 4, 0, 6, 2, 5, 2, 8, 4, 2, 1, 7, 0, 342 9, 4, 3, 0, 4, 0, 4, 0, 0, 7, 4, 3, 4, 8, 4, 4, 9, 7, 0, 7, 0, 3, 1, 2, 5, 1, 4, 2, 1, 0, 343 8, 5, 4, 7, 1, 5, 2, 0, 2, 0, 0, 3, 7, 1, 7, 4, 2, 2, 4, 8, 5, 3, 5, 1, 5, 6, 2, 5, 7, 1, 344 0, 5, 4, 2, 7, 3, 5, 7, 6, 0, 1, 0, 0, 1, 8, 5, 8, 7, 1, 1, 2, 4, 2, 6, 7, 5, 7, 8, 1, 2, 345 5, 3, 5, 5, 2, 7, 1, 3, 6, 7, 8, 8, 0, 0, 5, 0, 0, 9, 2, 9, 3, 5, 5, 6, 2, 1, 3, 3, 7, 8, 346 9, 0, 6, 2, 5, 1, 7, 7, 6, 3, 5, 6, 8, 3, 9, 4, 0, 0, 2, 5, 0, 4, 6, 4, 6, 7, 7, 8, 1, 0, 347 6, 6, 8, 9, 4, 5, 3, 1, 2, 5, 8, 8, 8, 1, 7, 8, 4, 1, 9, 7, 0, 0, 1, 2, 5, 2, 3, 2, 3, 3, 348 8, 9, 0, 5, 3, 3, 4, 4, 7, 2, 6, 5, 6, 2, 5, 4, 4, 4, 0, 8, 9, 2, 0, 9, 8, 5, 0, 0, 6, 2, 349 6, 1, 6, 1, 6, 9, 4, 5, 2, 6, 6, 7, 2, 3, 6, 3, 2, 8, 1, 2, 5, 2, 2, 2, 0, 4, 4, 6, 0, 4, 350 9, 2, 5, 0, 3, 1, 3, 0, 8, 0, 8, 4, 7, 2, 6, 3, 3, 3, 6, 1, 8, 1, 6, 4, 0, 6, 2, 5, 1, 1, 351 1, 0, 2, 2, 3, 0, 2, 4, 6, 2, 5, 1, 5, 6, 5, 4, 0, 4, 2, 3, 6, 3, 1, 6, 6, 8, 0, 9, 0, 8, 352 2, 0, 3, 1, 2, 5, 5, 5, 5, 1, 1, 1, 5, 1, 2, 3, 1, 2, 5, 7, 8, 2, 7, 0, 2, 1, 1, 8, 1, 5, 353 8, 3, 4, 0, 4, 5, 4, 1, 0, 1, 5, 6, 2, 5, 2, 7, 7, 5, 5, 5, 7, 5, 6, 1, 5, 6, 2, 8, 9, 1, 354 3, 5, 1, 0, 5, 9, 0, 7, 9, 1, 7, 0, 2, 2, 7, 0, 5, 0, 7, 8, 1, 2, 5, 1, 3, 8, 7, 7, 7, 8, 355 7, 8, 0, 7, 8, 1, 4, 4, 5, 6, 7, 5, 5, 2, 9, 5, 3, 9, 5, 8, 5, 1, 1, 3, 5, 2, 5, 3, 9, 0, 356 6, 2, 5, 6, 9, 3, 8, 8, 9, 3, 9, 0, 3, 9, 0, 7, 2, 2, 8, 3, 7, 7, 6, 4, 7, 6, 9, 7, 9, 2, 357 5, 5, 6, 7, 6, 2, 6, 9, 5, 3, 1, 2, 5, 3, 4, 6, 9, 4, 4, 6, 9, 5, 1, 9, 5, 3, 6, 1, 4, 1, 358 8, 8, 8, 2, 3, 8, 4, 8, 9, 6, 2, 7, 8, 3, 8, 1, 3, 4, 7, 6, 5, 6, 2, 5, 1, 7, 3, 4, 7, 2, 359 3, 4, 7, 5, 9, 7, 6, 8, 0, 7, 0, 9, 4, 4, 1, 1, 9, 2, 4, 4, 8, 1, 3, 9, 1, 9, 0, 6, 7, 3, 360 8, 2, 8, 1, 2, 5, 8, 6, 7, 3, 6, 1, 7, 3, 7, 9, 8, 8, 4, 0, 3, 5, 4, 7, 2, 0, 5, 9, 6, 2, 361 2, 4, 0, 6, 9, 5, 9, 5, 3, 3, 6, 9, 1, 4, 0, 6, 2, 5, 362 ]; 363 364 shift &= 63; 365 let x_a = TABLE[shift]; 366 let x_b = TABLE[shift + 1]; 367 let num_new_digits = (x_a >> 11) as _; 368 let pow5_a = (0x7FF & x_a) as usize; 369 let pow5_b = (0x7FF & x_b) as usize; 370 let pow5 = &TABLE_POW5[pow5_a..]; 371 372 for (i, &p5) in pow5.iter().enumerate().take(pow5_b - pow5_a) { 373 if i >= d.num_digits { 374 return num_new_digits - 1; 375 } else if d.digits[i] == p5 { 376 continue; 377 } else if d.digits[i] < p5 { 378 return num_new_digits - 1; 379 } else { 380 return num_new_digits; 381 } 382 } 383 384 num_new_digits 385 } COMMAND: nl -ba crate/dec2flt/parse.rs 1 //! Functions to parse floating-point numbers. 2 3 use dec2flt::common::{ByteSlice, is_8digits}; 4 use dec2flt::decimal::Decimal; 5 6 use crate::num::imp::{Float, dec2flt}; 7 8 const MIN_19DIGIT_INT: u64 = 100_0000_0000_0000_0000; 9 10 /// Parse 8 digits, loaded as bytes in little-endian order. 11 /// 12 /// This uses the trick where every digit is in [0x030, 0x39], 13 /// and therefore can be parsed in 3 multiplications, much 14 /// faster than the normal 8. 15 /// 16 /// This is based off the algorithm described in "Fast numeric string to 17 /// int", available here: . 18 fn parse_8digits(mut v: u64) -> u64 { 19 const MASK: u64 = 0x0000_00FF_0000_00FF; 20 const MUL1: u64 = 0x000F_4240_0000_0064; 21 const MUL2: u64 = 0x0000_2710_0000_0001; 22 v -= 0x3030_3030_3030_3030; 23 v = (v * 10) + (v >> 8); // will not overflow, fits in 63 bits 24 let v1 = (v & MASK).wrapping_mul(MUL1); 25 let v2 = ((v >> 16) & MASK).wrapping_mul(MUL2); 26 ((v1.wrapping_add(v2) >> 32) as u32) as u64 27 } 28 29 /// Parse digits until a non-digit character is found. 30 fn try_parse_digits(mut s: &[u8], mut x: u64) -> (&[u8], u64) { 31 // may cause overflows, to be handled later 32 33 while s.len() >= 8 { 34 // `chunk` is the source's local `num` under a nonconflicting name. 35 // The rename has no Rust effect and prevents the Lean backend from 36 // resolving `num.imp...` as a field projection on this local value. 37 let chunk = s.read_u64(); 38 if is_8digits(chunk) { 39 x = x.wrapping_mul(1_0000_0000).wrapping_add(parse_8digits(chunk)); 40 s = &s[8..]; 41 } else { 42 break; 43 } 44 } 45 46 // This is the removed `ByteSlice::parse_digits` call specialized to this 47 // accumulator: identical wrapping digit classification, accumulator 48 // update, and first-nondigit stop, without an unsupported closure state. 49 let mut count = 0; 50 while count < s.len() && s[count].wrapping_sub(b'0') < 10 { 51 let digit = s[count].wrapping_sub(b'0'); 52 x = x.wrapping_mul(10).wrapping_add(digit as _); 53 count += 1; 54 } 55 s = &s[count..]; 56 57 (s, x) 58 } 59 60 /// Parse up to 19 digits (the max that can be stored in a 64-bit integer). 61 fn try_parse_19digits(s_ref: &mut &[u8], x: &mut u64) { 62 let mut s = *s_ref; 63 64 while *x < MIN_19DIGIT_INT { 65 if let Some((c, s_next)) = s.split_first() { 66 let digit = c.wrapping_sub(b'0'); 67 68 if digit < 10 { 69 *x = (*x * 10) + digit as u64; // no overflows here 70 s = s_next; 71 } else { 72 break; 73 } 74 } else { 75 break; 76 } 77 } 78 79 *s_ref = s; 80 } 81 82 // This is the source prefix scan isolated from `parse_partial_number` because 83 // Aeneas cannot join its loop context while the enclosing function's other 84 // slice borrows are live. It visits the same bytes, in order, and performs 85 // the identical checked `isize` subtraction for every leading dot or zero. 86 fn adjust_many_digit_count(start: &[u8], mut n_digits: isize) -> isize { 87 let mut scan_index = 0; 88 let mut scanning = true; 89 while scan_index < start.len() && scanning { 90 let c = start[scan_index]; 91 if c == b'.' || c == b'0' { 92 n_digits -= c.saturating_sub(b'0' - 1) as isize; 93 scan_index += 1; 94 } else { 95 scanning = false; 96 } 97 } 98 n_digits 99 } 100 101 // This is the source many-digit retry as a transparent helper. Isolating its 102 // rebased slices avoids an Aeneas context-join failure; both calls, the branch, 103 // the offset arithmetic, and the explicit-exponent addition are unchanged. 104 fn parse_many_digits(start: &[u8], int_end: &[u8], exp_number: i64) -> (u64, i64) { 105 let mut mantissa = 0; 106 let mut s = start; 107 try_parse_19digits(&mut s, &mut mantissa); 108 let mut exponent = if mantissa >= MIN_19DIGIT_INT { 109 int_end.offset_from(s) 110 } else { 111 s = &s[1..]; 112 let before = s; 113 try_parse_19digits(&mut s, &mut mantissa); 114 -s.offset_from(before) 115 } as i64; 116 exponent += exp_number; 117 (mantissa, exponent) 118 } 119 120 /// Parse the scientific notation component of a float. 121 pub(super) fn parse_scientific(s_ref: &mut &[u8]) -> Option { 122 let mut exponent = 0i64; 123 let mut negative = false; 124 125 let mut s = *s_ref; 126 127 if let Some((&c, s_next)) = s.split_first() { 128 negative = c == b'-'; 129 if c == b'-' || c == b'+' { 130 s = s_next; 131 } 132 } 133 134 // `matches!` with a guarded slice pattern triggers an Aeneas internal 135 // error. This short-circuit test reads the same first byte exactly when 136 // it exists and therefore preserves both acceptance and evaluation order. 137 if !s.is_empty() && s[0].is_ascii_digit() { 138 // Specialized form of the revised source callback, shared with the 139 // sibling slow parser. The guard tests the pre-update accumulator: 140 // one digit can overshoot 2^59, up to 10 * 2^59 - 1, still below 141 // i64::MAX. This is not a clamp. Subsequent digits are still consumed 142 // and the first nondigit remains in the returned suffix, so the caller 143 // performs the same whole-input validation even after updates stop. 144 let mut count = 0; 145 while count < s.len() && s[count].wrapping_sub(b'0') < 10 { 146 let digit = s[count].wrapping_sub(b'0'); 147 if exponent < (1_i64 << 59) { 148 exponent = 10 * exponent + digit as i64; 149 } 150 count += 1; 151 } 152 *s_ref = &s[count..]; 153 if negative { Some(-exponent) } else { Some(exponent) } 154 } else { 155 *s_ref = s; 156 None 157 } 158 } 159 160 /// Parse a partial, non-special floating point number. 161 /// 162 /// This creates a representation of the float as the 163 /// significant digits and the decimal exponent. 164 fn parse_partial_number(mut s: &[u8]) -> Option<(Decimal, usize)> { 165 debug_assert!(!s.is_empty()); 166 167 // parse initial digits before dot 168 let mut mantissa = 0_u64; 169 let start = s; 170 let tmp = try_parse_digits(s, mantissa); 171 s = tmp.0; 172 mantissa = tmp.1; 173 let mut n_digits = s.offset_from(start); 174 175 // handle dot with the following digits 176 let mut n_after_dot = 0; 177 let mut exponent = 0_i64; 178 let int_end = s; 179 180 if let Some((&b'.', s_next)) = s.split_first() { 181 s = s_next; 182 let before = s; 183 let tmp = try_parse_digits(s, mantissa); 184 s = tmp.0; 185 mantissa = tmp.1; 186 n_after_dot = s.offset_from(before); 187 exponent = -n_after_dot as i64; 188 } 189 190 n_digits += n_after_dot; 191 if n_digits == 0 { 192 return None; 193 } 194 195 // handle scientific format 196 let mut exp_number = 0_i64; 197 if let Some((&c, s_next)) = s.split_first() { 198 if c == b'e' || c == b'E' { 199 s = s_next; 200 // If None, we have no trailing digits after exponent, or an invalid float. 201 exp_number = parse_scientific(&mut s)?; 202 exponent += exp_number; 203 } 204 } 205 206 let len = s.offset_from(start) as _; 207 208 // handle uncommon case with many digits 209 if n_digits <= 19 { 210 return Some((Decimal { exponent, mantissa, negative: false, many_digits: false }, len)); 211 } 212 213 n_digits -= 19; 214 let mut many_digits = false; 215 // The indexed loop is equivalent to the source `while let split_first`: 216 // it tests nonemptiness before the same byte read and consumes one byte 217 // only on the two source continuation cases. This avoids Aeneas's loop 218 // context mismatch without changing checked subtraction or slice bounds. 219 n_digits = adjust_many_digit_count(start, n_digits); 220 if n_digits > 0 { 221 // at this point we have more than 19 significant digits, let's try again 222 many_digits = true; 223 let retried = parse_many_digits(start, int_end, exp_number); 224 mantissa = retried.0; 225 exponent = retried.1; 226 } 227 228 Some((Decimal { exponent, mantissa, negative: false, many_digits }, len)) 229 } 230 231 /// Try to parse a non-special floating point number, 232 /// as well as two slices with integer and fractional parts 233 /// and the parsed exponent. 234 pub fn parse_number(s: &[u8]) -> Option { 235 if let Some((float, rest)) = parse_partial_number(s) { 236 if rest == s.len() { 237 return Some(float); 238 } 239 } 240 None 241 } 242 243 /// Try to parse a special, non-finite float. 244 pub(crate) fn parse_inf_nan(s: &[u8], negative: bool) -> Option { 245 // Since a valid string has at most the length 8, we can load 246 // all relevant characters into a u64 and work from there. 247 // This also generates much better code. 248 249 let mut register; 250 let len: usize; 251 252 // All valid strings are either of length 8 or 3. 253 if s.len() == 8 { 254 register = s.read_u64(); 255 len = 8; 256 } else if s.len() == 3 { 257 let a = s[0] as u64; 258 let b = s[1] as u64; 259 let c = s[2] as u64; 260 register = (c << 16) | (b << 8) | a; 261 len = 3; 262 } else { 263 return None; 264 } 265 266 // Clear out the bits which turn ASCII uppercase characters into 267 // lowercase characters. The resulting string is all uppercase. 268 // What happens to other characters is irrelevant. 269 register &= 0xDFDFDFDFDFDFDFDF; 270 271 // u64 values corresponding to relevant cases 272 const INF_3: u64 = 0x464E49; // "INF" 273 const INF_8: u64 = 0x5954494E49464E49; // "INFINITY" 274 const NAN: u64 = 0x4E414E; // "NAN" 275 276 // Match register value to constant to parse string. 277 // Also match on the string length to catch edge cases 278 // like "inf\0\0\0\0\0". 279 let float = match (register, len) { 280 (INF_3, 3) => F::INFINITY, 281 (INF_8, 8) => F::INFINITY, 282 (NAN, 3) => F::NAN, 283 _ => return None, 284 }; 285 286 if negative { Some(-float) } else { Some(float) } 287 } COMMAND: nl -ba crate/dec2flt/decimal_seq.rs 1 //! Arbitrary-precision decimal type used by fallback algorithms. 2 //! 3 //! This is only used if the fast-path (native floats) and 4 //! the Eisel-Lemire algorithm are unable to unambiguously 5 //! determine the float. 6 //! 7 //! The technique used is "Simple Decimal Conversion", developed 8 //! by Nigel Tao and Ken Thompson. A detailed description of the 9 //! algorithm can be found in "ParseNumberF64 by Simple Decimal Conversion", 10 //! available online: . 11 12 use dec2flt::common::{ByteSlice, is_8digits}; 13 use dec2flt::parse::parse_scientific; 14 15 use crate::num::imp::dec2flt; 16 17 /// A decimal floating-point number, represented as a sequence of decimal digits. 18 // Debug output is absent from the scoped observations. Removing only that 19 // implementation preserves the representation, Clone/PartialEq behavior, and 20 // every fallback operation independently of GOAL truth. 21 #[derive(Clone, PartialEq)] 22 pub struct DecimalSeq { 23 /// The number of significant digits in the decimal. 24 pub num_digits: usize, 25 /// The offset of the decimal point in the significant digits. 26 pub decimal_point: i32, 27 /// If the number of significant digits stored in the decimal is truncated. 28 pub truncated: bool, 29 /// Buffer of the raw digits, in the range [0, 9]. 30 pub digits: [u8; Self::MAX_DIGITS], 31 } 32 33 impl Default for DecimalSeq { 34 fn default() -> Self { 35 Self { num_digits: 0, decimal_point: 0, truncated: false, digits: [0; Self::MAX_DIGITS] } 36 } 37 } 38 39 impl DecimalSeq { 40 /// The maximum number of digits required to unambiguously round up to a 64-bit float. 41 /// 42 /// For an IEEE 754 binary64 float, this required 767 digits. So we store the max digits + 1. 43 /// 44 /// We can exactly represent a float in radix `b` from radix 2 if 45 /// `b` is divisible by 2. This function calculates the exact number of 46 /// digits required to exactly represent that float. 47 /// 48 /// According to the "Handbook of Floating Point Arithmetic", 49 /// for IEEE754, with `emin` being the min exponent, `p2` being the 50 /// precision, and `b` being the radix, the number of digits follows as: 51 /// 52 /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` 53 /// 54 /// For f32, this follows as: 55 /// emin = -126 56 /// p2 = 24 57 /// 58 /// For f64, this follows as: 59 /// emin = -1022 60 /// p2 = 53 61 /// 62 /// In Python: 63 /// `-emin + p2 + math.floor((emin+ 1)*math.log(2, b)-math.log(1-2**(-p2), b))` 64 pub const MAX_DIGITS: usize = 768; 65 66 /// The max decimal digits that can be exactly represented in a 64-bit integer. 67 pub(super) const MAX_DIGITS_WITHOUT_OVERFLOW: usize = 19; 68 pub(super) const DECIMAL_POINT_RANGE: i32 = 2047; 69 70 /// Append a digit to the buffer if it fits. 71 // FIXME(tgross35): it may be better for this to return an option 72 // FIXME(tgross35): incrementing the digit counter even if we don't push anything 73 // seems incorrect. 74 pub(super) fn try_add_digit(&mut self, digit: u8) { 75 if self.num_digits < Self::MAX_DIGITS { 76 self.digits[self.num_digits] = digit; 77 } 78 self.num_digits += 1; 79 } 80 81 /// Trim trailing zeros from the buffer. 82 // FIXME(tgross35): this could be `.rev().position()` if perf is okay 83 pub fn trim(&mut self) { 84 // All of the following calls to `DecimalSeq::trim` can't panic because: 85 // 86 // 1. `parse_decimal` sets `num_digits` to a max of `DecimalSeq::MAX_DIGITS`. 87 // 2. `right_shift` sets `num_digits` to `write_index`, which is bounded by `num_digits`. 88 // 3. `left_shift` `num_digits` to a max of `DecimalSeq::MAX_DIGITS`. 89 // 90 // Trim is only called in `right_shift` and `left_shift`. 91 debug_assert!(self.num_digits <= Self::MAX_DIGITS); 92 while self.num_digits != 0 && self.digits[self.num_digits - 1] == 0 { 93 self.num_digits -= 1; 94 } 95 } 96 97 pub(super) fn round(&self) -> u64 { 98 if self.num_digits == 0 || self.decimal_point < 0 { 99 return 0; 100 } else if self.decimal_point >= Self::MAX_DIGITS_WITHOUT_OVERFLOW as i32 { 101 return 0xFFFF_FFFF_FFFF_FFFF_u64; 102 } 103 104 let dp = self.decimal_point as usize; 105 let mut n = 0_u64; 106 107 for i in 0..dp { 108 n *= 10; 109 if i < self.num_digits { 110 n += self.digits[i] as u64; 111 } 112 } 113 114 let mut round_up = false; 115 116 if dp < self.num_digits { 117 round_up = self.digits[dp] >= 5; 118 if self.digits[dp] == 5 && dp + 1 == self.num_digits { 119 round_up = self.truncated || ((dp != 0) && (1 & self.digits[dp - 1] != 0)) 120 } 121 } 122 123 if round_up { 124 n += 1; 125 } 126 n 127 } 128 129 /// Computes decimal * 2^shift. 130 pub(super) fn left_shift(&mut self, shift: usize) { 131 if self.num_digits == 0 { 132 return; 133 } 134 let num_new_digits = number_of_digits_decimal_left_shift(self, shift); 135 let mut read_index = self.num_digits; 136 let mut write_index = self.num_digits + num_new_digits; 137 let mut n = 0_u64; 138 139 while read_index != 0 { 140 read_index -= 1; 141 write_index -= 1; 142 n += (self.digits[read_index] as u64) << shift; 143 let quotient = n / 10; 144 let remainder = n - (10 * quotient); 145 if write_index < Self::MAX_DIGITS { 146 self.digits[write_index] = remainder as u8; 147 } else if remainder > 0 { 148 self.truncated = true; 149 } 150 n = quotient; 151 } 152 153 while n > 0 { 154 write_index -= 1; 155 let quotient = n / 10; 156 let remainder = n - (10 * quotient); 157 if write_index < Self::MAX_DIGITS { 158 self.digits[write_index] = remainder as u8; 159 } else if remainder > 0 { 160 self.truncated = true; 161 } 162 n = quotient; 163 } 164 165 self.num_digits += num_new_digits; 166 167 if self.num_digits > Self::MAX_DIGITS { 168 self.num_digits = Self::MAX_DIGITS; 169 } 170 171 self.decimal_point += num_new_digits as i32; 172 self.trim(); 173 } 174 175 /// Computes decimal * 2^-shift. 176 pub(super) fn right_shift(&mut self, shift: usize) { 177 let mut read_index = 0; 178 let mut write_index = 0; 179 let mut n = 0_u64; 180 let mut all_zero = false; 181 while (n >> shift) == 0 && !all_zero { 182 if read_index < self.num_digits { 183 n = (10 * n) + self.digits[read_index] as u64; 184 read_index += 1; 185 } else if n == 0 { 186 // The source returns here from inside the loop. Recording the 187 // condition and returning immediately after the loop executes 188 // no intervening operation and preserves the unchanged value. 189 all_zero = true; 190 } else { 191 while (n >> shift) == 0 { 192 n *= 10; 193 read_index += 1; 194 } 195 break; 196 } 197 } 198 if all_zero { 199 return; 200 } 201 self.decimal_point -= read_index as i32 - 1; 202 if self.decimal_point < -Self::DECIMAL_POINT_RANGE { 203 // `self = Self::Default()`, but without the overhead of clearing `digits`. 204 self.num_digits = 0; 205 self.decimal_point = 0; 206 self.truncated = false; 207 return; 208 } 209 let mask = (1_u64 << shift) - 1; 210 while read_index < self.num_digits { 211 let new_digit = (n >> shift) as u8; 212 n = (10 * (n & mask)) + self.digits[read_index] as u64; 213 read_index += 1; 214 self.digits[write_index] = new_digit; 215 write_index += 1; 216 } 217 while n > 0 { 218 let new_digit = (n >> shift) as u8; 219 n = 10 * (n & mask); 220 if write_index < Self::MAX_DIGITS { 221 self.digits[write_index] = new_digit; 222 write_index += 1; 223 } else if new_digit > 0 { 224 self.truncated = true; 225 } 226 } 227 self.num_digits = write_index; 228 self.trim(); 229 } 230 } 231 232 // This is exactly the source reverse scan over the already-consumed prefix. 233 // It is separate because Aeneas cannot join the loop while `parse_decimal_seq` 234 // retains its other slice borrows. The downward index has the same visitation 235 // order and counts precisely the same zero bytes while ignoring dots. 236 fn count_trailing_zeros(start: &[u8], consumed_len: usize) -> usize { 237 let mut n_trailing_zeros = 0; 238 let mut i = consumed_len; 239 let mut scanning = true; 240 while i != 0 && scanning { 241 let c = start[i - 1]; 242 if c == b'0' || c == b'.' { 243 i -= 1; 244 if c == b'0' { 245 n_trailing_zeros += 1; 246 } 247 } else { 248 scanning = false; 249 } 250 } 251 n_trailing_zeros 252 } 253 254 // Equivalent to `ByteSlice::parse_digits(|digit| d.try_add_digit(digit))`. 255 // An explicit index keeps the closure's mutable borrow out of the enclosing 256 // parser context while retaining the same wrapping digit test and updates. 257 fn parse_digits_into_seq<'a>(s: &'a [u8], d: &mut DecimalSeq) -> &'a [u8] { 258 let mut count = 0; 259 while count < s.len() && s[count].wrapping_sub(b'0') < 10 { 260 let digit = s[count].wrapping_sub(b'0'); 261 d.try_add_digit(digit); 262 count += 1; 263 } 264 &s[count..] 265 } 266 267 /// Combine counts in i64 and clamp before casting to i32. 268 #[inline] 269 pub(super) fn final_decimal_point( 270 significant_count: usize, 271 fractional_count: usize, 272 explicit: i64, 273 ) -> i32 { 274 // This is the repaired upstream body, not an extraction replacement. 275 // Source-valid byte slices bound both counts by isize::MAX on this target; 276 // their i64 difference is therefore in range. Retain saturating_add and 277 // clamp as source operations, including the zero-count early return. 278 if significant_count == 0 { 279 return 0; 280 } 281 let base = significant_count as i64 - fractional_count as i64; 282 base.saturating_add(explicit) 283 .clamp(-(DecimalSeq::DECIMAL_POINT_RANGE as i64), DecimalSeq::DECIMAL_POINT_RANGE as i64) 284 as i32 285 } 286 287 /// Parse a big integer representation of the float as a decimal. 288 pub fn parse_decimal_seq(mut s: &[u8]) -> DecimalSeq { 289 let mut d = DecimalSeq::default(); 290 let start = s; 291 let mut fractional_count = 0; 292 293 // Aeneas rejects the literal-pattern `while let`; this loop performs the 294 // same nonempty check, byte comparison, and one-byte consumption in the 295 // same order, with identical slice bounds. 296 while !s.is_empty() && s[0] == b'0' { 297 s = &s[1..]; 298 } 299 300 s = parse_digits_into_seq(s, &mut d); 301 302 if !s.is_empty() && s[0] == b'.' { 303 s = &s[1..]; 304 let first = s; 305 // Skip leading zeros. 306 if d.num_digits == 0 { 307 // As above, this is the source leading-zero loop written in the 308 // indexed form accepted by Aeneas. 309 while !s.is_empty() && s[0] == b'0' { 310 s = &s[1..]; 311 } 312 } 313 while s.len() >= 8 && d.num_digits + 8 < DecimalSeq::MAX_DIGITS { 314 let v = s.read_u64(); 315 if !is_8digits(v) { 316 break; 317 } 318 d.digits[d.num_digits..].write_u64(v - 0x3030_3030_3030_3030); 319 d.num_digits += 8; 320 s = &s[8..]; 321 } 322 s = parse_digits_into_seq(s, &mut d); 323 // `first` precedes zero skipping and both digit scans. This difference 324 // includes every fractional digit, just as in repaired upstream. 325 fractional_count = first.len() - s.len(); 326 } 327 328 // Save the source's logical count before trimming and MAX_DIGITS capping; 329 // the stored digit prefix must not replace this count in point arithmetic. 330 let significant_count = d.num_digits; 331 if d.num_digits != 0 { 332 // Ignore the trailing zeros if there are any 333 let consumed_len = start.len() - s.len(); 334 // Walking an index downward visits exactly the same bytes as 335 // `.iter().rev()` and stops on the same first nonzero nondot byte. It 336 // also avoids the missing extracted `Iterator::rev` library field. 337 let n_trailing_zeros = count_trailing_zeros(start, consumed_len); 338 d.num_digits -= n_trailing_zeros; 339 if d.num_digits > DecimalSeq::MAX_DIGITS { 340 d.truncated = true; 341 d.num_digits = DecimalSeq::MAX_DIGITS; 342 } 343 } 344 345 // Indexed tests preserve `split_first`'s nonempty guard and byte order but 346 // avoid the loop-context joins Aeneas creates for nested slice patterns. 347 let mut explicit = 0; 348 if !s.is_empty() { 349 let ch = s[0]; 350 if ch == b'e' || ch == b'E' { 351 // Aeneas cannot join this branch when the enclosing `s` is 352 // rebased and mutably borrowed. A fresh slice local translates. 353 // The source never reads `s` after this call: all consumed-prefix, 354 // significant and fractional counts are already saved. Passing 355 // the identical suffix to the unchanged shared parser gives the 356 // same sign, digit consumption, bounded accumulation, checked 357 // operations and failures; only its unobserved suffix mutation 358 // targets a different local. Keep the call even for zero digits, 359 // and keep None-to-zero on missing/malformed exponent digits. 360 // This argument needs no numeric-validity or correctness premise; 361 // parse_number still observes the shared parser's returned suffix. 362 let mut exponent_suffix = &s[1..]; 363 explicit = parse_scientific(&mut exponent_suffix).unwrap_or(0); 364 } 365 } 366 d.decimal_point = final_decimal_point(significant_count, fractional_count, explicit); 367 368 for i in d.num_digits..DecimalSeq::MAX_DIGITS_WITHOUT_OVERFLOW { 369 d.digits[i] = 0; 370 } 371 372 d 373 } 374 375 fn number_of_digits_decimal_left_shift(d: &DecimalSeq, mut shift: usize) -> usize { 376 #[rustfmt::skip] 377 const TABLE: [u16; 65] = [ 378 0x0000, 0x0800, 0x0801, 0x0803, 0x1006, 0x1009, 0x100D, 0x1812, 0x1817, 0x181D, 0x2024, 379 0x202B, 0x2033, 0x203C, 0x2846, 0x2850, 0x285B, 0x3067, 0x3073, 0x3080, 0x388E, 0x389C, 380 0x38AB, 0x38BB, 0x40CC, 0x40DD, 0x40EF, 0x4902, 0x4915, 0x4929, 0x513E, 0x5153, 0x5169, 381 0x5180, 0x5998, 0x59B0, 0x59C9, 0x61E3, 0x61FD, 0x6218, 0x6A34, 0x6A50, 0x6A6D, 0x6A8B, 382 0x72AA, 0x72C9, 0x72E9, 0x7B0A, 0x7B2B, 0x7B4D, 0x8370, 0x8393, 0x83B7, 0x83DC, 0x8C02, 383 0x8C28, 0x8C4F, 0x9477, 0x949F, 0x94C8, 0x9CF2, 0x051C, 0x051C, 0x051C, 0x051C, 384 ]; 385 #[rustfmt::skip] 386 const TABLE_POW5: [u8; 0x051C] = [ 387 5, 2, 5, 1, 2, 5, 6, 2, 5, 3, 1, 2, 5, 1, 5, 6, 2, 5, 7, 8, 1, 2, 5, 3, 9, 0, 6, 2, 5, 1, 388 9, 5, 3, 1, 2, 5, 9, 7, 6, 5, 6, 2, 5, 4, 8, 8, 2, 8, 1, 2, 5, 2, 4, 4, 1, 4, 0, 6, 2, 5, 389 1, 2, 2, 0, 7, 0, 3, 1, 2, 5, 6, 1, 0, 3, 5, 1, 5, 6, 2, 5, 3, 0, 5, 1, 7, 5, 7, 8, 1, 2, 390 5, 1, 5, 2, 5, 8, 7, 8, 9, 0, 6, 2, 5, 7, 6, 2, 9, 3, 9, 4, 5, 3, 1, 2, 5, 3, 8, 1, 4, 6, 391 9, 7, 2, 6, 5, 6, 2, 5, 1, 9, 0, 7, 3, 4, 8, 6, 3, 2, 8, 1, 2, 5, 9, 5, 3, 6, 7, 4, 3, 1, 392 6, 4, 0, 6, 2, 5, 4, 7, 6, 8, 3, 7, 1, 5, 8, 2, 0, 3, 1, 2, 5, 2, 3, 8, 4, 1, 8, 5, 7, 9, 393 1, 0, 1, 5, 6, 2, 5, 1, 1, 9, 2, 0, 9, 2, 8, 9, 5, 5, 0, 7, 8, 1, 2, 5, 5, 9, 6, 0, 4, 6, 394 4, 4, 7, 7, 5, 3, 9, 0, 6, 2, 5, 2, 9, 8, 0, 2, 3, 2, 2, 3, 8, 7, 6, 9, 5, 3, 1, 2, 5, 1, 395 4, 9, 0, 1, 1, 6, 1, 1, 9, 3, 8, 4, 7, 6, 5, 6, 2, 5, 7, 4, 5, 0, 5, 8, 0, 5, 9, 6, 9, 2, 396 3, 8, 2, 8, 1, 2, 5, 3, 7, 2, 5, 2, 9, 0, 2, 9, 8, 4, 6, 1, 9, 1, 4, 0, 6, 2, 5, 1, 8, 6, 397 2, 6, 4, 5, 1, 4, 9, 2, 3, 0, 9, 5, 7, 0, 3, 1, 2, 5, 9, 3, 1, 3, 2, 2, 5, 7, 4, 6, 1, 5, 398 4, 7, 8, 5, 1, 5, 6, 2, 5, 4, 6, 5, 6, 6, 1, 2, 8, 7, 3, 0, 7, 7, 3, 9, 2, 5, 7, 8, 1, 2, 399 5, 2, 3, 2, 8, 3, 0, 6, 4, 3, 6, 5, 3, 8, 6, 9, 6, 2, 8, 9, 0, 6, 2, 5, 1, 1, 6, 4, 1, 5, 400 3, 2, 1, 8, 2, 6, 9, 3, 4, 8, 1, 4, 4, 5, 3, 1, 2, 5, 5, 8, 2, 0, 7, 6, 6, 0, 9, 1, 3, 4, 401 6, 7, 4, 0, 7, 2, 2, 6, 5, 6, 2, 5, 2, 9, 1, 0, 3, 8, 3, 0, 4, 5, 6, 7, 3, 3, 7, 0, 3, 6, 402 1, 3, 2, 8, 1, 2, 5, 1, 4, 5, 5, 1, 9, 1, 5, 2, 2, 8, 3, 6, 6, 8, 5, 1, 8, 0, 6, 6, 4, 0, 403 6, 2, 5, 7, 2, 7, 5, 9, 5, 7, 6, 1, 4, 1, 8, 3, 4, 2, 5, 9, 0, 3, 3, 2, 0, 3, 1, 2, 5, 3, 404 6, 3, 7, 9, 7, 8, 8, 0, 7, 0, 9, 1, 7, 1, 2, 9, 5, 1, 6, 6, 0, 1, 5, 6, 2, 5, 1, 8, 1, 8, 405 9, 8, 9, 4, 0, 3, 5, 4, 5, 8, 5, 6, 4, 7, 5, 8, 3, 0, 0, 7, 8, 1, 2, 5, 9, 0, 9, 4, 9, 4, 406 7, 0, 1, 7, 7, 2, 9, 2, 8, 2, 3, 7, 9, 1, 5, 0, 3, 9, 0, 6, 2, 5, 4, 5, 4, 7, 4, 7, 3, 5, 407 0, 8, 8, 6, 4, 6, 4, 1, 1, 8, 9, 5, 7, 5, 1, 9, 5, 3, 1, 2, 5, 2, 2, 7, 3, 7, 3, 6, 7, 5, 408 4, 4, 3, 2, 3, 2, 0, 5, 9, 4, 7, 8, 7, 5, 9, 7, 6, 5, 6, 2, 5, 1, 1, 3, 6, 8, 6, 8, 3, 7, 409 7, 2, 1, 6, 1, 6, 0, 2, 9, 7, 3, 9, 3, 7, 9, 8, 8, 2, 8, 1, 2, 5, 5, 6, 8, 4, 3, 4, 1, 8, 410 8, 6, 0, 8, 0, 8, 0, 1, 4, 8, 6, 9, 6, 8, 9, 9, 4, 1, 4, 0, 6, 2, 5, 2, 8, 4, 2, 1, 7, 0, 411 9, 4, 3, 0, 4, 0, 4, 0, 0, 7, 4, 3, 4, 8, 4, 4, 9, 7, 0, 7, 0, 3, 1, 2, 5, 1, 4, 2, 1, 0, 412 8, 5, 4, 7, 1, 5, 2, 0, 2, 0, 0, 3, 7, 1, 7, 4, 2, 2, 4, 8, 5, 3, 5, 1, 5, 6, 2, 5, 7, 1, 413 0, 5, 4, 2, 7, 3, 5, 7, 6, 0, 1, 0, 0, 1, 8, 5, 8, 7, 1, 1, 2, 4, 2, 6, 7, 5, 7, 8, 1, 2, 414 5, 3, 5, 5, 2, 7, 1, 3, 6, 7, 8, 8, 0, 0, 5, 0, 0, 9, 2, 9, 3, 5, 5, 6, 2, 1, 3, 3, 7, 8, 415 9, 0, 6, 2, 5, 1, 7, 7, 6, 3, 5, 6, 8, 3, 9, 4, 0, 0, 2, 5, 0, 4, 6, 4, 6, 7, 7, 8, 1, 0, 416 6, 6, 8, 9, 4, 5, 3, 1, 2, 5, 8, 8, 8, 1, 7, 8, 4, 1, 9, 7, 0, 0, 1, 2, 5, 2, 3, 2, 3, 3, 417 8, 9, 0, 5, 3, 3, 4, 4, 7, 2, 6, 5, 6, 2, 5, 4, 4, 4, 0, 8, 9, 2, 0, 9, 8, 5, 0, 0, 6, 2, 418 6, 1, 6, 1, 6, 9, 4, 5, 2, 6, 6, 7, 2, 3, 6, 3, 2, 8, 1, 2, 5, 2, 2, 2, 0, 4, 4, 6, 0, 4, 419 9, 2, 5, 0, 3, 1, 3, 0, 8, 0, 8, 4, 7, 2, 6, 3, 3, 3, 6, 1, 8, 1, 6, 4, 0, 6, 2, 5, 1, 1, 420 1, 0, 2, 2, 3, 0, 2, 4, 6, 2, 5, 1, 5, 6, 5, 4, 0, 4, 2, 3, 6, 3, 1, 6, 6, 8, 0, 9, 0, 8, 421 2, 0, 3, 1, 2, 5, 5, 5, 5, 1, 1, 1, 5, 1, 2, 3, 1, 2, 5, 7, 8, 2, 7, 0, 2, 1, 1, 8, 1, 5, 422 8, 3, 4, 0, 4, 5, 4, 1, 0, 1, 5, 6, 2, 5, 2, 7, 7, 5, 5, 5, 7, 5, 6, 1, 5, 6, 2, 8, 9, 1, 423 3, 5, 1, 0, 5, 9, 0, 7, 9, 1, 7, 0, 2, 2, 7, 0, 5, 0, 7, 8, 1, 2, 5, 1, 3, 8, 7, 7, 7, 8, 424 7, 8, 0, 7, 8, 1, 4, 4, 5, 6, 7, 5, 5, 2, 9, 5, 3, 9, 5, 8, 5, 1, 1, 3, 5, 2, 5, 3, 9, 0, 425 6, 2, 5, 6, 9, 3, 8, 8, 9, 3, 9, 0, 3, 9, 0, 7, 2, 2, 8, 3, 7, 7, 6, 4, 7, 6, 9, 7, 9, 2, 426 5, 5, 6, 7, 6, 2, 6, 9, 5, 3, 1, 2, 5, 3, 4, 6, 9, 4, 4, 6, 9, 5, 1, 9, 5, 3, 6, 1, 4, 1, 427 8, 8, 8, 2, 3, 8, 4, 8, 9, 6, 2, 7, 8, 3, 8, 1, 3, 4, 7, 6, 5, 6, 2, 5, 1, 7, 3, 4, 7, 2, 428 3, 4, 7, 5, 9, 7, 6, 8, 0, 7, 0, 9, 4, 4, 1, 1, 9, 2, 4, 4, 8, 1, 3, 9, 1, 9, 0, 6, 7, 3, 429 8, 2, 8, 1, 2, 5, 8, 6, 7, 3, 6, 1, 7, 3, 7, 9, 8, 8, 4, 0, 3, 5, 4, 7, 2, 0, 5, 9, 6, 2, 430 2, 4, 0, 6, 9, 5, 9, 5, 3, 3, 6, 9, 1, 4, 0, 6, 2, 5, 431 ]; 432 433 shift &= 63; 434 let x_a = TABLE[shift]; 435 let x_b = TABLE[shift + 1]; 436 let num_new_digits = (x_a >> 11) as _; 437 let pow5_a = (0x7FF & x_a) as usize; 438 let pow5_b = (0x7FF & x_b) as usize; 439 let pow5 = &TABLE_POW5[pow5_a..]; 440 441 for (i, &p5) in pow5.iter().enumerate().take(pow5_b - pow5_a) { 442 if i >= d.num_digits { 443 return num_new_digits - 1; 444 } else if d.digits[i] == p5 { 445 continue; 446 } else if d.digits[i] < p5 { 447 return num_new_digits - 1; 448 } else { 449 return num_new_digits; 450 } 451 } 452 453 num_new_digits 454 } COMMAND: nl -ba upstream/dec2flt/mod.rs 1 //! Converting decimal strings into IEEE 754 binary floating point numbers. 2 //! 3 //! # Problem statement 4 //! 5 //! We are given a decimal string such as `12.34e56`. This string consists of integral (`12`), 6 //! fractional (`34`), and exponent (`56`) parts. All parts are optional and interpreted as a 7 //! default value (1 or 0) when missing. 8 //! 9 //! We seek the IEEE 754 floating point number that is closest to the exact value of the decimal 10 //! string. It is well-known that many decimal strings do not have terminating representations in 11 //! base two, so we round to 0.5 units in the last place (in other words, as well as possible). 12 //! Ties, decimal values exactly half-way between two consecutive floats, are resolved with the 13 //! half-to-even strategy, also known as banker's rounding. 14 //! 15 //! Needless to say, this is quite hard, both in terms of implementation complexity and in terms 16 //! of CPU cycles taken. 17 //! 18 //! # Implementation 19 //! 20 //! First, we ignore signs. Or rather, we remove it at the very beginning of the conversion 21 //! process and re-apply it at the very end. This is correct in all edge cases since IEEE 22 //! floats are symmetric around zero, negating one simply flips the first bit. 23 //! 24 //! Then we remove the decimal point by adjusting the exponent: Conceptually, `12.34e56` turns 25 //! into `1234e54`, which we describe with a positive integer `f = 1234` and an integer `e = 54`. 26 //! The `(f, e)` representation is used by almost all code past the parsing stage. 27 //! 28 //! We then try a long chain of progressively more general and expensive special cases using 29 //! machine-sized integers and small, fixed-sized floating point numbers (first `f32`/`f64`, then 30 //! a type with 64 bit significand). The extended-precision algorithm 31 //! uses the Eisel-Lemire algorithm, which uses a 128-bit (or 192-bit) 32 //! representation that can accurately and quickly compute the vast majority 33 //! of floats. When all these fail, we bite the bullet and resort to using 34 //! a large-decimal representation, shifting the digits into range, calculating 35 //! the upper significant bits and exactly round to the nearest representation. 36 //! 37 //! Another aspect that needs attention is the ``RawFloat`` trait by which almost all functions 38 //! are parametrized. One might think that it's enough to parse to `f64` and cast the result to 39 //! `f32`. Unfortunately this is not the world we live in, and this has nothing to do with using 40 //! base two or half-to-even rounding. 41 //! 42 //! Consider for example two types `d2` and `d4` representing a decimal type with two decimal 43 //! digits and four decimal digits each and take "0.01499" as input. Let's use half-up rounding. 44 //! Going directly to two decimal digits gives `0.01`, but if we round to four digits first, 45 //! we get `0.0150`, which is then rounded up to `0.02`. The same principle applies to other 46 //! operations as well, if you want 0.5 ULP accuracy you need to do *everything* in full precision 47 //! and round *exactly once, at the end*, by considering all truncated bits at once. 48 //! 49 //! Primarily, this module and its children implement the algorithms described in: 50 //! "Number Parsing at a Gigabyte per Second", available online: 51 //! . 52 //! 53 //! # Other 54 //! 55 //! The conversion should *never* panic. There are assertions and explicit panics in the code, 56 //! but they should never be triggered and only serve as internal sanity checks. Any panics should 57 //! be considered a bug. 58 //! 59 //! There are unit tests but they are woefully inadequate at ensuring correctness, they only cover 60 //! a small percentage of possible errors. Far more extensive tests are located in the directory 61 //! `src/tools/test-float-parse` as a Rust program. 62 //! 63 //! A note on integer overflow: Many parts of this file perform arithmetic with the decimal 64 //! exponent `e`. Primarily, we shift the decimal point around: Before the first decimal digit, 65 //! after the last decimal digit, and so on. This could overflow if done carelessly. We rely on 66 //! the parsing submodule to only hand out sufficiently small exponents, where "sufficient" means 67 //! "such that the exponent +/- the number of decimal digits fits into a 64 bit integer". 68 //! Larger exponents are accepted, but we don't do arithmetic with them, they are immediately 69 //! turned into {positive,negative} {zero,infinity}. 70 //! 71 //! # Notation 72 //! 73 //! This module uses the same notation as the Lemire paper: 74 //! 75 //! - `m`: binary mantissa; always nonnegative 76 //! - `p`: binary exponent; a signed integer 77 //! - `w`: decimal significand; always nonnegative 78 //! - `q`: decimal exponent; a signed integer 79 //! 80 //! This gives `m * 2^p` for the binary floating-point number, with `w * 10^q` as the decimal 81 //! equivalent. 82 83 #![doc(hidden)] 84 #![unstable( 85 feature = "dec2flt", 86 reason = "internal routines only exposed for testing", 87 issue = "none" 88 )] 89 90 use common::BiasedFp; 91 use lemire::compute_float; 92 use parse::{parse_inf_nan, parse_number}; 93 use slow::parse_long_mantissa; 94 95 use crate::f64; 96 use crate::num::ParseFloatError; 97 use crate::num::float_parse::FloatErrorKind; 98 use crate::num::imp::FloatExt; 99 100 mod common; 101 pub mod decimal; 102 pub mod decimal_seq; 103 mod fpu; 104 pub mod lemire; 105 pub mod parse; 106 mod slow; 107 mod table; 108 109 /// Extension to `Float` that are necessary for parsing using the Lemire method. 110 /// 111 /// See the parent module's doc comment for why this is necessary. 112 /// 113 /// Not intended for use outside of the `dec2flt` module. 114 #[doc(hidden)] 115 pub trait Lemire: FloatExt { 116 /// Maximum exponent for a fast path case, or `⌊(SIG_BITS+1)/log2(5)⌋` 117 // assuming FLT_EVAL_METHOD = 0 118 const MAX_EXPONENT_FAST_PATH: i64 = { 119 let log2_5 = f64::consts::LOG2_10 - 1.0; 120 (Self::SIG_TOTAL_BITS as f64 / log2_5) as i64 121 }; 122 123 /// Minimum exponent for a fast path case, or `-⌊(SIG_BITS+1)/log2(5)⌋` 124 const MIN_EXPONENT_FAST_PATH: i64 = -Self::MAX_EXPONENT_FAST_PATH; 125 126 /// Maximum exponent that can be represented for a disguised-fast path case. 127 /// This is `MAX_EXPONENT_FAST_PATH + ⌊(SIG_BITS+1)/log2(10)⌋` 128 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 129 Self::MAX_EXPONENT_FAST_PATH + (Self::SIG_TOTAL_BITS as f64 / f64::consts::LOG2_10) as i64; 130 131 /// Maximum mantissa for the fast-path (`1 << 53` for f64). 132 const MAX_MANTISSA_FAST_PATH: u64 = 1 << Self::SIG_TOTAL_BITS; 133 134 /// Gets a small power-of-ten for fast-path multiplication. 135 fn pow10_fast_path(exponent: usize) -> Self; 136 137 /// Converts integer into float through an as cast. 138 /// This is only called in the fast-path algorithm, and therefore 139 /// will not lose precision, since the value will always have 140 /// only if the value is <= Self::MAX_MANTISSA_FAST_PATH. 141 fn from_u64(v: u64) -> Self; 142 } 143 144 #[cfg(target_has_reliable_f16)] 145 impl Lemire for f16 { 146 fn pow10_fast_path(exponent: usize) -> Self { 147 #[allow(clippy::use_self)] 148 const TABLE: [f16; 8] = [1e0, 1e1, 1e2, 1e3, 1e4, 0.0, 0.0, 0.]; 149 TABLE[exponent & 7] 150 } 151 152 #[inline] 153 fn from_u64(v: u64) -> Self { 154 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH); 155 v as _ 156 } 157 } 158 159 impl Lemire for f32 { 160 fn pow10_fast_path(exponent: usize) -> Self { 161 #[allow(clippy::use_self)] 162 const TABLE: [f32; 16] = 163 [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 0., 0., 0., 0., 0.]; 164 TABLE[exponent & 15] 165 } 166 167 #[inline] 168 fn from_u64(v: u64) -> Self { 169 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH); 170 v as _ 171 } 172 } 173 174 impl Lemire for f64 { 175 fn pow10_fast_path(exponent: usize) -> Self { 176 const TABLE: [f64; 32] = [ 177 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 178 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 0., 0., 0., 0., 0., 0., 0., 0., 0., 179 ]; 180 TABLE[exponent & 31] 181 } 182 183 #[inline] 184 fn from_u64(v: u64) -> Self { 185 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH); 186 v as _ 187 } 188 } 189 190 #[inline] 191 pub(super) fn pfe_empty() -> ParseFloatError { 192 ParseFloatError { kind: FloatErrorKind::Empty } 193 } 194 195 // Used in unit tests, keep public. 196 // This is much better than making FloatErrorKind and ParseFloatError::kind public. 197 #[inline] 198 pub fn pfe_invalid() -> ParseFloatError { 199 ParseFloatError { kind: FloatErrorKind::Invalid } 200 } 201 202 /// Converts a `BiasedFp` to the closest machine float type. 203 fn biased_fp_to_float(x: BiasedFp) -> F { 204 let mut word = x.m; 205 word |= (x.p_biased as u64) << F::SIG_BITS; 206 F::from_u64_bits(word) 207 } 208 209 /// Converts a decimal string into a floating point number. 210 #[inline(always)] // Will be inlined into a function with `#[inline(never)]`, see above 211 pub fn dec2flt(s: &str) -> Result { 212 let mut s = s.as_bytes(); 213 let Some(&c) = s.first() else { return Err(pfe_empty()) }; 214 let negative = c == b'-'; 215 if c == b'-' || c == b'+' { 216 s = &s[1..]; 217 } 218 if s.is_empty() { 219 return Err(pfe_invalid()); 220 } 221 222 let mut num = match parse_number(s) { 223 Some(r) => r, 224 None if let Some(value) = parse_inf_nan(s, negative) => return Ok(value), 225 None => return Err(pfe_invalid()), 226 }; 227 num.negative = negative; 228 if !cfg!(feature = "optimize_for_size") { 229 if let Some(value) = num.try_fast_path::() { 230 return Ok(value); 231 } 232 } 233 234 // If significant digits were truncated, then we can have rounding error 235 // only if `mantissa + 1` produces a different result. We also avoid 236 // redundantly using the Eisel-Lemire algorithm if it was unable to 237 // correctly round on the first pass. 238 let mut fp = compute_float::(num.exponent, num.mantissa); 239 if num.many_digits 240 && fp.p_biased >= 0 241 && fp != compute_float::(num.exponent, num.mantissa + 1) 242 { 243 fp.p_biased = -1; 244 } 245 // Unable to correctly round the float using the Eisel-Lemire algorithm. 246 // Fallback to a slower, but always correct algorithm. 247 if fp.p_biased < 0 { 248 fp = parse_long_mantissa::(s); 249 } 250 251 let mut float = biased_fp_to_float::(fp); 252 if num.negative { 253 float = -float; 254 } 255 Ok(float) 256 } COMMAND: nl -ba crate/dec2flt/mod.rs 1 //! Converting decimal strings into IEEE 754 binary floating point numbers. 2 //! 3 //! # Problem statement 4 //! 5 //! We are given a decimal string such as `12.34e56`. This string consists of integral (`12`), 6 //! fractional (`34`), and exponent (`56`) parts. All parts are optional and interpreted as a 7 //! default value (1 or 0) when missing. 8 //! 9 //! We seek the IEEE 754 floating point number that is closest to the exact value of the decimal 10 //! string. It is well-known that many decimal strings do not have terminating representations in 11 //! base two, so we round to 0.5 units in the last place (in other words, as well as possible). 12 //! Ties, decimal values exactly half-way between two consecutive floats, are resolved with the 13 //! half-to-even strategy, also known as banker's rounding. 14 //! 15 //! Needless to say, this is quite hard, both in terms of implementation complexity and in terms 16 //! of CPU cycles taken. 17 //! 18 //! # Implementation 19 //! 20 //! First, we ignore signs. Or rather, we remove it at the very beginning of the conversion 21 //! process and re-apply it at the very end. This is correct in all edge cases since IEEE 22 //! floats are symmetric around zero, negating one simply flips the first bit. 23 //! 24 //! Then we remove the decimal point by adjusting the exponent: Conceptually, `12.34e56` turns 25 //! into `1234e54`, which we describe with a positive integer `f = 1234` and an integer `e = 54`. 26 //! The `(f, e)` representation is used by almost all code past the parsing stage. 27 //! 28 //! We then try a long chain of progressively more general and expensive special cases using 29 //! machine-sized integers and small, fixed-sized floating point numbers (first `f32`/`f64`, then 30 //! a type with 64 bit significand). The extended-precision algorithm 31 //! uses the Eisel-Lemire algorithm, which uses a 128-bit (or 192-bit) 32 //! representation that can accurately and quickly compute the vast majority 33 //! of floats. When all these fail, we bite the bullet and resort to using 34 //! a large-decimal representation, shifting the digits into range, calculating 35 //! the upper significant bits and exactly round to the nearest representation. 36 //! 37 //! Another aspect that needs attention is the ``RawFloat`` trait by which almost all functions 38 //! are parametrized. One might think that it's enough to parse to `f64` and cast the result to 39 //! `f32`. Unfortunately this is not the world we live in, and this has nothing to do with using 40 //! base two or half-to-even rounding. 41 //! 42 //! Consider for example two types `d2` and `d4` representing a decimal type with two decimal 43 //! digits and four decimal digits each and take "0.01499" as input. Let's use half-up rounding. 44 //! Going directly to two decimal digits gives `0.01`, but if we round to four digits first, 45 //! we get `0.0150`, which is then rounded up to `0.02`. The same principle applies to other 46 //! operations as well, if you want 0.5 ULP accuracy you need to do *everything* in full precision 47 //! and round *exactly once, at the end*, by considering all truncated bits at once. 48 //! 49 //! Primarily, this module and its children implement the algorithms described in: 50 //! "Number Parsing at a Gigabyte per Second", available online: 51 //! . 52 //! 53 //! # Other 54 //! 55 //! The conversion should *never* panic. There are assertions and explicit panics in the code, 56 //! but they should never be triggered and only serve as internal sanity checks. Any panics should 57 //! be considered a bug. 58 //! 59 //! There are unit tests but they are woefully inadequate at ensuring correctness, they only cover 60 //! a small percentage of possible errors. Far more extensive tests are located in the directory 61 //! `src/tools/test-float-parse` as a Rust program. 62 //! 63 //! A note on integer overflow: Many parts of this file perform arithmetic with the decimal 64 //! exponent `e`. Primarily, we shift the decimal point around: Before the first decimal digit, 65 //! after the last decimal digit, and so on. This could overflow if done carelessly. We rely on 66 //! the parsing submodule to only hand out sufficiently small exponents, where "sufficient" means 67 //! "such that the exponent +/- the number of decimal digits fits into a 64 bit integer". 68 //! Larger exponents are accepted, but we don't do arithmetic with them, they are immediately 69 //! turned into {positive,negative} {zero,infinity}. 70 //! 71 //! # Notation 72 //! 73 //! This module uses the same notation as the Lemire paper: 74 //! 75 //! - `m`: binary mantissa; always nonnegative 76 //! - `p`: binary exponent; a signed integer 77 //! - `w`: decimal significand; always nonnegative 78 //! - `q`: decimal exponent; a signed integer 79 //! 80 //! This gives `m * 2^p` for the binary floating-point number, with `w * 10^q` as the decimal 81 //! equivalent. 82 83 #![doc(hidden)] 84 #![unstable( 85 feature = "dec2flt", 86 reason = "internal routines only exposed for testing", 87 issue = "none" 88 )] 89 90 pub use common::BiasedFp; 91 use lemire::compute_float; 92 use parse::{parse_inf_nan, parse_number}; 93 use slow::parse_long_mantissa; 94 95 use crate::f64; 96 use crate::num::ParseFloatError; 97 use crate::num::float_parse::FloatErrorKind; 98 use crate::num::imp::FloatExt; 99 100 mod common; 101 pub mod decimal; 102 pub mod decimal_seq; 103 mod fpu; 104 pub mod lemire; 105 pub mod parse; 106 mod slow; 107 mod table; 108 109 /// Extension to `Float` that are necessary for parsing using the Lemire method. 110 /// 111 /// See the parent module's doc comment for why this is necessary. 112 /// 113 /// Not intended for use outside of the `dec2flt` module. 114 #[doc(hidden)] 115 pub trait Lemire: FloatExt { 116 /// Maximum exponent for a fast path case, or `⌊(SIG_BITS+1)/log2(5)⌋` 117 // assuming FLT_EVAL_METHOD = 0 118 const MAX_EXPONENT_FAST_PATH: i64; 119 120 /// Minimum exponent for a fast path case, or `-⌊(SIG_BITS+1)/log2(5)⌋` 121 const MIN_EXPONENT_FAST_PATH: i64 = -Self::MAX_EXPONENT_FAST_PATH; 122 123 /// Maximum exponent that can be represented for a disguised-fast path case. 124 /// This is `MAX_EXPONENT_FAST_PATH + ⌊(SIG_BITS+1)/log2(10)⌋` 125 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64; 126 127 /// Maximum mantissa for the fast-path (`1 << 53` for f64). 128 const MAX_MANTISSA_FAST_PATH: u64 = 1 << Self::SIG_TOTAL_BITS; 129 130 /// Gets a small power-of-ten for fast-path multiplication. 131 fn pow10_fast_path(exponent: usize) -> Self; 132 133 /// Converts integer into float through an as cast. 134 /// This is only called in the fast-path algorithm, and therefore 135 /// will not lose precision, since the value will always have 136 /// only if the value is <= Self::MAX_MANTISSA_FAST_PATH. 137 fn from_u64(v: u64) -> Self; 138 } 139 140 #[cfg(target_has_reliable_f16)] 141 // The f16 Lemire instance is outside the exclusively f64 scope. Disabling it 142 // leaves every retained f64 parser/helper/trace body, native decision, checked 143 // operation, debug assertion, return value, and scoped observation unchanged. 144 #[cfg(any())] 145 impl Lemire for f16 { 146 // These are the exact integer results of the upstream compile-time float 147 // formulae for `SIG_TOTAL_BITS = 11`: floor(11/log2(5)) = 4 and 148 // 4 + floor(11/log2(10)) = 7. Concrete integers avoid unsupported const 149 // float arithmetic without changing either fast-path guard. 150 const MAX_EXPONENT_FAST_PATH: i64 = 4; 151 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 7; 152 153 fn pow10_fast_path(exponent: usize) -> Self { 154 // Each integer is the exact IEEE encoding of the corresponding 155 // upstream table literal; the masked lookup and fallback zeros are 156 // unchanged. Aeneas cannot translate arrays containing float values. 157 match exponent & 7 { 158 0 => f16::from_bits(0x3C00), 159 1 => f16::from_bits(0x4900), 160 2 => f16::from_bits(0x5640), 161 3 => f16::from_bits(0x63D0), 162 4 => f16::from_bits(0x70E2), 163 _ => f16::from_bits(0), 164 } 165 } 166 167 #[inline] 168 // This method is exactly the upstream primitive `u64 as f16` conversion. 169 // Charon extracts the cast, but Aeneas reports it unreachable; making only 170 // this primitive boundary opaque preserves all guards and dispatcher logic. 171 #[charon::opaque] 172 fn from_u64(v: u64) -> Self { 173 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH); 174 v as _ 175 } 176 } 177 178 // The f32 Lemire instance is likewise unused by the retained f64 179 // specialization, so disabling it cannot affect any retained body or observed 180 // f64 execution independently of the correctness GOALs. 181 #[cfg(any())] 182 impl Lemire for f32 { 183 // Exact upstream formula results for `SIG_TOTAL_BITS = 24`. 184 const MAX_EXPONENT_FAST_PATH: i64 = 10; 185 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 17; 186 187 fn pow10_fast_path(exponent: usize) -> Self { 188 // Bit constructors preserve the exact table values and masked lookup, 189 // while avoiding Aeneas's unsupported float-valued array constants. 190 match exponent & 15 { 191 0 => f32::from_bits(0x3F80_0000), 192 1 => f32::from_bits(0x4120_0000), 193 2 => f32::from_bits(0x42C8_0000), 194 3 => f32::from_bits(0x447A_0000), 195 4 => f32::from_bits(0x461C_4000), 196 5 => f32::from_bits(0x47C3_5000), 197 6 => f32::from_bits(0x4974_2400), 198 7 => f32::from_bits(0x4B18_9680), 199 8 => f32::from_bits(0x4CBE_BC20), 200 9 => f32::from_bits(0x4E6E_6B28), 201 10 => f32::from_bits(0x5015_02F9), 202 _ => f32::from_bits(0), 203 } 204 } 205 206 #[inline] 207 // This is exactly the source `u64 as f32` conversion. The narrow opaque 208 // boundary is required because Aeneas rejects the primitive cast itself; 209 // its input guard and every caller remain transparent. 210 #[charon::opaque] 211 fn from_u64(v: u64) -> Self { 212 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH); 213 v as _ 214 } 215 } 216 217 impl Lemire for f64 { 218 // Exact upstream formula results for `SIG_TOTAL_BITS = 53`. 219 const MAX_EXPONENT_FAST_PATH: i64 = 22; 220 const MAX_EXPONENT_DISGUISED_FAST_PATH: i64 = 37; 221 222 fn pow10_fast_path(exponent: usize) -> Self { 223 // These bit patterns are exactly the source table's rounded binary64 224 // literals. The match is the same masked lookup; it merely keeps float 225 // constants out of Aeneas's unsupported constant interpreter. 226 match exponent & 31 { 227 0 => f64::from_bits(0x3FF0_0000_0000_0000), 228 1 => f64::from_bits(0x4024_0000_0000_0000), 229 2 => f64::from_bits(0x4059_0000_0000_0000), 230 3 => f64::from_bits(0x408F_4000_0000_0000), 231 4 => f64::from_bits(0x40C3_8800_0000_0000), 232 5 => f64::from_bits(0x40F8_6A00_0000_0000), 233 6 => f64::from_bits(0x412E_8480_0000_0000), 234 7 => f64::from_bits(0x4163_12D0_0000_0000), 235 8 => f64::from_bits(0x4197_D784_0000_0000), 236 9 => f64::from_bits(0x41CD_CD65_0000_0000), 237 10 => f64::from_bits(0x4202_A05F_2000_0000), 238 11 => f64::from_bits(0x4237_4876_E800_0000), 239 12 => f64::from_bits(0x426D_1A94_A200_0000), 240 13 => f64::from_bits(0x42A2_309C_E540_0000), 241 14 => f64::from_bits(0x42D6_BCC4_1E90_0000), 242 15 => f64::from_bits(0x430C_6BF5_2634_0000), 243 16 => f64::from_bits(0x4341_C379_37E0_8000), 244 17 => f64::from_bits(0x4376_3457_85D8_A000), 245 18 => f64::from_bits(0x43AB_C16D_674E_C800), 246 19 => f64::from_bits(0x43E1_58E4_6091_3D00), 247 20 => f64::from_bits(0x4415_AF1D_78B5_8C40), 248 21 => f64::from_bits(0x444B_1AE4_D6E2_EF50), 249 22 => f64::from_bits(0x4480_F0CF_064D_D592), 250 _ => f64::from_bits(0), 251 } 252 } 253 254 #[inline] 255 // Aeneas cannot translate the source `u64 as f64` primitive conversion, so 256 // `charon::opaque` makes this entire asserted conversion external: both the 257 // unchanged `debug_assert!` and the unchanged cast below are in the opaque 258 // body. The callers, their fast-path guards, and their surrounding 259 // computation remain mechanically visible. A corresponding model binding 260 // must fail the assertion above `MAX_MANTISSA_FAST_PATH` and return the 261 // exact binary64 conversion at or below that bound. 262 #[charon::opaque] 263 fn from_u64(v: u64) -> Self { 264 debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH); 265 v as _ 266 } 267 } 268 269 #[inline] 270 pub(super) fn pfe_empty() -> ParseFloatError { 271 ParseFloatError { kind: FloatErrorKind::Empty } 272 } 273 274 // Used in unit tests, keep public. 275 // This is much better than making FloatErrorKind and ParseFloatError::kind public. 276 #[inline] 277 pub fn pfe_invalid() -> ParseFloatError { 278 ParseFloatError { kind: FloatErrorKind::Invalid } 279 } 280 281 /// Converts a `BiasedFp` to the closest machine float type. 282 fn biased_fp_to_float(x: BiasedFp) -> F { 283 let mut word = x.m; 284 word |= (x.p_biased as u64) << F::SIG_BITS; 285 F::from_u64_bits(word) 286 } 287 288 /// Observable control-flow record for a dispatcher execution. 289 /// 290 /// These variants add no decisions to the conversion: each stores values 291 /// already computed at the corresponding source branch. In particular, the 292 /// first component returned by `dec2flt_with_trace` is the ordinary parser 293 /// result, so projecting it preserves every public source observation without 294 /// assuming any correctness goal. 295 pub enum Dec2FltTrace<'a, F> { 296 /// The original string was empty; no helper was called. 297 EmptyInput, 298 /// Removing one lexical sign left an empty body; no helper was called. 299 SignOnly { body: &'a [u8], negative: bool }, 300 /// Both lexical helpers returned `None`; no raw pair was selected. 301 Invalid { 302 body: &'a [u8], 303 negative: bool, 304 parse_number_result: Option, 305 parse_inf_nan_result: Option, 306 }, 307 /// The special helper supplied the directly returned value; no pair was selected. 308 Special { 309 body: &'a [u8], 310 negative: bool, 311 parse_number_result: Option, 312 parse_inf_nan_result: Option, 313 result: F, 314 }, 315 /// The ordinary native shortcut supplied the directly returned value. 316 FastPath { 317 body: &'a [u8], 318 negative: bool, 319 parse_number_result: Option, 320 fast_path_input: decimal::Decimal, 321 fast_path_result: Option, 322 result: F, 323 }, 324 /// The integer/slow path selected and assembled one raw pair. 325 Assembled(Dec2FltAssemblyTrace<'a, F>), 326 } 327 328 /// Full observation record for the dispatcher path that performs final assembly. 329 pub struct Dec2FltAssemblyTrace<'a, F> { 330 pub body: &'a [u8], 331 pub negative: bool, 332 pub parse_number_result: Option, 333 pub fast_path_input: decimal::Decimal, 334 pub fast_path_result: Option, 335 pub first_compute_exponent: i64, 336 pub first_compute_mantissa: u64, 337 pub first_compute_result: BiasedFp, 338 pub second_compute_guard: bool, 339 pub second_compute_exponent: Option, 340 pub second_compute_mantissa: Option, 341 pub second_compute_result: Option, 342 pub second_equals_first: Option, 343 pub forced_deferral: bool, 344 pub post_comparison_pair: BiasedFp, 345 pub slow_path_guard: bool, 346 pub slow_path_result: Option, 347 pub selected_pair: BiasedFp, 348 pub assembled_word: u64, 349 pub assembly_result: F, 350 pub lexical_sign_applied: bool, 351 pub result: F, 352 } 353 354 /// Run the actual dispatcher while retaining its goal-relevant internal observations. 355 pub fn dec2flt_with_trace< 356 'a, 357 F: Lemire 358 + core::ops::Div 359 + core::ops::Mul 360 + core::ops::Neg, 361 >( 362 s: &'a str, 363 ) -> (Result, Dec2FltTrace<'a, F>) { 364 let mut body = s.as_bytes(); 365 let Some(&c) = body.first() else { 366 return (Err(pfe_empty()), Dec2FltTrace::EmptyInput); 367 }; 368 let negative = c == b'-'; 369 if c == b'-' || c == b'+' { 370 body = &body[1..]; 371 } 372 if body.is_empty() { 373 return (Err(pfe_invalid()), Dec2FltTrace::SignOnly { body, negative }); 374 } 375 376 let parse_number_result = parse_number(body); 377 let parsed = match parse_number_result { 378 Some(r) => r, 379 None => { 380 let parse_inf_nan_result = parse_inf_nan(body, negative); 381 return match parse_inf_nan_result { 382 Some(value) => ( 383 Ok(value), 384 Dec2FltTrace::Special { 385 body, 386 negative, 387 parse_number_result, 388 parse_inf_nan_result, 389 result: value, 390 }, 391 ), 392 None => ( 393 Err(pfe_invalid()), 394 Dec2FltTrace::Invalid { 395 body, 396 negative, 397 parse_number_result, 398 parse_inf_nan_result, 399 }, 400 ), 401 }; 402 } 403 }; 404 405 let mut num = parsed; 406 num.negative = negative; 407 if !cfg!(feature = "optimize_for_size") { 408 let fast_path_result = num.try_fast_path::(); 409 if let Some(value) = fast_path_result { 410 return ( 411 Ok(value), 412 Dec2FltTrace::FastPath { 413 body, 414 negative, 415 parse_number_result, 416 fast_path_input: num, 417 fast_path_result, 418 result: value, 419 }, 420 ); 421 } 422 } 423 424 let first_compute_exponent = num.exponent; 425 let first_compute_mantissa = num.mantissa; 426 let first_compute_result = compute_float::(first_compute_exponent, first_compute_mantissa); 427 let mut fp = first_compute_result; 428 429 // This expands the source short-circuit conjunction without moving the 430 // checked `mantissa + 1`: that addition and the second helper call still 431 // occur exactly when `many_digits && fp.p_biased >= 0`. 432 let second_compute_guard = num.many_digits && fp.p_biased >= 0; 433 let mut second_compute_exponent = None; 434 let mut second_compute_mantissa = None; 435 let mut second_compute_result = None; 436 let mut second_equals_first = None; 437 let mut forced_deferral = false; 438 if second_compute_guard { 439 let exponent = num.exponent; 440 let mantissa = num.mantissa + 1; 441 let second = compute_float::(exponent, mantissa); 442 let equal = fp == second; 443 second_compute_exponent = Some(exponent); 444 second_compute_mantissa = Some(mantissa); 445 second_compute_result = Some(second); 446 second_equals_first = Some(equal); 447 if !equal { 448 fp.p_biased = -1; 449 forced_deferral = true; 450 } 451 } 452 let post_comparison_pair = fp; 453 454 let slow_path_guard = fp.p_biased < 0; 455 let mut slow_path_result = None; 456 if slow_path_guard { 457 // The exact slow-path input is the trace's common `body`; the guard 458 // records whether this call occurred, avoiding a duplicate live slice 459 // reference that Aeneas cannot join across this branch. 460 let replacement = parse_long_mantissa::(body); 461 slow_path_result = Some(replacement); 462 fp = replacement; 463 } 464 465 let selected_pair = fp; 466 // This is the same pure cast/shift/OR used by `biased_fp_to_float`; recording 467 // it neither changes the selected pair nor introduces a new branch or call. 468 let assembled_word = fp.m | ((fp.p_biased as u64) << F::SIG_BITS); 469 let assembly_result = biased_fp_to_float::(fp); 470 let lexical_sign_applied = num.negative; 471 let result = if lexical_sign_applied { 472 core::ops::Neg::neg(assembly_result) 473 } else { 474 assembly_result 475 }; 476 477 ( 478 Ok(result), 479 Dec2FltTrace::Assembled(Dec2FltAssemblyTrace { 480 body, 481 negative, 482 parse_number_result, 483 fast_path_input: num, 484 fast_path_result: None, 485 first_compute_exponent, 486 first_compute_mantissa, 487 first_compute_result, 488 second_compute_guard, 489 second_compute_exponent, 490 second_compute_mantissa, 491 second_compute_result, 492 second_equals_first, 493 forced_deferral, 494 post_comparison_pair, 495 slow_path_guard, 496 slow_path_result, 497 selected_pair, 498 assembled_word, 499 assembly_result, 500 lexical_sign_applied, 501 result, 502 }), 503 ) 504 } 505 506 /// Converts a decimal string into a floating point number. 507 #[inline(always)] // Will be inlined into a function with `#[inline(never)]`, see above 508 pub fn dec2flt< 509 F: Lemire 510 + core::ops::Div 511 + core::ops::Mul 512 + core::ops::Neg, 513 >( 514 s: &str, 515 ) -> Result { 516 // `Lemire` already implies `Neg` through `Float`; the direct 517 // clause admits exactly the same instances and lets Charon resolve the 518 // explicit, source-equivalent final negation. 519 // The public function is now exactly the result projection of the single 520 // instrumented implementation. No conversion step is duplicated, and 521 // discarding the trace cannot affect Rust evaluation or the returned bits. 522 dec2flt_with_trace::(s).0 523 } COMMAND: sed -n '1664,1770p' generated.lean /-- [dec2flt_model::num::imp::dec2flt::decimal_seq::final_decimal_point]: Source: 'num/imp/../../dec2flt/decimal_seq.rs', lines 269:0-285:1 -/ def num.imp.dec2flt.decimal_seq.final_decimal_point (significant_count : Std.Usize) (fractional_count : Std.Usize) (explicit : Std.I64) : Result Std.I32 := do if significant_count = 0#usize then ok 0#i32 else let i ← lift (UScalar.hcast .I64 significant_count) let i1 ← lift (UScalar.hcast .I64 fractional_count) let base ← i - i1 let i2 ← lift (core.num.I64.saturating_add base explicit) let i3 ← lift (IScalar.cast .I64 num.imp.dec2flt.decimal_seq.DecimalSeq.DECIMAL_POINT_RANGE) let i4 ← -. i3 let i5 ← lift (IScalar.cast .I64 num.imp.dec2flt.decimal_seq.DecimalSeq.DECIMAL_POINT_RANGE) let i6 ← core.cmp.impls.OrdI64.clamp i2 i4 i5 ok (IScalar.cast .I32 i6) /-- [dec2flt_model::num::imp::dec2flt::parse::parse_scientific]: loop body 0: Source: 'num/imp/../../dec2flt/parse.rs', lines 145:8-151:9 -/ @[rust_loop_body] def num.imp.dec2flt.parse.parse_scientific_loop.body (s : Slice Std.U8) (exponent : Std.I64) (count : Std.Usize) : Result (ControlFlow (Std.I64 × Std.Usize) (Std.I64 × Std.Usize)) := do let i := Slice.len s if count < i then let i1 ← Slice.index_usize s count let i2 ← lift (core.num.U8.wrapping_sub i1 48#u8) if i2 < 10#u8 then let digit ← lift (core.num.U8.wrapping_sub i1 48#u8) let i3 ← 1#i64 <<< 59#i32 let exponent1 ← if exponent < i3 then do let i4 ← 10#i64 * exponent let i5 ← lift (UScalar.hcast .I64 digit) i4 + i5 else ok exponent let count1 ← count + 1#usize ok (cont (exponent1, count1)) else ok (done (exponent, count)) else ok (done (exponent, count)) /-- [dec2flt_model::num::imp::dec2flt::parse::parse_scientific]: loop 0: Source: 'num/imp/../../dec2flt/parse.rs', lines 145:8-151:9 -/ @[rust_loop] def num.imp.dec2flt.parse.parse_scientific_loop (exponent : Std.I64) (s : Slice Std.U8) (count : Std.Usize) : Result (Std.I64 × Std.Usize) := do loop (fun (exponent1, count1) => num.imp.dec2flt.parse.parse_scientific_loop.body s exponent1 count1) (exponent, count) /-- [dec2flt_model::num::imp::dec2flt::parse::parse_scientific]: Source: 'num/imp/../../dec2flt/parse.rs', lines 121:0-158:1 -/ def num.imp.dec2flt.parse.parse_scientific (s_ref : Slice Std.U8) : Result ((Option Std.I64) × (Slice Std.U8)) := do let o ← core.slice.Slice.split_first s_ref let (negative, s) ← match o with | none => ok (false, s_ref) | some p => do let (c, s_next) := p let s1 ← if c = 45#u8 then ok s_next else if c = 43#u8 then ok s_next else ok s_ref ok (c = 45#u8, s1) let b ← core.slice.Slice.is_empty s if b then ok (none, s) else let i ← Slice.index_usize s 0#usize let b1 ← core.num.U8.is_ascii_digit i if b1 then let (exponent, count) ← num.imp.dec2flt.parse.parse_scientific_loop 0#i64 s 0#usize let s_ref1 ← core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s { start := count } if negative then let i1 ← -. exponent ok (some i1, s_ref1) else ok (some exponent, s_ref1) else ok (none, s) /-- [dec2flt_model::num::imp::dec2flt::decimal_seq::parse_decimal_seq]: loop body 0: Source: 'num/imp/../../dec2flt/decimal_seq.rs', lines 296:4-298:5 Visibility: public -/ HISTORICAL PREDECESSOR RECORDS BELOW, NOT CURRENT-SOURCE SUPPORT Dispatcher contract and trace evidence Files inspected (SHA-256 from sha256sum 9.1): upstream/dec2flt/mod.rs 7198e238c554b692405537a446b3526ad66805ec2900cd0e299f10c51402a44a crate/dec2flt/mod.rs ecadc1d7df05dfda85fcf99fc45da7e40cb36aa9736d12d1b3a75f60f532907d upstream/dec2flt/parse.rs 9daf21ab9445a84552535152f376eef8c30f3d5827296c0645f5952d3b22bbf1 crate/dec2flt/parse.rs 50d95265e5b1af43ee4f0033c9ff8d1b8dfd62d766ab14668ceec19955adba1f Tablet/num_imp_dec2flt_dec2flt_with_trace.lean fc6b6d0c31c801820e9e1981a1a777701b6a70dac0892b22ace44edbca4eeeb7 Tablet/num_imp_dec2flt_Dec2FltAssemblyTrace.lean e1021975d4efe22771953025dd5145bc3f1305f2046a4cf20790ff9ff633c520 Reproduction commands: sha256sum upstream/dec2flt/mod.rs crate/dec2flt/mod.rs \ upstream/dec2flt/parse.rs crate/dec2flt/parse.rs \ Tablet/num_imp_dec2flt_dec2flt_with_trace.lean \ Tablet/num_imp_dec2flt_Dec2FltAssemblyTrace.lean nl -ba upstream/dec2flt/mod.rs | sed -n '209,255p' nl -ba crate/dec2flt/mod.rs | sed -n '354,523p' nl -ba upstream/dec2flt/parse.rs | sed -n '198,242p' nl -ba crate/dec2flt/parse.rs | sed -n '240,284p' nl -ba Tablet/num_imp_dec2flt_dec2flt_with_trace.lean | sed -n '36,194p' nl -ba Tablet/num_imp_dec2flt_Dec2FltAssemblyTrace.lean | sed -n '31,52p' Raw source observations: upstream lines 212-225 convert the string to bytes, strip at most one leading sign, reject an empty body, call parse_number first, and call parse_inf_nan only after parse_number returns None. upstream lines 227-232 overwrite Decimal.negative with the lexical sign and return a Some result from try_fast_path directly. upstream lines 238-249 call compute_float(exponent, mantissa), call compute_float(exponent, mantissa + 1) exactly when many_digits and the first biased exponent is nonnegative, set that exponent to -1 on disagreement, and replace every negative-exponent current pair with parse_long_mantissa(body). upstream lines 251-255 assemble the selected pair, negate only after assembly when Decimal.negative is true, and return the resulting float. upstream parse.rs lines 199-241 show the special helper's length branches, register construction and masking, keyword match, and final sign branch. They locate the helper body called by the dispatcher; this excerpt alone is not used to establish a DispatchContracts semantic law. Raw adapted-source observations: crate lines 354-504 are the traced dispatcher. Its sign/body and lexical branches are lines 364-403; the native call and direct return are lines 405-421; and integer calls, comparison/deferral, slow fallback, assembly, final sign, and trace construction are lines 424-503. These lines record branch order, call boundaries, and already-computed observations; they do not establish the semantic contracts of the called helpers. crate lines 506-523 define the public dispatcher as the first projection of the one traced implementation, with the projection call at line 522. crate parse.rs lines 241-283 retain that special-parser control structure: the same length split, case mask, three constants and matches, rejection branch, selected branch value, and final sign branch appear at lines 249-283. Concrete satisfaction of the abstract special-parser laws is not inferred from this syntactic comparison. Raw extracted-model observations: num_imp_dec2flt_dec2flt_with_trace.lean lines 36-77 retain the sign-removal, empty/sign-only, parse_number, parse_inf_nan, invalid, and special branches. Lines 78-115 retain the native call, first integer call, exact second-call guard, checked U64 addition, second call, equality comparison, and exponent -1 update. Lines 116-194 retain the slow replacement, Rust cast/shift/OR assembled word, biased_fp_to_float call, optional negation, and every trace field in both sign branches. num_imp_dec2flt_Dec2FltAssemblyTrace.lean lines 31-52 list, in order, the body and sign; parsed and fast-path values; first and second integer values; comparison and deferral values; post-comparison, slow, and selected pairs; and assembly, sign, and final-result values used by the paired contracts. Scope of this evidence: The excerpts below support only branch order, helper call boundaries, the observations recorded by the trace, and the fact that public dec2flt projects the result of the single traced computation. Seeing a helper call or its source body is not evidence that the extracted helper returns normally or satisfies a DispatchContracts semantic law. Those facts belong to the separate dispatch_component_compliance obligation. Captured excerpts (command output, with trailing whitespace removed): --- upstream/dec2flt/mod.rs lines 209-255 --- $ nl -ba upstream/dec2flt/mod.rs | sed -n '209,255p' 209 /// Converts a decimal string into a floating point number. 210 #[inline(always)] // Will be inlined into a function with `#[inline(never)]`, see above 211 pub fn dec2flt(s: &str) -> Result { 212 let mut s = s.as_bytes(); 213 let Some(&c) = s.first() else { return Err(pfe_empty()) }; 214 let negative = c == b'-'; 215 if c == b'-' || c == b'+' { 216 s = &s[1..]; 217 } 218 if s.is_empty() { 219 return Err(pfe_invalid()); 220 } 221 222 let mut num = match parse_number(s) { 223 Some(r) => r, 224 None if let Some(value) = parse_inf_nan(s, negative) => return Ok(value), 225 None => return Err(pfe_invalid()), 226 }; 227 num.negative = negative; 228 if !cfg!(feature = "optimize_for_size") { 229 if let Some(value) = num.try_fast_path::() { 230 return Ok(value); 231 } 232 } 233 234 // If significant digits were truncated, then we can have rounding error 235 // only if `mantissa + 1` produces a different result. We also avoid 236 // redundantly using the Eisel-Lemire algorithm if it was unable to 237 // correctly round on the first pass. 238 let mut fp = compute_float::(num.exponent, num.mantissa); 239 if num.many_digits 240 && fp.p_biased >= 0 241 && fp != compute_float::(num.exponent, num.mantissa + 1) 242 { 243 fp.p_biased = -1; 244 } 245 // Unable to correctly round the float using the Eisel-Lemire algorithm. 246 // Fallback to a slower, but always correct algorithm. 247 if fp.p_biased < 0 { 248 fp = parse_long_mantissa::(s); 249 } 250 251 let mut float = biased_fp_to_float::(fp); 252 if num.negative { 253 float = -float; 254 } 255 Ok(float) --- crate/dec2flt/mod.rs lines 354-523 --- $ nl -ba crate/dec2flt/mod.rs | sed -n '354,523p' 354 /// Run the actual dispatcher while retaining its approved internal observations. 355 pub fn dec2flt_with_trace< 356 'a, 357 F: Lemire 358 + core::ops::Div 359 + core::ops::Mul 360 + core::ops::Neg, 361 >( 362 s: &'a str, 363 ) -> (Result, Dec2FltTrace<'a, F>) { 364 let mut body = s.as_bytes(); 365 let Some(&c) = body.first() else { 366 return (Err(pfe_empty()), Dec2FltTrace::EmptyInput); 367 }; 368 let negative = c == b'-'; 369 if c == b'-' || c == b'+' { 370 body = &body[1..]; 371 } 372 if body.is_empty() { 373 return (Err(pfe_invalid()), Dec2FltTrace::SignOnly { body, negative }); 374 } 375 376 let parse_number_result = parse_number(body); 377 let parsed = match parse_number_result { 378 Some(r) => r, 379 None => { 380 let parse_inf_nan_result = parse_inf_nan(body, negative); 381 return match parse_inf_nan_result { 382 Some(value) => ( 383 Ok(value), 384 Dec2FltTrace::Special { 385 body, 386 negative, 387 parse_number_result, 388 parse_inf_nan_result, 389 result: value, 390 }, 391 ), 392 None => ( 393 Err(pfe_invalid()), 394 Dec2FltTrace::Invalid { 395 body, 396 negative, 397 parse_number_result, 398 parse_inf_nan_result, 399 }, 400 ), 401 }; 402 } 403 }; 404 405 let mut num = parsed; 406 num.negative = negative; 407 if !cfg!(feature = "optimize_for_size") { 408 let fast_path_result = num.try_fast_path::(); 409 if let Some(value) = fast_path_result { 410 return ( 411 Ok(value), 412 Dec2FltTrace::FastPath { 413 body, 414 negative, 415 parse_number_result, 416 fast_path_input: num, 417 fast_path_result, 418 result: value, 419 }, 420 ); 421 } 422 } 423 424 let first_compute_exponent = num.exponent; 425 let first_compute_mantissa = num.mantissa; 426 let first_compute_result = compute_float::(first_compute_exponent, first_compute_mantissa); 427 let mut fp = first_compute_result; 428 429 // This expands the source short-circuit conjunction without moving the 430 // checked `mantissa + 1`: that addition and the second helper call still 431 // occur exactly when `many_digits && fp.p_biased >= 0`. 432 let second_compute_guard = num.many_digits && fp.p_biased >= 0; 433 let mut second_compute_exponent = None; 434 let mut second_compute_mantissa = None; 435 let mut second_compute_result = None; 436 let mut second_equals_first = None; 437 let mut forced_deferral = false; 438 if second_compute_guard { 439 let exponent = num.exponent; 440 let mantissa = num.mantissa + 1; 441 let second = compute_float::(exponent, mantissa); 442 let equal = fp == second; 443 second_compute_exponent = Some(exponent); 444 second_compute_mantissa = Some(mantissa); 445 second_compute_result = Some(second); 446 second_equals_first = Some(equal); 447 if !equal { 448 fp.p_biased = -1; 449 forced_deferral = true; 450 } 451 } 452 let post_comparison_pair = fp; 453 454 let slow_path_guard = fp.p_biased < 0; 455 let mut slow_path_result = None; 456 if slow_path_guard { 457 // The exact slow-path input is the trace's common `body`; the guard 458 // records whether this call occurred, avoiding a duplicate live slice 459 // reference that Aeneas cannot join across this branch. 460 let replacement = parse_long_mantissa::(body); 461 slow_path_result = Some(replacement); 462 fp = replacement; 463 } 464 465 let selected_pair = fp; 466 // This is the same pure cast/shift/OR used by `biased_fp_to_float`; recording 467 // it neither changes the selected pair nor introduces a new branch or call. 468 let assembled_word = fp.m | ((fp.p_biased as u64) << F::SIG_BITS); 469 let assembly_result = biased_fp_to_float::(fp); 470 let lexical_sign_applied = num.negative; 471 let result = if lexical_sign_applied { 472 core::ops::Neg::neg(assembly_result) 473 } else { 474 assembly_result 475 }; 476 477 ( 478 Ok(result), 479 Dec2FltTrace::Assembled(Dec2FltAssemblyTrace { 480 body, 481 negative, 482 parse_number_result, 483 fast_path_input: num, 484 fast_path_result: None, 485 first_compute_exponent, 486 first_compute_mantissa, 487 first_compute_result, 488 second_compute_guard, 489 second_compute_exponent, 490 second_compute_mantissa, 491 second_compute_result, 492 second_equals_first, 493 forced_deferral, 494 post_comparison_pair, 495 slow_path_guard, 496 slow_path_result, 497 selected_pair, 498 assembled_word, 499 assembly_result, 500 lexical_sign_applied, 501 result, 502 }), 503 ) 504 } 505 506 /// Converts a decimal string into a floating point number. 507 #[inline(always)] // Will be inlined into a function with `#[inline(never)]`, see above 508 pub fn dec2flt< 509 F: Lemire 510 + core::ops::Div 511 + core::ops::Mul 512 + core::ops::Neg, 513 >( 514 s: &str, 515 ) -> Result { 516 // `Lemire` already implies `Neg` through `Float`; the direct 517 // clause admits exactly the same instances and lets Charon resolve the 518 // explicit, source-equivalent final negation. 519 // The public function is now exactly the result projection of the single 520 // instrumented implementation. No conversion step is duplicated, and 521 // discarding the trace cannot affect Rust evaluation or the returned bits. 522 dec2flt_with_trace::(s).0 523 } --- upstream/dec2flt/parse.rs lines 198-242 --- $ nl -ba upstream/dec2flt/parse.rs | sed -n '198,242p' 198 /// Try to parse a special, non-finite float. 199 pub(crate) fn parse_inf_nan(s: &[u8], negative: bool) -> Option { 200 // Since a valid string has at most the length 8, we can load 201 // all relevant characters into a u64 and work from there. 202 // This also generates much better code. 203 204 let mut register; 205 let len: usize; 206 207 // All valid strings are either of length 8 or 3. 208 if s.len() == 8 { 209 register = s.read_u64(); 210 len = 8; 211 } else if s.len() == 3 { 212 let a = s[0] as u64; 213 let b = s[1] as u64; 214 let c = s[2] as u64; 215 register = (c << 16) | (b << 8) | a; 216 len = 3; 217 } else { 218 return None; 219 } 220 221 // Clear out the bits which turn ASCII uppercase characters into 222 // lowercase characters. The resulting string is all uppercase. 223 // What happens to other characters is irrelevant. 224 register &= 0xDFDFDFDFDFDFDFDF; 225 226 // u64 values corresponding to relevant cases 227 const INF_3: u64 = 0x464E49; // "INF" 228 const INF_8: u64 = 0x5954494E49464E49; // "INFINITY" 229 const NAN: u64 = 0x4E414E; // "NAN" 230 231 // Match register value to constant to parse string. 232 // Also match on the string length to catch edge cases 233 // like "inf\0\0\0\0\0". 234 let float = match (register, len) { 235 (INF_3, 3) => F::INFINITY, 236 (INF_8, 8) => F::INFINITY, 237 (NAN, 3) => F::NAN, 238 _ => return None, 239 }; 240 241 if negative { Some(-float) } else { Some(float) } 242 } --- crate/dec2flt/parse.rs lines 240-284 --- $ nl -ba crate/dec2flt/parse.rs | sed -n '240,284p' 240 /// Try to parse a special, non-finite float. 241 pub(crate) fn parse_inf_nan(s: &[u8], negative: bool) -> Option { 242 // Since a valid string has at most the length 8, we can load 243 // all relevant characters into a u64 and work from there. 244 // This also generates much better code. 245 246 let mut register; 247 let len: usize; 248 249 // All valid strings are either of length 8 or 3. 250 if s.len() == 8 { 251 register = s.read_u64(); 252 len = 8; 253 } else if s.len() == 3 { 254 let a = s[0] as u64; 255 let b = s[1] as u64; 256 let c = s[2] as u64; 257 register = (c << 16) | (b << 8) | a; 258 len = 3; 259 } else { 260 return None; 261 } 262 263 // Clear out the bits which turn ASCII uppercase characters into 264 // lowercase characters. The resulting string is all uppercase. 265 // What happens to other characters is irrelevant. 266 register &= 0xDFDFDFDFDFDFDFDF; 267 268 // u64 values corresponding to relevant cases 269 const INF_3: u64 = 0x464E49; // "INF" 270 const INF_8: u64 = 0x5954494E49464E49; // "INFINITY" 271 const NAN: u64 = 0x4E414E; // "NAN" 272 273 // Match register value to constant to parse string. 274 // Also match on the string length to catch edge cases 275 // like "inf\0\0\0\0\0". 276 let float = match (register, len) { 277 (INF_3, 3) => F::INFINITY, 278 (INF_8, 8) => F::INFINITY, 279 (NAN, 3) => F::NAN, 280 _ => return None, 281 }; 282 283 if negative { Some(-float) } else { Some(float) } 284 } --- Tablet/num_imp_dec2flt_dec2flt_with_trace.lean lines 36-194 --- $ nl -ba Tablet/num_imp_dec2flt_dec2flt_with_trace.lean | sed -n '36,194p' 36 do 37 let body ← core.str.Str.as_bytes s 38 let o ← core.slice.Slice.first body 39 match o with 40 | none => 41 let pfe ← num.imp.dec2flt.pfe_empty 42 ok (core.result.Result.Err pfe, num.imp.dec2flt.Dec2FltTrace.EmptyInput) 43 | some c => 44 let body1 ← 45 if c = 45#u8 46 then 47 core.slice.index.Slice.index 48 (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) body 49 { start := 1#usize } 50 else 51 if c = 43#u8 52 then 53 core.slice.index.Slice.index 54 (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) body 55 { start := 1#usize } 56 else ok body 57 let b ← core.slice.Slice.is_empty body1 58 if b 59 then 60 let pfe ← num.imp.dec2flt.pfe_invalid 61 ok (core.result.Result.Err pfe, num.imp.dec2flt.Dec2FltTrace.SignOnly 62 body1 (c = 45#u8)) 63 else 64 let parse_number_result ← num.imp.dec2flt.parse.parse_number body1 65 match parse_number_result with 66 | none => 67 let parse_inf_nan_result ← 68 num.imp.dec2flt.parse.parse_inf_nan 69 LemireInst.traitsFloatExtInst.FloatInst body1 (c = 45#u8) 70 match parse_inf_nan_result with 71 | none => 72 let pfe ← num.imp.dec2flt.pfe_invalid 73 ok (core.result.Result.Err pfe, num.imp.dec2flt.Dec2FltTrace.Invalid 74 body1 (c = 45#u8) none none) 75 | some value => 76 ok (core.result.Result.Ok value, num.imp.dec2flt.Dec2FltTrace.Special 77 body1 (c = 45#u8) none parse_inf_nan_result value) 78 | some r => 79 let fast_path_result ← 80 num.imp.dec2flt.decimal.Decimal.try_fast_path LemireInst 81 coreopsarithDivInst coreopsarithMulInst coreopsarithNegInst 82 { r with negative := (c = 45#u8) } 83 match fast_path_result with 84 | none => 85 let first_compute_result ← 86 num.imp.dec2flt.lemire.compute_float 87 LemireInst.traitsFloatExtInst.FloatInst r.exponent r.mantissa 88 let (b1, b2, first_compute_result1, fp, second_compute_guard) ← 89 if r.many_digits 90 then 91 ok (true, true, first_compute_result, first_compute_result, 92 first_compute_result.p_biased >= 0#i32) 93 else 94 ok (false, false, first_compute_result, first_compute_result, 95 false) 96 let (post_comparison_pair, second_compute_exponent, 97 second_compute_mantissa, second_compute_result, 98 second_equals_first, forced_deferral) ← 99 if second_compute_guard 100 then 101 do 102 let mantissa ← r.mantissa + 1#u64 103 let second ← 104 num.imp.dec2flt.lemire.compute_float 105 LemireInst.traitsFloatExtInst.FloatInst r.exponent mantissa 106 let equal ← 107 num.imp.dec2flt.common.BiasedFp.Insts.CoreCmpPartialEqBiasedFp.eq 108 fp second 109 let (bf, b3) ← 110 if equal 111 then ok (fp, false) 112 else ok ({ fp with p_biased := (-1)#i32 }, true) 113 ok (bf, some r.exponent, some mantissa, some second, some equal, 114 b3) 115 else ok (fp, none, none, none, none, false) 116 let (selected_pair, slow_path_guard, slow_path_result) ← 117 if post_comparison_pair.p_biased < 0#i32 118 then 119 do 120 let replacement ← 121 num.imp.dec2flt.slow.parse_long_mantissa 122 LemireInst.traitsFloatExtInst.FloatInst body1 123 ok (replacement, true, some replacement) 124 else ok (post_comparison_pair, false, none) 125 let i ← lift (IScalar.hcast .U64 selected_pair.p_biased) 126 let i1 ← LemireInst.traitsFloatExtInst.FloatInst.SIG_BITS 127 let i2 ← i <<< i1 128 let assembled_word ← lift (selected_pair.m ||| i2) 129 let assembly_result ← 130 num.imp.dec2flt.biased_fp_to_float LemireInst.traitsFloatExtInst 131 selected_pair 132 if c = 45#u8 133 then 134 let result ← coreopsarithNegInst.neg assembly_result 135 ok (core.result.Result.Ok result, 136 num.imp.dec2flt.Dec2FltTrace.Assembled 137 { 138 body := body1, 139 negative := true, 140 parse_number_result := (some { r with many_digits := b1 }), 141 fast_path_input := 142 { r with negative := true, many_digits := b2 }, 143 fast_path_result := none, 144 first_compute_exponent := r.exponent, 145 first_compute_mantissa := r.mantissa, 146 first_compute_result := first_compute_result1, 147 second_compute_guard, 148 second_compute_exponent, 149 second_compute_mantissa, 150 second_compute_result, 151 second_equals_first, 152 forced_deferral, 153 post_comparison_pair, 154 slow_path_guard, 155 slow_path_result, 156 selected_pair, 157 assembled_word, 158 assembly_result, 159 lexical_sign_applied := true, 160 result 161 }) 162 else 163 ok (core.result.Result.Ok assembly_result, 164 num.imp.dec2flt.Dec2FltTrace.Assembled 165 { 166 body := body1, 167 negative := false, 168 parse_number_result := (some { r with many_digits := b1 }), 169 fast_path_input := 170 { r with negative := false, many_digits := b2 }, 171 fast_path_result := none, 172 first_compute_exponent := r.exponent, 173 first_compute_mantissa := r.mantissa, 174 first_compute_result := first_compute_result1, 175 second_compute_guard, 176 second_compute_exponent, 177 second_compute_mantissa, 178 second_compute_result, 179 second_equals_first, 180 forced_deferral, 181 post_comparison_pair, 182 slow_path_guard, 183 slow_path_result, 184 selected_pair, 185 assembled_word, 186 assembly_result, 187 lexical_sign_applied := false, 188 result := assembly_result 189 }) 190 | some value => 191 ok (core.result.Result.Ok value, 192 num.imp.dec2flt.Dec2FltTrace.FastPath body1 (c = 45#u8) 193 parse_number_result { r with negative := (c = 45#u8) } 194 fast_path_result value) --- Tablet/num_imp_dec2flt_Dec2FltAssemblyTrace.lean lines 31-52 --- $ nl -ba Tablet/num_imp_dec2flt_Dec2FltAssemblyTrace.lean | sed -n '31,52p' 31 body : Slice Std.U8 32 negative : Bool 33 parse_number_result : Option num.imp.dec2flt.decimal.Decimal 34 fast_path_input : num.imp.dec2flt.decimal.Decimal 35 fast_path_result : Option F 36 first_compute_exponent : Std.I64 37 first_compute_mantissa : Std.U64 38 first_compute_result : num.imp.dec2flt.common.BiasedFp 39 second_compute_guard : Bool 40 second_compute_exponent : Option Std.I64 41 second_compute_mantissa : Option Std.U64 42 second_compute_result : Option num.imp.dec2flt.common.BiasedFp 43 second_equals_first : Option Bool 44 forced_deferral : Bool 45 post_comparison_pair : num.imp.dec2flt.common.BiasedFp 46 slow_path_guard : Bool 47 slow_path_result : Option num.imp.dec2flt.common.BiasedFp 48 selected_pair : num.imp.dec2flt.common.BiasedFp 49 assembled_word : Std.U64 50 assembly_result : F 51 lexical_sign_applied : Bool 52 result : F HISTORICAL PREDECESSOR TABLET EVIDENCE (not current-source support) Request-9 recovery archives the following obsolete or redundant nodes. Their predecessor extraction identity is 45b5027c42f9bb25bf22d3573fdb0f93784cf93d2a7b92ef1a7687c8f66c25a9. The current extraction is 438af8398703b81aa311d7885dfb34f1909125bee48b096dacc93baefcc4bcf9. The old 65545-byte parser counterexample claimed 1.0 under the old cutoff; the current source uses 2^59 and that input's target is positive infinity. The old 2^31-all-ones slow witness used an I32 wrap that the current source has removed. Current saved-count arithmetic clips its positive point to 2047. Giant-count mathematical certificates are not executions of allocated inputs. The old empty-contract proof concerns the archived, unbounded contracts only. No archived statement supplies a current GOAL claim or primitive binding. ===== HISTORICAL Tablet/DecimalSeqExponentEval.lean ===== import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: DecimalSeqExponentEval] def DecimalSeqExponentEval (s : Slice Std.U8) (base : Std.I32) : Result Std.I32 := -- BODY do let empty <- core.slice.Slice.is_empty s if empty then ok base else let ch <- Slice.index_usize s 0#usize if ch = 101#u8 then let s3 <- core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s { start := 1#usize } let b2 <- core.slice.Slice.is_empty s3 let (s4, exp_sign) <- if b2 then ok (s3, 1#i32) else do let ch1 <- Slice.index_usize s3 0#usize let exp_sign1 <- if ch1 = 45#u8 then ok (-1)#i32 else ok 1#i32 let s5 <- if ch1 = 45#u8 then core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s3 { start := 1#usize } else if ch1 = 43#u8 then core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s3 { start := 1#usize } else ok s3 ok (s5, exp_sign1) let exp_num <- num.imp.dec2flt.decimal_seq.parse_decimal_exponent s4 let signed <- exp_sign * exp_num base + signed else if ch = 69#u8 then let s3 <- core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s { start := 1#usize } let b2 <- core.slice.Slice.is_empty s3 let (s4, exp_sign) <- if b2 then ok (s3, 1#i32) else do let ch1 <- Slice.index_usize s3 0#usize let exp_sign1 <- if ch1 = 45#u8 then ok (-1)#i32 else ok 1#i32 let s5 <- if ch1 = 45#u8 then core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s3 { start := 1#usize } else if ch1 = 43#u8 then core.slice.index.Slice.index (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8) s3 { start := 1#usize } else ok s3 ok (s5, exp_sign1) let exp_num <- num.imp.dec2flt.decimal_seq.parse_decimal_exponent s4 let signed <- exp_sign * exp_num base + signed else ok base end dec2flt_model ===== HISTORICAL Tablet/DecimalSeqExponentEval.tex ===== \begin{definition}[Optional decimal exponent evaluation] For a residual byte slice $s$ and an I32 base value, define \texttt{DecimalSeqExponentEval} to be the extracted parser's optional exponent computation: return the base on an empty residual; otherwise inspect an uppercase or lowercase exponent marker, consume an optional sign, fold the remaining decimal exponent digits, apply the sign, and add the signed exponent to the base. A non-exponent marker leaves the base unchanged. \end{definition} \begin{preservation} \begin{claim} For every residual byte slice $r$ and every I32 base $p$, \texttt{DecimalSeqExponentEval}$(r,p)$ is exactly, as a monadic \texttt{Result} computation, the optional-exponent fragment repeated in the pinned \texttt{parse_decimal_seq} declaration. Thus it returns $p$ when $r$ is empty or its first byte is neither \texttt{e} nor \texttt{E}; after either marker it removes an optional \texttt{-} or \texttt{+}, invokes the pinned decimal-exponent parser on the resulting suffix, multiplies by the corresponding I32 sign, and adds the result to $p$. Equality includes both the normal I32 result and failure at the same checked operation. This is also the behavior of the optional-exponent source fragment at \texttt{crate/dec2flt/decimal_seq.rs:336--358} and of the corresponding original fragment after the recorded source adaptation. \end{claim} \begin{proof} Expand \texttt{DecimalSeqExponentEval} and compare it with the repeated optional-exponent fragments in the pinned \texttt{parse_decimal_seq} declaration \noderef{num_imp_dec2flt_decimal_seq_parse_decimal_seq}. Both computations first call \texttt{Slice.is_empty}. If $r$ is empty, both immediately return \texttt{ok} $p$, so neither performs an index, a slice, exponent parsing, or arithmetic. If $r$ is nonempty, both index position zero. The preceding nonemptiness branch is exactly the bounds justification for that index; any modeled failure of the bind is propagated before the byte tests in both computations. For a first byte other than decimal 101 and 69, the nested tests reach \texttt{ok} $p$. For decimal 101 (ASCII \texttt{e}), each computation takes the suffix from index one; for decimal 69 (ASCII \texttt{E}), it takes a second, textually duplicated branch with the same operations. In either case the marker branch itself just established that $r$ is nonempty, so the range-from-one slice has a valid boundary. A failure of that slice operation is nevertheless the same next monadic failure on each side. Write $t$ for the post-marker suffix. Both computations test whether $t$ is empty. If it is, they pass the pair $(t,1)$ onward without indexing it. If it is not, they index its first byte under that guard. A minus byte (decimal 45) selects sign $-1$ and slices from one; a plus byte (decimal 43) selects sign $1$ and slices from one; every other byte selects sign $1$ and leaves $t$ unchanged. Consequently the exponent-digit suffix and sign agree in the empty, minus, plus, and no-sign cases. The two guarded range slices have the same bound and the same failure propagation as their inline counterparts. Both sides next call the pinned \texttt{parse_decimal_exponent} declaration on exactly that suffix \noderef{num_imp_dec2flt_decimal_seq_parse_decimal_exponent}. Its result is bound before further arithmetic, so its failure is returned unchanged. On a normal result $e$, both sides perform the same checked I32 multiplication of the selected sign by $e$ and then the same checked I32 addition to $p$; a failure of either operation is therefore returned at the same point, while two successful operations yield the same $p+(\mathord{\pm}e)$. Finally, the source/adaptation comparison \evidenceref{reference/model-evidence/source-adaptation-delta.txt} checks the source split-first and digit-fold fragment against the adapted guarded indexing and slicing. It records that \texttt{parse_decimal_exponent} has the same digit order, wrapping ASCII classification, and $\mathtt{0x10000}$ update guard as the original closure. That guard bounds the accumulated nonnegative exponent, so multiplication by $-1$ is defined and equals the source's negative branch; multiplication by $1$ equals its positive branch. The evidence also records that the final checked decimal-point addition remains in the same position. Hence the pinned fragment, this factoring, the adapted source, and the original source have identical normal and modeled-failure behavior for every $r$ and $p$. \end{proof} \begin{goalproof}{parser_totality}This definition is only a name for the existing optional-exponent \texttt{Result} fragment, on every residual and base and with identical failures. Replacing the inline fragment by this name adds no domain premise and changes no normal-or-panic observation relevant to totality.\end{goalproof} \begin{goalproof}{parser_numeric_acceptance}On the numeric path, the same \texttt{e}/\texttt{E}, sign, exponent-fold, and checked-add branches are executed. The factoring neither strengthens numeric grammar nor assumes acceptance, so it preserves whatever \texttt{dec2flt} returns for each numeric literal.\end{goalproof} \begin{goalproof}{parser_invalid_rejection}Empty, non-exponent, signed-exponent, and exponent-parser failure cases are all preserved exactly. Thus this modeling name neither consumes an extra invalid byte nor turns a failure into success, and it adds no premise to the invalid-input claim.\end{goalproof} \begin{goalproof}{parser_nan_acceptance}NaN inputs are handled by the special-literal branch before decimal-sequence parsing. Naming this numeric slow-path fragment leaves that branch, its returned word, and its domain unchanged.\end{goalproof} \begin{goalproof}{parser_infinity}Infinity inputs likewise use the special helper rather than the decimal-sequence exponent fragment. The definition therefore does not alter either lexical sign or the returned infinity.\end{goalproof} \begin{goalproof}{parser_non_nan_results}For a numeric execution that reaches the slow path, the decimal point and every failure are unchanged; for a special execution, this definition is not invoked. Hence it introduces no new source of a NaN and assumes no no-NaN conclusion.\end{goalproof} \begin{goalproof}{parser_numeric_sign}The public lexical sign is applied outside \texttt{parse_decimal_seq}; the sign factored here is only the explicit decimal exponent sign and produces the identical point update. Thus the returned-word sign path is untouched.\end{goalproof} \begin{goalproof}{parser_signed_zero}The helper changes neither the public lexical-sign bit nor the significand digits, and its exponent adjustment is exactly the existing one. Consequently the zero path and its later sign assembly are not modified or restricted.\end{goalproof} \begin{goalproof}{parser_exact_rounding}The slow conversion receives exactly the decimal-point value produced by the pinned parser, including every optional-exponent case. This factoring adds no condition on a numeric literal and does not assume that its eventual rounded result is correct.\end{goalproof} \begin{goalproof}{parser_selected_exponent}Any raw pair selected downstream is computed from the same decimal-sequence point because the factored branch has the same I32 result or failure. No range premise on the selected biased exponent is introduced.\end{goalproof} \begin{goalproof}{parser_selected_magnitude_sign}This fragment changes no raw-pair assembly or public sign application; it merely reproduces the existing decimal-point update. The selected magnitude word is therefore the same word as in the pinned execution.\end{goalproof} \begin{goalproof}{dispatch_abstract_composition}The optional-exponent computation inside the slow numeric component is represented extensionally on its full model domain, with no extra precondition. Abstract components and dispatcher calls therefore see precisely the old normal result or failure, independently of whether the composition claim is true.\end{goalproof} \begin{goalproof}{dispatch_component_compliance}The actual slow component still performs the pinned optional-exponent code for every call-site residual and base. The factoring neither supplies nor assumes any disputed component contract and adds no dispatcher premise.\end{goalproof} \begin{goalproof}{parser_accumulated_rounding}The bounded explicit exponent contributes to the accumulated-exponent value through exactly the same signed I32 addition. The parser's result, failure behavior, and accumulated target are unchanged, without assuming that the result rounds to that target.\end{goalproof} \begin{goalproof}{parser_equal_target_rounding}Because the exact and accumulated targets are defined from the same literal while this definition preserves the parser's exponent update, their equality condition and the parser output are unchanged. No equality-of-targets premise is added by the factoring.\end{goalproof} \begin{goalproof}{number_helper_acceptance}The \texttt{parse_number} helper has its own exponent scan and returns a \texttt{Decimal} record; it does not call this decimal-sequence finalizer. Its byte-slice domain and \texttt{Option} result are therefore unaffected.\end{goalproof} \begin{goalproof}{number_helper_rejection}Invalid rejection by \texttt{parse_number} is decided before any slow decimal-sequence conversion. This separate \texttt{Result I32} definition cannot change the helper's \texttt{None} cases.\end{goalproof} \begin{goalproof}{number_helper_record_bounds}This definition constructs no \texttt{Decimal} record and modifies neither \texttt{mantissa}, \texttt{negative}, nor \texttt{many_digits}. The record-bound obligation is noninterfering.\end{goalproof} \begin{goalproof}{number_helper_accumulated_value}The diagnostic statement concerns the record returned by \texttt{parse_number}, whereas this factoring is used later by \texttt{parse_decimal_seq}. It changes neither record exponent nor mantissa and hence is noninterfering.\end{goalproof} \begin{goalproof}{special_helper_infinity}The \texttt{parse_inf_nan} helper and its separate sign argument do not use decimal-sequence exponent evaluation. Keyword recognition and the infinity word are unchanged.\end{goalproof} \begin{goalproof}{special_helper_nan}NaN keyword recognition and NaN construction occur in \texttt{parse_inf_nan}, disjoint from this definition. No byte, sign argument, or result of that helper is altered.\end{goalproof} \begin{goalproof}{special_helper_rejection}The special helper's three-keyword comparison does not call this definition. Its \texttt{None} behavior on every other byte slice is therefore unchanged.\end{goalproof} \begin{goalproof}{native_correct_or_defer}The native shortcut consumes a \texttt{Decimal} record and does not construct a \texttt{DecimalSeq}. Optional decimal-sequence exponent evaluation is not on that path, so its \texttt{Option} result and rounding expression are unchanged.\end{goalproof} \begin{goalproof}{integer_correct_or_defer}\texttt{compute_float} operates on an already supplied I64 exponent and U64 mantissa. It neither calls nor observes this residual-slice computation, so its raw-pair behavior is unchanged.\end{goalproof} \begin{goalproof}{slow_accumulated_rounding}\texttt{parse_long_mantissa} obtains its record from \texttt{parse_decimal_seq}; this definition exactly factors that parser's optional-exponent point update and adds no premise on the unsigned numeric input. Thus the full-significand record and all later slow-path observations are preserved without assuming the rounding conclusion.\end{goalproof} \begin{goalproof}{assembly_correspondence}Assembly takes only a completed \texttt{BiasedFp} and performs word operations. It has no residual slice or decimal-point input, so this definition cannot alter its all-field-values statement.\end{goalproof} \begin{goalproof}{classification_totality}Classification is a mathematical relation on every finite byte string and does not evaluate the extracted optional-exponent helper. Its domain and three possible classifications remain unchanged.\end{goalproof} \begin{goalproof}{classification_determinism}The uniqueness of a grammatical classification and parsed content is specified independently of this executable factoring. No grammar production or parsed mathematical exponent is redefined.\end{goalproof} \begin{goalproof}{classification_significand_digit}Whether a numeric grammar derivation contains a significand digit is independent of the later decimal-sequence point update. This definition neither adds nor removes any grammar derivation.\end{goalproof} \begin{goalproof}{rounding_totality}The abstract rounding relation ranges over nonnegative reals and has no slice, I32 base, or parser execution. Its existence claim is therefore noninterfering.\end{goalproof} \begin{goalproof}{rounding_determinism}The uniqueness of the binary64 target is likewise an abstract real-number property. Naming an extracted parser fragment does not change its input, candidate targets, or equality relation.\end{goalproof} \begin{goalproof}{exponent_value_agreement}This mathematical goal compares exact and bounded-accumulation values under an explicit equality hypothesis; it does not execute \texttt{parse_decimal_seq}. The factoring neither changes those definitions nor assumes their exponent-equality premise, so it is noninterfering.\end{goalproof} \end{preservation} ===== HISTORICAL Tablet/DecimalSeqFractionalFinish.lean ===== import Tablet.DecimalSeqExponentEval import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: DecimalSeqFractionalFinish] def DecimalSeqFractionalFinish (s rest : Slice Std.U8) (d : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := -- BODY do let consumed <- Slice.len s - Slice.len rest let trailing <- num.imp.dec2flt.decimal_seq.count_trailing_zeros s consumed let p1 <- d.decimal_point + UScalar.hcast .I32 trailing let kept <- d.num_digits - trailing let point <- p1 + UScalar.hcast .I32 kept let (nDigits, flag) <- if kept > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS then ok (num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS, true) else ok (kept, d.truncated) let finalPoint <- DecimalSeqExponentEval rest point let a <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop1 { start := nDigits, «end» := num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW } d.digits ok (num.imp.dec2flt.decimal_seq.DecimalSeq.mk nDigits finalPoint flag a) end dec2flt_model ===== HISTORICAL Tablet/DecimalSeqFractionalFinish.tex ===== \begin{definition}[Decimal-sequence fractional finalization] \label{def:DecimalSeqFractionalFinish} For arbitrary modeled slices $s$ and \texttt{rest} and an arbitrary modeled decimal-sequence record $d$, \texttt{DecimalSeqFractionalFinish} is the following checked monadic computation. It subtracts $|\texttt{rest}|$ from $|s|$ and passes the resulting \texttt{consumed} count to the extracted trailing-zero counter on $s$. It casts the returned \texttt{trailing} count to I32 and adds it to $d.\texttt{decimal\_point}$; subtracts \texttt{trailing} from $d.\texttt{num\_digits}$ to obtain \texttt{kept}; casts \texttt{kept} to I32 and adds it to the intermediate point; and then selects \[ (\texttt{nDigits},\texttt{flag})= \begin{cases}(768,\mathsf{true}),&\texttt{kept}>768,\\ (\texttt{kept},d.\texttt{truncated}),&\texttt{kept}\le768. \end{cases} \] It applies \noderef{DecimalSeqExponentEval} to \texttt{rest} and the resulting point. Finally it runs the extracted parser loop~1 on $d.\texttt{digits}$ over the half-open array-index interval $[\texttt{nDigits},19)$, setting exactly those cells to zero and leaving every other cell unchanged, and returns the record made from \texttt{nDigits}, the exponent-adjusted point, \texttt{flag}, and that array. Each failed or divergent checked operation is propagated by its monadic bind. \end{definition} \begin{preservation} \begin{claim} Consider an actual execution of \texttt{crate/dec2flt/decimal_seq.rs:320--363} after the integral and optional fractional scans. Let $s_0$ be the exact original source slice stored as \texttt{start}, let $r$ be the exact current residual suffix stored as \texttt{s}, and let $d$ be the exact post-scan \texttt{DecimalSeq}. On the branch $d.\texttt{num_digits}\ne0$, the remainder of that source execution is exactly \texttt{DecimalSeqFractionalFinish}$(s_0,r,d)$: it has the same final record on normal return and fails at the same modeled checked operation on an abnormal return. No claim is made that the source invokes this finalization from an arbitrary state with zero digit count. \end{claim} \begin{proof} Fix an execution and $s_0,r,d$ satisfying the claim. The branch hypothesis is the source guard at line 320, so the assignments at lines 322--333 execute; it is not an invented premise on the public parser. Compare those assignments and the subsequent exponent and fill code with the corresponding branches of the pinned \texttt{parse_decimal_seq} declaration \noderef{num_imp_dec2flt_decimal_seq_parse_decimal_seq}. First, the source sets \texttt{consumed_len} to $|s_0|-|r|$. The definition binds the same Usize subtraction \texttt{Slice.len} $s_0-$ \texttt{Slice.len} $r$. Since $r$ is the exact residual suffix of this execution, $|r|\le |s_0|$ on every source-reachable state. At the model level the two fragments still use the same checked subtraction, so an underflow, if presented outside that source invariant, would be the same first propagated failure rather than a different result. Next both call the pinned reverse scanner \noderef{num_imp_dec2flt_decimal_seq_count_trailing_zeros} on $s_0$ and that same consumed length. The adaptation record \evidenceref{reference/model-evidence/source-adaptation-delta.txt} establishes that this indexed helper visits positions \texttt{consumed_len-1}, \ldots, $0$ in the same order as the original \texttt{iter().rev()} loop, increments exactly on ASCII zero, passes over a decimal point, and stops at the first byte that is neither zero nor point. Thus its Usize result is exactly the source value \texttt{n_trailing_zeros}; a helper failure is bound and returned before any record update on both model fragments. Let $z$ be that Usize result, and write $\operatorname{cast32}(u)$ for the signed I32 representative of the low 32 bits of a Usize value $u$. Rust's narrowing \texttt{u as i32} and Aeneas's pure \texttt{UScalar.hcast .I32 u} both compute exactly $\operatorname{cast32}(u)$; this operation truncates and cannot fail (the \texttt{lift} surrounding it in the pinned parser merely places that pure value in the \texttt{Result} computation). Thus both fragments first perform the same checked I32 addition $d.\texttt{decimal_point}+\operatorname{cast32}(z)$, which either fails on both sides or produces the same intermediate point. They next perform the same checked Usize subtraction $d.\texttt{num_digits}-z$; if it succeeds, call its Usize result $k$. Both then compute the identical pure value $\operatorname{cast32}(k)$ and perform the same checked I32 addition to the intermediate point. Consequently, whenever both additions and the subtraction succeed, the uncapped point on each side is the I32 value $d.\texttt{decimal_point}+\operatorname{cast32}(z) +\operatorname{cast32}(k)$; subtraction and addition failures coincide, and neither narrowing cast contributes a failure. The next test is the same strict comparison $k>\texttt{DecimalSeq::MAX_DIGITS}$, whose pinned value is 768 by \noderef{num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS}. In the true branch both retain 768 digits and set \texttt{truncated} to true. In the false branch both retain $k$ and preserve $d.\texttt{truncated}$. This establishes the same pair $(n,f)$ of stored digit count and flag, including the equality case $k=768$. It remains to justify the residual observation made before the optional exponent computation. The cited pinned parser has four source-reachable copies of this nonzero finalization. When the residual $s_2$ is empty, the outer \texttt{Slice.is_empty} result is saved across finalization. After a decimal point, the two copies (according as the pre-fractional digit count is zero or nonzero) use the post-scan residual $s_6$ or $s_5$ and test it after finalization. In the remaining nonempty, non-decimal-point copy, the parser saves both the false emptiness result and the byte $s_2[0]$ across finalization. In every copy, the intervening consumed-length computation, trailing-zero scan, casts, arithmetic, cap test, and flag update only read the residual slice; none changes that slice. Thus the argument $r$ passed to the factoring is respectively that same $s_2$, $s_6$, $s_5$, or $s_2$. By the Aeneas slice semantics, \texttt{Slice.is_empty} is total and returns the deterministic test of whether the slice length is zero. Recomputing it on the unchanged $r$ therefore returns the parser's saved Boolean in the first and fourth copies, and is the identical test already made by the parser in the two post-decimal copies. In the empty case both computations take the empty branch and neither indexes $r$. In every nonempty case, index zero is in bounds; \texttt{Slice.index_usize} therefore succeeds deterministically and returns the same byte, including the byte saved by the outer parser in the fourth copy. Hence the factoring's extra emptiness and index observations cannot fail or diverge, and both sides select the same nonmarker, lowercase-\texttt{e}, or uppercase-\texttt{E} branch. Only after that observation equality is established, apply the optional exponent computation \noderef{DecimalSeqExponentEval} to the identical residual $r$ and the identical cast-correct I32 base $d.\texttt{decimal_point}+\operatorname{cast32}(z) +\operatorname{cast32}(k)$. Its empty/marker, optional-sign, decimal-exponent-parser, checked-multiplication, and checked-addition analysis then gives the same final point $p$ or the same first arithmetic or parser failure. Separately, the source/adaptation evidence cited above identifies the guarded nonempty/index tests with the original source's split-first tests; it is used for that source-preservation comparison, not for the saved-versus-recomputed observation equality just proved. Finally the source loop at lines 361--363 ranges from $n$ to \texttt{MAX_DIGITS_WITHOUT_OVERFLOW} and writes zero to each selected digit cell. Aeneas duplicated this one source loop across control-flow branches as \texttt{parse_decimal_seq_loop1}, \texttt{loop4}, \texttt{loop6}, and \texttt{loop7} in the pinned node; their range iterator, array update, state, and exit bodies are identical. The factoring calls \texttt{loop1} with the same range and original $d.\texttt{digits}$, and hence produces exactly the same filled array $a$, or propagates the same range/array failure at the same iteration. When all binds succeed, both computations construct \texttt{DecimalSeq.mk} with fields \texttt{num_digits}$=n$, \texttt{decimal_point}$=p$, \texttt{truncated}$=f$, and \texttt{digits}$=a$. Monadic short-circuiting also shows that any earlier failure prevents this construction on both sides. This proves equality of normal and failure behavior precisely on the source's nonzero-digit post-scan branch, while making no assertion about source use at zero count. \end{proof} \begin{goalproof}{parser_totality}On every actual nonzero post-scan branch this definition is the pinned parser's own checked finalization, including its first failure; the zero-count branch is left untouched. Factoring therefore adds no public-input premise and changes no termination or panic observation.\end{goalproof} \begin{goalproof}{parser_numeric_acceptance}Every numeric execution reaching this nonzero branch retains the exact residual, point, digit count, truncation flag, exponent update, and zero-filled array of \texttt{parse_decimal_seq}. The definition adds no grammar condition and assumes no acceptance result.\end{goalproof} \begin{goalproof}{parser_invalid_rejection}The same residual byte controls the optional-exponent branch, and nonmarker and failure cases are preserved without extra consumption. Thus finalization cannot change a later invalidity decision or impose a new premise.\end{goalproof} \begin{goalproof}{parser_nan_acceptance}NaN literals are accepted by the special helper and do not enter the numeric decimal-sequence finalization. Restricting this claim to the actual nonzero numeric branch leaves NaN recognition and construction unchanged.\end{goalproof} \begin{goalproof}{parser_infinity}Infinity literals also bypass \texttt{parse_decimal_seq}. This factoring changes neither their keyword path nor their lexical sign.\end{goalproof} \begin{goalproof}{parser_non_nan_results}For numeric slow executions, the factored record and every failure coincide with the pinned parser; for special executions it is unused. It therefore neither creates a NaN nor assumes the no-spurious-NaN conclusion.\end{goalproof} \begin{goalproof}{parser_numeric_sign}The public lexical sign is stored and assembled outside this unsigned decimal-sequence record. Preserving the exact post-scan record leaves the eventual sign application unchanged.\end{goalproof} \begin{goalproof}{parser_signed_zero}Trailing-zero removal changes only the canonical record exactly as in the pinned parser, while the public sign remains outside it. The zero magnitude and later signed assembly paths are therefore unchanged and unrestricted.\end{goalproof} \begin{goalproof}{parser_exact_rounding}The slow converter receives the same capped digits, decimal point, sticky/truncation flag, and zero-filled tail as before. This source-branch factoring adds no hypothesis about exact value or rounding and preserves the parser observation used by the goal.\end{goalproof} \begin{goalproof}{parser_selected_exponent}All downstream raw-pair computations see the identical \texttt{DecimalSeq} or the identical prior failure. No biased-exponent range fact is inserted as a premise.\end{goalproof} \begin{goalproof}{parser_selected_magnitude_sign}The definition neither applies the public sign nor assembles a raw pair; it preserves the magnitude record supplied to the slow converter. Hence selected magnitude words are unchanged.\end{goalproof} \begin{goalproof}{dispatch_abstract_composition}This definition extensionally factors the actual nonzero finalization inside the slow numeric component while preserving the source's zero-count alternative. It adds no component precondition and does not assume the disputed abstract-composition conclusion.\end{goalproof} \begin{goalproof}{dispatch_component_compliance}At a real slow-component call, $s_0$, $r$, and $d$ are exactly the parser-produced source slice, residual, and state required by the claim; that is a control-flow fact, not a strengthened caller contract. The component's normal and failure behavior remains exact.\end{goalproof} \begin{goalproof}{parser_accumulated_rounding}Trailing-zero normalization, retained digits, sticky flag, and signed explicit-exponent update determine the same accumulated decimal record as the pinned parser. Factoring adds no premise and does not assume the record is ultimately rounded correctly.\end{goalproof} \begin{goalproof}{parser_equal_target_rounding}Both the parser result and the decimal-sequence input to slow rounding are unchanged on the branch, while exact/accumulated target equality remains the GOAL's own condition. No new equality condition is introduced.\end{goalproof} \begin{goalproof}{number_helper_acceptance}\texttt{parse_number} returns a \texttt{Decimal} before the optional slow decimal-sequence conversion and never calls this finalizer. Its nonempty-slice domain and \texttt{Some} cases are unaffected.\end{goalproof} \begin{goalproof}{number_helper_rejection}The number helper's \texttt{None} decision precedes and is independent of \texttt{parse_decimal_seq}. A definition over \texttt{DecimalSeq} states no new condition on that decision.\end{goalproof} \begin{goalproof}{number_helper_record_bounds}The helper-bound fields belong to \texttt{Decimal}, whereas this definition consumes and constructs \texttt{DecimalSeq}. It cannot change the returned mantissa, negative flag, or $10^{19}$ bound.\end{goalproof} \begin{goalproof}{number_helper_accumulated_value}The mantissa/exponent interval in this goal describes the earlier \texttt{parse_number} record. Post-scan trailing-zero and array finalization occurs only later on the slow path and leaves that record untouched.\end{goalproof} \begin{goalproof}{special_helper_infinity}\texttt{parse_inf_nan} neither produces nor consumes a \texttt{DecimalSeq}. Its keyword bytes, separate sign argument, and infinity result are noninterfering.\end{goalproof} \begin{goalproof}{special_helper_nan}The special NaN helper is disjoint from this numeric slow-path finalization. No NaN payload, classification, or sign argument is changed.\end{goalproof} \begin{goalproof}{special_helper_rejection}Inputs rejected by the special helper are decided by its keyword comparisons, not by decimal-sequence state. Its \texttt{None} cases remain identical.\end{goalproof} \begin{goalproof}{native_correct_or_defer}\texttt{try_fast_path} operates directly on the \texttt{Decimal} record and runs before slow decimal-sequence parsing. This finalizer changes neither a native-path \texttt{Some} value nor a deferral.\end{goalproof} \begin{goalproof}{integer_correct_or_defer}\texttt{compute_float} accepts scalar exponent and mantissa arguments and does not observe any \texttt{DecimalSeq} array. Its returned or deferred \texttt{BiasedFp} is unaffected.\end{goalproof} \begin{goalproof}{slow_accumulated_rounding}This is the relevant consumer: \texttt{parse_long_mantissa} calls \texttt{parse_decimal_seq} and receives precisely the final record factored here on the actual nonzero branch, with the zero branch preserved separately. No premise is added to unsigned numeric inputs, and no rounding result is assumed.\end{goalproof} \begin{goalproof}{assembly_correspondence}\texttt{biased_fp_to_float} consumes only a completed raw pair, not a source slice, residual, or decimal digit array. This finalizer cannot alter the assembly formula quantified over all field values.\end{goalproof} \begin{goalproof}{classification_totality}The mathematical classification relation ranges over finite byte strings and is defined before any decimal-sequence execution. Its coverage by numeric, special, or invalid is unchanged.\end{goalproof} \begin{goalproof}{classification_determinism}No grammar rule or parsed lexical content is changed by factoring a later source branch. Classification uniqueness and uniqueness of numeric content are therefore noninterfering.\end{goalproof} \begin{goalproof}{classification_significand_digit}The existence of a significand digit is a property of numeric syntax; the finalizer is entered only after scanning such bytes and does not redefine the grammar. The goal is unchanged.\end{goalproof} \begin{goalproof}{rounding_totality}Abstract rounding totality quantifies over nonnegative real numbers, with no parser state or byte slice. The source-branch factoring has no effect on its candidates or domain.\end{goalproof} \begin{goalproof}{rounding_determinism}Abstract target uniqueness is likewise independent of the construction of a \texttt{DecimalSeq}. Its real input and binary64 comparison relation remain unchanged.\end{goalproof} \begin{goalproof}{exponent_value_agreement}The mathematical exact and accumulated exponent values are defined from lexical content, not from this finalizer's implementation. The definition preserves the implementation but neither changes those values nor assumes their stated equality, so the agreement goal is noninterfering.\end{goalproof} \end{preservation} ===== HISTORICAL Tablet/DecimalSeqFractionalLeadingParserCore.lean ===== import Tablet.DecimalSeqDuplicateLoops import Tablet.DecimalSeqFractionalFinish import Tablet.DecimalSeqExponentEval import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxRecDepth 100000 set_option maxHeartbeats 3000000 namespace dec2flt_model private def leadingParserFinish4 (s rest : Slice Std.U8) (d : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (nDigits, point, flag) <- do let consumed <- Slice.len s - Slice.len rest let trailing <- num.imp.dec2flt.decimal_seq.count_trailing_zeros s consumed let p1 <- d.decimal_point + UScalar.hcast .I32 trailing let kept <- d.num_digits - trailing let point <- p1 + UScalar.hcast .I32 kept let (nDigits, flag) <- if kept > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS then ok (num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS, true) else ok (kept, d.truncated) ok (nDigits, point, flag) let finalPoint <- DecimalSeqExponentEval rest point let a <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop4 { start := nDigits, «end» := num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW } d.digits ok (num.imp.dec2flt.decimal_seq.DecimalSeq.mk nDigits finalPoint flag a) private def leadingBase (afterPoint rest : Slice Std.U8) : Result Std.I32 := (UScalar.hcast .I32 (Slice.len rest) : Std.I32) - UScalar.hcast .I32 (Slice.len afterPoint) private def leadingAfterBase (s rest : Slice Std.U8) (d2 : num.imp.dec2flt.decimal_seq.DecimalSeq) (base : Std.I32) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (nDigits, point, flag) <- if d2.num_digits != 0#usize then do let consumed <- Slice.len s - Slice.len rest let trailing <- num.imp.dec2flt.decimal_seq.count_trailing_zeros s consumed let p1 <- base + UScalar.hcast .I32 trailing let kept <- d2.num_digits - trailing let point <- p1 + UScalar.hcast .I32 kept let (nDigits, flag) <- if kept > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS then ok (num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS, true) else ok (kept, d2.truncated) ok (nDigits, point, flag) else ok (d2.num_digits, base, d2.truncated) let finalPoint <- DecimalSeqExponentEval rest point let a <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop4 { start := nDigits, «end» := num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW } d2.digits ok (num.imp.dec2flt.decimal_seq.DecimalSeq.mk nDigits finalPoint flag a) private def leadingAfterScan2 (s afterPoint rest : Slice Std.U8) (d2 : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let base <- leadingBase afterPoint rest leadingAfterBase s rest d2 base private def leadingAfterBulk (s afterPoint bulkRest : Slice Std.U8) (d1 : num.imp.dec2flt.decimal_seq.DecimalSeq) (count : Std.Usize) (arr : Array Std.U8 768#usize) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (rest, d2) <- num.imp.dec2flt.decimal_seq.parse_digits_into_seq bulkRest { d1 with num_digits := count, digits := arr } leadingAfterScan2 s afterPoint rest d2 private def leadingAfterZeros (s afterPoint sigStart : Slice Std.U8) (d1 : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (bulkRest, count, arr) <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop3 sigStart d1.num_digits d1.digits leadingAfterBulk s afterPoint bulkRest d1 count arr private def leadingAfterPoint (s afterPoint : Slice Std.U8) (d1 : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let sigStart <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop2 afterPoint leadingAfterZeros s afterPoint sigStart d1 -- [TABLET NODE: DecimalSeqFractionalLeadingParserCore] theorem DecimalSeqFractionalLeadingParserCore (s s1 pointRest afterPoint sigStart bulkRest rest : Slice Std.U8) (d0 d1 d2 d : num.imp.dec2flt.decimal_seq.DecimalSeq) (bulkCount : Std.Usize) (bulkArray : Array Std.U8 768#usize) (hdefault : num.imp.dec2flt.decimal_seq.DecimalSeq.Insts.CoreDefaultDefault.default = ok d0) (hlead : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop0 s = ok s1) (hscan1 : num.imp.dec2flt.decimal_seq.parse_digits_into_seq s1 d0 = ok (pointRest, d1)) (hpointRestNe : pointRest.val ≠ []) (hpointIndex : Slice.index_usize pointRest 0#usize = ok 46#u8) (hdropPoint : core.slice.index.SliceIndexRangeFromUsizeSlice.index { start := 1#usize } pointRest = ok afterPoint) (hd1zero : d1.num_digits = 0#usize) (hloop2 : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop2 afterPoint = ok sigStart) (hloop3 : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop3 sigStart d1.num_digits d1.digits = ok (bulkRest, bulkCount, bulkArray)) (hscan2 : num.imp.dec2flt.decimal_seq.parse_digits_into_seq bulkRest { d1 with num_digits := bulkCount, digits := bulkArray } = ok (rest, d2)) (hd2valNe : d2.num_digits.val ≠ 0) (hparse : num.imp.dec2flt.decimal_seq.parse_decimal_seq s = ok d) : exists base : Std.I32, (UScalar.hcast .I32 (Slice.len rest) : Std.I32) - UScalar.hcast .I32 (Slice.len afterPoint) = ok base /\ DecimalSeqFractionalFinish s rest { d2 with decimal_point := base } = ok d := by -- BODY have hbranch : leadingAfterPoint s afterPoint d1 = ok d := by as_aux_lemma => unfold num.imp.dec2flt.decimal_seq.parse_decimal_seq at hparse rw [hdefault] at hparse simp only [bind_tc_ok] at hparse rw [hlead] at hparse simp only [bind_tc_ok] at hparse rw [hscan1] at hparse simp only [bind_tc_ok] at hparse simp [core.slice.Slice.is_empty, hpointRestNe, hpointIndex, hdropPoint, hd1zero] at hparse simpa [leadingAfterPoint, leadingAfterZeros, leadingAfterBulk, leadingAfterScan2, leadingBase, leadingAfterBase, DecimalSeqExponentEval, Aeneas.Std.lift, hd1zero] using hparse have hzeros : leadingAfterZeros s afterPoint sigStart d1 = ok d := by as_aux_lemma => unfold leadingAfterPoint at hbranch rw [hloop2] at hbranch simpa only [bind_tc_ok] using hbranch have hbulk : leadingAfterBulk s afterPoint bulkRest d1 bulkCount bulkArray = ok d := by as_aux_lemma => unfold leadingAfterZeros at hzeros rw [hloop3] at hzeros simpa only [bind_tc_ok] using hzeros have hafter : leadingAfterScan2 s afterPoint rest d2 = ok d := by as_aux_lemma => unfold leadingAfterBulk at hbulk rw [hscan2] at hbulk simpa only [bind_tc_ok] using hbulk have hd2ne : d2.num_digits ≠ 0#usize := by intro heq apply hd2valNe exact congrArg UScalar.val heq have bindOk {α β : Type} (r : Result α) (k : α -> Result β) (y : β) (h : r >>= k = ok y) : exists x, r = ok x := by cases r <;> simp_all have hbaseOk : exists base : Std.I32, leadingBase afterPoint rest = ok base := by apply bindOk (leadingBase afterPoint rest) (leadingAfterBase s rest d2) d simpa only [leadingAfterScan2] using hafter rcases hbaseOk with ⟨base, hb⟩ have hafterBase : leadingAfterBase s rest d2 base = ok d := by as_aux_lemma => unfold leadingAfterScan2 at hafter rw [hb] at hafter simpa only [bind_tc_ok] using hafter have hfinish4 : leadingParserFinish4 s rest { d2 with decimal_point := base } = ok d := by as_aux_lemma => unfold leadingAfterBase at hafterBase have hcond : (d2.num_digits != 0#usize) = true := by simpa only [bne_iff_ne] using hd2ne simp only [hcond, if_true] at hafterBase change leadingParserFinish4 s rest { d2 with decimal_point := base } = ok d at hafterBase exact hafterBase refine ⟨base, ?_, ?_⟩ · simpa only [leadingBase] using hb unfold leadingParserFinish4 at hfinish4 unfold DecimalSeqFractionalFinish simpa only [DecimalSeqDuplicateLoops.2.2.1, bind_assoc, bind_tc_ok] using hfinish4 end dec2flt_model ===== HISTORICAL Tablet/DecimalSeqFractionalLeadingParserCore.tex ===== \begin{lemma}[Exact leading-fractional parser branch] Suppose a successful extracted decimal-sequence parse reaches a decimal point after the initial leading-zero loop and an empty first scalar digit scan. Suppose the point is removed exactly, loop~2 consumes the stated leading fractional zeroes, loop~3 and the second scalar scan return the stated residual suffix and state, and that second state has nonzero logical count. Then the checked difference between the residual-suffix length and the whole post-point slice length succeeds with some base point, and the parser result is exactly \noderef{DecimalSeqFractionalFinish} from the second state and that base. \end{lemma} \begin{proof} Unfold the extracted parser and reduce its default construction, initial leading-zero loop, and first scalar scan by the supplied equations. The nonempty residual begins with byte 46, so the exact range-index equation takes the fractional branch and removes the point. The zero first count selects loop~2, whose supplied success equation leaves the first significant fractional byte. The supplied loop~3 and second scalar-scan equations then leave exactly the stated suffix and scan state. At this point the branch first casts the residual and post-point lengths to signed 32-bit values and subtracts them. Since the whole parse returned successfully, inversion of this result-monad bind proves that the subtraction returned some base $b$. The nonzero second count selects reverse trimming, cap selection, exponent handling, and fill loop~4. This continuation is the common finalizer \noderef{DecimalSeqFractionalFinish} except for its copied fill loop and the extractor's intermediate tuple. The loop~4/loop~1 clause of \noderef{DecimalSeqDuplicateLoops} and result-monad associativity identify the two computations, proving the finalizer equation and the claimed base subtraction equation. \end{proof} ===== HISTORICAL Tablet/DecimalSeqFractionalParserCore.lean ===== import Tablet.DecimalSeqDuplicateLoops import Tablet.DecimalSeqFractionalFinish import Tablet.DecimalSeqExponentEval import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxRecDepth 100000 set_option maxHeartbeats 3000000 namespace dec2flt_model private def fracParserFinish6 (s rest : Slice Std.U8) (d : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (nDigits, point, flag) <- do let consumed <- Slice.len s - Slice.len rest let trailing <- num.imp.dec2flt.decimal_seq.count_trailing_zeros s consumed let p1 <- d.decimal_point + UScalar.hcast .I32 trailing let kept <- d.num_digits - trailing let point <- p1 + UScalar.hcast .I32 kept let (nDigits, flag) <- if kept > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS then ok (num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS, true) else ok (kept, d.truncated) ok (nDigits, point, flag) let finalPoint <- DecimalSeqExponentEval rest point let a <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop6 { start := nDigits, «end» := num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW } d.digits ok (num.imp.dec2flt.decimal_seq.DecimalSeq.mk nDigits finalPoint flag a) private def fracBase (afterPoint rest : Slice Std.U8) : Result Std.I32 := (UScalar.hcast .I32 (Slice.len rest) : Std.I32) - UScalar.hcast .I32 (Slice.len afterPoint) private def fracAfterBase (s rest : Slice Std.U8) (d2 : num.imp.dec2flt.decimal_seq.DecimalSeq) (base : Std.I32) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (nDigits, point, flag) <- if d2.num_digits != 0#usize then do let consumed <- Slice.len s - Slice.len rest let trailing <- num.imp.dec2flt.decimal_seq.count_trailing_zeros s consumed let p1 <- base + UScalar.hcast .I32 trailing let kept <- d2.num_digits - trailing let point <- p1 + UScalar.hcast .I32 kept let (nDigits, flag) <- if kept > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS then ok (num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS, true) else ok (kept, d2.truncated) ok (nDigits, point, flag) else ok (d2.num_digits, base, d2.truncated) let finalPoint <- DecimalSeqExponentEval rest point let a <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop6 { start := nDigits, «end» := num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW } d2.digits ok (num.imp.dec2flt.decimal_seq.DecimalSeq.mk nDigits finalPoint flag a) private def fracAfterScan2 (s afterPoint rest : Slice Std.U8) (d2 : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let base <- fracBase afterPoint rest fracAfterBase s rest d2 base private def fracAfterBulk (s afterPoint bulkRest : Slice Std.U8) (d1 : num.imp.dec2flt.decimal_seq.DecimalSeq) (count : Std.Usize) (arr : Array Std.U8 768#usize) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (rest, d2) <- num.imp.dec2flt.decimal_seq.parse_digits_into_seq bulkRest { d1 with num_digits := count, digits := arr } fracAfterScan2 s afterPoint rest d2 private def fracAfterPointNonzero (s afterPoint : Slice Std.U8) (d1 : num.imp.dec2flt.decimal_seq.DecimalSeq) : Result num.imp.dec2flt.decimal_seq.DecimalSeq := do let (bulkRest, count, arr) <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop5 afterPoint d1.num_digits d1.digits fracAfterBulk s afterPoint bulkRest d1 count arr -- [TABLET NODE: DecimalSeqFractionalParserCore] theorem DecimalSeqFractionalParserCore (s s1 pointRest afterPoint bulkRest rest : Slice Std.U8) (d0 d1 d2 d : num.imp.dec2flt.decimal_seq.DecimalSeq) (bulkCount : Std.Usize) (bulkArray : Array Std.U8 768#usize) (hdefault : num.imp.dec2flt.decimal_seq.DecimalSeq.Insts.CoreDefaultDefault.default = ok d0) (hlead : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop0 s = ok s1) (hscan1 : num.imp.dec2flt.decimal_seq.parse_digits_into_seq s1 d0 = ok (pointRest, d1)) (hpointRestNe : pointRest.val ≠ []) (hpointIndex : Slice.index_usize pointRest 0#usize = ok 46#u8) (hdropPoint : core.slice.index.SliceIndexRangeFromUsizeSlice.index { start := 1#usize } pointRest = ok afterPoint) (hd1ne : d1.num_digits ≠ 0#usize) (hloop5 : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop5 afterPoint d1.num_digits d1.digits = ok (bulkRest, bulkCount, bulkArray)) (hscan2 : num.imp.dec2flt.decimal_seq.parse_digits_into_seq bulkRest { d1 with num_digits := bulkCount, digits := bulkArray } = ok (rest, d2)) (hd2valNe : d2.num_digits.val ≠ 0) (hparse : num.imp.dec2flt.decimal_seq.parse_decimal_seq s = ok d) : exists base : Std.I32, (UScalar.hcast .I32 (Slice.len rest) : Std.I32) - UScalar.hcast .I32 (Slice.len afterPoint) = ok base /\ DecimalSeqFractionalFinish s rest { d2 with decimal_point := base } = ok d := by -- BODY have hbranch : fracAfterPointNonzero s afterPoint d1 = ok d := by as_aux_lemma => unfold num.imp.dec2flt.decimal_seq.parse_decimal_seq at hparse rw [hdefault] at hparse simp only [bind_tc_ok] at hparse rw [hlead] at hparse simp only [bind_tc_ok] at hparse rw [hscan1] at hparse simp only [bind_tc_ok] at hparse simp [core.slice.Slice.is_empty, hpointRestNe, hpointIndex, hdropPoint, hd1ne] at hparse simpa [fracAfterPointNonzero, fracAfterBulk, fracAfterScan2, fracBase, fracAfterBase, DecimalSeqExponentEval] using hparse have hbulk : fracAfterBulk s afterPoint bulkRest d1 bulkCount bulkArray = ok d := by as_aux_lemma => unfold fracAfterPointNonzero at hbranch rw [hloop5] at hbranch simpa only [bind_tc_ok] using hbranch have hafter : fracAfterScan2 s afterPoint rest d2 = ok d := by as_aux_lemma => unfold fracAfterBulk at hbulk rw [hscan2] at hbulk simpa only [bind_tc_ok] using hbulk have hd2ne : d2.num_digits ≠ 0#usize := by intro heq apply hd2valNe exact congrArg UScalar.val heq have bindOk {α β : Type} (r : Result α) (k : α -> Result β) (y : β) (h : r >>= k = ok y) : exists x, r = ok x := by cases r <;> simp_all have hbaseOk : exists base : Std.I32, fracBase afterPoint rest = ok base := by apply bindOk (fracBase afterPoint rest) (fracAfterBase s rest d2) d simpa only [fracAfterScan2] using hafter rcases hbaseOk with ⟨base, hb⟩ have hafterBase : fracAfterBase s rest d2 base = ok d := by as_aux_lemma => unfold fracAfterScan2 at hafter rw [hb] at hafter simpa only [bind_tc_ok] using hafter have hfinish6 : fracParserFinish6 s rest { d2 with decimal_point := base } = ok d := by as_aux_lemma => unfold fracAfterBase at hafterBase have hcond : (d2.num_digits != 0#usize) = true := by simpa only [bne_iff_ne] using hd2ne simp only [hcond, if_true] at hafterBase change fracParserFinish6 s rest { d2 with decimal_point := base } = ok d at hafterBase exact hafterBase refine ⟨base, ?_, ?_⟩ · simpa only [fracBase] using hb unfold fracParserFinish6 at hfinish6 unfold DecimalSeqFractionalFinish simpa only [DecimalSeqDuplicateLoops.2.2.2.1, bind_assoc, bind_tc_ok] using hfinish6 end dec2flt_model ===== HISTORICAL Tablet/DecimalSeqFractionalParserCore.tex ===== \begin{lemma}[Exact nonzero-integer fractional parser branch] Suppose a successful call to the extracted decimal-sequence parser reaches a decimal point after its leading-zero loop and first scalar digit scan. Suppose the first scan stored at least one significant digit, the point byte is removed exactly, loop~5 and the second scalar scan return the stated residual suffix and state, and that state has a nonzero logical digit count. Then the checked difference between the residual-suffix length and the post-point slice length succeeds with some base point, and the parser result is exactly the common fractional finalization \noderef{DecimalSeqFractionalFinish} from that second scan state and base. \end{lemma} \begin{proof} Unfold the extracted parser. Its default-state call, initial leading-zero loop, and first scalar scan reduce by the three supplied success equations. The residual slice is nonempty and its index-zero byte is the decimal point, so the parser takes the fractional branch and the supplied range-index equation removes exactly that point. The nonzero first count selects the loop~5 branch. Reducing loop~5 and the second scalar scan with their supplied success equations leaves the checked cast-and-subtraction that computes the base point, followed by the common finalization. Because the whole parser call returned successfully, inversion of the result-monad bind shows that this checked subtraction also returned successfully; call its value $b$. The nonzero second logical count selects the trimming branch. The residual computation is then precisely \noderef{DecimalSeqFractionalFinish}, except that the extracted fractional branch invokes fill loop~6. The loop identity from \noderef{DecimalSeqDuplicateLoops} identifies loop~6 with loop~1. Monad associativity removes the extractor's intermediate tuple packaging, yielding the claimed finalization equation with base $b$. \end{proof} ===== HISTORICAL Tablet/DispatchContractsUninhabited.lean ===== import Tablet.DecimalGoalVocabularyDefault import Tablet.DecimalLexeme import Tablet.DispatchContracts import Tablet.F64 import Tablet.SourceValidByteSlice open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: DispatchContractsUninhabited] theorem DispatchContractsUninhabited : ¬ Nonempty DispatchContracts := by -- BODY let zeros : List Nat := List.replicate 65535 0 let fraction : List Nat := zeros ++ [1] have zeros_eq : zeros = List.replicate 65535 0 := rfl have fraction_eq : fraction = zeros ++ [1] := rfl let witness : DecimalLexeme := { leadingSign := none integerDigits := [0] fractionDigits := some fraction exponent := some (false, none, [6, 5, 5, 3, 6, 0]) } let witnessBytes : List Std.U8 := [48#u8, 46#u8] ++ List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8] have witnessBytes_length : witnessBytes.length = 65545 := by simp only [witnessBytes, List.length_append, List.length_replicate, List.length_cons, List.length_nil] let witnessSlice : Slice Std.U8 := ⟨witnessBytes, by rw [witnessBytes_length]; scalar_tac⟩ have fold_zeros (k : Nat) : (List.replicate k 0).foldl (fun a d => 10 * a + d) 0 = 0 := by induction k with | zero => rfl | succ k ih => simpa [List.replicate_succ] using ih have zeros_fold : zeros.foldl (fun a d => 10 * a + d) 0 = 0 := by rw [zeros_eq] exact fold_zeros 65535 have zeros_length : zeros.length = 65535 := by rw [zeros_eq] exact List.length_replicate have zeros_mem {d : Nat} (h : d ∈ zeros) : d = 0 := by rw [zeros_eq, List.mem_replicate] at h exact h.2 have zeros_map : zeros.map (fun d => 48 + d) = List.replicate 65535 48 := by rw [zeros_eq, List.map_replicate] have fraction_length : fraction.length = 65536 := by rw [fraction_eq, List.length_append, zeros_length] rfl have significand_fold : ([0] ++ fraction).foldl (fun a d => 10 * a + d) 0 = 1 := by rw [List.foldl_append] simp only [List.foldl_cons, List.foldl_nil, mul_zero, zero_add] rw [fraction_eq, List.foldl_append, zeros_fold] rfl have witness_source_valid : SourceValidByteSlice witnessSlice := by change witnessBytes.length ≤ 9223372036854775807 rw [witnessBytes_length] norm_num have witness_unsigned : witness.leadingSign = none := rfl have witness_valid : DecimalGoalVocabularyDefault.validNumeric witness := by dsimp only [DecimalGoalVocabularyDefault] constructor · simp [witness] constructor · simp only [witness] intro d hd rw [fraction_eq] at hd rcases List.mem_append.mp hd with hd | hd · rw [zeros_mem hd] norm_num · simp only [List.mem_singleton] at hd omega constructor · left simp [witness] · simp [witness] have witness_render : DecimalGoalVocabularyDefault.renderNumeric witness = DecimalGoalVocabularyDefault.bytes witnessSlice := by dsimp only [DecimalGoalVocabularyDefault] simp only [witness, witnessSlice, witnessBytes, fraction, List.map_append, List.map_cons, List.map_nil, List.map_replicate, Bool.false_eq_true, reduceIte, Nat.reduceAdd, List.nil_append, List.cons_append] rw [zeros_map] norm_num have witness_exact : DecimalGoalVocabularyDefault.exactMagnitude witness = (10 : Real) ^ (589824 : Nat) := by dsimp only [DecimalGoalVocabularyDefault, witness] rw [significand_fold, fraction_length] norm_num rfl have witness_accumulated : DecimalGoalVocabularyDefault.accumulatedMagnitude witness = 1 := by dsimp only [DecimalGoalVocabularyDefault, witness] rw [significand_fold, fraction_length] norm_num let infinityBits : Nat := 2047 * 2 ^ 52 have one_not_infinity_target (w : F64) (hw : w.val = infinityBits) : ¬ DecimalGoalVocabularyDefault.roundsMagnitude (1 : Real) w := by dsimp only [DecimalGoalVocabularyDefault] simp only [hw, infinityBits] norm_num calc (1 : Real) + 2 ^ 970 ≤ 2 ^ 970 + 2 ^ 970 := by gcongr exact one_le_pow₀ (by norm_num) _ = 2 ^ 971 := by rw [show (971 : Nat) = 970 + 1 by norm_num, pow_add] ring _ < 2 ^ 1024 := by rw [show (1024 : Nat) = 971 + 53 by norm_num, pow_add] norm_num have huge_target_is_infinity (w : F64) (hw : DecimalGoalVocabularyDefault.roundsMagnitude ((10 : Real) ^ (589824 : Nat)) w) : w.val = infinityBits := by dsimp only [DecimalGoalVocabularyDefault] at hw rcases hw with ⟨_, _, hw⟩ by_contra hne have hne' : w.val ≠ 2047 * 2 ^ 52 := by simpa [infinityBits] using hne rw [if_neg hne'] at hw have hthreshold : ((2 : Real) ^ (1024 : Nat)) - ((2 : Real) ^ (970 : Nat)) ≤ (10 : Real) ^ (589824 : Nat) := by calc (2 : Real) ^ 1024 - 2 ^ 970 ≤ 2 ^ 1024 := sub_le_self _ (by positivity) _ ≤ 10 ^ 1024 := by gcongr <;> norm_num _ ≤ 10 ^ 589824 := by rw [show (589824 : Nat) = 1024 + 588800 by norm_num, pow_add] exact le_mul_of_one_le_right (by positivity) (one_le_pow₀ (by norm_num)) exact (not_lt_of_ge hthreshold) hw.1 rintro ⟨C⟩ have hslow := C.slow_spec witnessSlice witness witness_source_valid witness_unsigned witness_valid witness_render have hexact := C.slowTarget_spec witnessSlice witness witness_source_valid witness_unsigned witness_valid witness_render dsimp only at hslow hexact rw [witness_accumulated] at hslow rw [witness_exact] at hexact have hinfinity := huge_target_is_infinity _ hexact exact one_not_infinity_target _ hinfinity hslow.2.2.1 end dec2flt_model ===== HISTORICAL Tablet/DispatchContractsUninhabited.tex ===== \begin{theorem} There is no dispatcher contract package: \texttt{DispatchContracts} is empty. \end{theorem} \begin{proof} Suppose, for contradiction, that a package $C$ exists. We construct a single unsigned numeric witness to which two laws of $C$ assign incompatible rounding requirements. In the four-field representation of \noderef{DecimalLexeme}, let $x$ have no leading sign, integer digits $[0]$, fractional digits consisting of $65{,}535$ zeroes followed by $1$, and exponent digits $[6,5,5,3,6,0]$ with neither an exponent sign nor uppercase marker. Let $b$ be the byte slice spelling \[ \texttt{0.}\;\underbrace{\texttt{00\ldots0}}_{65{,}535\text{ zeroes}} \texttt{1e655360}. \] Its list has $2+65{,}535+1+1+6=65{,}545$ bytes. Hence its length is less than $2^{63}-1$, so it is source-valid by \noderef{SourceValidByteSlice}. We next check every lexical premise rather than assuming that this large input is accepted. All entries in the integer, fractional, and exponent digit lists lie between $0$ and $9$; the integer list and exponent list are nonempty. Thus $x$ is valid according to \noderef{DecimalGoalVocabularyDefault}. Its rendering maps the integer zero to byte $48$, inserts byte $46$ for the point, maps the replicated fractional zeroes to $65{,}535$ copies of byte $48$ and the final fractional one to byte $49$, inserts lowercase exponent byte $101$, and maps the six exponent digits to bytes $54,53,53,51,54,48$. This is exactly the byte list underlying $b$, so $x$ has absent leading sign and renders $b$. The complete significand digit list is one leading zero, then $65{,}535$ zeroes, then one. Repeatedly applying the decimal fold $a\mathrel{:=}10a+d$ leaves the accumulator zero through every zero and makes it one at the final digit. The fractional length is $65{,}536$. For the exact exponent, the same unrestricted fold on $[6,5,5,3,6,0]$ gives $655{,}360$. The exact-magnitude definition in \noderef{DecimalGoalVocabularyDefault} therefore gives \[ \operatorname{exactMagnitude}(x) =1\cdot10^{655360-65536}=10^{589824}. \] For the accumulated exponent, its guarded fold updates only while the previous accumulator is below $65{,}536$. The successive updated values on the first five digits are $6,65,655,6553,65536$; at the last digit the guard is false, so the final zero is ignored. The accumulated exponent is consequently $65{,}536$, and \[ \operatorname{accumulatedMagnitude}(x) =1\cdot10^{65536-65536}=1. \] Let $I=2047\cdot2^{52}$, the positive-infinity word in the rounding relation of \noderef{DecimalGoalVocabularyDefault}; \noderef{F64} ensures this raw word is a binary64 carrier. Every rounding target $w$ of $10^{589824}$ must satisfy $w.\mathit{val}=I$. Indeed, if its word were not $I$, the finite branch of \texttt{roundsMagnitude} would require \[ 10^{589824}<2^{1024}-2^{970}. \] But $2^{1024}-2^{970}\leq2^{1024}\leq10^{1024}\leq10^{589824}$: the middle inequality follows from $2\leq10$, and the last from $10^{589824}=10^{1024}10^{588800}$ with the second factor at least one. This contradicts the required strict inequality. Conversely, the word $I$ is not a rounding target of $1$. At $I$, the infinity branch would require $2^{1024}-2^{970}\leq1$. Yet $1\leq2^{970}$ gives $1+2^{970}\leq2^{971}$, and $2^{971}<2^{1024}$; subtracting $2^{970}$ yields $1<2^{1024}-2^{970}$. Apply the two slow-fallback laws in \noderef{DispatchContracts} to the source-valid slice $b$ and the unsigned valid lexeme $x$ with the rendering equality proved above. Writing $f=C.\mathit{assemble}(C.\mathit{slow}(\operatorname{bytes}(b)))$, the \texttt{slow\_spec} clause says that $f$ rounds the accumulated magnitude, hence that $f$ rounds $1$. The \texttt{slowTarget\_spec} clause says that the same $f$ rounds the exact magnitude $10^{589824}$. The latter fact forces $f.\mathit{val}=I$, while the former is impossible for a word equal to $I$ by the preceding paragraph. This contradiction eliminates the assumed package $C$, proving that \texttt{DispatchContracts} is empty. \end{proof} ===== HISTORICAL Tablet/ParserExactRoundingScientific.lean ===== import Tablet.num_imp_dec2flt_parse_parse_scientific open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: ParserExactRoundingScientific] theorem ParserExactRoundingScientific (s : Slice Std.U8) (hs : s.val = [54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8]) : exists rest, num.imp.dec2flt.parse.parse_scientific s = ok (some 65536#i64, rest) /\ rest.val = [] := by -- BODY have ht : s = (⟨[54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8], by rcases Usize.bounds_eq with q | q <;> norm_num [q, U32.max_eq, U64.max_eq]⟩ : Slice Std.U8) := by exact (Slice.eq_iff _ _).2 hs rw [ht] refine ⟨⟨[], by simp⟩, ?_, by rfl⟩ have addOne (x y : Usize) (hxy : x.val + 1 = y.val) : x + 1#usize = ok y := by have hmax : x.val + (1#usize).val <= UScalar.max .Usize := by rw [show (1#usize).val = 1 by rfl, hxy] have hy := UScalar.hrBounds y simpa [UScalar.rMax_eq_max] using hy obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists (UScalar.add_spec hmax) rw [hz] congr 1 apply UScalar.eq_of_val_eq simpa [hxy] using hzval simp [num.imp.dec2flt.parse.parse_scientific, core.slice.Slice.split_first, dec2flt_model.ModelSliceSplitFirst, core.num.U8.is_ascii_digit, dec2flt_model.ModelU8IsAsciiDigit, Slice.index_usize] simp [num.imp.dec2flt.parse.parse_scientific_loop] rw [Aeneas.Std.loop.eq_1] have first_product : (10#i64 * 0#i64) = ok 0#i64 := by rfl have first_sum : (0#i64 + 6#i64) = ok 6#i64 := by rfl have first_digit : UScalar.hcast IScalarTy.I64 (core.num.U8.wrapping_sub 54#u8 48#u8) = 6#i64 := by rfl have first_sum2 : 0#i64 + UScalar.hcast IScalarTy.I64 (core.num.U8.wrapping_sub 54#u8 48#u8) = ok 6#i64 := by rfl have first_sum3 : 0#i64 + UScalar.hcast IScalarTy.I64 (UScalar.wrapping_sub 54#u8 48#u8) = ok 6#i64 := by rfl have first_count : (0#usize + 1#usize) = ok 1#usize := addOne _ _ (by rfl) have second_product : (10#i64 * 6#i64) = ok 60#i64 := by rfl have second_sum : 60#i64 + UScalar.hcast IScalarTy.I64 (UScalar.wrapping_sub 53#u8 48#u8) = ok 65#i64 := by rfl have second_count : (1#usize + 1#usize) = ok 2#usize := addOne _ _ (by rfl) have third_product : (10#i64 * 65#i64) = ok 650#i64 := by rfl have third_sum : 650#i64 + UScalar.hcast IScalarTy.I64 (UScalar.wrapping_sub 53#u8 48#u8) = ok 655#i64 := by rfl have third_count : (2#usize + 1#usize) = ok 3#usize := addOne _ _ (by rfl) have fourth_product : (10#i64 * 655#i64) = ok 6550#i64 := by rfl have fourth_sum : 6550#i64 + UScalar.hcast IScalarTy.I64 (UScalar.wrapping_sub 51#u8 48#u8) = ok 6553#i64 := by rfl have fourth_count : (3#usize + 1#usize) = ok 4#usize := addOne _ _ (by rfl) have fifth_product : (10#i64 * 6553#i64) = ok 65530#i64 := by rfl have fifth_sum : 65530#i64 + UScalar.hcast IScalarTy.I64 (UScalar.wrapping_sub 54#u8 48#u8) = ok 65536#i64 := by rfl have fifth_count : (4#usize + 1#usize) = ok 5#usize := addOne _ _ (by rfl) have sixth_count : (5#usize + 1#usize) = ok 6#usize := addOne _ _ (by rfl) simp [num.imp.dec2flt.parse.parse_scientific_loop.body, Slice.index_usize, Aeneas.Std.lift, core.num.U8.wrapping_sub, U8.size_eq, first_product, first_sum, first_count, first_digit, first_sum2] rw [first_sum3] simp rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.parse.parse_scientific_loop.body, Slice.index_usize, Aeneas.Std.lift, core.num.U8.wrapping_sub, U8.size_eq] simp [second_product, second_sum, second_count] rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.parse.parse_scientific_loop.body, Slice.index_usize, Aeneas.Std.lift, core.num.U8.wrapping_sub, U8.size_eq] simp [third_product, third_sum, third_count] rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.parse.parse_scientific_loop.body, Slice.index_usize, Aeneas.Std.lift, core.num.U8.wrapping_sub, U8.size_eq] simp [fourth_product, fourth_sum, fourth_count] rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.parse.parse_scientific_loop.body, Slice.index_usize, Aeneas.Std.lift, core.num.U8.wrapping_sub, U8.size_eq] simp [fifth_product, fifth_sum, fifth_count] rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.parse.parse_scientific_loop.body, Slice.index_usize, Aeneas.Std.lift, core.num.U8.wrapping_sub, U8.size_eq, sixth_count] rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.parse.parse_scientific_loop.body, core.slice.index.SliceIndexRangeFromUsizeSlice.index, Slice.drop, Slice.length, List.drop] end dec2flt_model ===== HISTORICAL Tablet/ParserExactRoundingScientific.tex ===== \begin{helper}[Exact scientific suffix] \label{helper:ParserExactRoundingScientific} For a model byte slice whose value is the ASCII digit list \texttt{[54,53,53,51,54,48]}, the extracted \texttt{parse\_scientific} succeeds with exponent $65536$ and an empty remaining slice. \end{helper} \begin{proof} Expand \noderef{num_imp_dec2flt_parse_parse_scientific}. Its first-byte split sees ASCII `6', so the unsigned branch invokes the scientific digit loop at accumulator zero and index zero. At each of the six iterations, the bounds-checked slice index reads respectively bytes $54,53,53,51,54,48$. Subtracting ASCII zero gives digits $6,5,5,3,6,0$, and the loop recurrence $a\mapsto10a+d$ therefore produces \[ 0,6,65,655,6553,65536,655360. \] The model caps accumulation before accepting a further digit once the pre-digit accumulator exceeds $65535$. Thus on the sixth byte it consumes the final zero and returns the previous accumulated value $65536$ at index $6$. Each index increment is bounded because Aeneas permits pointer widths $32$ or $64$ and all indices are at most six. The final drop by index six is the empty slice, so the parser returns exponent $65536$ and no remaining bytes, as claimed. \end{proof} ===== HISTORICAL Tablet/ParserExactRoundingExecution.lean ===== import Tablet.ParserExactRoundingDigitScans import Tablet.ParserExactRoundingAdjustment import Tablet.ParserExactRoundingFastPath import Tablet.ParserExactRoundingOffsets import Tablet.ParserExactRoundingScientific import Tablet.ModelSliceSplitFirst import Tablet.ModelSliceFirst import Tablet.ModelStrAsBytes import Tablet.num_imp_dec2flt_parse_parse_number import Tablet.num_imp_dec2flt_dec2flt open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxHeartbeats 2000000 set_option maxRecDepth 1000000 namespace dec2flt_model -- [TABLET NODE: ParserExactRoundingExecution] theorem ParserExactRoundingExecution (s : Str) (hs : s.val = [48#u8, 46#u8] ++ List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8]) : num.imp.dec2flt.dec2flt F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64 F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64 F64.Insts.CoreOpsArithNegF64 s = ok (core.result.Result.Ok (⟨BitVec.ofNat 64 4607182418800017408⟩ : F64)) := by -- BODY have parse_number_exact (body : Slice Std.U8) (hbody : body.val = [48#u8, 46#u8] ++ List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8]) : num.imp.dec2flt.parse.parse_number body = ok (some { exponent := 0#i64, mantissa := 1#u64, negative := false, many_digits := false }) := by have hbodyLen : body.val.length = 65545 := by simp only [hbody, List.length_append, List.length_replicate, List.length_cons, List.length_nil] obtain ⟨point, hscan0, hpoint⟩ := ParserExactRoundingDigitScans.2 body hbody have hpointLen : point.val.length = 65544 := by simp only [hpoint, List.length_cons, List.length_append, List.length_replicate, List.length_nil] obtain ⟨nDigits, hnDigits, hnDigitsVal⟩ := ParserExactRoundingOffsets body point (by omega) (by omega) have hnDigitsEq : nDigits = 1#isize := by apply IScalar.eq_of_val_eq rw [hnDigitsVal, hbodyLen, hpointLen] norm_num subst nDigits let fraction : Slice Std.U8 := ⟨List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8], by simp only [List.length_append, List.length_replicate, List.length_cons, List.length_nil] rcases Usize.bounds_eq with q | q <;> norm_num [q, U32.max_eq, U64.max_eq]⟩ have hfraction : fraction.val = List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8] := by rfl have hsplitPoint : core.slice.Slice.split_first point = ok (some (46#u8, fraction)) := by let point' : Slice Std.U8 := ⟨46#u8 :: fraction.val, by rw [hfraction] simp only [List.length_cons, List.length_append, List.length_replicate, List.length_nil] rcases Usize.bounds_eq with q | q <;> norm_num [q, U32.max_eq, U64.max_eq]⟩ have hpointEq : point = point' := (Slice.eq_iff _ _).2 (by rw [hpoint, show point'.val = 46#u8 :: fraction.val by rfl, hfraction] rfl) rw [hpointEq] simp [core.slice.Slice.split_first, dec2flt_model.ModelSliceSplitFirst, point'] obtain ⟨expRest, hscan1, hexpRest⟩ := ParserExactRoundingDigitScans.1 fraction hfraction have hfractionLen : fraction.val.length = 65543 := by simp only [hfraction, List.length_append, List.length_replicate, List.length_cons, List.length_nil] have hexpRestLen : expRest.val.length = 7 := by simp [hexpRest] obtain ⟨nAfter, hnAfter, hnAfterVal⟩ := ParserExactRoundingOffsets fraction expRest (by omega) (by omega) have hnAfterEq : nAfter = 65536#isize := by apply IScalar.eq_of_val_eq rw [hnAfterVal, hfractionLen, hexpRestLen] norm_num subst nAfter have hnAfterNotMin : (65536#isize) ≠ IScalar.min .Isize := by rw [IScalar.min] rcases System.Platform.numBits_eq with hbits | hbits <;> simp [IScalarTy.numBits, hbits] obtain ⟨negAfter, hnegAfter, hnegAfterVal⟩ := Aeneas.Std.WP.spec_imp_exists (HNeg.hNeg.step (65536#isize) hnAfterNotMin) have hnegAfterEq : negAfter = (-65536)#isize := by apply IScalar.eq_of_val_eq simpa using hnegAfterVal subst negAfter have hcastFractionExponent : lift (IScalar.cast .I64 ((-65536)#isize)) = ok (-65536)#i64 := by have hc := IScalar.cast_inBounds_spec .I64 ((-65536)#isize) (by constructor · rw [IScalar.min_IScalarTy_I64_eq, I64.min_eq] norm_num · rw [IScalar.max_IScalarTy_I64_eq, I64.max_eq] norm_num) obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists hc rw [hz] congr 2 apply IScalar.eq_of_val_eq simpa using hzval have haddBounds : IScalar.min .Isize <= (1#isize).val + (65536#isize).val /\ (1#isize).val + (65536#isize).val <= IScalar.max .Isize := by rcases System.Platform.numBits_eq with hbits | hbits <;> simp [IScalar.min, IScalar.max, IScalarTy.numBits, hbits] obtain ⟨totalDigits, haddDigits, htotalDigitsVal⟩ := Aeneas.Std.WP.spec_imp_exists (IScalar.add_spec haddBounds.1 haddBounds.2) have htotalDigitsEq : totalDigits = 65537#isize := by apply IScalar.eq_of_val_eq norm_num at htotalDigitsVal simpa using htotalDigitsVal subst totalDigits let exponentDigits : Slice Std.U8 := ⟨[54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8], by rcases Usize.bounds_eq with q | q <;> norm_num [q, U32.max_eq, U64.max_eq]⟩ have hsplitExponent : core.slice.Slice.split_first expRest = ok (some (101#u8, exponentDigits)) := by let expRest' : Slice Std.U8 := ⟨101#u8 :: exponentDigits.val, by rw [← hexpRest] exact expRest.property⟩ have hexpRestEq : expRest = expRest' := (Slice.eq_iff _ _).2 (by rw [hexpRest]) rw [hexpRestEq] simp [core.slice.Slice.split_first, dec2flt_model.ModelSliceSplitFirst, expRest'] have hexponentDigits : exponentDigits.val = [54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8] := by rfl obtain ⟨empty, hscientific, hempty⟩ := ParserExactRoundingScientific exponentDigits hexponentDigits have hexponentAdd : ((-65536)#i64 + 65536#i64) = ok 0#i64 := by have hb : IScalar.min .I64 <= ((-65536)#i64).val + (65536#i64).val /\ ((-65536)#i64).val + (65536#i64).val <= IScalar.max .I64 := by rw [IScalar.min_IScalarTy_I64_eq, I64.min_eq, IScalar.max_IScalarTy_I64_eq, I64.max_eq] norm_num obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists (IScalar.add_spec hb.1 hb.2) rw [hz] congr 1 apply IScalar.eq_of_val_eq simpa using hzval obtain ⟨fullOffset, hfullOffset, hfullOffsetVal⟩ := ParserExactRoundingOffsets body empty (by omega) (by rw [hempty] simp) have hfullOffsetValExact : fullOffset.val = 65545 := by rw [hfullOffsetVal, hbodyLen, hempty] rfl have hfullCastBounds : 0 <= fullOffset.val /\ fullOffset.val <= UScalar.max .Usize := by rw [hfullOffsetValExact] rcases System.Platform.numBits_eq with hbits | hbits <;> simp [UScalar.max, hbits] obtain ⟨fullLen, hcastLen0, hfullLenVal⟩ := Aeneas.Std.WP.spec_imp_exists (IScalar.hcast_inBounds_spec .Usize fullOffset hfullCastBounds) have hfullLenEq : fullLen = Slice.len body := by apply UScalar.eq_of_val_eq rw [hfullOffsetVal] at hfullLenVal simpa [hempty, Slice.len_val] using hfullLenVal subst fullLen have hcastLen : lift (IScalar.hcast .Usize fullOffset) = ok (Slice.len body) := by simpa [Aeneas.Std.lift] using hcastLen0 have htotalNonzero : ¬ (65537#isize).val = 0 := by norm_num have htotalLarge : ¬ (65537#isize).val <= (19#isize).val := by norm_num have hsubBounds : IScalar.min .Isize <= (65537#isize).val - (19#isize).val /\ (65537#isize).val - (19#isize).val <= IScalar.max .Isize := by rcases System.Platform.numBits_eq with hbits | hbits <;> simp [IScalar.min, IScalar.max, IScalarTy.numBits, hbits] obtain ⟨moreDigits, hsubDigits0, hmoreDigitsVal⟩ := Aeneas.Std.WP.spec_imp_exists (IScalar.sub_spec hsubBounds.1 hsubBounds.2) have hmoreDigitsEq : moreDigits = 65518#isize := by apply IScalar.eq_of_val_eq norm_num at hmoreDigitsVal simpa using hmoreDigitsVal subst moreDigits have hadjust := ParserExactRoundingAdjustment body hbody let pointPhase := (match (46#u8 : Std.U8) with | 46#uscalar => ok (expRest, 1#u64, 65536#isize, (-65536)#i64) | _ => ok (point, 0#u64, 0#isize, 0#i64)) have hpointMatch : pointPhase = ok (expRest, 1#u64, 65536#isize, (-65536)#i64) := by rfl have hnotEmpty : core.slice.Slice.is_empty body = ok false := by unfold core.slice.Slice.is_empty rw [show body.length = 65545 by simpa [Slice.length] using hbodyLen] rfl have hnonemptyVal : body.val ≠ [] := by intro h rw [h] at hbodyLen norm_num at hbodyLen have hmassert : massert (¬ body.val = []) = ok () := by simp [hnonemptyVal] have hpartial : num.imp.dec2flt.parse.parse_partial_number body = ok (some ({ exponent := 0#i64, mantissa := 1#u64, negative := false, many_digits := false }, Slice.len body)) := by unfold num.imp.dec2flt.parse.parse_partial_number simp [hnotEmpty, hmassert, hscan0, hnDigits, hsplitPoint, hscan1, hnAfter, hnegAfter, hcastFractionExponent] change (do let x ← pointPhase; _) = _ rw [hpointMatch] simp [haddDigits, hsplitExponent, hscientific, hexponentAdd, hfullOffset, hcastLen, htotalNonzero, htotalLarge, hsubDigits0, hadjust] rw [show core.option.Option.Insts.CoreOpsTry_traitTry.branch (some 65536#i64) = ok (core.ops.control_flow.ControlFlow.Continue 65536#i64) by rfl] change (do let exponent ← (-65536)#i64 + 65536#i64 ok (some (({ exponent, mantissa := 1#u64, negative := false, many_digits := false } : num.imp.dec2flt.decimal.Decimal), Slice.len body))) = _ rw [hexponentAdd] rfl unfold num.imp.dec2flt.parse.parse_number simp [hpartial] have hcompact : s.val = 48#u8 :: 46#u8 :: (List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8]) := by rw [hs] rfl have hslen : s.val.length = 65545 := by simp only [hs, List.length_append, List.length_replicate, List.length_cons, List.length_nil] have hfirst : core.slice.Slice.first s = ok (some 48#u8) := by unfold core.slice.Slice.first ModelSliceFirst rw [hcompact] rfl have hnonempty : s.val ≠ [] := by intro h rw [h] at hslen norm_num at hslen have hnotEmpty : core.slice.Slice.is_empty s = ok false := by unfold core.slice.Slice.is_empty rw [show s.length = 65545 by simpa [Slice.length] using hslen] rfl have hparse := parse_number_exact s hs simp [num.imp.dec2flt.dec2flt, num.imp.dec2flt.dec2flt_with_trace, core.str.Str.as_bytes, ModelStrAsBytes, hfirst, hnotEmpty, hnonempty, hparse, ParserExactRoundingFastPath] end dec2flt_model ===== HISTORICAL Tablet/ParserExactRoundingExecution.tex ===== \begin{helper}[Exact execution of the long decimal witness] Let \texttt{s} contain the ASCII bytes \texttt{0.}, followed by exactly $65{,}535$ zero bytes, and then \texttt{1e655360}. The extracted public binary64 parser returns success with the binary64 word \texttt{0x3ff0000000000000}, namely $1.0$. \end{helper} \begin{proof} By \noderef{ParserExactRoundingDigitScans}, the initial digit scan consumes the integer zero and leaves the point with accumulator zero. Splitting the point and applying the second scan consumes the $65{,}535$ fractional zeros and terminal one, leaves \texttt{e655360}, and produces mantissa one. The exact suffix-length equations supplied by \noderef{ParserExactRoundingOffsets} are as follows. The initial digit count is $65{,}545-65{,}544=1$; the after-point count is $65{,}543-7=65{,}536$; and the complete consumed length is $65{,}545$. Negating and casting the after-point count therefore gives fractional exponent $-65{,}536$, while the total digit count is $1+65{,}536=65{,}537$. Every value lies in both the 32-bit and 64-bit signed or unsigned pointer bounds admitted by the model. Splitting the exponent marker leaves the six digits \texttt{655360}. \noderef{ParserExactRoundingScientific} gives their exact parsed value $65{,}536$ and an empty remainder, so checked exponent addition gives zero. Since $65{,}537>19$, the extracted parser subtracts nineteen and obtains $65{,}518$. By \noderef{ParserExactRoundingAdjustment}, the many-digit adjustment is $-18$, which is not positive. Consequently the parser keeps the already accumulated mantissa one and sets \texttt{many\_digits} to false. The exact record is therefore exponent zero, mantissa one, negative false, and many-digits false, and the consumed length equals the input length. The first input byte is \texttt{0}, so the dispatcher takes neither sign branch. It receives the exact decimal record above and, by \noderef{ParserExactRoundingFastPath}, the ordinary fast path returns binary64 $1.0$. The dispatcher propagates that successful value, and the public \texttt{dec2flt} wrapper discards only the trace and returns the same result. \end{proof} ===== HISTORICAL Tablet/ParserExactRoundingWitness.lean ===== import Tablet.Binary64ModelDefault import Tablet.DecimalGoalVocabularyDefault import Tablet.ParserExactRoundingExecution open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxHeartbeats 0 set_option maxRecDepth 1000000 namespace dec2flt_model -- [TABLET NODE: ParserExactRoundingWitness] theorem ParserExactRoundingWitness : exists (s : Str) (x : DecimalLexeme) (f : F64), s.val = [48#u8, 46#u8] ++ List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8] /\ x = { leadingSign := none integerDigits := [0] fractionDigits := some (List.replicate 65535 0 ++ [1]) exponent := some (false, none, [6, 5, 5, 3, 6, 0]) } /\ f = (⟨BitVec.ofNat 64 4607182418800017408⟩ : F64) /\ DecimalGoalVocabularyDefault.sourceString s /\ DecimalGoalVocabularyDefault.validNumeric x /\ DecimalGoalVocabularyDefault.bytes s = DecimalGoalVocabularyDefault.renderNumeric x /\ num.imp.dec2flt.dec2flt F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64 F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64 F64.Insts.CoreOpsArithNegF64 s = ok (core.result.Result.Ok f) /\ Not (exists magnitude : F64, DecimalGoalVocabularyDefault.roundsMagnitude (DecimalGoalVocabularyDefault.exactMagnitude x) magnitude /\ DecimalGoalVocabularyDefault.signedMagnitude (DecimalGoalVocabularyDefault.lexicalNegative x) magnitude f) := by -- BODY let zeros : List Nat := List.replicate 65535 0 let fraction : List Nat := zeros ++ [1] let lexeme : DecimalLexeme := { leadingSign := none integerDigits := [0] fractionDigits := some fraction exponent := some (false, none, [6, 5, 5, 3, 6, 0]) } let witnessBytes : List Std.U8 := [48#u8, 46#u8] ++ List.replicate 65535 48#u8 ++ [49#u8, 101#u8, 54#u8, 53#u8, 53#u8, 51#u8, 54#u8, 48#u8] have witnessBytes_length : witnessBytes.length = 65545 := by simp only [witnessBytes, List.length_append, List.length_replicate, List.length_cons, List.length_nil] let witness : Str := ⟨witnessBytes, by rw [witnessBytes_length] rcases Usize.bounds_eq with q | q <;> norm_num [q, U32.max_eq, U64.max_eq]⟩ let one : F64 := ⟨BitVec.ofNat 64 4607182418800017408⟩ have byteArray_toList_eq_data (b : ByteArray) : b.toList = b.data.toList := by have aux (i : Nat) (r : List UInt8) (hi : i ≤ b.size) : ByteArray.toList.loop b i r = r.reverse ++ b.data.toList.drop i := by fun_induction ByteArray.toList.loop b i r with | case1 i r h ih => rw [ih (by omega)] simp only [List.reverse_cons, List.append_assoc, List.singleton_append] have hlen : i < b.data.toList.length := by simpa using h rw [List.drop_eq_getElem_cons hlen] congr cases b rename_i data exact getElem!_pos data i (by simpa using h) | case2 i r h => have hieq : i = b.size := by omega simp [hieq] unfold ByteArray.toList simpa using aux 0 [] (Nat.zero_le _) let witnessString : String := String.ofList (['0', '.'] ++ List.replicate 65535 '0' ++ ['1', 'e', '6', '5', '5', '3', '6', '0']) have utf8_ofList (l : List Char) : (String.ofList l).toUTF8.toList = l.flatMap String.utf8EncodeChar := by rw [String.toUTF8, String.toByteArray_ofList] rw [byteArray_toList_eq_data] simp only [List.utf8Encode, List.toList_data_toByteArray] have utf8_zeros (n : Nat) : (List.replicate n '0').flatMap String.utf8EncodeChar = List.replicate n (48 : UInt8) := by rw [List.flatMap_replicate] have h : String.utf8EncodeChar '0' = [(48 : UInt8)] := by decide rw [h, List.flatten_replicate_singleton] have witness_source : DecimalGoalVocabularyDefault.sourceString witness := by dsimp only [DecimalGoalVocabularyDefault] constructor · change witnessBytes.length ≤ 9223372036854775807 rw [witnessBytes_length] norm_num · refine ⟨witnessString, ?_⟩ simp only [witnessString] rw [utf8_ofList] simp only [witness, witnessBytes, List.flatMap_append, utf8_zeros, List.flatMap_cons, List.flatMap_nil, List.map_append, List.map_replicate, List.map_cons, List.map_nil] have h0 : (String.utf8EncodeChar '0').map UInt8.toNat = [48] := by decide have hd : (String.utf8EncodeChar '.').map UInt8.toNat = [46] := by decide have h1 : (String.utf8EncodeChar '1').map UInt8.toNat = [49] := by decide have he : (String.utf8EncodeChar 'e').map UInt8.toNat = [101] := by decide have h6 : (String.utf8EncodeChar '6').map UInt8.toNat = [54] := by decide have h5 : (String.utf8EncodeChar '5').map UInt8.toNat = [53] := by decide have h3 : (String.utf8EncodeChar '3').map UInt8.toNat = [51] := by decide rw [h0, hd, h1, he, h6, h5, h3] have u48 : (48#u8 : Std.U8).val = 48 := by decide have u46 : (46#u8 : Std.U8).val = 46 := by decide have u49 : (49#u8 : Std.U8).val = 49 := by decide have u101 : (101#u8 : Std.U8).val = 101 := by decide have u54 : (54#u8 : Std.U8).val = 54 := by decide have u53 : (53#u8 : Std.U8).val = 53 := by decide have u51 : (51#u8 : Std.U8).val = 51 := by decide have ui48 : UInt8.toNat (48 : UInt8) = 48 := by decide rw [u48, u46, u49, u101, u54, u53, u51, ui48] rfl have zeros_fold : zeros.foldl (fun a d => 10 * a + d) 0 = 0 := by have fold_zeros (k : Nat) : (List.replicate k 0).foldl (fun a d => 10 * a + d) 0 = 0 := by induction k with | zero => rfl | succ k ih => simpa [List.replicate_succ] using ih exact fold_zeros 65535 have fraction_length : fraction.length = 65536 := by simp only [fraction, zeros, List.length_append, List.length_replicate, List.length_cons, List.length_nil] have significand_fold : ([0] ++ fraction).foldl (fun a d => 10 * a + d) 0 = 1 := by rw [List.foldl_append] simp only [List.foldl_cons, List.foldl_nil, mul_zero, zero_add] simp only [fraction] rw [List.foldl_append, zeros_fold] rfl have lexeme_valid : DecimalGoalVocabularyDefault.validNumeric lexeme := by have zeros_mem {d : Nat} (h : d ∈ zeros) : d = 0 := by simp only [zeros, List.mem_replicate] at h exact h.2 dsimp only [DecimalGoalVocabularyDefault] constructor · simp [lexeme] constructor · simp only [lexeme] intro d hd simp only [fraction] at hd rcases List.mem_append.mp hd with hd | hd · rw [zeros_mem hd] norm_num · simp only [List.mem_singleton] at hd omega constructor · left simp [lexeme] · simp [lexeme] have lexeme_render : DecimalGoalVocabularyDefault.bytes witness = DecimalGoalVocabularyDefault.renderNumeric lexeme := by dsimp only [DecimalGoalVocabularyDefault] simp only [lexeme, witness, witnessBytes, fraction, zeros, List.map_append, List.map_cons, List.map_nil, List.map_replicate, Bool.false_eq_true, reduceIte, Nat.reduceAdd, List.nil_append, List.cons_append] norm_num have lexeme_exact : DecimalGoalVocabularyDefault.exactMagnitude lexeme = (10 : Real) ^ (589824 : Nat) := by dsimp only [DecimalGoalVocabularyDefault, lexeme] rw [significand_fold, fraction_length] norm_num rfl let infinityBits : Nat := 2047 * 2 ^ 52 have huge_target_is_infinity (w : F64) (hw : DecimalGoalVocabularyDefault.roundsMagnitude ((10 : Real) ^ (589824 : Nat)) w) : w.val = infinityBits := by dsimp only [DecimalGoalVocabularyDefault] at hw rcases hw with ⟨_, _, hw⟩ by_contra hne have hne' : w.val ≠ 2047 * 2 ^ 52 := by simpa [infinityBits] using hne rw [if_neg hne'] at hw have hthreshold : ((2 : Real) ^ (1024 : Nat)) - ((2 : Real) ^ (970 : Nat)) ≤ (10 : Real) ^ (589824 : Nat) := by calc (2 : Real) ^ 1024 - 2 ^ 970 ≤ 2 ^ 1024 := sub_le_self _ (by positivity) _ ≤ 10 ^ 1024 := by gcongr <;> norm_num _ ≤ 10 ^ 589824 := by rw [show (589824 : Nat) = 1024 + 588800 by norm_num, pow_add] exact le_mul_of_one_le_right (by positivity) (one_le_pow₀ (by norm_num)) exact (not_lt_of_ge hthreshold) hw.1 have hRun : num.imp.dec2flt.dec2flt F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64 F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64 F64.Insts.CoreOpsArithNegF64 witness = ok (core.result.Result.Ok one) := by exact ParserExactRoundingExecution witness (by rfl) refine ⟨witness, lexeme, one, ?_, ?_, rfl, witness_source, lexeme_valid, lexeme_render, hRun, ?_⟩ · rfl · rfl · rintro ⟨magnitude, hround, hsigned⟩ rw [lexeme_exact] at hround have hinf := huge_target_is_infinity magnitude hround dsimp only [DecimalGoalVocabularyDefault, lexeme, one] at hsigned rw [hinf] at hsigned have bad := hsigned.2 change (4607182418800017408 : Nat) = infinityBits + 0 at bad norm_num [infinityBits] at bad ===== HISTORICAL Tablet/ParserExactRoundingWitness.tex ===== \begin{theorem}[Concrete failure of exact rounding] \label{thm:ParserExactRoundingWitness} There are a model string $s$, a decimal lexeme $x$, and a binary64 value $f$ with the following concrete values and properties. The bytes of $s$ are the ASCII encoding of \[ 0.\underbrace{00\cdots0}_{65535\text{ zeros}}1e655360. \] The lexeme $x$ has no sign, integer digits $[0]$, fractional digits consisting of $65535$ zeros followed by $1$, and the unsigned decimal exponent $655360$. The value $f$ has binary64 word $4607182418800017408$, namely the word for $1.0$. The string is a source string, the lexeme is valid, rendering the lexeme gives exactly the bytes of $s$, and the extracted public parser returns $f$ successfully on $s$. Nevertheless, there is no binary64 magnitude which both rounds the exact magnitude of $x$ according to \texttt{roundsMagnitude} and acquires the lexical sign of $x$ to yield $f$. \end{theorem} \begin{proof} Let $s$, $x$, and $f$ have the concrete values in the statement. Their byte, lexeme, and word equalities are definitional. The byte list has length $65545$, hence satisfies the model string bound. Encode the displayed ASCII string character by character. ASCII `0', `.', `1', `e', `6', `5', and `3' encode respectively to bytes $48,46,49,101,54,53,51$; mapping the repeated zero characters therefore gives precisely the symbolic repeated-byte segment. This supplies the string required by \texttt{sourceString} in \noderef{DecimalGoalVocabularyDefault}. Every integer and fractional digit lies below ten, the integer part is nonempty, and the exponent digit list is nonempty, so $x$ satisfies \texttt{validNumeric}. Expanding \texttt{renderNumeric} and the ASCII digit encoding yields the stated bytes. The parser execution is exactly \noderef{ParserExactRoundingExecution}: its hypothesis is the concrete byte equality already established, and its conclusion is the required successful return of the word for $1.0$. It remains to show that the contract conclusion is false. Folding the $65535$ fractional zeros leaves zero, appending the final digit gives significand $1$, and the fractional length is $65536$. Thus \texttt{exactMagnitude} from \noderef{DecimalGoalVocabularyDefault} is $10^{655360-65536}=10^{589824}$. Suppose some binary64 magnitude rounded that real and then, with the positive lexical sign, yielded $f$. By \noderef{Binary64ModelDefault}, every finite binary64 value represented by a word other than positive infinity denotes a real strictly below $2^{1024}-2^{970}$. But \[ 2^{1024}-2^{970}\le 2^{1024}\le 10^{1024}\le 10^{589824}. \] Consequently the strict upper condition in \texttt{roundsMagnitude} rules out every non-infinity word, so the magnitude word must be the positive-infinity word $2047\cdot2^{52}$. Since $x$ is nonnegative, \texttt{signedMagnitude} would then require that word to equal the word of $f$, namely $4607182418800017408$. Direct arithmetic shows these words are unequal. This contradiction proves the final negation and hence all clauses of the witness theorem. \end{proof} ===== HISTORICAL Tablet/SlowAccumulatedRoundingDecimal.lean ===== import Tablet.SlowAccumulatedRoundingCount import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxHeartbeats 2000000 namespace dec2flt_model -- [TABLET NODE: SlowAccumulatedRoundingDecimal] theorem SlowAccumulatedRoundingDecimal (s : Slice Std.U8) (hs : s.val = List.replicate 2147483648 49#u8) : exists a : Array Std.U8 768#usize, num.imp.dec2flt.decimal_seq.parse_decimal_seq s = ok { num_digits := 768#usize decimal_point := (-2147483648)#i32 truncated := true digits := a } := by -- BODY let d0 : num.imp.dec2flt.decimal_seq.DecimalSeq := { num_digits := 0#usize decimal_point := 0#i32 truncated := false digits := Array.repeat 768#usize 0#u8 } have hdefault : num.imp.dec2flt.decimal_seq.DecimalSeq.Insts.CoreDefaultDefault.default = ok d0 := by rfl have hsLen : s.val.length = 2147483648 := by rw [hs] exact List.length_replicate have hnonempty : 0 < s.val.length := by omega have hidx0 : Slice.index_usize s 0#usize = ok 49#u8 := by have hget : s.val[0]'(by omega) = 49#u8 := by simpa only [hs, List.getElem_replicate] obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists (Slice.index_usize_spec s 0#usize (by simpa [Slice.length] using hnonempty)) rw [hz] congr exact hzval.trans hget have hleading : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop0 s = ok s := by unfold num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop0 rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop0.body, core.slice.Slice.is_empty, hnonempty, hidx0] obtain ⟨empty, d1, hscan, hempty, hdcount, hdpoint, hdtrunc⟩ := SlowAccumulatedRoundingCount s d0 hs rfl rfl rfl have hemptyLen : empty.val.length = 0 := by rw [hempty]; rfl have hemptyTest : core.slice.Slice.is_empty empty = ok true := by simp [core.slice.Slice.is_empty, hempty] have hsUsize : Slice.len s = 2147483648#usize := by apply UScalar.eq_of_val_eq simpa [Slice.len_val] using hsLen have hemptyUsize : Slice.len empty = 0#usize := by apply UScalar.eq_of_val_eq simpa [Slice.len_val] using hemptyLen have hconsumed : (2147483648#usize : Std.Usize) - 0#usize = ok 2147483648#usize := by obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists (UScalar.sub_spec (x := 2147483648#usize) (y := 0#usize) (by norm_num)) rw [hz] congr 2 apply UScalar.eq_of_val_eq simpa using hzval have hpred : (2147483648#usize : Std.Usize) - 1#usize = ok 2147483647#usize := by obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists (UScalar.sub_spec (x := 2147483648#usize) (y := 1#usize) (by norm_num)) rw [hz] congr 2 apply UScalar.eq_of_val_eq simpa using hzval have hlast : Slice.index_usize s 2147483647#usize = ok 49#u8 := by have hget : s.val[2147483647]'(by omega) = 49#u8 := by simpa only [hs, List.getElem_replicate] obtain ⟨z, hz, hzval⟩ := Aeneas.Std.WP.spec_imp_exists (Slice.index_usize_spec s 2147483647#usize (by simp [Slice.length, hsLen])) rw [hz] congr exact hzval.trans hget have hzeros : num.imp.dec2flt.decimal_seq.count_trailing_zeros s 2147483648#usize = ok 0#usize := by unfold num.imp.dec2flt.decimal_seq.count_trailing_zeros unfold num.imp.dec2flt.decimal_seq.count_trailing_zeros_loop rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.decimal_seq.count_trailing_zeros_loop.body, hpred, hlast] rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.decimal_seq.count_trailing_zeros_loop.body] have hcastZero : UScalar.hcast .I32 (0#usize : Std.Usize) = 0#i32 := by rw [IScalar.eq_equiv_bv_eq] apply BitVec.eq_of_toNat_eq simp only [UScalar.hcast, BitVec.zeroExtend_eq_setWidth, BitVec.toNat_setWidth, UScalar.bv_toNat, I32.ofInt_bv, BitVec.toNat_ofInt] norm_num have hcastN : UScalar.hcast .I32 (2147483648#usize : Std.Usize) = (-2147483648)#i32 := by rw [IScalar.eq_equiv_bv_eq] apply BitVec.eq_of_toNat_eq simp only [UScalar.hcast, BitVec.zeroExtend_eq_setWidth, BitVec.toNat_setWidth, UScalar.bv_toNat, I32.ofInt_bv, BitVec.toNat_ofInt] norm_num rfl have haddZero : ((0#i32 : Std.I32) + 0#i32) = ok 0#i32 := by rfl have hsubZero : ((2147483648#usize : Std.Usize) - 0#usize) = ok 2147483648#usize := hconsumed have haddMin : ((0#i32 : Std.I32) + (-2147483648)#i32) = ok (-2147483648)#i32 := by rfl have hlarge : (2147483648#usize : Std.Usize) > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS := by rw [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def] norm_num have hcleanup (a : Array Std.U8 768#usize) : num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop1 { start := 768#usize, «end» := num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW } a = ok a := by have hlt : core.iter.range.StepUsize.partialOrdInst.lt 768#usize 19#usize = ok false := by rfl unfold num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop1 rw [Aeneas.Std.loop.eq_1] simp [num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop1.body, core.iter.range.IteratorRange.next, num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW.eq_def, hlt] refine ⟨d1.digits, ?_⟩ unfold num.imp.dec2flt.decimal_seq.parse_decimal_seq simp [hdefault, hleading, hscan, hempty, hemptyTest, hdcount, hsUsize, hemptyUsize, hconsumed, hzeros, hcastZero, hdpoint, haddZero, hsubZero, hcastN, haddMin, hlarge, hcleanup, hdtrunc, Aeneas.Std.lift, num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def] end dec2flt_model ===== HISTORICAL Tablet/SlowAccumulatedRoundingDecimal.tex ===== \begin{lemma}[Exact long decimal-sequence result] Let \(N=2147483648\). If an Aeneas byte slice \(s\) satisfies \(s.\mathit{val}=\operatorname{replicate}(N,49\#\mathrm{u8})\), then there is an array \(a\) of 768 unsigned bytes for which \texttt{parse\_decimal\_seq(s)} returns the record \[ \{\mathit{num\_digits}=768,\ \mathit{decimal\_point}=-2147483648,\ \mathit{truncated}=\mathrm{true},\ \mathit{digits}=a\}. \] \end{lemma} \begin{proof} Unfold the decimal parser in \noderef{num_imp_dec2flt_decimal_seq_parse_decimal_seq}. Its default record, from \noderef{num_imp_dec2flt_decimal_seq_DecimalSeq_Insts_CoreDefaultDefault_default}, has zero count, zero point, false truncation, and a 768-byte zero array. The input is nonempty. Its bounds-checked zeroth byte is \(49\), so the leading-zero loop sees a byte unequal to \(48\) and immediately returns the original slice. Apply \noderef{SlowAccumulatedRoundingCount} to the following digit loop. It returns an empty residual slice and a sequence \(d_1\) with exact count \(N\), zero point, and false truncation. During those iterations the first 768 digits are the only array entries eligible for update; each scanned digit is \(49-48=1\), and later iterations leave the bounded array alone. Denote the resulting array by \(a=d_1.\mathit{digits}\). The theorem only needs this array's fixed type, not an extensional expansion of its 768 entries. The consumed length is \(N-0=N\). The last bounds-checked input byte, at index \(N-1=2147483647\), is \(49\), not ASCII zero; hence \noderef{num_imp_dec2flt_decimal_seq_count_trailing_zeros} takes one loop step and returns zero trailing zeroes. Casting that zero to \texttt{i32} gives zero. The parser's cast of the consumed count is the 32-bit two's-complement narrowing \[ \operatorname{hcast}_{\mathrm{i32}}(2147483648) = -2147483648. \] This equality follows directly by comparing the 32-bit vectors, whose unsigned value on both sides is \(2^{31}\). Adding it to the old point zero does not overflow and gives \texttt{i32::MIN}. Since \(N>768\), the parser exposes \(\min(N,768)=768\) as its final digit count and changes the truncation flag to true. The cleanup range starts at 768 and ends at the fixed \texttt{MAX\_DIGITS\_WITHOUT\_OVERFLOW} value 19, so its comparison is false and it performs no update. Substitution into the cited parser definition gives exactly the displayed record. \end{proof} ===== HISTORICAL Tablet/SlowAccumulatedRoundingSlow.lean ===== import Tablet.SlowAccumulatedRoundingDecimal import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatExtU64 import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_BITS import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SIG_TOTAL_BITS import Tablet.ModelF64MantissaDigits import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2 import Tablet.num_imp_dec2flt_slow_parse_long_mantissa import Tablet.num_imp_traits_Float_EXP_BITS_default import Tablet.num_imp_traits_Float_EXP_SAT_default import Tablet.num_imp_traits_Float_INFINITE_POWER_default import Tablet.num_imp_traits_Float_SIG_BITS_default open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxHeartbeats 2000000 namespace dec2flt_model -- [TABLET NODE: SlowAccumulatedRoundingSlow] theorem SlowAccumulatedRoundingSlow (s : Slice Std.U8) (hs : s.val = List.replicate 2147483648 49#u8) : num.imp.dec2flt.slow.parse_long_mantissa F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 s = ok { m := 0#u64, p_biased := 0#i32 } := by -- BODY obtain ⟨a, hdecimal⟩ := SlowAccumulatedRoundingDecimal s hs have hsig53 : F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.SIG_TOTAL_BITS = ok 53#u32 := by simp only [F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.SIG_TOTAL_BITS.eq_def, core.f64.F64.MANTISSA_DIGITS, ModelF64MantissaDigits, Binary64ModelDefault] have hinf : F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.INFINITE_POWER = ok 2047#i32 := by simp [F64.Insts.Dec2flt_modelNumImpTraitsFloatU64, num.imp.traits.Float.INFINITE_POWER.default.eq_def, num.imp.traits.Float.EXP_SAT.default.eq_def, num.imp.traits.Float.EXP_BITS.default.eq_def, num.imp.traits.Float.SIG_BITS.default.eq_def, F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.BITS.eq_def, hsig53] have h : (do let x ← 53#u32 - 1#u32 let x ← 64#u32 - x let x ← x - 1#u32 let x ← 1#u32 <<< x let i ← x - 1#u32 ok (UScalar.hcast .I32 i)) ⦃ x => x = 2047#i32 ⦄ := by step step step step step apply IScalar.eq_of_val_eq have hi : i.val = 2047 := by scalar_tac have hs := UScalar.hcast_inBounds_spec .I32 i (by scalar_tac) rw [hi] at hs simpa [Aeneas.Std.lift, WP.spec_ok] using hs obtain ⟨x, hx, hxt⟩ := Aeneas.Std.WP.spec_imp_exists h simpa [hxt] using hx have hzero : num.imp.dec2flt.common.BiasedFp.zero_pow2 0#i32 = ok { m := 0#u64, p_biased := 0#i32 } := by rfl have hinfFp : num.imp.dec2flt.common.BiasedFp.zero_pow2 2047#i32 = ok { m := 0#u64, p_biased := 2047#i32 } := by rfl let infPower := F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.INFINITE_POWER have hinf' : infPower = ok 2047#i32 := hinf unfold num.imp.dec2flt.slow.parse_long_mantissa rw [hzero] simp only [bind_tc_ok] change (do let i ← infPower; _) = _ rw [hinf'] simp only [bind_tc_ok] rw [hinfFp] simp only [bind_tc_ok] rw [hdecimal] simp end dec2flt_model ===== HISTORICAL Tablet/SlowAccumulatedRoundingSlow.tex ===== \begin{lemma}[Early slow-path zero pair] Let \(N=2147483648\). If an Aeneas byte slice \(s\) satisfies \(s.\mathit{val}=\operatorname{replicate}(N,49\#\mathrm{u8})\), then the binary64 specialization of \texttt{parse\_long\_mantissa(s)} returns \[ \{\mathit{m}=0\#\mathrm{u64},\ \mathit{p\_biased}=0\#\mathrm{i32}\}. \] \end{lemma} \begin{proof} By \noderef{SlowAccumulatedRoundingDecimal}, the decimal-sequence parser returns a record whose decimal point is \(\mathrm{i32::MIN}\), digit count is 768, and truncation flag is true. The exact binary64 mantissa-digit constant in \noderef{ModelF64MantissaDigits} gives 53 total significand bits. Unfolding the default trait computations in \noderef{F64_Insts_Dec2flt_modelNumImpTraitsFloatU64} then evaluates the binary64 infinite biased exponent to 2047: subtracting one from 53 leaves 52, subtracting 52 and then one from 64 leaves 11, and \(2^{11}-1=2047\). Every subtraction and shift lies within its displayed unsigned scalar range. Now unfold \noderef{num_imp_dec2flt_slow_parse_long_mantissa}. Its two calls to \noderef{num_imp_dec2flt_common_BiasedFp_zero_pow2} first construct the zero pair with biased exponent zero and then the infinity pair with biased exponent 2047. After the decimal parser result is substituted, the first comparison in the slow helper is \[ -2147483648 < -324, \] which is true. Therefore the early decimal-point branch returns the previously constructed zero pair before inspecting the digit array or entering any later slow-path arithmetic. This is the claimed normal result. \end{proof} ===== HISTORICAL Tablet/SlowAccumulatedRoundingWitness.lean ===== import Tablet.SlowAccumulatedRoundingLexical import Tablet.SlowAccumulatedRoundingSlow import Tablet.SlowAccumulatedRoundingMagnitude open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false set_option maxHeartbeats 2000000 namespace dec2flt_model -- [TABLET NODE: SlowAccumulatedRoundingWitness] theorem SlowAccumulatedRoundingWitness : exists (s : Slice Std.U8) (x : DecimalLexeme), s.val = List.replicate 2147483648 49#u8 /\ x = { leadingSign := none integerDigits := List.replicate 2147483648 1 fractionDigits := none exponent := none } /\ Not (SourceValidByteSlice s -> x.leadingSign = none -> DecimalGoalVocabularyDefault.validNumeric x -> DecimalGoalVocabularyDefault.bytes s = DecimalGoalVocabularyDefault.renderNumeric x -> num.imp.dec2flt.slow.parse_long_mantissa F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 s = ok { m := 0#u64, p_biased := 0#i32 } -> exists target : F64, DecimalGoalVocabularyDefault.assembledWord { m := 0#u64, p_biased := 0#i32 } target /\ DecimalGoalVocabularyDefault.roundsMagnitude (DecimalGoalVocabularyDefault.accumulatedMagnitude x) target) := by -- BODY obtain ⟨s, x, hs, hx, hsource, hsign, hvalid, hrender⟩ := SlowAccumulatedRoundingLexical have hslow := SlowAccumulatedRoundingSlow s hs obtain ⟨_, hnoTarget⟩ := SlowAccumulatedRoundingMagnitude x hx refine ⟨s, x, hs, hx, ?_⟩ intro hmatrix exact hnoTarget (hmatrix hsource hsign hvalid hrender hslow) end dec2flt_model ===== HISTORICAL Tablet/SlowAccumulatedRoundingWitness.tex ===== \begin{lemma}[Concrete slow accumulated-rounding witness] There are an Aeneas byte slice \(s\) and decimal lexeme \(x\) such that \[ \begin{aligned} s.\mathit{val}&=\operatorname{replicate}(2147483648,49\#\mathrm{u8}),\\ x&=(\mathrm{none},\operatorname{replicate}(2147483648,1), \mathrm{none},\mathrm{none}), \end{aligned} \] and the following implication is false: \[ \begin{aligned} &s\text{ is source-valid} \mathbin{\Longrightarrow}x.\mathit{leadingSign}=\mathrm{none} \mathbin{\Longrightarrow}x\text{ is valid numeric syntax}\\ &\mathbin{\Longrightarrow} \mathit{bytes}(s)=\mathit{renderNumeric}(x) \mathbin{\Longrightarrow} \texttt{parse\_long\_mantissa}(s) =\texttt{ok }\{\mathit{m}=0\#\mathrm{u64}, \mathit{p\_biased}=0\#\mathrm{i32}\}\\ &\mathbin{\Longrightarrow}\exists t:\mathrm{F64},\quad \mathit{assembledWord} (\{\mathit{m}=0\#\mathrm{u64},\mathit{p\_biased}=0\#\mathrm{i32}\},t) \ \land\ \mathit{roundsMagnitude}(\mathit{accumulatedMagnitude}(x),t). \end{aligned} \] Here the parser call is its binary64 specialization; the bytes/rendering equality says exactly that the rendering of \(x\) is the observed content of \(s\). \end{lemma} \begin{proof} Choose the slice and lexeme supplied by \noderef{SlowAccumulatedRoundingLexical}. That lemma gives source validity, absence of a sign, numeric validity, and exact byte rendering, together with the two displayed replicate equalities. Applying \noderef{SlowAccumulatedRoundingSlow} to the slice equality gives the normal slow-parser result \(\{\mathit{m}=0,\mathit{p\_biased}=0\}\). Assume for contradiction that the displayed implication holds. Apply it to the source validity, no-leading-sign, valid-syntax, and exact-rendering facts from the lexical lemma, and then to the slow-parser result above. It yields a binary64 target that is both the unrestricted assembly of the zero pair and a rounding target of the accumulated magnitude of \(x\). But \noderef{SlowAccumulatedRoundingMagnitude}, applied to the displayed equality for \(x\), says that no such target exists. This contradiction proves that the implication is false for the chosen \(s\) and \(x\). \end{proof} ===== HISTORICAL Tablet/NumberHelperDigitScanSafeLength.lean ===== import Tablet.Assumptions import Tablet.NumberHelperEightDigitWord import Tablet.NumberHelperEightDigitWordAccepted import Tablet.NumberHelperParseEightDigitsSafe import Tablet.NumberHelperReadEightBytes import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_read_u64 import Tablet.num_imp_dec2flt_common_is_8digits import Tablet.num_imp_dec2flt_parse_parse_8digits import Tablet.num_imp_dec2flt_parse_try_parse_digits open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: NumberHelperDigitScanSafeLength] theorem NumberHelperDigitScanSafeLength : forall (s : Slice Std.U8) (initial : Std.U64) (digits tail : List Std.U8), s.val = digits ++ tail -> (forall b, List.Mem b digits -> 48 <= b.val /\ b.val <= 57) -> (forall b rest, tail = b :: rest -> Not (48 <= b.val /\ b.val <= 57)) -> s.val.length <= 9223372036854120458 -> exists (value : Std.U64) (rest : Slice Std.U8), num.imp.dec2flt.parse.try_parse_digits s initial = ok (rest, value) /\ rest.val = tail := by -- BODY intro s initial digits tail hs hdigits htail hlen have fast : forall (t : Slice Std.U8) (a : Std.U64) (ds : List Std.U8), t.val = ds ++ tail -> (forall b, List.Mem b ds -> 48 <= b.val /\ b.val <= 57) -> t.val.length <= 9223372036854120458 -> num.imp.dec2flt.parse.try_parse_digits_loop0 t a ⦃ p => exists rem : List Std.U8, p.1.val = rem ++ tail /\ (forall b, List.Mem b rem -> 48 <= b.val /\ b.val <= 57) /\ p.1.val.length <= 9223372036854120458 ⦄ := by intro t a ds htds hds htlen unfold num.imp.dec2flt.parse.try_parse_digits_loop0 apply Aeneas.Std.loop.spec_decr_nat (fun p : Slice Std.U8 × Std.U64 => p.1.length) (fun p => exists rem : List Std.U8, p.1.val = rem ++ tail /\ (forall b, List.Mem b rem -> 48 <= b.val /\ b.val <= 57) /\ p.1.val.length <= 9223372036854120458) (fun p => exists rem : List Std.U8, p.1.val = rem ++ tail /\ (forall b, List.Mem b rem -> 48 <= b.val /\ b.val <= 57) /\ p.1.val.length <= 9223372036854120458) (fun p => num.imp.dec2flt.parse.try_parse_digits_loop0.body p.1 p.2) (t, a) · intro p hp rcases p with ⟨u, x⟩ rcases hp with ⟨rem, hurem, hrem, hulen⟩ change u.val = rem ++ tail at hurem change u.val.length <= 9223372036854120458 at hulen simp [num.imp.dec2flt.parse.try_parse_digits_loop0.body, WP.spec_ok, Slice.length] split · rename_i h8 obtain ⟨chunk, hread, hbyte⟩ := NumberHelperReadEightBytes u h8 rw [hread] simp [num.imp.dec2flt.common.is_8digits, Aeneas.Std.lift] split · rename_i haccepted have haccepted : num.imp.dec2flt.common.is_8digits chunk = ok true := by simp [num.imp.dec2flt.common.is_8digits, Aeneas.Std.lift, haccepted] have hrem8 : 8 <= rem.length := by by_contra hn have hrem_lt : rem.length < 8 := by omega have htail_pos : 0 < tail.length := by by_contra hzero have ht0 : tail = [] := List.eq_nil_of_length_eq_zero (by omega) have heq := congrArg List.length hurem simp [ht0] at heq omega obtain ⟨b, rest, htail_eq⟩ := List.exists_cons_of_length_pos htail_pos have hindex : rem.length < u.val.length := by omega have hbyte_eq := hbyte rem.length hrem_lt have hword_digit := NumberHelperEightDigitWord chunk haccepted rem.length hrem_lt have hu_digit : 48 <= (u.val[rem.length]'hindex).val /\ (u.val[rem.length]'hindex).val <= 57 := by omega have hu_eq : (u.val[rem.length]'hindex) = b := by simp [hurem, htail_eq] rw [hu_eq] at hu_digit exact (htail b rest htail_eq) hu_digit obtain ⟨z, hparse⟩ := NumberHelperParseEightDigitsSafe chunk haccepted rw [hparse] simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index, Slice.drop, Slice.length, WP.spec_ok, h8] constructor · refine ⟨rem.drop 8, ?_, ?_, ?_⟩ · rw [hurem, List.drop_append_of_le_length hrem8] · intro b hb exact hrem b (List.mem_of_mem_drop hb) · omega · omega · simp [WP.spec_ok] exact ⟨rem, hurem, hrem, hulen⟩ · exact ⟨rem, hurem, hrem, hulen⟩ · exact ⟨ds, htds, hds, htlen⟩ have scalar : forall (t : Slice Std.U8) (a : Std.U64) (rem : List Std.U8), t.val = rem ++ tail -> (forall b, List.Mem b rem -> 48 <= b.val /\ b.val <= 57) -> t.val.length <= 9223372036854120458 -> num.imp.dec2flt.parse.try_parse_digits_loop1 t a 0#usize ⦃ p => p.2.val = rem.length ⦄ := by intro t a rem htrem hrem htlen unfold num.imp.dec2flt.parse.try_parse_digits_loop1 apply Aeneas.Std.loop.spec_decr_nat (fun p : Std.U64 × Std.Usize => rem.length - p.2.val) (fun p => p.2.val <= rem.length) (fun p => p.2.val = rem.length) (fun p => num.imp.dec2flt.parse.try_parse_digits_loop1.body t p.1 p.2) (a, 0#usize) · intro p hp rcases p with ⟨x, count⟩ change count.val <= rem.length at hp simp [num.imp.dec2flt.parse.try_parse_digits_loop1.body, WP.spec_ok, Slice.length] split · rename_i hcount_t step by_cases hinside : count.val < rem.length · have hi_mem : List.Mem i1 rem := by have hi_eq : i1 = rem[count.val]'hinside := by rw [i1_post] simp [htrem, hinside] rw [hi_eq] exact List.getElem_mem _ have hi_digit := hrem i1 hi_mem step have hi2_val : i2.val = i1.val - 48 := by rw [i2_post] rw [core.num.U8.wrapping_sub_val_eq] simp only [UScalar.size_UScalarTyU8, U8.size_eq] norm_num omega have hi2_lt : i2.val < 10 := by omega simp [hi2_lt] step step step step step omega · have hcount_eq : count.val = rem.length := by omega have htail_pos : 0 < tail.length := by have hlen_eq := congrArg List.length htrem simp at hlen_eq omega obtain ⟨b, rest, htail_eq⟩ := List.exists_cons_of_length_pos htail_pos have hi_eq : i1 = b := by rw [i1_post] simp [htrem, htail_eq, hcount_eq] have hb_not := htail b rest htail_eq step have hi2_not : Not (i2.val < 10) := by rw [i2_post, hi_eq] rw [core.num.U8.wrapping_sub_val_eq] simp only [UScalar.size_UScalarTyU8, U8.size_eq] norm_num scalar_tac simp [hi2_not, WP.spec_ok, hcount_eq] · rename_i hcount_not simp [WP.spec_ok] have hlen_eq := congrArg List.length htrem simp at hlen_eq omega · simp unfold num.imp.dec2flt.parse.try_parse_digits have hf := fast s initial digits hs hdigits hlen obtain ⟨p, hfast, hfp⟩ := Aeneas.Std.WP.spec_imp_exists hf rcases p with ⟨s1, x1⟩ rcases hfp with ⟨rem, hs1, hrem, hs1len⟩ change s1.val = rem ++ tail at hs1 change s1.val.length <= 9223372036854120458 at hs1len have hsc := scalar s1 x1 rem hs1 hrem hs1len obtain ⟨q, hscalar, hcount⟩ := Aeneas.Std.WP.spec_imp_exists hsc rcases q with ⟨x2, count⟩ change count.val = rem.length at hcount have hcount_le : count.val <= s1.val.length := by rw [hcount, hs1] simp simp [hfast, hscalar] simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index, Slice.drop, Slice.length, hcount_le] rw [hcount, hs1, List.drop_append_of_le_length (Nat.le_refl _)] simp end dec2flt_model ===== HISTORICAL Tablet/NumberHelperDigitScanSafeLength.tex ===== \begin{lemma}[Safe and exact digit scanning] Let a byte slice of length at most $9223372036854120458$ be the concatenation of a list of ASCII decimal digits and a tail whose first byte, if any, is not an ASCII decimal digit. For every initial unsigned accumulator, the extracted \texttt{try\_parse\_digits} returns normally, and its returned slice is exactly that tail. \end{lemma} \begin{proof} Put $C=9223372036854120458$ and let $L$ be the input length. By \noderef{Assumptions}, the target has 64-bit \texttt{usize} and \texttt{isize}; in particular $L\leq C<2^{63}<2^{64}$. We audit the two loops in \noderef{num_imp_dec2flt_parse_try_parse_digits}. In the first loop, a read is made only when at least eight bytes remain. Thus \noderef{SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_read_u64} copies an in-bounds eight-byte prefix and returns its little-endian word. We first show that the predicate in \noderef{num_imp_dec2flt_common_is_8digits} accepts exactly when all eight bytes are digits. Soundness in the forward direction is the only subtle part. Write the bytes as $b_0,\ldots,b_7$. In the wrapping subtraction by eight copies of \texttt{0x30}, induct from the least significant byte. The incoming borrow is initially zero. If $b_i<48$, the result byte is in $[208,255]$, contradicting the accepted word's zero \texttt{0x80} bit. Consequently $b_i\geq48$, no borrow leaves that byte, and the result-byte high bit further gives $b_i\leq175$. In the wrapping addition by eight copies of \texttt{0x46}, the incoming carry is likewise initially zero. Under the preceding bound, $b_i\geq58$ would produce a byte in $[128,245]$, again contradicting the zero high bit. Hence $b_i\leq57$ and no carry leaves the byte. Both inductions cross all seven byte boundaries, so there is no false positive. Conversely, bytes in $[48,57]$ plainly create neither a borrow nor a high bit in either operation, so the test accepts them. On an accepted word, the checked subtraction in \noderef{num_imp_dec2flt_parse_parse_8digits} produces a word $v'<2^{60}$. Its checked multiplication by ten is below $10\cdot2^{60}<2^{64}$; the checked shift by eight is defined and below $2^{52}$, and the checked sum is below $10\cdot2^{60}+2^{52}<2^{64}$. The later shifts by $16$ and $32$ are also in range. The intervening masked multiplications and addition are wrapping, and the word after the final shift is at most $2^{32}-1$, so its checked cast to \texttt{u32} succeeds. The outer accumulator update is wrapping. The continuing branch then drops exactly the eight bytes just read. Each continuation strictly reduces the remaining length, so the first loop terminates after consuming whole eight-byte blocks contained in the stated digit prefix. It cannot cross into the tail, because a block containing its nondigit first byte fails the exact test. The scalar loop starts on the resulting suffix. At count $j$ its guard $j<$ the suffix length justifies the byte access. For a digit, wrapping subtraction by $48$ gives a value below ten, the byte-to-\texttt{u64} cast is exact, the accumulator multiplication and addition are wrapping, and the checked increment gives $j+1$ no larger than the suffix length and hence no larger than $L<2^{64}$. It therefore consumes all remaining bytes of the given digit prefix. At the first tail byte the digit test fails, or at an empty tail the length guard fails. The final slice begins at this bounded count, so it succeeds and equals the unconsumed tail. This proves both the normal return and the asserted exact remainder for every initial accumulator. \end{proof} ===== HISTORICAL Tablet/NumberHelperSharpFractionBytes.lean ===== import Tablet.Preamble open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: NumberHelperSharpFractionBytes] theorem NumberHelperSharpFractionBytes : exists l : List Std.U8, l = List.replicate 9223372036854120450 49#u8 ++ [101#u8, 45#u8, 54#u8, 53#u8, 53#u8, 51#u8, 53#u8, 57#u8] /\ l.length = 9223372036854120458 := by -- BODY let tail : List Std.U8 := [101#u8, 45#u8, 54#u8, 53#u8, 53#u8, 51#u8, 53#u8, 57#u8] let bs : List Std.U8 := (tail.reverse ++ List.replicate 9223372036854120450 49#u8).reverse have hlen : bs.length = 9223372036854120458 := by simp only [bs, List.length_reverse, List.length_append, List.length_replicate, tail, List.length_cons, List.length_nil] refine ⟨bs, ?_, hlen⟩ simp only [bs, List.reverse_append, List.reverse_replicate, List.reverse_reverse, tail] end dec2flt_model ===== HISTORICAL Tablet/NumberHelperSharpFractionBytes.tex ===== \begin{lemma}[Certified sharp fractional byte list] There exists a byte list equal to $9223372036854120450$ copies of ASCII \texttt{1} followed by the eight ASCII bytes of \texttt{e-655359}, and its length is $9223372036854120458$. \end{lemma} \begin{proof} Let $E$ be the eight-byte list for \texttt{e-655359}, and take \[ l=(\operatorname{reverse}(E)\mathbin{++} \operatorname{replicate}(9223372036854120450,49))^{\mathrm{reverse}}. \] Reversal of an append swaps its operands, reversal leaves a replicated constant list unchanged, and reversing $E$ twice restores $E$. Hence $l$ is the required replicated prefix followed by $E$. Reversal preserves length, so \[ |l|=|E|+9223372036854120450 =8+9223372036854120450=9223372036854120458. \] Thus this $l$ has both asserted properties. \end{proof} ===== HISTORICAL Tablet/ParserNumericWriteEightCertificate.lean ===== import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_write_u64 open Aeneas Aeneas.Std Result ControlFlow Error set_option autoImplicit false namespace dec2flt_model -- [TABLET NODE: ParserNumericWriteEightCertificate] theorem ParserNumericWriteEightCertificate (s : Slice Std.U8) (v : Std.U64) (hlen : 8 <= s.val.length) : exists s', SliceU8.Insts.Dec2flt_modelNumImpDec2fltCommonByteSlice.write_u64 s v = ok s' := by -- BODY have htake : (s.val.take 8).length = 8 := by simp [hlen] have hbytes : (List.map (fun b : BitVec 8 => (@UScalar.mk .U8 b)) v.bv.toLEBytes).length = 8 := by simp unfold SliceU8.Insts.Dec2flt_modelNumImpDec2fltCommonByteSlice.write_u64 simp [core.ops.index.IndexMutSlice, core.slice.index.Slice.index_mut, core.slice.index.SliceIndexRangeToUsizeSlice.index_mut, hlen, Array.to_slice, core.slice.Slice.copy_from_slice, Slice.length, Aeneas.Std.lift, core.num.U64.to_le_bytes] split · simp · rename_i hne exfalso apply hne apply UScalar.eq_of_val_eq simpa [Slice.len_val] using htake.trans hbytes.symm end dec2flt_model ===== HISTORICAL Tablet/ParserNumericWriteEightCertificate.tex ===== \begin{helper}[Eight-byte write succeeds] For every Aeneas byte slice of length at least eight and every unsigned 64-bit word, the extracted byte-slice \texttt{write\_u64} operation succeeds. \end{helper} \begin{proof} Expand \noderef{SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_write_u64}. The range-to index of the first eight positions is in bounds by the length hypothesis, so it produces a destination slice of length eight. The little-endian byte representation of a \texttt{u64} has exactly eight bytes, and conversion of that array to a slice is total. Thus the two slice lengths tested by \texttt{copy\_from\_slice} agree. The copy succeeds, and applying the range update continuation yields the required output slice. \end{proof}