ParserAccumulatedRounding

Lean checked

Statement

This explanation was written alongside the formalization to describe the statement and its reasoning.

Theorem

For every accepted source-valid numeric literal, the returned word is its lexical sign applied to the binary64 magnitude rounding target of the accumulated-exponent value, whose explicit exponent uses the source's bounded accumulation rule while retaining every significand digit.

Lean statement

Trellis authored these statements and proofs. Lean checks the formal proofs; the assumptions used by each proof are listed below.

import Tablet.Assumptions
import Tablet.DecimalGoalVocabularyDefault
import Tablet.SourceValidByteSlice
import Tablet.SpecialHelperRejection
import Tablet.NumberHelperAccumulatedValue
import Tablet.NativeCorrectOrDefer
import Tablet.IntegerCorrectOrDefer
import Tablet.AssemblyCorrespondence
import Tablet.ParserSuccessfulTrace
import Tablet.ParserNumericTraceShape
import Tablet.ParserFastPathAccumulatedRounding
import Tablet.ParserAssembledDirectAccumulatedRounding
import Tablet.ParserAssembledSlowAccumulatedRounding
import Tablet.F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64
import Tablet.F64_Insts_CoreOpsArithDivF64F64
import Tablet.F64_Insts_CoreOpsArithMulF64F64
import Tablet.F64_Insts_CoreOpsArithNegF64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatExtU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_BITS
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SIG_TOTAL_BITS
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SMALLEST_POWER_OF_TEN
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_LARGEST_POWER_OF_TEN
import Tablet.ModelF64MantissaDigits
import Tablet.ModelF64Neg
import Tablet.ModelSliceFirst
import Tablet.ModelStrAsBytes
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.ModelU64Shr
import Tablet.U64_Insts_CoreOpsBitBitAndU64U64
import Tablet.U64_Insts_CoreOpsBitBitOrU64U64
import Tablet.U64_Insts_CoreOpsBitShlU32U64
import Tablet.U64_Insts_CoreOpsBitShrU32U64
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_offset_from
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_read_u64
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_write_u64
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_common_BiasedFp
import Tablet.num_imp_dec2flt_common_BiasedFp_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
import Tablet.num_imp_dec2flt_common_is_8digits
import Tablet.num_imp_dec2flt_dec2flt
import Tablet.num_imp_dec2flt_dec2flt_with_trace
import Tablet.num_imp_dec2flt_parse_MIN_19DIGIT_INT
import Tablet.num_imp_dec2flt_parse_adjust_many_digit_count
import Tablet.num_imp_dec2flt_parse_parse_many_digits
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_inf_nan
import Tablet.num_imp_dec2flt_parse_parse_partial_number
import Tablet.num_imp_dec2flt_parse_parse_scientific
import Tablet.num_imp_dec2flt_parse_try_parse_19digits
import Tablet.num_imp_dec2flt_parse_try_parse_digits
import Tablet.num_imp_dec2flt_decimal_Decimal_try_fast_path
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_DECIMAL_POINT_RANGE
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_Insts_CoreDefaultDefault_default
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS_WITHOUT_OVERFLOW
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_left_shift
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_right_shift
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_round
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_trim
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_try_add_digit
import Tablet.num_imp_dec2flt_decimal_seq_count_trailing_zeros
import Tablet.num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift
import Tablet.num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift_TABLE
import Tablet.num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift_TABLE_POW5
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_exponent
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq
import Tablet.num_imp_dec2flt_decimal_seq_parse_digits_into_seq
import Tablet.num_imp_dec2flt_lemire_compute_float
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_MAX_SHIFT
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_NUM_POWERS
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_POWERS
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_closure_Insts_CoreOpsFunctionFnTupleUsizeUsize_call
import Tablet.num_imp_dec2flt_biased_fp_to_float
import Tablet.num_imp_traits_Float_EXP_BIAS_default
import Tablet.num_imp_traits_Float_EXP_BITS_default
import Tablet.num_imp_traits_Float_EXP_MIN_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

namespace dec2flt_model

-- [TABLET NODE: ParserAccumulatedRounding]
theorem ParserAccumulatedRounding :
    ∀ (s : Str) (x : DecimalLexeme) (f : 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) ->
      ∃ magnitude : F64, DecimalGoalVocabularyDefault.roundsMagnitude (DecimalGoalVocabularyDefault.accumulatedMagnitude x) magnitude ∧
        DecimalGoalVocabularyDefault.signedMagnitude (DecimalGoalVocabularyDefault.lexicalNegative x) magnitude f := by
Proof

Natural-language proof

The status above describes the Lean proof. Its explanatory prose may remain a sketch after that proof closes.

Explanatory prose status

Prose retained as authored. The explanatory prose is preserved as it stood when captured.

Proof

Fix a source string s, a valid numeric lexeme x, and a word f satisfying the four hypotheses. Write B for the byte list of s, and let x_0 be x with its leading-sign field replaced by none. Put
\epsilon=\operatorname{lexicalNegative}(x).
We prove first that the actual dispatcher body is exactly the unsigned rendering of x_0 and that its separate Boolean sign is exactly \epsilon. Unfolding only the concrete fields of DecimalGoalVocabularyDefault, validity says that every recorded digit is in 0,\ldots,9, at least one significand digit is present, and a present exponent has a digit. Rendering is the concatenation of the optional one-byte sign, the integer digits, the optional point and fractional digits, and the optional exponent. Hence it is nonempty. Its first byte is 45 precisely when x.\mathit{leadingSign}=\texttt{some true}, is 43 precisely when that field is some false, and otherwise belongs to \{46,48,\ldots,57\}. In particular, an unsigned rendering never starts with 43 or 45.
By ModelStrAsBytes, the first bind in num imp dec2flt dec2flt with trace returns the slice with exactly the bytes B. By ModelSliceFirst and nonemptiness, the next bind returns its first byte. The two sign tests in the extracted dispatcher therefore have the following exact effects: a leading 45 is removed and sets the later comparison c=45 to true; a leading 43 is removed and that comparison is false; with no sign no byte is removed and the comparison is also false. Both range-from-one operations are in bounds because the sign byte exists. Thus, in all three cases, the resulting slice, call it b, satisfies
\operatorname{bytes}(b)=\operatorname{renderNumeric}(x_0), \qquad b.\mathit{val}\ne[], \qquad(c=45)=\epsilon. \tag{1}
The first conjunct of sourceString gives |B|\le2^{63}-1. Removing at most one element cannot increase length, so |b|\le2^{63}-1; by the definition and preservation statement of SourceValidByteSlice, b is source-valid. Changing only the sign field does not affect any digit or nonemptiness clause, so x_0 is valid and has leading sign none. The machine widths and checked-scalar conventions used here and below are those fixed by Assumptions.
The public wrapper num imp dec2flt dec2flt only binds the pair returned by the traced function and projects its first component. Since its result is the assumed ok (Ok f), result-monad inversion gives a trace \tau with
\texttt{dec2flt\_with\_trace}(s)=\texttt{ok (Ok $f$, $\tau$)}. \tag{2}
Every failed bind in the traced computation would instead propagate that failure, and every Err arm would make the first component of (2) an Err. The concrete arguments in this equation are exactly the Lemire and FloatExt records F64 Insts Dec2flt modelNumImpDec2fltLemireU64 and F64 Insts Dec2flt modelNumImpTraitsFloatExtU64, and the arithmetic records F64 Insts CoreOpsArithDivF64F64, F64 Insts CoreOpsArithMulF64F64, and F64 Insts CoreOpsArithNegF64. We use bind propagation below each time the extracted body contains a checked operation.
We next identify the numeric record. The unsigned rendering in (1) cannot be an unsigned special keyword: its first byte is a digit or a point, whereas the case-insensitive bodies in specialLiteral start with ASCII i or n. Therefore SpecialHelperRejection, applied with the actual Boolean \epsilon, states that parse_inf_nan(b, \epsilon) = ok none. If parse_number(b) were ok none, the two nested matches in num imp dec2flt dec2flt with trace would call the exact specialized helper num imp dec2flt parse parse inf nan, use this equation, and return the invalid Err, contradicting (2). A failure of parse_number also contradicts (2) by bind propagation. Hence there is a record d such that
\texttt{parse\_number($b$)=ok (some $d$)}. \tag{3}
Applying NumberHelperAccumulatedValue to (1), source-validity, validity, and (3) gives, with
L=d.m\,10^{d.e},\qquad U=(d.m+1)10^{d.e},\qquad A=\operatorname{accumulatedMagnitude}(x),
the exhaustive alternative
(d.\mathit{many}=\mathrm{false}\ \wedge\ L=A) \quad\hbox{or}\quad (d.\mathit{many}=\mathrm{true}\ \wedge\ L\le A<U). \tag{4}
Here x and x_0 have identical significand and exponent fields, so their accumulated magnitudes agree. Notice that (3) is the unsigned record: the dispatcher changes only its negative field to \epsilon before the native call.
We now follow the trace split. The native call num imp dec2flt decimal Decimal try fast path cannot fail by (2), so it has an equation try_fast_path(d[negative:=\epsilon])=ok o. If o=\texttt{some }f, apply NativeCorrectOrDefer. Its successful arm supplies a nonnegative magnitude m, says d.\mathit{many}=\mathrm{false}, says that m rounds L, and says that applying sign \epsilon to m gives f. The true arm of (4) is then impossible and the false arm rewrites L to A. This m is the required witness.
It remains to treat o=\texttt{none}. The first call to num imp dec2flt lemire compute float cannot fail, so write its result as p_0, a record of the exact form fixed by num imp dec2flt common BiasedFp. The trace schemas num imp dec2flt Dec2FltTrace and num imp dec2flt Dec2FltAssemblyTrace, together with the exact body of num imp dec2flt dec2flt with trace, give the following complete case split. If many_digits is false, the post-comparison pair is p_0. If it is true but p_0.p<0, the second-computation guard is false and the post-comparison pair is again p_0. If it is true and p_0.p\ge0, the checked increment of d.m must succeed (otherwise (2) fails), producing the U64 word whose value is d.m+1; the second compute call and the extracted comparison in num imp dec2flt common BiasedFp Insts CoreCmpPartialEqBiasedFp eq must also return normally. Equal pairs retain p_0 and set forced_deferral false. Unequal pairs retain p_0.m, replace its biased exponent by -1, and set forced_deferral true. Finally a negative biased exponent invokes num imp dec2flt slow parse long mantissa; a nonnegative one is selected directly.
Consider first a directly selected pair p. Its biased exponent is nonnegative. If many_digits is false, p=p_0 and IntegerCorrectOrDefer, applied to the first compute equation, cannot take its negative-exponent alternative. It supplies a word m that assembles from p and rounds L=A by (4). If many_digits is true, direct selection can occur only after the second guard and an equal comparison, so p=p_0=p_1. Applying IntegerCorrectOrDefer to both compute equations, and again excluding the negative alternatives, gives the same assembled word m as a rounding target of both L and U. The word is the same because assembledWord is an explicit raw-word equality in DecimalGoalVocabularyDefault and the two pairs are equal.
For completeness, a common binary64 rounding target of L and U is also a target of every y\in[L,U]. This includes all boundary cases. If m is positive infinity, its two hypotheses say L and U are at or above the overflow midpoint, hence so is y. If m is finite, for each other finite word v the inequality
|z-\operatorname{value}(m)|\le |z-\operatorname{value}(v)|
defines a half-line in the real variable z (square both nonnegative sides; the difference is affine), and hence is convex. Both endpoints lie in every such half-line, so every intermediate y does too. When equality occurs, the definition requires the selected word to have even low bit. If m is even this is automatic; if m is odd, both endpoint inequalities are strict against every competitor, and an interval between two points in an open half-line remains in that open half-line. The finite overflow inequality z<2^{1024}-2^{970} is likewise preserved between L and U. Thus the nearest-even and infinity clauses of roundsMagnitude all hold for y. Its word bound is inherited from either endpoint, and 0\le L\le y because d.m is unsigned and 10^{d.e}>0, so the nonnegativity clause also holds. Taking y=A and using the second arm of (4) proves that the directly selected assembled word m rounds A.
We record why the remaining slow call is correct at this call site. This is not an appeal to an unrestricted slow-helper contract; the unrestricted claim is false. The argument is a direct invariant proof for the current b,x_0,d and the branch constraints just obtained.
First, the parser declarations num imp dec2flt parse try parse digits, num imp dec2flt parse adjust many digit count, num imp dec2flt parse try parse 19digits, num imp dec2flt parse parse many digits, num imp dec2flt parse parse scientific, num imp dec2flt parse parse partial number, and num imp dec2flt parse parse number, with the exact offset operation SliceU8 Insts Dec2flt modelNumImpDec2fltCommonByteSlice offset from, give the following count identity. Delete leading significand zeroes, let P be the decimal-point position in the remaining digit string, and let E be the bounded accumulated signed exponent. In a many-digit record the nineteen-digit retry consumes the first nineteen significant-position digits (or skips the point and consumes through the nineteenth fractional digit), and its returned exponent is
q=P-19+E. \tag{5}
If fewer significant-position digits exist, the corresponding equation has their actual consumed count in place of 19 and many_digits is false. These equations follow by induction over the displayed digit loops: the retry threshold in num imp dec2flt parse MIN 19DIGIT INT is exactly 10^{18}, so at most nineteen significant digits are accumulated; each digit access is guarded by the slice length; each wrapping mantissa update affects only the mantissa, not a count; each checked Usize count is at most |b|\le2^{63}-1<2^{64}; offset_from subtracts the two suffix lengths as signed isize values; and the scientific loop performs exactly the same update a\mapsto10a+r while a<65536 as the accumulated exponent in DecimalGoalVocabularyDefault. Its last updating step is at most 10\cdot65535+9=655359, after which it freezes, so
|E|\le655359. \tag{6}
All digit-to-U8 and U8-to-I64 casts are in range, the point contribution is zero in adjust_many_digit_count, and the zero-byte contribution is one; hence no count or sign is hidden in (5).
A slow call means either the first pair was the error pair with negative biased exponent, or two adjacent nonnegative results differed and forced the exponent to -1. The early guards in num imp dec2flt lemire compute float, using the exact bounds -342 and 308 from F64 Insts Dec2flt modelNumImpTraitsFloatU64 SMALLEST POWER OF TEN and F64 Insts Dec2flt modelNumImpTraitsFloatU64 LARGEST POWER OF TEN, return the zero pair for q<-342 and the infinity pair for q>308. Those pairs have nonnegative biased exponents, and in the many-digit case the two adjacent calls return the same early pair. Consequently the slow branch forces
-342\le q\le308. \tag{7}
Equations (5)--(7) bound the true decimal point P well inside the signed 32-bit range.
Now unfold num imp dec2flt decimal seq parse decimal seq. Its default record from num imp dec2flt decimal seq DecimalSeq Insts CoreDefaultDefault default has the fields of num imp dec2flt decimal seq DecimalSeq: zero count and point, false truncated, and 768 zero bytes, where 768 is num imp dec2flt decimal seq DecimalSeq MAX DIGITS. The initial loop removes exactly the leading integer zeroes. The bulk loops use SliceU8 Insts Dec2flt modelNumImpDec2fltCommonByteSlice read u64, num imp dec2flt common is 8digits, and SliceU8 Insts Dec2flt modelNumImpDec2fltCommonByteSlice write u64 to recognize, convert, and store guarded blocks of eight digits. Their guard is i+8<768, so the read has eight source bytes and the destination suffix has eight array cells. The scalar loop num imp dec2flt decimal seq parse digits into seq consumes every remaining decimal byte. Crucially, the extracted insertion num imp dec2flt decimal seq DecimalSeq try add digit does exactly two things: it stores the digit when the old count is below 768, and it always increments the count. It never reads or changes truncated. The increment cannot overflow on this execution because the count is at most the number of consumed bytes, which is at most the source-valid length in (1). Thus after both integer and fraction scans the array is the first 768 digits after the skipped leading zeroes, the count is the number of all such digits, and truncated is still false.
We keep the omitted digits as ghost data instead of prematurely identifying them with that Boolean. Let C be the complete digit word just counted, let t be the length of its terminal zero run (the point byte is not a digit), and let C' be C with those t zeroes deleted. Write N=|C'|. The loop num imp dec2flt decimal seq count trailing zeros starts at the proved consumed length, first decrements a positive index, reads that index, passes across the point without increasing its counter, and increases the counter exactly on a zero byte. It therefore returns t. The extracted subtraction computes i_6=|C|-t=N. If N>768, the branch in num imp dec2flt decimal seq parse decimal seq sets the returned count to 768 and truncated to true. If N\le768, it returns count N and inherits the old false field. These are the only two assignments to the returned field.
This proves the exact sticky assertion, including the easily missed all-zero omitted tail. Before trailing-zero removal, positions 768 onward may be omitted even when every one is zero; in that case t removes all of them, N\le768, and the bit remains false. If N>768, the suffix of C' after position 767 contains its last digit, which is nonzero by construction, so the remaining omitted suffix is nonzero and the bit is true. Conversely, there is no remaining omitted position when N\le768. Hence the late cap, not try_add_digit, sets truncated exactly when the suffix remaining after removal of all terminal zeroes contains a nonzero digit.
The parser narrows several Usize counts to I32. Let h(n) denote the signed low-32-bit value produced by the extracted hcast. Every subsequent I32 addition or subtraction is checked; normal return of the slow call in (2) implies that every executed one returned normally. In the integer branch the final point is congruent modulo 2^{32} to P+E. A significant integer span of at least 2^{31} would make (5) and (6) give q>308; the two adjacent integer conversions would be the same infinity pair, contradicting the slow-branch constraint (7). Thus this count does not wrap on a reachable slow call. In particular, the unrestricted slow-helper witness consisting of 2^{31} one-digits is irrelevant here: its dispatcher exponent is 2^{31}-19>308, so the dispatcher never invokes the helper.
In the fractional branch the extracted order is h(r)-h(\ell), addition of the narrowed trailing-zero count, and addition of the narrowed count N, where \ell is the full fractional suffix length and r the residual length. This is congruent modulo 2^{32} to P; the exponent parser then adds the accumulated E. By (5)--(7), P+E equals q plus the number of significant-position digits consumed by the retry (nineteen in the many-digit case), and lies strictly inside I32. The normally returned value also lies in I32. Two I32 values congruent modulo 2^{32} are equal, since their difference has absolute value below 2^{32}. Therefore the returned point is exactly p=P+E. The length-2^{31} fractional counterexample to the unrestricted helper instead fails at the checked subtraction 0-(-2^{31}); bind propagation excludes it from (2).
Let the first n=\min(N,768) digits of C' be a_0,\ldots,a_{n-1}, and define
R(D)=\sum_{j<n}a_j10^{p-j-1}.
Writing the complete integer represented by C' as I10^{N-n}+J, with I represented by the stored prefix, gives the exact identity
A=R(D)+J10^{p-N}. \tag{8}
If N\le768, then J=0 and truncated is false. If N>768, then 0<J<10^{N-n} and truncated is true, so
R(D)<A<R(D)+10^{p-n}. \tag{9}
Thus the parser supplies the required singleton or half-open interval, but also supplies the stronger datum J: the entire omitted suffix and the fact that its nonzeroness is exactly the sticky bit. The cleanup loop from n to num imp dec2flt decimal seq DecimalSeq MAX DIGITS WITHOUT OVERFLOW, whose value is 19, writes zero only to guarded cells at indices below 768 and does not change (8). Finally, num imp dec2flt decimal seq parse decimal exponent performs the same guard-before-update fold as the accumulated exponent. Hence (8) concerns A, not the literal with an unbounded mathematical exponent.
We next prove, rather than assume, the quantitative shift rule needed below. For a reached sequence D with retained value R=R(D), let X denote the exact value which that sequence is intended to carry at this stage. In addition to the exact error \eta=X-R, carry a positive ghost cutoff unit u. The invariant is
X=R+\eta,\qquad 0\le\eta<u,\qquad D.\mathit{truncated}\ \Longleftrightarrow\ \eta>0. \tag{10}
At the parser return put u_0=10^{p-768}, treating every absent stored cell through index 767 as a ghost zero. If N\le768, then \eta_0=0<u_0. If N>768, (8) gives
0<\eta_0=J10^{p-N}<10^{N-768}10^{p-N}=u_0. \tag{11}
Thus (10) is initially quantitative: the entire omitted suffix, not merely its nonzeroness, lies below the first omitted decimal place. We also retain the upper endpoint R+u. If the cumulative scale applied since parsing is \lambda>0, the stronger endpoint identity is
R+u=\lambda(R_0+u_0),
where R_0 is the parser's retained prefix. This identity will make the cutoff usable in boundary comparisons rather than leaving u as an unrelated error estimate.
Consider an actual call to num imp dec2flt decimal seq DecimalSeq left shift with count n, point p, and shift k. Put I=\sum_{j<n}a_j10^{n-j-1}. If n=0 the body returns the record unchanged, and (10) is unchanged. Otherwise let q be num_new_digits. In the first extracted loop, after r least significant input digits have been read, the variables satisfy
2^k I_{\rm low}(r)=c_r10^r+W_r,\quad 0\le W_r<10^r,
where the U64 variable n is c_r, read_index is n-r, write_index is n+q-r, and the r remainders already visited are the base-ten digits of W_r in their final positions. The next body reads a_{n-r-1}, forms c_r+2^ka_{n-r-1}, writes its remainder modulo ten, and uses the quotient by ten as c_{r+1}, proving the carry invariant at r+1. A remainder whose destination is at least 768 is not written and changes the Boolean to true exactly when it is nonzero. At r=n, the second loop repeats the same quotient/remainder step on c_n until it is zero. The definition of q proved below says that these are exactly the remaining leading digits of 2^kI and that the final write index is zero.
Let R' be the value of the retained leading at most 768 product digits at the returned point p'=p+q, and let
\rho_L=2^kR(D)-R'.
The loop invariant makes \rho_L precisely the nonnegative value of product digits whose destinations were at least 768. If n+q\le768, no such digit exists and \rho_L=0. If the count is capped, every such destination is at or beyond index 768, so the returned point and count give the explicit bound
0\le\rho_L<10^{p'-768}.
Define the new ghost values by
\eta'=\rho_L+2^k\eta,\qquad u'=\rho_L+2^ku. \tag{12}
Then 2^kX=R'+\eta', and 0\le\eta'<u' follows by multiplying \eta<u by 2^k and adding the same \rho_L to both sides. Moreover
R'+u'=2^k(R+u),
which proves the endpoint identity at the new cumulative scale. The returned Boolean is the disjunction of the old Boolean and the tests that a discarded remainder is positive. Since the two summands defining \eta' are nonnegative, that disjunction is equivalent to \eta'>0; no cancellation is possible. The count is \min(n+q,768) and the point is p+q, exactly as required by the positions in the carry invariant. Thus the left shift preserves all three clauses of (10) with a numerical error bound, including both the old omitted suffix and the newly discarded product digits.
Now consider num imp dec2flt decimal seq DecimalSeq right shift. In its first loop, after reading r digits, the U64 accumulator is the base-ten integer formed by precisely those digits (and, after the stored word ends, by the explicit zeroes appended by the inner branch). The guard n >>> k = 0 is n<2^k. The loop either proves the represented prefix zero and returns it unchanged, or stops at the least r with n\ge2^k. In the latter case the first quotient digit belongs at point
p'=p-(r-1), \tag{13}
which is exactly the extracted subtraction. In the second loop, after each subsequent input digit a the invariant is
10c+a=2^k d+c',\qquad 0\le c'<2^k, \tag{14}
where c is the old masked remainder, d is the emitted digit n >>> k, and c' is the new masked remainder. It advances each read index once and each write index once. After the input is exhausted, the third loop applies (14) with a=0 until the remainder is zero; it writes while the index is below 768 and otherwise sets the Boolean exactly when an emitted digit is nonzero.
If R' is the retained quotient prefix at (13), put \rho_R=2^{-k}R(D)-R'. Equations (13)--(14) say that \rho_R is exactly the nonnegative value of the generated quotient digits omitted beyond index 767. It is zero if the terminating quotient fits; if output is capped, the returned point p' and count 768 give
0\le\rho_R<10^{p'-768}.
Set
\eta'=\rho_R+2^{-k}\eta,\qquad u'=\rho_R+2^{-k}u. \tag{15}
Then 2^{-k}X=R'+\eta', 0\le\eta'<u', and
R'+u'=2^{-k}(R+u).
Again the returned Boolean is old sticky OR a newly discarded positive digit, so it is equivalent to \eta'>0. This proves the quantitatively bounded interval for every actual right shift, including a pre-existing omitted suffix. The zero-reset branch inside the extracted right shift would require the point in (13) to be below -2047; the finite-step bounds proved below exclude that branch at every call.
Both shift proofs also justify all machine side conditions. The selector num imp dec2flt slow parse long mantissa closure Insts CoreOpsFunctionFnTupleUsizeUsize call reads num imp dec2flt slow parse long mantissa POWERS below the bound 19 from num imp dec2flt slow parse long mantissa NUM POWERS, and otherwise returns the value 60 from num imp dec2flt slow parse long mantissa MAX SHIFT. Thus 0\le k\le60<64. In the left-shift carry invariant, the carry plus 2^ka is below 10\cdot2^{60}; in (14), 10c+a<10\cdot2^{60}+9<2^{64}. Every quotient digit is at most nine, so its U8 cast succeeds. Reads use indices below the current count, writes are either below 768 or take the nonwriting sticky branch, and all increments are bounded by the finite input or output digit word. The U64 operations are the displayed operations in U64 Insts CoreOpsBitBitAndU64U64, U64 Insts CoreOpsBitBitOrU64U64, U64 Insts CoreOpsBitShlU32U64, and U64 Insts CoreOpsBitShrU32U64, with their mathematical meanings fixed by ModelU64BitAnd, ModelU64BitOr, ModelU64Shl, and ModelU64Shr.
The call to num imp dec2flt decimal seq DecimalSeq trim asserts a count at most 768, then repeatedly inspects the positive count minus one and decrements exactly on a zero. Deleting z terminal stored zeroes leaves R' unchanged. It also leaves X, \eta', u', and the Boolean unchanged. Although the returned count decreases and the next stored-digit unit becomes larger, the ghost cutoff remains at its old absolute decimal position, with the deleted cells recorded as ghost zeroes. Hence (10), (12), and (14)--(15) survive trimming, and the endpoint identity still bounds the whole omitted tail rather than only the suffix following the trimmed count.
For completeness, here is the finite certificate used for the digit-count and normalization selectors. At indices 0,\ldots,18 the displayed POWERS array is
0,3,6,9,13,16,19,23,26,29,33,36,39,43,46,49,53,56,59;
for every 1\le m\le18, direct integer comparison gives, for its entry k,
2^k\le10^m<2^{k+1}.
The entry at zero is zero. For the fallback entry 60, the exact integer comparisons are
10^{18}<2^{60}<10^{19}.
These inequalities, not a claim that every shift changes the point, are the normalization certificate used below. They allow the point to stall while forcing the represented significand into a range from which the next selected shift must change the point or meet the exit test.
For the left digit count, unfold num imp dec2flt decimal seq number of digits decimal left shift, num imp dec2flt decimal seq number of digits decimal left shift TABLE, and num imp dec2flt decimal seq number of digits decimal left shift TABLE POW5. For each 0\le k\le60, the high five bits of TABLE[k] give the larger possible digit increase, and the low eleven bits s_k and s_{k+1} delimit the decimal digits of 5^k in TABLE_POW5. Since 2^kI=10^kI/5^k, lexicographic comparison of the leading digits of I with that block subtracts one exactly for the smaller possible increase. This proves that q in the carry invariant is the actual digit increase of 2^kI. The certificate includes the endpoint that the previous proof omitted: for k=60, TABLE[60] = 0x9cf2, so s_{60}=1266, and the required next entry is TABLE[61] = 0x051c = 1308. The slice [1266,1308) is the 42-digit word
867361737988403547205962240695953369140625=5^{60},
and 1308 is exactly the length, hence the final delimiter, of TABLE_POW5. Entries 62, 63, and 64 are unused: an actual k\le60 reads only entries k and k+1. Thus all 61 shifts k=0,\ldots,60 have both table entries and their complete power-of-five block checked.
The quantitative certificate now has to be connected to binary64 boundaries. Every midpoint between adjacent nonnegative finite binary64 words is a dyadic number. After cancellation, a fractional midpoint has the form
H=a2^{-r}, \qquad 1\le a\le2^{54}-1,\quad 1\le r\le1075,
with a odd; the bound on a follows by writing the two adjacent 53-bit significands over their common grid, including the 2^{54}-1 numerator at a binade boundary. Its terminating decimal coefficient is a5^r. Hence it has no more significant decimal digits than
C=(2^{54}-1)5^{1075}. \tag{16}
This bound really is 768, not 767. The elementary integer estimates 0.30102<\log_{10}2<0.30103 can be certified without floating-point arithmetic by binary exponentiation of 10^{30102}<2^{100000}<10^{30103}. Since 2^{53}<2^{54}-1<2^{54} and \log_{10}5=1-\log_{10}2, these bounds give
767.34734 =1075-1022(0.30103) <\log_{10}C <1075-1021(0.30102) =767.65858.
Thus 10^{767}<C<10^{768}. Because C is odd times a positive power of five, it ends in 5 and has no trailing decimal zero. In particular the actual adjacency midpoint
(2^{54}-1)2^{-1075} =C10^{-1075}
has exactly 768 significant decimal digits. It is the midpoint between (2-2^{-52})2^{-1022}, the largest word in the minimum-normal binade, and 2^{-1021}, the next binade endpoint. This is the maximum, not one less than the maximum. Midpoints with a nonnegative power of two are smaller than 2^{1024}<10^{309} and therefore have at most 309 digits. The zero/subnormal threshold 2^{-1075}=5^{1075}10^{-1075} is bounded by (16), and the overflow threshold (2^{54}-1)2^{970}=2^{1024}-2^{970} is an integer below 10^{309}. Consequently every finite adjacency midpoint and both endpoint thresholds used by roundsMagnitude terminate in at most 768 significant decimal positions.
We now isolate the exact boundary-comparison principle that will be used below. Let H_0 be any positive number whose terminating decimal expansion has at most 768 significant positions. At the parser state compare H_0 lexicographically with R_0, padding its terminating expansion by zeroes. If a digit first differs within the first 768 positions, its decimal place dominates every later place. More explicitly, in the below case the grid spacing u_0=10^{p-768} and the assumed termination give
R_0+u_0\le H_0;
then (11) gives A<R_0+u_0\le H_0. In the above case R_0\ge H_0+u_0 (or the first difference is at a still larger place), so A\ge R_0>H_0. If all boundary digits agree, then R_0=H_0; the exact-tail case \eta_0=0 gives equality, while \eta_0>0 gives the upper side. This is the initial lexicographic trichotomy, with the strict error bound supplying the fact that a later tail cannot reverse the first differing digit.
Here is the relational form of that comparison; importantly, it is conditional on the particular boundary, not a claim about every boundary after every dyadic scale. Follow one H_0 through a specified prefix of the actual shift sequence, multiplying it by exactly the same cumulative factor \lambda as X. Suppose that at every state in this prefix the scaled boundary H=\lambda H_0 has a terminating expansion with at most 768 significant positions. Apply the digit recurrences (12) and (15) also to the zero-padded digits of H. No nonzero boundary digit is then lost. Positive multiplication or division preserves order, and taking 768 leading digits is monotone. Thus, if the data prefix is above the boundary prefix, it stays above until the first differing digit is discarded; at that step the discarded digit is positive and the extracted test sets truncated. If the prefixes subsequently agree, that sticky bit still records the strict upper side. Exact equality follows identical digit recurrences and discards only padded zeroes, so its sticky bit remains false. In the below case, the endpoint identities following (12) and (15) give at every state
R+u=\lambda(R_0+u_0)\le\lambda H_0, \qquad X<R+u,
so even equality of displayed prefixes cannot hide a crossing. In particular, truncation cannot turn a genuinely below value into equality or an above value. Together with the preceding above and equality cases this proves the following comparison-transport rule: for this one boundary and this one shift prefix, a first stored digit difference decides the side, while agreement through the terminating boundary is decided by false versus true sticky. Later uses of this rule will separately verify its finite-expansion hypothesis for the boundary and states actually in question.
If the parsed count is zero then A=0 by (8). If its point is below -324, its first digit is nonzero and 0<A<10^{-324}<2^{-1075}, so zero is strictly nearest. If its point is at least 310, then A\ge10^{309}>2^{1024}-2^{970}, so the infinity clause holds. These prove the three early exits.
On the remaining path, loop 0 maintains
A=X(D)2^{e_2}. \tag{17}
A right shift by k changes X(D) to 2^{-k}X(D) by (15), and the checked update changes e_2 to e_2+k, preserving (17). Loop 1 uses (12) and e_2-k, preserving the same equation. We now prove termination and all point bounds from the two selector inequalities above, allowing stalls explicitly.
The retained value of a nonempty sequence with point p satisfies 10^{p-1}\le R<10^p. In loop 0, if p\ge19, division by 2^{60} and 10^{18}<2^{60}<10^{19} put the returned point in \{p-19,p-18\}, so it decreases by at least 18. If 1\le p\le18, take k=\texttt{POWERS}[p]. The inequalities 2^k\le10^p<2^{k+1} put R/2^k in [0.1,2), hence the returned point is zero or one. Point one may stall: for example 9/2^3=1.125 still has point one. But after any such stall the retained value is below 2; the next selector is \texttt{POWERS}[1]=3, so division by eight puts it below 1/4 and its point is zero. Thus the measure consisting of p for p\ge2, followed by a one-bit ``point-one stall still available'' flag, decreases on every iteration. Loop 0 terminates at point zero.
This calculation also excludes both zero exits in loop 0. The early guards give p\le309, and every returned point just found is nonnegative. Therefore the point passed to num imp dec2flt decimal seq DecimalSeq right shift never approaches -2047, its internal reset test is false, and the following comparison with the negation of num imp dec2flt decimal seq DecimalSeq DECIMAL POINT RANGE is false at every iteration. The right-shift digit recurrence retains a nonzero leading quotient digit, so truncation cannot alter these point alternatives.
For loop 1, suppose first that p\le-19. Multiplication by 2^{60} puts the new point in \{p+18,p+19\}, so it increases by at least 18 and remains at most zero. If -18\le p\le-1, set m=-p and use k=\texttt{POWERS}[m]. From the selector certificate, more explicitly from 2^k\le10^m<2^{k+1}, the product lies in [0.05,1); its point is therefore -1 or zero. A point--1 stall is possible, as 0.01\cdot2^3=0.08 shows. Such a stalled product is at least 0.05; the next shift is again three, so the following product lies in [0.4,0.8) and has point zero.
At point zero the first stored digit is nonzero: parsing removed leading zeroes, right shift starts with its first nonzero quotient digit, and the certified left-shift digit count writes the first nonzero product digit at index zero. A digit at least five exits. Digit one selects shift two and maps [0.1,0.2) into [0.4,0.8); a digit from two through four selects shift one and maps [0.2,0.5) into [0.4,1). If the resulting leading digit is four, one further shift by one puts the value in [0.8,1); otherwise the leading digit is already at least five. Hence after reaching point zero there are at most two continuing iterations. Combining this finite tail with the at-least-18 increase for p\le-19 and the single permitted point--1 stall proves termination of loop 1 without point monotonicity on every step.
These same half-open intervals prove a fact needed for the upper endpoint: loop 1 cannot exit by changing the retained point from zero to one. In the digit-one case the retained product is strictly below 0.8; in the digit-two-through-four case it is strictly below 1; and the possible final digit-four product is also strictly below 1. A negative-point iteration has retained product in [0.05,1). Thus every regular exit has retained point zero and leading digit at least five. This statement concerns the retained digits only; the positive omitted tail is handled separately below.
The non-early path began with -324\le p<310. The preceding alternatives keep every loop-1 point in [-324,0] and every loop-0 point in [0,309]. Thus no left shift produces a point above 2047, and no right shift produces one below -2047; both optional sentinel results and the right-shift reset are excluded at every intermediate state. There are at most 18 fallback steps in either direction, two small-selector steps, and the one documented stall; with every k\le60, all updates of the initially zero e_2 remain between -1200 and 1200, so each checked I32 addition, subtraction, negation, and Usize conversion in the two extracted loops succeeds.
Let S=X(D) at the regular exit, let e_{21} be its exponent, and let \lambda=2^{-e_{21}} be the cumulative scale from the parser state. Before using a boundary comparison, we first obtain a coarse bound which does not assume that the displayed prefix decides the side of 1. The digit recurrences give the required loss estimate without identifying sequential truncation with one final truncation. At any state let Y=\lambda R_0 and \delta=Y-R\ge0. Initially \delta=0. At a shift, write s for its positive dyadic factor and \rho=sR-R' for the digits newly discarded by the recurrence. If p' is the returned point, then 0\le\rho<10^{p'-768} and R'\ge10^{p'-1}, so, with h=10^{-767},
\alpha:=\rho/(sR)<h, \qquad \frac{sY-R'}{R'} =\frac{\delta/R+\alpha}{1-\alpha}. \tag{18a}
Here sR>0, and trimming changes neither side. Since h<1/2, induction in (18a), using (q+h)/(1-h)<2(q+h), bounds the relative loss after m shifts by (2^{m+1}-2)h. The termination proof above permits at most 18 fallback shifts, two small-selector shifts, and one stall, hence m\le21 and
0\le(\lambda R_0-R)/R<2^{22}h<10^{-760}.
If p_0 is the parser point, its nonzero retained prefix satisfies R_0\ge10^{p_0-1}, whereas u_0=10^{p_0-768}; hence u_0/R_0\le10^{-767}. Since R<1, we have \lambda R_0<R(1+10^{-760}), and consequently
S<\lambda(R_0+u_0) \le\lambda R_0(1+10^{-767}) <(1+10^{-760})(1+10^{-767})<2. \tag{18b}
This estimate includes every positive parser tail and every digit discarded by an intermediate shift. On the other hand the exit's leading digit is at least five, so S\ge R\ge1/2.
The non-early path has parser point at least -324, and hence A\ge10^{-325}>2^{-1080}. From A=S2^{e_{21}} and (18b), an integer e_{21}\le-1081 would give A<2\cdot2^{-1081}=2^{-1080}, a contradiction. Thus
e_{21}\ge-1080. \tag{18c}
We can now verify, boundary by boundary, the hypothesis of the comparison- transport rule for c=1/2 and c=1. The parser pullback of c is H_0=c2^{e_{21}}, and at a normalization state with exponent e its scaled form is c2^{e_{21}-e}. If the initial parsed point was positive, loop 0 increases e from zero to a final value e_0, while the point-zero tail of loop 1 subtracts in total at most three; hence e_{21}=e_0-L with 0\le L\le3. Along this path a negative exponent in c2^{e_{21}-e} has magnitude at most four, while a positive one is at most 1200 by the already proved checked-update bound. Such a number has at most 362 significant decimal digits. If the initial point was nonpositive, loop 0 is empty and loop 1 decreases e monotonically from zero to e_{21}. By (18c), every denominator is then at worst 2^{1081}; its terminating coefficient is at most 5^{1081}, which has at most 756 digits because 1081(1-0.30102)<756. Thus every intermediate scaled copy of each of the two boundaries fits in 768 cells.
The comparison-transport rule now applies, but only to these two verified boundaries. The final retained word has point zero and leading digit at least five, so its comparison with 1/2 gives the lower side. Its entire retained expansion is strictly below the terminating boundary 1; transport rules out a hidden crossing by the positive omitted tail and gives the upper side. Therefore
\tfrac12\le S\le1. \tag{18}
Equations (17)--(18) give A=S2^{e_{21}}. The next checked subtraction sets e_{22}=e_{21}-1, and hence
A=S2^{e_{22}+1}. \tag{19}
Loop 2 repeats right shifts by \min(60,-1022-e) while e<-1022. Its invariant is (19): division of the decimal by 2^k and replacement of e by e+k preserve the right side. This loop also cannot reach the reset branch. On this nonzero, non-early path the initial point is at least -324, so A\ge10^{-325}>2^{-1080} (the last inequality is the integer comparison 10^{325}<2^{1080}). Since S\le1 in (19), this implies e_{22}\ge-1080. Therefore -1022-e_{22}\le58: loop 2 performs at most one right shift, and its selected count is at most 58. Starting from S\ge1/2, the one loop-2 shift transports this comparison to the particular boundary 2^{-(k+1)} with k\le58. Its terminating coefficient 5^{k+1} has fewer than 43 digits, so the comparison-transport hypothesis is immediate; the retained result is at least 2^{-59}>10^{-18}. Its decimal point is therefore at least -17, far above the reset threshold -2047. The checked exponent update lands exactly at -1022 and the loop terminates with
e_{23}=\max(e_{22},-1022),\qquad A=T2^{e_{23}+1}, \tag{20}
where T=S in the normal case and T=S2^{e_{22}-e_{23}} in the subnormal case. Thus 0<T\le1, and e_{23}=-1022 whenever T<1/2. The computed biased candidate before rounding is exactly e_{23}-(-1022)+1=e_{23}+1023. If it is at least 2047 then e_{23}\ge1024; (18)--(20) give A\ge2^{1024}, which is already beyond the overflow midpoint, so this guard correctly returns infinity.
On the finite branch the checked cast 52 to Usize and checked increment produce 53. The following left shift and (20) expose
Z=T2^{53}=A/\Delta,\qquad \Delta=2^{e_{23}-52}. \tag{21}
Unfold num imp dec2flt decimal seq DecimalSeq round. Since 0<Z\le2^{53}<10^{19}, its point is at most 16 and cannot take the U64-maximum branch. For each integer j examined here, put B=j+\tfrac12 and H_0=\Delta B. This parser-time pullback is exactly the zero/subnormal threshold or an adjacency midpoint between the two corresponding binary64 candidates, so (16) proves that its parser expansion fits in 768 cells. We must still check its later scaled expansions rather than inherit that fact from the normalization argument. Write B=(2j+1)/2, where 2j+1\le2^{54}-1. The exponent invariant has two different forms at the checked decrement, and the boundary scale must follow that change. Through normalization loops 0 and 1 a state (D,e) satisfies A=X(D)2^e. Thus at such a pre-decrement state the displayed copy of H_0 is
(2j+1)2^{e_{23}-53-e};
its reduced denominator exponent is r_e=\max(0,53+e-e_{23}). If e_{23}=e_{21}-1\ge-1022, then the positive- initial-point case has e-e_{21}\le3, giving r_e\le57, while in the nonpositive-initial-point case e\le0 and e_{21}\ge-1021, giving r_e\le1075. If e_{23}=-1022, only the latter path is possible: a positive initial point has A\ge1, and S\le1 then forces e_{21}\ge0 and e_{23}\ge-1. Thus in the -1022 case r_e=\max(0,1075+e)\le1075.
The subtraction e_{22}=e_{21}-1 does not shift D. From that point and throughout loop 2 the invariant is instead A=X(D)2^{e+1}, as in (19)--(20), so the displayed copy of the same H_0 is
(2j+1)2^{e_{23}-54-e}. \tag{21a}
At the decrement these formulas agree: substituting e=e_{21} in the pre-decrement formula and e=e_{22}=e_{21}-1 in (21a) gives the same number. During loop 2, e runs from e_{22} through e_{23}, and hence the reduced denominator exponent in (21a) is
\max(0,54+e-e_{23})\le54. \tag{21b}
At the final loop-2 state e=e_{23}, (21a) is (2j+1)2^{-54}. The ensuing 53-bit left shift multiplies both the exact decimal and this displayed boundary by 2^{53}, producing (2j+1)/2=B exactly, as required by the argument of round.
It remains to check the integral as well as the fractional scaled copies. Every fractional copy just listed has odd coefficient at most 2^{54}-1 and denominator exponent at most 1075, so (16) bounds it by 768 significant digits. For a pre-decrement copy having nonnegative power of two, the finite guard gives e_{23}\le1023 and the earlier checked-update bound gives e\ge-1200; its magnitude is therefore below 2^{54}2^{1023-53+1200}=2^{2224}<10^{670}. In loop 2, 0\le e_{23}-54-e\le4 whenever that power is nonnegative, because e_{23}-e\le e_{23}-e_{22}\le58; its magnitude is then below 2^{58}. Finally B<2^{53}. These integral copies also terminate in fewer than 768 decimal positions. We have therefore verified the finite-expansion hypothesis separately at the parser state, every pre-decrement normalization state, the checked decrement, every loop-2 state, and the final 53-bit shift.
The conditional comparison-transport rule therefore applies separately to each B actually inspected by round. In particular, a negative stored point places the exact Z below 1/2, so the zero return is correct; this conclusion does not follow merely from the stored prefix.
For a nonnegative point, the extracted loop over integer positions maintains n_j=\sum_{i<j}a_i10^{j-i-1}; multiplication by ten and digit addition stay below 10^{19}<2^{64}. At the next position, a digit below five is on the lower side of n+1/2, and a digit above five is on the upper side. A five followed by another stored digit is strictly above. When five is the last stored digit, (10), (12), and (15) say that truncated is true exactly when the exact Z has a positive omitted remainder, so it distinguishes strictly above from exact equality. With equality and no suffix, the extracted bit-one test on the previous decimal digit is the parity of the integer part, since base ten preserves parity; when the point is zero, the separate false branch selects the even integer zero. If there is no stored next digit, the just-verified boundary-specific transport puts the whole error below the half-integer rather than inferring this from \eta\ge0. Thus the result M is the nearest integer to the exact Z, with ties to the even integer, not merely the nearest integer to the retained prefix.
Because Z\le2^{53}, M\le2^{53}. First suppose M<2^{53}. Put P=e_{23}+1023. If M<2^{52}, (18)--(21) force e_{23}=-1022, and the extracted decrement changes P=1 to zero; the pair then represents the subnormal value M2^{-1074}=M\Delta. If M\ge2^{52}, the exponent remains P\ge1, masking subtracts the implicit 2^{52} from its fraction field, and the decoded normal value is again M2^{e_{23}-52}=M\Delta. At M=2^{52} these two descriptions meet at the minimum normal value, so the subnormal/normal transition has neither a gap nor a duplicate candidate.
If M=2^{53}, the exact value Z lies at least 2^{53}-\tfrac12. The extracted one-bit right shift applies (15), increments to e_{24}=e_{23}+1, and rounds again. Its exact argument is Z/2, which lies in [2^{52}-\tfrac14,2^{52}]. The only lower rounding boundary relevant to this interval is B_1=2^{52}-1/2. Pulling it back to the parser gives
2\Delta B_1=(2^{53}-1)\Delta,
a dyadic with odd coefficient at most 2^{53}-1 and denominator exponent at most 1074. Put q=2^{53}-1. At a pre-decrement normalization state, where A=X(D)2^e, its displayed copy is
q2^{e_{23}-52-e},
with reduced denominator exponent \max(0,52+e-e_{23}). Repeating the three pre-decrement cases just checked for r_e bounds this by 1074: the positive normal case gives at most 56, the nonpositive normal case at most 1074, and the subnormal case gives \max(0,1074+e)\le1074.
After e_{22}=e_{21}-1, the invariant A=X(D)2^{e+1} instead gives the displayed copy
q2^{e_{23}-53-e}. \tag{21c}
The pre- and post-decrement formulas again agree when e=e_{21} and e=e_{22} respectively. During loop 2 its reduced denominator exponent is
\max(0,53+e-e_{23})\le53, \tag{21d}
because e runs from e_{22} to e_{23}. Fractional copies are therefore covered by (16). A nonnegative-power pre-decrement copy is below 2^{53}2^{1023-52+1200}=2^{2224}, while a nonnegative-power loop-2 copy is below 2^{53}2^5=2^{58} because e_{23}-e\le58; so these integral copies also fit in 768 cells. At e=e_{23}, (21c) is q2^{-53}. The final 53-bit left shift takes it exactly to the integer boundary q=2^{53}-1; the subsequent one-bit right shift takes that boundary exactly to q/2=B_1. Thus the parser state, every pre-decrement state, the decrement, every loop-2 state, the 53-bit shift, and the final one-bit shift all satisfy the finite-expansion hypothesis for this boundary.
Only now apply the conditional boundary-specific transport rule. It says that the stored second-round argument is strictly above B_1 and at most the integer 2^{52}. Unfolding the same decimal rounding branches proves that the second nearest-even result is exactly M_1=2^{52}. The retained value before this division is at least 2^{53}-1, so division by two leaves point 16; the internal -2047 reset is therefore false for this final right shift as well. The represented real is
M_1 2^{e_{24}-52}=2^{53}2^{e_{23}-52},
the same binade-boundary value selected by the carry. The second overflow guard tests e_{24}+1023\ge2047. At the top binade its threshold Z\ge2^{53}-\tfrac12 is exactly
A\ge(2^{53}-\tfrac12)2^{971} =2^{1024}-2^{970},
so equality, whose integer choice 2^{53} is even, and every larger value return infinity. Below that threshold the carry is an ordinary finite renormalization.
It remains to pass from nearest integer in (21) to the global roundsMagnitude relation in DecimalGoalVocabularyDefault. For e_{23}=-1022, the candidates j\Delta, 0\le j\le2^{52}, are consecutively positive zero, all subnormals, and the minimum normal; thus the zero/subnormal midpoint 2^{-1075} and the subnormal/normal boundary are covered by the same integer nearest-even calculation. For a normal exponent e_{23}, the candidates j\Delta, 2^{52}\le j\le2^{53}, are the entire binade including both endpoints. At its lower endpoint, every value under consideration is on or above that endpoint, so the closer candidate cannot be the predecessor from the lower binade. At its upper endpoint, the predecessor has spacing \Delta and the successor in the new binade has spacing 2\Delta; inputs normalized in the old binade are at or below the endpoint, so only the predecessor and endpoint can minimize distance. The carry selects that endpoint. This proves the transition between every pair of adjacent binades, while interior candidates are the uniform \Delta grid.
For every finite returned word, its raw low bit is the low bit of M: in the subnormal case the raw word is M; in the normal case the exponent is a multiple of 2^{52} and the fraction is M-2^{52}; after a carry both are even simultaneously. Hence every exact distance tie selects a word with even low bit. No finite word outside the just-described neighboring grid can be closer, because the finite magnitudes are ordered and such a word lies beyond one of the two adjacent candidates. The overflow calculation above selects positive infinity exactly at and above the stipulated midpoint and a finite minimizer strictly below it. Finally A\ge0 by its all-digit formula, and all constructed magnitude words are at most 2047\cdot2^{52}. We have used the corrected state-by-state certificates exactly twice: the first certificate makes the initial result M the nearest-even integer to Z, and the second makes the M=2^{53} reround return M_1=2^{52}. Those certified decisions are the interior-grid and carry-endpoint cases in the preceding global comparison, so the omitted decimal tail cannot invalidate any of its distance or parity conclusions. We have therefore proved for the slow pair p_s and its assembled word m that
\operatorname{roundsMagnitude}(A,m). \tag{22}
This is the required global binary64 result, including zero/subnormal, subnormal/normal, every adjacent-binade boundary, exact parity ties, the 2^{53} carry, and the overflow midpoint.
In either the direct or slow case, let p be the selected pair and let m be the word just proved to assemble from it and round A. The dispatcher next performs an I32-to-U64 low-bit cast, obtains the shift 52, shifts by that in-range count, and ORs with the mantissa. Normality of (2), the concrete trait declarations above, and the cited shift/OR operations discharge every one of these otherwise failing binds. By AssemblyCorrespondence, the following call num imp dec2flt biased fp to float returns normally with the unique word satisfying the same explicit assembledWord equality; therefore its result is m. If \epsilon is false, the dispatcher returns m. If \epsilon is true, its final operation is the concrete negation ModelF64Neg, which sets bit 63 of this nonnegative magnitude word. Unfolding signedMagnitude in DecimalGoalVocabularyDefault and using (1) shows in both cases
\operatorname{signedMagnitude}(\operatorname{lexicalNegative}(x),m,f).
Together with (22), or the corresponding native/direct result, this m is the existential witness required by the theorem.

Lean proof


  intro s x f hsource hvalid hrender hresult
  obtain ⟨tr, htrace⟩ := ParserSuccessfulTrace s f hresult
  rcases ParserNumericTraceShape s x f tr hsource hvalid hrender htrace with
    hfast | hassembled
  · obtain ⟨body, negative, parsed, fastInput, fastResult, htr,
        _, _, _, _, _⟩ := hfast
    subst tr
    exact ParserFastPathAccumulatedRounding s x f body negative parsed
      fastInput fastResult hsource hvalid hrender htrace
  · obtain ⟨assemblyTrace, parsed, htr, _, _, _, _, _, _⟩ := hassembled
    subst tr
    cases hguard : assemblyTrace.slow_path_guard with
    | false =>
        exact ParserAssembledDirectAccumulatedRounding s x f assemblyTrace
          hsource hvalid hrender htrace hguard
    | true =>
        exact ParserAssembledSlowAccumulatedRounding s x f assemblyTrace
          hsource hvalid hrender htrace hguard

end dec2flt_model

Download Lean source · Download TeX source

Complete Lean module
import Tablet.Assumptions
import Tablet.DecimalGoalVocabularyDefault
import Tablet.SourceValidByteSlice
import Tablet.SpecialHelperRejection
import Tablet.NumberHelperAccumulatedValue
import Tablet.NativeCorrectOrDefer
import Tablet.IntegerCorrectOrDefer
import Tablet.AssemblyCorrespondence
import Tablet.ParserSuccessfulTrace
import Tablet.ParserNumericTraceShape
import Tablet.ParserFastPathAccumulatedRounding
import Tablet.ParserAssembledDirectAccumulatedRounding
import Tablet.ParserAssembledSlowAccumulatedRounding
import Tablet.F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64
import Tablet.F64_Insts_CoreOpsArithDivF64F64
import Tablet.F64_Insts_CoreOpsArithMulF64F64
import Tablet.F64_Insts_CoreOpsArithNegF64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatExtU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_BITS
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SIG_TOTAL_BITS
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SMALLEST_POWER_OF_TEN
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_LARGEST_POWER_OF_TEN
import Tablet.ModelF64MantissaDigits
import Tablet.ModelF64Neg
import Tablet.ModelSliceFirst
import Tablet.ModelStrAsBytes
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.ModelU64Shr
import Tablet.U64_Insts_CoreOpsBitBitAndU64U64
import Tablet.U64_Insts_CoreOpsBitBitOrU64U64
import Tablet.U64_Insts_CoreOpsBitShlU32U64
import Tablet.U64_Insts_CoreOpsBitShrU32U64
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_offset_from
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_read_u64
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_write_u64
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_common_BiasedFp
import Tablet.num_imp_dec2flt_common_BiasedFp_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
import Tablet.num_imp_dec2flt_common_is_8digits
import Tablet.num_imp_dec2flt_dec2flt
import Tablet.num_imp_dec2flt_dec2flt_with_trace
import Tablet.num_imp_dec2flt_parse_MIN_19DIGIT_INT
import Tablet.num_imp_dec2flt_parse_adjust_many_digit_count
import Tablet.num_imp_dec2flt_parse_parse_many_digits
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_inf_nan
import Tablet.num_imp_dec2flt_parse_parse_partial_number
import Tablet.num_imp_dec2flt_parse_parse_scientific
import Tablet.num_imp_dec2flt_parse_try_parse_19digits
import Tablet.num_imp_dec2flt_parse_try_parse_digits
import Tablet.num_imp_dec2flt_decimal_Decimal_try_fast_path
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_DECIMAL_POINT_RANGE
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_Insts_CoreDefaultDefault_default
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS_WITHOUT_OVERFLOW
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_left_shift
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_right_shift
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_round
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_trim
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq_try_add_digit
import Tablet.num_imp_dec2flt_decimal_seq_count_trailing_zeros
import Tablet.num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift
import Tablet.num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift_TABLE
import Tablet.num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift_TABLE_POW5
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_exponent
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq
import Tablet.num_imp_dec2flt_decimal_seq_parse_digits_into_seq
import Tablet.num_imp_dec2flt_lemire_compute_float
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_MAX_SHIFT
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_NUM_POWERS
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_POWERS
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa_closure_Insts_CoreOpsFunctionFnTupleUsizeUsize_call
import Tablet.num_imp_dec2flt_biased_fp_to_float
import Tablet.num_imp_traits_Float_EXP_BIAS_default
import Tablet.num_imp_traits_Float_EXP_BITS_default
import Tablet.num_imp_traits_Float_EXP_MIN_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

namespace dec2flt_model

-- [TABLET NODE: ParserAccumulatedRounding]
theorem ParserAccumulatedRounding :
    ∀ (s : Str) (x : DecimalLexeme) (f : 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) ->
      ∃ magnitude : F64, DecimalGoalVocabularyDefault.roundsMagnitude (DecimalGoalVocabularyDefault.accumulatedMagnitude x) magnitude ∧
        DecimalGoalVocabularyDefault.signedMagnitude (DecimalGoalVocabularyDefault.lexicalNegative x) magnitude f := by
-- BODY
  intro s x f hsource hvalid hrender hresult
  obtain ⟨tr, htrace⟩ := ParserSuccessfulTrace s f hresult
  rcases ParserNumericTraceShape s x f tr hsource hvalid hrender htrace with
    hfast | hassembled
  · obtain ⟨body, negative, parsed, fastInput, fastResult, htr,
        _, _, _, _, _⟩ := hfast
    subst tr
    exact ParserFastPathAccumulatedRounding s x f body negative parsed
      fastInput fastResult hsource hvalid hrender htrace
  · obtain ⟨assemblyTrace, parsed, htr, _, _, _, _, _, _⟩ := hassembled
    subst tr
    cases hguard : assemblyTrace.slow_path_guard with
    | false =>
        exact ParserAssembledDirectAccumulatedRounding s x f assemblyTrace
          hsource hvalid hrender htrace hguard
    | true =>
        exact ParserAssembledSlowAccumulatedRounding s x f assemblyTrace
          hsource hvalid hrender htrace hguard

end dec2flt_model

Proof structure

Follow the declared dependencies to read the supporting statements and proofs.

Uses

All 86 entries

Explore this dependency tree

Inspect related source (201)
More program dependencies (159)
Standard-library dependencies (39)

Related source and models come from the extraction records and declared dependencies.

Proof assumptions and review

Lean checks the formal proof. Trellis also reviews how the statement corresponds to the intended requirement.

Transitive assumptions

This list combines the assumptions recorded for this declaration and its dependencies. It may include assumptions used by auxiliary declarations in those modules.

Helper theorems included
All 333 entries
Technical checking records
Local closure summary
{
  "node": "ParserAccumulatedRounding",
  "closure_version": "patch_c_v1",
  "active_decl_hash": "1d470d780558092e816c7b07514b5bf41a3a4bb6af3d496473c758b3db718b17",
  "active_statement_hash": "1c4132dd623fd5977710f0a00a34c3c8ede399775507edf0b9c569fe428d9e4e",
  "kernel_axioms": [
    "propext"
  ],
  "toolchain_hash": "ce4c4e3d87434b9663f46de25ce34b48a0cf0d392e0a320a0787b4674a2d7b61",
  "lean_executable_hash": "3e0d0d3d801675359f2d4cf9815bfdb417b20b92fdd9d48b3b14c95bbae28bbf",
  "checker_script_hash": "c8e4a03273e23b9a8f2e141020652a4e0b7b0a8ab0883366ea9d031ca3f37aa1",
  "approved_axioms_hash": "ab64d13f256386ee0e494a5abcc6a5db49512cf3d90bbdfcabd6327793a31f95",
  "axcheck_status": "Agreed",
  "accepted_at_snapshot_id": "revalidate-cycle-202",
  "boundary_theorems": {},
  "strict_theorem_deps": {
    "ParserAssembledDirectAccumulatedRounding": "f0f616d0737f8106",
    "ParserAssembledSlowAccumulatedRounding": "002cc637e53e8c41",
    "ParserFastPathAccumulatedRounding": "d6e5e03c2fecffaf",
    "ParserNumericTraceShape": "5cc80ccbad3dbbfc",
    "ParserSuccessfulTrace": "a086038bb9a607eb"
  },
  "strict_definition_deps": {
    "DecimalGoalVocabulary": "c08dd4b4aea4abb4",
    "DecimalGoalVocabularyDefault": "512f8d0aea894250",
    "DecimalLexeme": "c43614ff2149ecf2",
    "F64": "ec4e25fbaf4e11d4",
    "F64_Insts_CoreOpsArithDivF64F64": "dc44e13a99fc6bed",
    "F64_Insts_CoreOpsArithMulF64F64": "1ae1a9021a654abd",
    "F64_Insts_CoreOpsArithNegF64": "2d9be310c546ea2e",
    "F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64": "30963b4ef656cc79",
    "SourceValidByteSlice": "3dc42716a6378d26",
    "num_float_parse_ParseFloatError": "c43614ff2149ecf2",
    "num_imp_dec2flt_Dec2FltAssemblyTrace": "14686667070c5b6e",
    "num_imp_dec2flt_Dec2FltTrace": "644abe66cec8ac98",
    "num_imp_dec2flt_dec2flt": "f9f7d93449a25efa",
    "num_imp_dec2flt_dec2flt_with_trace": "ebe6a57c6dce0df6",
    "num_imp_dec2flt_decimal_Decimal": "c43614ff2149ecf2",
    "num_imp_dec2flt_parse_parse_number": "f73f8bc11faa6db3"
  }
}
Prose assessment
{
  "label": "Recorded Sound: VerifierPass",
  "assessment_status": "VerifierPass",
  "fingerprint_relation": "matches current fingerprint",
  "assessment_fingerprint": "sound-v2:d7a3b6a226604ffb8355b518893819347d68e34b254a12fed4c32109bc2ae523",
  "current_fingerprint": "sound-v2:d7a3b6a226604ffb8355b518893819347d68e34b254a12fed4c32109bc2ae523",
  "superseded_for_theorem_closure": false
}
Review verdicts
{
  "corr_status": "Pass",
  "sound_status": "Pass",
  "substantiveness_status": "Pass"
}