ParserNonNanResults

Lean checked

Statement

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

Theorem

For every source-valid Rust string that is not a NaN literal, every normally returned successful f64 parse result is not a binary64 NaN.

Lean statement

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

import Tablet.DecimalGoalVocabularyDefault
import Tablet.SourceValidByteSlice
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.ModelF64MantissaDigits
import Tablet.ModelF64Neg
import Tablet.ModelStrAsBytes
import Tablet.ModelSliceFirst
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.SpecialHelperRejection
import Tablet.SpecialHelperInfinity
import Tablet.NativeCorrectOrDefer
import Tablet.ParserSelectedExponent
import Tablet.ParserSelectedMantissaBound
import Tablet.ParserComputeFloatInfinityMantissa
import Tablet.ParserSlowInfinityMantissa
import Tablet.ParserAssembledPairNonNan
import Tablet.ParserSelectedMagnitudeSign
import Tablet.AssemblyCorrespondence
import Tablet.num_imp_dec2flt_dec2flt
import Tablet.num_imp_dec2flt_dec2flt_with_trace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_inf_nan
import Tablet.num_imp_dec2flt_decimal_Decimal_try_fast_path
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
import Tablet.num_imp_dec2flt_common_BiasedFp_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_lemire_compute_float
import Tablet.num_imp_dec2flt_lemire_compute_product_approx
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_closure_Insts_CoreOpsFunctionFnTupleUsizeUsize_call
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq
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_biased_fp_to_float
import Tablet.num_imp_traits_Float_SIG_BITS_default
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

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: ParserNonNanResults]
theorem ParserNonNanResults :
    ∀ (s : Str) (f : F64), DecimalGoalVocabularyDefault.sourceString s ->
      (¬ ∃ negative, DecimalGoalVocabularyDefault.specialLiteral (DecimalGoalVocabularyDefault.bytes s) negative true) ->
      num.imp.dec2flt.dec2flt F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64
        F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64
        F64.Insts.CoreOpsArithNegF64 s = ok (core.result.Result.Ok f) -> ¬ DecimalGoalVocabularyDefault.isNan 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 modeled string s and result f satisfying the three hypotheses. Put U=2^{52}, S=2^{63}, and I=2047U. Unfolding DecimalGoalVocabularyDefault, the conclusion says that it is impossible to have simultaneously
(f.\mathit{val}\bmod S)/U=2047 \quad\hbox{and}\quad f.\mathit{val}\bmod U\ne0. \tag{1}

The public call and the sign-stripped body.

Unfold num imp dec2flt dec2flt. It first binds the result of dec2flt_with_trace and then returns the first projection unchanged. The assumed successful public result therefore supplies a trace T with
\texttt{dec2flt_with_trace}(s)=\texttt{ok }(\texttt{Ok }f,T), \tag{2}
where throughout the proof the four concrete instance arguments are F64 Insts Dec2flt modelNumImpDec2fltLemireU64, F64 Insts CoreOpsArithDivF64F64, F64 Insts CoreOpsArithMulF64F64, and F64 Insts CoreOpsArithNegF64. This follows by case analysis on the bound result: failure would propagate, and an ok pair whose first projection differed from Ok f could not yield the assumed final ok (Ok f).
We shall use the exact body and sign selected in (2). By ModelStrAsBytes, the first bind of num imp dec2flt dec2flt with trace returns the byte slice underlying s without changing its elements or order. By ModelSliceFirst, the next bind returns none exactly when that list is empty and otherwise returns its head c. The none branch returns Err with the EmptyInput trace, so it is incompatible with (2). Thus c exists. The extracted sign branch sets
(B,n,\sigma)= \begin{cases} (\operatorname{tail}(\operatorname{bytes}(s)),\mathsf{true}, \texttt{some true}),&c=45,\\ (\operatorname{tail}(\operatorname{bytes}(s)),\mathsf{false}, \texttt{some false}),&c=43,\\ (\operatorname{bytes}(s),\mathsf{false},\texttt{none}),& c\notin\{45,43\}, \end{cases} \tag{3}
where B is the list of values in the selected slice body1, n is the Boolean argument later passed to the special parser, and \sigma is the corresponding optional lexical sign. In the first two cases the range starts at one; the existence of c proves that this range is in bounds. The next emptiness branch returns Err with a SignOnly trace, so (2) also proves that body1 is nonempty.
The first conjunct of the source-string hypothesis is |\operatorname{bytes}(s)|\le 2^{63}-1. Formula (3) gives |B|=|\operatorname{bytes}(s)| or |B|=|\operatorname{bytes}(s)|-1. Consequently body1 satisfies SourceValidByteSlice. Also, unfolding the sign-prefix and specialLiteral fields of DecimalGoalVocabularyDefault, (3) gives, for each Boolean k,
\texttt{specialLiteral}(B,\texttt{none},k) \Longrightarrow \texttt{specialLiteral}(\operatorname{bytes}(s),\sigma,k). \tag{4}
Indeed, prepend byte 45, prepend byte 43, or prepend nothing in the three cases of (3), retaining the same case-insensitive body witness. The theorem's second hypothesis and (4) therefore imply
\neg\texttt{specialLiteral}(B,\texttt{none},\mathsf{true}). \tag{5}
The constructors listed by num imp dec2flt Dec2FltTrace are disjoint and exhaustive. In the exact dispatcher body, empty input, sign-only input, and failure of both parsers produce Err with traces EmptyInput, SignOnly, and Invalid; none can equal (2). The only remaining traces are Special, FastPath, and Assembled. We treat them in turn.

Special result.

Suppose T is Special. Constructor injectivity applied to (2) and the record-free Special return in num imp dec2flt dec2flt with trace gives the exact helper equation
\texttt{parse_inf_nan}(\texttt{body1},n)=\texttt{ok (some }f\texttt{)}. \tag{6}
Assume temporarily that B is not an unsigned infinity spelling. Together with the source-valid bound and (5), the theorem SpecialHelperRejection would make the left side of (6) ok none, a contradiction. Hence B is an unsigned inf/infinity spelling. Apply SpecialHelperInfinity with the same slice and Boolean n. It gives some g for which the same deterministic helper call is ok (some g) and isInfinity n\ g. Comparing with (6), injectivity of ok and some gives g=f.
Thus isInfinity n\ f. By its definition in DecimalGoalVocabularyDefault, f.\mathit{val} is either I or I+S. In either case reduction modulo S is I, while reduction modulo U is zero. Therefore the second conjunct of (1) is false, and f is not a NaN in the Special case. Notice that (5), rather than an assumption that the special parser itself prefers infinity, is what excluded its NaN match.

Native fast path.

Suppose T is FastPath. The exact constructor fields in num imp dec2flt Dec2FltTrace and the corresponding return in num imp dec2flt dec2flt with trace supply a parsed Decimal r and the overwritten-sign record
d=\{r\text{ with }\mathit{negative}:=n\} \quad\hbox{such that}\quad \texttt{try_fast_path}(d)=\texttt{ok (some }f\texttt{)}. \tag{7}
Apply NativeCorrectOrDefer to (7). Its out = none alternative contradicts out = some f. In its other alternative, injectivity of some identifies its returned value with f, and we obtain a magnitude word v satisfying
\texttt{roundsMagnitude}(\texttt{decimalMagnitude}(d),v), \qquad \texttt{signedMagnitude}(n,v,f). \tag{8}
The first relation, unfolded from DecimalGoalVocabularyDefault, contains the bound v.\mathit{val}\le I. The second contains v.\mathit{val}<S and f.\mathit{val}=v.\mathit{val} or v.\mathit{val}+S according as n is false or true. Hence in both cases
f.\mathit{val}\bmod S=v.\mathit{val},\qquad f.\mathit{val}\bmod U=v.\mathit{val}\bmod U. \tag{9}
If the first conjunct of (1) held, (9) would give v.\mathit{val}/U=2047. Euclidean division then gives v.\mathit{val}\ge2047U=I; combined with the bound in (8), this forces v.\mathit{val}=I. Its remainder modulo U is zero, contradicting the second conjunct of (1) through (9). Thus the FastPath result is not NaN.

A local invariant for the assembled path.

It remains to handle T=\texttt{Assembled }A. The statements of the assembly support theorems do not by themselves say that an exponent-2047 pair has zero fraction, so we prove the required converter invariant directly. First evaluate the concrete constants. Through the Lemire and FloatExt records F64 Insts Dec2flt modelNumImpDec2fltLemireU64 and F64 Insts Dec2flt modelNumImpTraitsFloatExtU64, the selected Float record is F64 Insts Dec2flt modelNumImpTraitsFloatU64. Its bit width is 64 by F64 Insts Dec2flt modelNumImpTraitsFloatU64 BITS; its SIG_TOTAL_BITS method F64 Insts Dec2flt modelNumImpTraitsFloatU64 SIG TOTAL BITS invokes ModelF64MantissaDigits and returns 53. The checked subtraction in num imp traits Float SIG BITS default is therefore 53-1=52. The checked subtractions in num imp traits Float EXP BITS default give 64-52-1=11; the legal shift and subtraction in num imp traits Float EXP SAT default give 2^{11}-1=2047; and num imp traits Float INFINITE POWER default casts this in-range value exactly to signed 2047. All these monadic constant computations succeed.
We claim that every successful integer conversion
\texttt{compute_float}(q,w)=\texttt{ok }b \tag{10}
at this concrete Float record satisfies
b.m\le U,\qquad b.m=U\Longrightarrow b.p_{\rm biased}=1, \qquad b.p_{\rm biased}=2047\Longrightarrow b.m=0. \tag{11}
Unfold num imp dec2flt lemire compute float. Its eager zero, infinity, and error sentinels are made by num imp dec2flt common BiasedFp zero pow2, hence are respectively (0,0), (0,2047), and (0,-1). Every early return of one of these pairs satisfies (11).
On either nonsentinel product branch, the successful call to num imp dec2flt lemire compute product approx supplies 64-bit words (lo,hi). The shifts in this function have signed I32 counts, so we use their actual Aeneas semantics rather than the unsigned-count shift binding. Unfolding UScalar.shiftRight_IScalar, a shift by a signed count c first tests 0\le c; when that test succeeds it calls UScalar.shiftRight with c.\texttt{toNat}, which separately tests c.\texttt{toNat}<64 and then returns the zero-filling BitVec.ushiftRight. Thus there are two possible failure guards to discharge for each such shift.
For hi\mathbin{\mathtt{>>>}}63\#\texttt{i32}, the signed value 63 is nonnegative, its toNat is the same natural number 63, and 63<64. Thus the nonnegative and below-width success tests both hold, excluding both failure alternatives, and the returned U64 value is the logical natural right shift hi\mathbin{\mathtt{>>}}63. Since 0\le hi<2^{64}, this value is either zero or one. The exact widening cast makes that same integer the I32 value upperbit. Consequently the checked calculation 64+\texttt{upperbit}-52-3 succeeds with I32 value 9 or 10; call this count c. In particular 0\le c<64 and c.\texttt{toNat} is respectively the natural number 9 or 10. Unfolding the same two Aeneas definitions for hi\mathbin{\mathtt{>>>}}c discharges first the nonnegativity guard and then the width guard, and identifies the returned mantissa with the logical unsigned shift by that same natural count. If upperbit is zero, hi\mathbin{\mathtt{>>}}63=0 implies hi<2^{63}, so hi\mathbin{\mathtt{>>}}9<2^{54}; if it is one, the U64 carrier bound hi<2^{64} gives hi\mathbin{\mathtt{>>}}10<2^{54}. Thus the local pre-rounding mantissa is always below 2^{54}. All casts and checked operations which calculate the accompanying power2 precede every remaining result monadically; on the assumed successful execution they have succeeded. The two blocks below the two outcomes of the lo test are textually the same, so the following argument covers both.
If power2\le0, its successful checked negation produces i20 with value -\texttt{power2}\ge0, and its checked addition of one produces i21 with value k=-\texttt{power2}+1\ge1. The branch k\ge64 returns the zero sentinel. On its false branch, therefore, 1\le k<64. The code repeats the very same checked addition to form i22; determinism of that operation gives \texttt{i22.val}=k. Hence this signed count is nonnegative, its toNat is the same natural k, and that natural is below 64. For the operation \texttt{mantissa}\mathbin{\mathtt{>>>}}\texttt{i22}, unfolding UScalar.shiftRight_IScalar and then UScalar.shiftRight discharges respectively the sign and width guards and identifies mantissa1 with the logical shift by k. If k\le54, the pre-rounding bound gives \texttt{mantissa1}<2^{54-k}\le2^{53}; if k>54, then \texttt{mantissa}<2^{54}<2^k, so mantissa1 is zero. Thus in all cases x=\texttt{mantissa1}<2^{53}. By ModelU64BitAnd, e=x\mathbin{\mathtt{\&}}1 is its low bit, so x+e\le2^{53}; the checked addition producing mantissa2 therefore cannot overflow.
The next operation has the signed count 1\#\texttt{i32}. Its value is nonnegative, its toNat is the natural number one, and 1<64; the outer and inner success tests therefore hold, excluding both failure alternatives. The same unfolding identifies mantissa3 with the logical halving \lfloor\texttt{mantissa2}/2\rfloor, which is at most 2^{52}=U. The legal shift 1\mathbin{\mathtt{<<}}52=U is governed by ModelU64Shl, and the returned exponent is exactly the Boolean value of m\ge U. Hence m=U implies exponent one, while exponent 2047 is impossible on this ordinary return.
If power2>0$, the optional tie adjustment only clears the low bit by ModelU64BitAnd. Thus mantissa1<2^{54}, and adding its low bit produces mantissa2\le2^{54} without overflow. Its next shift again has signed count 1\#\texttt{i32}: 0\le1, its \texttt{toNat}=1<64, so the two success tests in UScalar.shiftRight_IScalar and UScalar.shiftRight are true and neither failure alternative is reachable. The result is the logical halving \texttt{mantissa3}=\lfloor\texttt{mantissa2}/2\rfloor\le2^{53}. The legal thresholds 2\mathbin{\mathtt{<<}}52=2^{53} and 1\mathbin{\mathtt{<<}}52=U either replace a carrying value by U or leave it below 2^{53}. The final conjunction with the complement of U clears bit 52, and no higher bit is set, so the ordinary record has mantissa strictly below U. Its final exponent test returns the zero-mantissa infinity sentinel whenever the computed exponent is at least 2047; otherwise the ordinary record has exponent below 2047. This proves all three clauses of (11), including both duplicated product blocks and every underflow, ordinary, and infinity exit. Any failed product, cast, checked arithmetic, or shift would propagate and cannot be confused with the successful premise (10).
The slow converter has the stronger successful-return invariant
\texttt{parse_long_mantissa}(t)=\texttt{ok }b \Longrightarrow b.m<U\ \land\ (b.p_{\rm biased}=2047\Longrightarrow b.m=0). \tag{12}
Unfold num imp dec2flt slow parse long mantissa. Its eager zero and infinity sentinels again come from num imp dec2flt common BiasedFp zero pow2 and have mantissa zero. A failure of num imp dec2flt decimal seq parse decimal seq propagates; zero digits and decimal point below -324 return zero, while decimal point at least 310 returns the infinity sentinel.
For the first loop, the invariant is that loop_result is none or the zero sentinel. It holds initially, and the only branch which writes the field does so after the closure call num imp dec2flt slow parse long mantissa closure Insts CoreOpsFunctionFnTupleUsizeUsize call and num imp dec2flt decimal seq DecimalSeq right shift, writing exactly that sentinel. Every other branch preserves the field or terminates. The second loop analogously keeps loop_result equal to none or the infinity sentinel; its only writes occur after num imp dec2flt decimal seq DecimalSeq left shift and store exactly that sentinel. All intervening casts, array accesses, shifts, and checked exponent operations are monadic, so a failure cannot yield the successful outer result. Therefore every some exit from either loop has mantissa zero.
If both loop-result fields are none, the third loop repeatedly caps its positive shift by num imp dec2flt slow parse long mantissa MAX SHIFT, whose value is 60, applies num imp dec2flt decimal seq DecimalSeq right shift, and continues; its only final branch is the one where the exponent has reached the concrete minimum. Write E_{\min} for the exactly returned EXP_MIN value. After the loop, the successful checked subtraction and addition name
\texttt{i7}=\texttt{exp23}-E_{\min}+1.
The already evaluated infinite-power value i is 2047. If the first guard i7 >= i is true, the function returns the zero-mantissa infinity sentinel. If it is false, the signed comparison gives the strict integer inequality
\texttt{i7}<2047. \tag{12a}
The code then shifts the decimal sequence and calls num imp dec2flt decimal seq DecimalSeq round.
On the noncarry branch, the later successful checked operations recompute power2=\texttt{exp23}-E_{\min}+1, so power2=\texttt{i7}. The returned power21 is either power2, or, when the rounded mantissa is below U, the successful checked subtraction power2 - 1. In the first case (12a) applies directly; in the second, \texttt{power21}=\texttt{power2}-1<\texttt{power2}<2047. Thus every ordinary noncarry return has exponent strictly below 2047.
On the carry branch, the successful checked increment gives exp24=\texttt{exp23}+1, the code shifts right once, rounds again, and names
\texttt{i14}=\texttt{exp24}-E_{\min}+1.
If its second saturation guard is true, the function again returns the zero-mantissa infinity sentinel. On the false branch, i14<2047. The immediately following checked subtraction and addition recompute exactly the same expression, so the local power2 equals i14. Again power21 is either power2 or the successfully computed power2 - 1; hence in both cases power21<2047. Thus every ordinary carry return also has exponent strictly below 2047.
On either ordinary return the code forms U-1 and conjoins the rounded word with that mask. By ModelU64BitAnd, the result is at most U-1. We have now shown more than the second clause of (12): every ordinary post-loop record has exponent below 2047, whereas every post-loop return with exponent 2047 is the zero-mantissa infinity sentinel. Together with the eager and loop-sentinel cases above, this exhausts the direct, loop-sentinel, carry, noncarry, and saturation exits and proves (12); all checked-operation failures instead propagate.
Now inspect selection in num imp dec2flt dec2flt with trace. The first integer result obeys (11). If many_digits makes the second-computation guard true, the checked increment and the second call must both succeed, and the second result also obeys (11). The comparison num imp dec2flt common BiasedFp Insts CoreCmpPartialEqBiasedFp eq is the exact comparison of both fields. Equality retains the first pair; inequality retains its mantissa but replaces its exponent by -1. Thus a second-call disagreement cannot be assembled: the subsequent negative- exponent guard forces the slow call. The same slow replacement occurs for any other negative post-comparison exponent. If the guard is false, the post-comparison pair itself is selected. Combining (11), (12), and these first/second/forced-deferral/slow choices gives the exact local invariant for the selected pair b:
b.m\le U,\qquad b.m=U\Longrightarrow b.p_{\rm biased}=1, \qquad b.p_{\rm biased}=2047\Longrightarrow b.m=0. \tag{13}
The endpoint clause is important: a blanket claim b.m<U would be false for the integer converter's carry into exponent one, but (13) is precisely what the assembly argument needs.

Assembly and the final sign.

Constructor injectivity in (2), using the field schema num imp dec2flt Dec2FltAssemblyTrace, identifies the local selected pair b with A.\texttt{selected_pair} and the locally computed OR word W with A.\texttt{assembled_word}. Apply ParserSelectedExponent to (2):
0\le p=b.p_{\rm biased}\le2047. \tag{14}
Apply ParserSelectedMagnitudeSign to the same execution: the recorded W satisfies assembledWord b\ W and W<S.
Since p is nonnegative, its signed-to-unsigned cast is exactly p. The shift count 52 is legal by ModelU64Shl, and ModelU64BitOr identifies the assembly operation with
W=\operatorname{lor}(b.m,pU). \tag{15}
If b.m=U, (13) gives p=1, and (15) is lor(U,U)=U<I. If b.m<U and p\le2046, the operands occupy disjoint exponent and fraction fields, so W=pU+b.m\le2046U+(U-1)<I. Finally, if p=2047, (13) gives b.m=0 and W=I. These cases are exhaustive by (13)--(14), and therefore
W<I\quad\hbox{or}\quad W=I. \tag{16}
In the first case W/U<2047; in the second W\bmod U=0. Thus a carrier whose raw word is W cannot satisfy (1).
The exact trace execution also contains biased_fp_to_float(b)=\texttt{ok }A.\texttt{assembly_result}. Apply AssemblyCorrespondence to b. It supplies a carrier g with the same deterministic call result and with assembledWord b\ g. Comparing the two result equations gives g=A.\texttt{assembly_result}; unfolding the assembled-word relation and using (15) identifies its raw word with W. This also agrees with the recorded assembly fact from ParserSelectedMagnitudeSign; no proof-internal invariant of either cited theorem is being used.
If the lexical sign is not minus, the extracted false-sign return sets f=A.\texttt{assembly_result}, so (16) proves that f is not NaN. If it is minus, the final call uses the concrete negation instance F64 Insts CoreOpsArithNegF64. Its operation ModelF64Neg succeeds and toggles exactly bit 63. Because W<S by ParserSelectedMagnitudeSign, the final raw word is W+S. Reduction modulo S and modulo U therefore gives the same exponent and fraction fields as W, so (16) again excludes (1). This completes the Assembled case and, with the three exhaustive successful trace cases, proves the theorem.

Lean proof


  intro s f hsource hnotNanLiteral hpublic
  have bind_ok_inv : ∀ {α β : Type} (r : Result α) (g : α → Result β) y,
      Bind.bind r g = ok y → ∃ z, r = ok z ∧ g z = ok y := by
    intro α β r g y hr
    cases r with
    | fail err => simp [Bind.bind, Aeneas.Std.bind] at hr
    | div => simp [Bind.bind, Aeneas.Std.bind] at hr
    | ok z => exact ⟨z, rfl, hr⟩
  have infinity_not_nan : ∀ (negative : Bool) (value : F64),
      DecimalGoalVocabularyDefault.isInfinity negative value ->
      ¬ DecimalGoalVocabularyDefault.isNan value := by
    intro negative value hinfinity hnan
    dsimp only [DecimalGoalVocabularyDefault] at hinfinity hnan
    cases negative <;>
      simp only [Bool.false_eq_true, if_false, if_true] at hinfinity
    · rw [hinfinity] at hnan
      norm_num at hnan
    · rw [hinfinity] at hnan
      norm_num at hnan
  have signed_bounded_not_nan : ∀ (negative : Bool) (magnitude result : F64),
      magnitude.val ≤ 2047 * 2 ^ 52 ->
      DecimalGoalVocabularyDefault.signedMagnitude negative magnitude result ->
      ¬ DecimalGoalVocabularyDefault.isNan result := by
    intro negative magnitude result hbound hsigned hnan
    dsimp only [DecimalGoalVocabularyDefault] at hsigned hnan
    rcases hsigned with ⟨hmag, hresult⟩
    rcases hnan with ⟨hexponent, hfraction⟩
    have hmodSign : result.val % (2 ^ 63) = magnitude.val := by
      cases negative with
      | false =>
        simp only [Bool.false_eq_true, if_false, add_zero] at hresult
        rw [hresult, Nat.mod_eq_of_lt hmag]
      | true =>
        simp only [if_true] at hresult
        rw [hresult, Nat.add_mod]
        have hm := Nat.mod_eq_of_lt hmag
        rw [hm, Nat.mod_self, Nat.add_zero, hm]
    have hmodFraction :
        result.val % (2 ^ 52) = magnitude.val % (2 ^ 52) := by
      cases negative with
      | false =>
        simp only [Bool.false_eq_true, if_false, add_zero] at hresult
        rw [hresult]
      | true =>
        simp only [if_true] at hresult
        rw [hresult, Nat.add_mod]
        norm_num
    rw [hmodSign] at hexponent
    have hdecomp := Nat.mod_add_div magnitude.val (2 ^ 52)
    rw [hexponent] at hdecomp
    have hmagExact : magnitude.val = 2047 * 2 ^ 52 := by
      norm_num at hdecomp ⊢
      omega
    rw [hmodFraction, hmagExact] at hfraction
    norm_num at hfraction
  unfold num.imp.dec2flt.dec2flt at hpublic
  obtain ⟨out, hout, hpublic⟩ := bind_ok_inv _ _ _ hpublic
  rcases out with ⟨publicResult, trace⟩
  cases hpublic
  have traced :
      num.imp.dec2flt.dec2flt_with_trace
        F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64
        F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64
        F64.Insts.CoreOpsArithNegF64 s =
        ok (core.result.Result.Ok f, trace) := hout
  rcases s with ⟨source, source_bound⟩
  cases source with
  | nil =>
      unfold num.imp.dec2flt.dec2flt_with_trace at traced
      obtain ⟨body, hbody, traced⟩ := bind_ok_inv _ _ _ traced
      have hbodyEq : body = (⟨[], source_bound⟩ : Slice Std.U8) := by
        simpa [core.str.Str.as_bytes, ModelStrAsBytes] using hbody.symm
      subst body
      obtain ⟨firstOption, hfirst, traced⟩ := bind_ok_inv _ _ _ traced
      have hfirstEq : firstOption = none := by
        simpa [core.slice.Slice.first, ModelSliceFirst] using hfirst.symm
      subst firstOption
      obtain ⟨pfe, hpfe, traced⟩ := bind_ok_inv _ _ _ traced
      cases traced
  | cons first tail =>
      unfold num.imp.dec2flt.dec2flt_with_trace at traced
      obtain ⟨body, hbody, traced⟩ := bind_ok_inv _ _ _ traced
      have hbodyEq : body = (⟨first :: tail, source_bound⟩ : Slice Std.U8) := by
        simpa [core.str.Str.as_bytes, ModelStrAsBytes] using hbody.symm
      subst body
      obtain ⟨firstOption, hfirst, traced⟩ := bind_ok_inv _ _ _ traced
      have hfirstEq : firstOption = some first := by
        simpa [core.slice.Slice.first, ModelSliceFirst] using hfirst.symm
      subst firstOption
      obtain ⟨body1, hbody1, traced⟩ := bind_ok_inv _ _ _ traced
      have body1Valid : SourceValidByteSlice body1 := by
        unfold SourceValidByteSlice
        have hslen := hsource.1
        by_cases hminus : first = 45#u8
        · simp only [hminus, if_true] at hbody1
          simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
            Slice.drop] at hbody1
          cases hbody1
          simp at hslen ⊢
          omega
        · simp only [hminus, if_false] at hbody1
          by_cases hplus : first = 43#u8
          · simp only [hplus, if_true] at hbody1
            simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
              Slice.drop] at hbody1
            cases hbody1
            simp at hslen ⊢
            omega
          · simp only [hplus, if_false] at hbody1
            cases hbody1
            exact hslen
      have noNanBody : ¬ DecimalGoalVocabularyDefault.specialLiteral
          (DecimalGoalVocabularyDefault.bytes body1) none true := by
        intro hspecial
        apply hnotNanLiteral
        by_cases hminus : first = 45#u8
        · simp only [hminus, if_true] at hbody1
          simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
            Slice.drop] at hbody1
          cases hbody1
          refine ⟨some true, ?_⟩
          dsimp only [DecimalGoalVocabularyDefault] at hspecial ⊢
          rcases hspecial with ⟨specialBody, hspecialBody, hcase⟩
          refine ⟨specialBody, ?_, hcase⟩
          subst first
          simpa using hspecialBody
        · simp only [hminus, if_false] at hbody1
          by_cases hplus : first = 43#u8
          · simp only [hplus, if_true] at hbody1
            simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
              Slice.drop] at hbody1
            cases hbody1
            refine ⟨some false, ?_⟩
            dsimp only [DecimalGoalVocabularyDefault] at hspecial ⊢
            rcases hspecial with ⟨specialBody, hspecialBody, hcase⟩
            refine ⟨specialBody, ?_, hcase⟩
            subst first
            simpa using hspecialBody
          · simp only [hplus, if_false] at hbody1
            cases hbody1
            exact ⟨none, hspecial⟩
      obtain ⟨empty, hempty, traced⟩ := bind_ok_inv _ _ _ traced
      by_cases emptyTrue : empty = true
      · simp only [emptyTrue, if_true] at traced
        obtain ⟨pfe, hpfe, traced⟩ := bind_ok_inv _ _ _ traced
        cases traced
      · have emptyFalse : empty = false := Bool.eq_false_of_not_eq_true emptyTrue
        simp only [emptyFalse, if_false] at traced
        obtain ⟨parsed, hparsed, traced⟩ := bind_ok_inv _ _ _ traced
        cases parsed with
        | none =>
          obtain ⟨special, hspecial, traced⟩ := bind_ok_inv _ _ _ traced
          cases special with
          | none =>
            obtain ⟨pfe, hpfe, traced⟩ := bind_ok_inv _ _ _ traced
            cases traced
          | some value =>
            cases traced
            by_cases hInf : DecimalGoalVocabularyDefault.specialLiteral
                (DecimalGoalVocabularyDefault.bytes body1) none false
            · obtain ⟨infinity, hinfinityEq, hinfinity⟩ :=
                SpecialHelperInfinity body1 (decide (first = 45#u8)) hInf
              rw [hspecial] at hinfinityEq
              cases hinfinityEq
              exact infinity_not_nan _ _ hinfinity
            · have hrejection := SpecialHelperRejection body1
                (decide (first = 45#u8)) body1Valid hInf noNanBody
              rw [hspecial] at hrejection
              cases hrejection
        | some r =>
          obtain ⟨fast, hfast, traced⟩ := bind_ok_inv _ _ _ traced
          cases fast with
          | some value =>
            have hnative := NativeCorrectOrDefer
              ({ r with negative := decide (first = 45#u8) })
              (some value) hfast
            rcases hnative with hnone |
              ⟨value', magnitude, hvalue, _, hrounds, hsigned⟩
            · simp at hnone
            · cases hvalue
              cases traced
              dsimp only [DecimalGoalVocabularyDefault] at hrounds
              exact signed_bounded_not_nan _ _ _ hrounds.2.1 hsigned
          | none =>
            obtain ⟨firstPair, hfirstPair, traced⟩ := bind_ok_inv _ _ _ traced
            have hfirstInfinity :=
              ParserComputeFloatInfinityMantissa _ _ _ hfirstPair
            obtain ⟨phase1, hphase1, traced⟩ := bind_ok_inv _ _ _ traced
            rcases phase1 with ⟨many1, many2, firstPair1, fp, guard⟩
            have hfp : fp = firstPair := by
              by_cases hm : r.many_digits
              · simp only [hm, if_true] at hphase1
                cases hphase1
                rfl
              · simp only [hm, if_false] at hphase1
                cases hphase1
                rfl
            subst fp
            obtain ⟨phase2, hphase2, traced⟩ := bind_ok_inv _ _ _ traced
            rcases phase2 with
              ⟨post, secondExp, secondMant, secondResult, secondEqual, forced⟩
            have hpostInfinity :
                post.p_biased.val = 2047 -> post.m.val = 0 := by
              cases guard with
              | false =>
                simp only [Bool.false_eq_true, if_false] at hphase2
                cases hphase2
                exact hfirstInfinity
              | true =>
                simp only [if_true] at hphase2
                obtain ⟨mantissa, hmantissa, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                obtain ⟨second, hsecond, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                obtain ⟨equal, hequal, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                obtain ⟨chosen, hchosen, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                rcases chosen with ⟨bf, wasForced⟩
                have hbf : bf.p_biased.val = 2047 -> bf.m.val = 0 := by
                  by_cases heq : equal = true
                  · simp only [heq, if_true] at hchosen
                    cases hchosen
                    exact hfirstInfinity
                  · have heqf : equal = false :=
                      Bool.eq_false_of_not_eq_true heq
                    simp only [heqf, if_false] at hchosen
                    cases hchosen
                    intro hp
                    norm_num at hp
                cases hphase2
                exact hbf
            obtain ⟨phase3, hphase3, traced⟩ := bind_ok_inv _ _ _ traced
            rcases phase3 with ⟨selected, slowGuard, slowResult⟩
            have hselectedInfinity :
                selected.p_biased.val = 2047 -> selected.m.val = 0 := by
              by_cases hneg : post.p_biased < 0#i32
              · simp only [hneg, if_true] at hphase3
                obtain ⟨replacement, hreplacement, hphase3⟩ :=
                  bind_ok_inv _ _ _ hphase3
                have hreplacement :=
                  ParserSlowInfinityMantissa _ _ hreplacement
                cases hphase3
                exact hreplacement
              · simp only [hneg, if_false] at hphase3
                cases hphase3
                exact hpostInfinity
            obtain ⟨i, hi, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨i1, hi1, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨i2, hi2, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨word, hword, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨assembled, hassembled, traced⟩ := bind_ok_inv _ _ _ traced
            by_cases negative : first = 45#u8
            · simp only [negative, if_true] at traced
              obtain ⟨result, hresult, traced⟩ := bind_ok_inv _ _ _ traced
              cases traced
              obtain ⟨wordSpec, wordBound⟩ :=
                ParserSelectedMagnitudeSign
                  (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have exponentBound := ParserSelectedExponent
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have mantissaBound := ParserSelectedMantissaBound
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              change DecimalGoalVocabularyDefault.assembledWord selected word at wordSpec
              change word.val < 2 ^ 63 at wordBound
              have hwordNonNan := ParserAssembledPairNonNan selected word
                exponentBound.1 exponentBound.2 mantissaBound
                hselectedInfinity wordSpec wordBound
              obtain ⟨canonical, hcanonical, canonicalSpec⟩ :=
                AssemblyCorrespondence selected
              rw [hassembled] at hcanonical
              cases hcanonical
              have assembledVal : assembled.val = word.val := by
                dsimp only [DecimalGoalVocabularyDefault] at wordSpec canonicalSpec
                exact canonicalSpec.trans wordSpec.symm
              have assembledEq : assembled = word :=
                UScalar.eq_of_val_eq assembledVal
              subst assembled
              change ModelF64Neg word = ok f at hresult
              cases hresult
              dsimp only [DecimalGoalVocabularyDefault] at hwordNonNan ⊢
              intro hnan
              apply hwordNonNan
              rcases hnan with ⟨hexponent, hfraction⟩
              refine ⟨?_, ?_⟩
              · change (((word.bv ^^^ BitVec.ofNat 64 (2 ^ 63)).toNat) %
                    2 ^ 63) / 2 ^ 52 = 2047 at hexponent
                rw [BitVec.toNat_xor] at hexponent
                have hbit : (BitVec.ofNat 64 (2 ^ 63)).toNat = 2 ^ 63 := by
                  norm_num
                rw [hbit] at hexponent
                change (word.val ^^^ (2 ^ 63)) % (2 ^ 63) /
                    (2 ^ 52) = 2047 at hexponent
                have hxor : word.val ^^^ (2 ^ 63) = word.val + 2 ^ 63 := by
                  have hor := Nat.two_pow_add_eq_or_of_lt wordBound 1
                  have hx : word.val ^^^ (2 ^ 63) =
                      (2 ^ 63) ||| word.val := by
                    apply Nat.eq_of_testBit_eq
                    intro k
                    rw [Nat.testBit_xor, Nat.testBit_or, Nat.testBit_two_pow]
                    by_cases hk : k = 63
                    · subst k
                      rw [Nat.testBit_lt_two_pow wordBound]
                      decide
                    · have hk' : 63 ≠ k := Ne.symm hk
                      simp [hk, hk']
                  exact hx.trans (by simpa [Nat.add_comm] using hor.symm)
                rw [hxor, Nat.add_mod] at hexponent
                norm_num at hexponent
                exact hexponent
              · change (((word.bv ^^^ BitVec.ofNat 64 (2 ^ 63)).toNat) %
                    2 ^ 52) ≠ 0 at hfraction
                rw [BitVec.toNat_xor] at hfraction
                have hbit : (BitVec.ofNat 64 (2 ^ 63)).toNat = 2 ^ 63 := by
                  norm_num
                rw [hbit] at hfraction
                change (word.val ^^^ (2 ^ 63)) % (2 ^ 52) ≠ 0 at hfraction
                have hxor : word.val ^^^ (2 ^ 63) = word.val + 2 ^ 63 := by
                  have hor := Nat.two_pow_add_eq_or_of_lt wordBound 1
                  have hx : word.val ^^^ (2 ^ 63) =
                      (2 ^ 63) ||| word.val := by
                    apply Nat.eq_of_testBit_eq
                    intro k
                    rw [Nat.testBit_xor, Nat.testBit_or, Nat.testBit_two_pow]
                    by_cases hk : k = 63
                    · subst k
                      rw [Nat.testBit_lt_two_pow wordBound]
                      decide
                    · have hk' : 63 ≠ k := Ne.symm hk
                      simp [hk, hk']
                  exact hx.trans (by simpa [Nat.add_comm] using hor.symm)
                rw [hxor, Nat.add_mod] at hfraction
                norm_num at hfraction
                exact hfraction
            · simp only [negative, if_false] at traced
              cases traced
              obtain ⟨wordSpec, wordBound⟩ :=
                ParserSelectedMagnitudeSign
                  (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have exponentBound := ParserSelectedExponent
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have mantissaBound := ParserSelectedMantissaBound
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              change DecimalGoalVocabularyDefault.assembledWord selected word at wordSpec
              change word.val < 2 ^ 63 at wordBound
              have hwordNonNan := ParserAssembledPairNonNan selected word
                exponentBound.1 exponentBound.2 mantissaBound
                hselectedInfinity wordSpec wordBound
              obtain ⟨canonical, hcanonical, canonicalSpec⟩ :=
                AssemblyCorrespondence selected
              rw [hassembled] at hcanonical
              cases hcanonical
              have resultVal : f.val = word.val := by
                dsimp only [DecimalGoalVocabularyDefault] at wordSpec canonicalSpec
                exact canonicalSpec.trans wordSpec.symm
              dsimp only [DecimalGoalVocabularyDefault] at hwordNonNan ⊢
              simpa [resultVal] using hwordNonNan

end dec2flt_model

Download Lean source · Download TeX source

Complete Lean module
import Tablet.DecimalGoalVocabularyDefault
import Tablet.SourceValidByteSlice
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.ModelF64MantissaDigits
import Tablet.ModelF64Neg
import Tablet.ModelStrAsBytes
import Tablet.ModelSliceFirst
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.SpecialHelperRejection
import Tablet.SpecialHelperInfinity
import Tablet.NativeCorrectOrDefer
import Tablet.ParserSelectedExponent
import Tablet.ParserSelectedMantissaBound
import Tablet.ParserComputeFloatInfinityMantissa
import Tablet.ParserSlowInfinityMantissa
import Tablet.ParserAssembledPairNonNan
import Tablet.ParserSelectedMagnitudeSign
import Tablet.AssemblyCorrespondence
import Tablet.num_imp_dec2flt_dec2flt
import Tablet.num_imp_dec2flt_dec2flt_with_trace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_inf_nan
import Tablet.num_imp_dec2flt_decimal_Decimal_try_fast_path
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
import Tablet.num_imp_dec2flt_common_BiasedFp_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_lemire_compute_float
import Tablet.num_imp_dec2flt_lemire_compute_product_approx
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_closure_Insts_CoreOpsFunctionFnTupleUsizeUsize_call
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq
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_biased_fp_to_float
import Tablet.num_imp_traits_Float_SIG_BITS_default
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

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: ParserNonNanResults]
theorem ParserNonNanResults :
    ∀ (s : Str) (f : F64), DecimalGoalVocabularyDefault.sourceString s ->
      (¬ ∃ negative, DecimalGoalVocabularyDefault.specialLiteral (DecimalGoalVocabularyDefault.bytes s) negative true) ->
      num.imp.dec2flt.dec2flt F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64
        F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64
        F64.Insts.CoreOpsArithNegF64 s = ok (core.result.Result.Ok f) -> ¬ DecimalGoalVocabularyDefault.isNan f := by
-- BODY
  intro s f hsource hnotNanLiteral hpublic
  have bind_ok_inv : ∀ {α β : Type} (r : Result α) (g : α → Result β) y,
      Bind.bind r g = ok y → ∃ z, r = ok z ∧ g z = ok y := by
    intro α β r g y hr
    cases r with
    | fail err => simp [Bind.bind, Aeneas.Std.bind] at hr
    | div => simp [Bind.bind, Aeneas.Std.bind] at hr
    | ok z => exact ⟨z, rfl, hr⟩
  have infinity_not_nan : ∀ (negative : Bool) (value : F64),
      DecimalGoalVocabularyDefault.isInfinity negative value ->
      ¬ DecimalGoalVocabularyDefault.isNan value := by
    intro negative value hinfinity hnan
    dsimp only [DecimalGoalVocabularyDefault] at hinfinity hnan
    cases negative <;>
      simp only [Bool.false_eq_true, if_false, if_true] at hinfinity
    · rw [hinfinity] at hnan
      norm_num at hnan
    · rw [hinfinity] at hnan
      norm_num at hnan
  have signed_bounded_not_nan : ∀ (negative : Bool) (magnitude result : F64),
      magnitude.val ≤ 2047 * 2 ^ 52 ->
      DecimalGoalVocabularyDefault.signedMagnitude negative magnitude result ->
      ¬ DecimalGoalVocabularyDefault.isNan result := by
    intro negative magnitude result hbound hsigned hnan
    dsimp only [DecimalGoalVocabularyDefault] at hsigned hnan
    rcases hsigned with ⟨hmag, hresult⟩
    rcases hnan with ⟨hexponent, hfraction⟩
    have hmodSign : result.val % (2 ^ 63) = magnitude.val := by
      cases negative with
      | false =>
        simp only [Bool.false_eq_true, if_false, add_zero] at hresult
        rw [hresult, Nat.mod_eq_of_lt hmag]
      | true =>
        simp only [if_true] at hresult
        rw [hresult, Nat.add_mod]
        have hm := Nat.mod_eq_of_lt hmag
        rw [hm, Nat.mod_self, Nat.add_zero, hm]
    have hmodFraction :
        result.val % (2 ^ 52) = magnitude.val % (2 ^ 52) := by
      cases negative with
      | false =>
        simp only [Bool.false_eq_true, if_false, add_zero] at hresult
        rw [hresult]
      | true =>
        simp only [if_true] at hresult
        rw [hresult, Nat.add_mod]
        norm_num
    rw [hmodSign] at hexponent
    have hdecomp := Nat.mod_add_div magnitude.val (2 ^ 52)
    rw [hexponent] at hdecomp
    have hmagExact : magnitude.val = 2047 * 2 ^ 52 := by
      norm_num at hdecomp ⊢
      omega
    rw [hmodFraction, hmagExact] at hfraction
    norm_num at hfraction
  unfold num.imp.dec2flt.dec2flt at hpublic
  obtain ⟨out, hout, hpublic⟩ := bind_ok_inv _ _ _ hpublic
  rcases out with ⟨publicResult, trace⟩
  cases hpublic
  have traced :
      num.imp.dec2flt.dec2flt_with_trace
        F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64
        F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64
        F64.Insts.CoreOpsArithNegF64 s =
        ok (core.result.Result.Ok f, trace) := hout
  rcases s with ⟨source, source_bound⟩
  cases source with
  | nil =>
      unfold num.imp.dec2flt.dec2flt_with_trace at traced
      obtain ⟨body, hbody, traced⟩ := bind_ok_inv _ _ _ traced
      have hbodyEq : body = (⟨[], source_bound⟩ : Slice Std.U8) := by
        simpa [core.str.Str.as_bytes, ModelStrAsBytes] using hbody.symm
      subst body
      obtain ⟨firstOption, hfirst, traced⟩ := bind_ok_inv _ _ _ traced
      have hfirstEq : firstOption = none := by
        simpa [core.slice.Slice.first, ModelSliceFirst] using hfirst.symm
      subst firstOption
      obtain ⟨pfe, hpfe, traced⟩ := bind_ok_inv _ _ _ traced
      cases traced
  | cons first tail =>
      unfold num.imp.dec2flt.dec2flt_with_trace at traced
      obtain ⟨body, hbody, traced⟩ := bind_ok_inv _ _ _ traced
      have hbodyEq : body = (⟨first :: tail, source_bound⟩ : Slice Std.U8) := by
        simpa [core.str.Str.as_bytes, ModelStrAsBytes] using hbody.symm
      subst body
      obtain ⟨firstOption, hfirst, traced⟩ := bind_ok_inv _ _ _ traced
      have hfirstEq : firstOption = some first := by
        simpa [core.slice.Slice.first, ModelSliceFirst] using hfirst.symm
      subst firstOption
      obtain ⟨body1, hbody1, traced⟩ := bind_ok_inv _ _ _ traced
      have body1Valid : SourceValidByteSlice body1 := by
        unfold SourceValidByteSlice
        have hslen := hsource.1
        by_cases hminus : first = 45#u8
        · simp only [hminus, if_true] at hbody1
          simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
            Slice.drop] at hbody1
          cases hbody1
          simp at hslen ⊢
          omega
        · simp only [hminus, if_false] at hbody1
          by_cases hplus : first = 43#u8
          · simp only [hplus, if_true] at hbody1
            simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
              Slice.drop] at hbody1
            cases hbody1
            simp at hslen ⊢
            omega
          · simp only [hplus, if_false] at hbody1
            cases hbody1
            exact hslen
      have noNanBody : ¬ DecimalGoalVocabularyDefault.specialLiteral
          (DecimalGoalVocabularyDefault.bytes body1) none true := by
        intro hspecial
        apply hnotNanLiteral
        by_cases hminus : first = 45#u8
        · simp only [hminus, if_true] at hbody1
          simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
            Slice.drop] at hbody1
          cases hbody1
          refine ⟨some true, ?_⟩
          dsimp only [DecimalGoalVocabularyDefault] at hspecial ⊢
          rcases hspecial with ⟨specialBody, hspecialBody, hcase⟩
          refine ⟨specialBody, ?_, hcase⟩
          subst first
          simpa using hspecialBody
        · simp only [hminus, if_false] at hbody1
          by_cases hplus : first = 43#u8
          · simp only [hplus, if_true] at hbody1
            simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
              Slice.drop] at hbody1
            cases hbody1
            refine ⟨some false, ?_⟩
            dsimp only [DecimalGoalVocabularyDefault] at hspecial ⊢
            rcases hspecial with ⟨specialBody, hspecialBody, hcase⟩
            refine ⟨specialBody, ?_, hcase⟩
            subst first
            simpa using hspecialBody
          · simp only [hplus, if_false] at hbody1
            cases hbody1
            exact ⟨none, hspecial⟩
      obtain ⟨empty, hempty, traced⟩ := bind_ok_inv _ _ _ traced
      by_cases emptyTrue : empty = true
      · simp only [emptyTrue, if_true] at traced
        obtain ⟨pfe, hpfe, traced⟩ := bind_ok_inv _ _ _ traced
        cases traced
      · have emptyFalse : empty = false := Bool.eq_false_of_not_eq_true emptyTrue
        simp only [emptyFalse, if_false] at traced
        obtain ⟨parsed, hparsed, traced⟩ := bind_ok_inv _ _ _ traced
        cases parsed with
        | none =>
          obtain ⟨special, hspecial, traced⟩ := bind_ok_inv _ _ _ traced
          cases special with
          | none =>
            obtain ⟨pfe, hpfe, traced⟩ := bind_ok_inv _ _ _ traced
            cases traced
          | some value =>
            cases traced
            by_cases hInf : DecimalGoalVocabularyDefault.specialLiteral
                (DecimalGoalVocabularyDefault.bytes body1) none false
            · obtain ⟨infinity, hinfinityEq, hinfinity⟩ :=
                SpecialHelperInfinity body1 (decide (first = 45#u8)) hInf
              rw [hspecial] at hinfinityEq
              cases hinfinityEq
              exact infinity_not_nan _ _ hinfinity
            · have hrejection := SpecialHelperRejection body1
                (decide (first = 45#u8)) body1Valid hInf noNanBody
              rw [hspecial] at hrejection
              cases hrejection
        | some r =>
          obtain ⟨fast, hfast, traced⟩ := bind_ok_inv _ _ _ traced
          cases fast with
          | some value =>
            have hnative := NativeCorrectOrDefer
              ({ r with negative := decide (first = 45#u8) })
              (some value) hfast
            rcases hnative with hnone |
              ⟨value', magnitude, hvalue, _, hrounds, hsigned⟩
            · simp at hnone
            · cases hvalue
              cases traced
              dsimp only [DecimalGoalVocabularyDefault] at hrounds
              exact signed_bounded_not_nan _ _ _ hrounds.2.1 hsigned
          | none =>
            obtain ⟨firstPair, hfirstPair, traced⟩ := bind_ok_inv _ _ _ traced
            have hfirstInfinity :=
              ParserComputeFloatInfinityMantissa _ _ _ hfirstPair
            obtain ⟨phase1, hphase1, traced⟩ := bind_ok_inv _ _ _ traced
            rcases phase1 with ⟨many1, many2, firstPair1, fp, guard⟩
            have hfp : fp = firstPair := by
              by_cases hm : r.many_digits
              · simp only [hm, if_true] at hphase1
                cases hphase1
                rfl
              · simp only [hm, if_false] at hphase1
                cases hphase1
                rfl
            subst fp
            obtain ⟨phase2, hphase2, traced⟩ := bind_ok_inv _ _ _ traced
            rcases phase2 with
              ⟨post, secondExp, secondMant, secondResult, secondEqual, forced⟩
            have hpostInfinity :
                post.p_biased.val = 2047 -> post.m.val = 0 := by
              cases guard with
              | false =>
                simp only [Bool.false_eq_true, if_false] at hphase2
                cases hphase2
                exact hfirstInfinity
              | true =>
                simp only [if_true] at hphase2
                obtain ⟨mantissa, hmantissa, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                obtain ⟨second, hsecond, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                obtain ⟨equal, hequal, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                obtain ⟨chosen, hchosen, hphase2⟩ :=
                  bind_ok_inv _ _ _ hphase2
                rcases chosen with ⟨bf, wasForced⟩
                have hbf : bf.p_biased.val = 2047 -> bf.m.val = 0 := by
                  by_cases heq : equal = true
                  · simp only [heq, if_true] at hchosen
                    cases hchosen
                    exact hfirstInfinity
                  · have heqf : equal = false :=
                      Bool.eq_false_of_not_eq_true heq
                    simp only [heqf, if_false] at hchosen
                    cases hchosen
                    intro hp
                    norm_num at hp
                cases hphase2
                exact hbf
            obtain ⟨phase3, hphase3, traced⟩ := bind_ok_inv _ _ _ traced
            rcases phase3 with ⟨selected, slowGuard, slowResult⟩
            have hselectedInfinity :
                selected.p_biased.val = 2047 -> selected.m.val = 0 := by
              by_cases hneg : post.p_biased < 0#i32
              · simp only [hneg, if_true] at hphase3
                obtain ⟨replacement, hreplacement, hphase3⟩ :=
                  bind_ok_inv _ _ _ hphase3
                have hreplacement :=
                  ParserSlowInfinityMantissa _ _ hreplacement
                cases hphase3
                exact hreplacement
              · simp only [hneg, if_false] at hphase3
                cases hphase3
                exact hpostInfinity
            obtain ⟨i, hi, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨i1, hi1, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨i2, hi2, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨word, hword, traced⟩ := bind_ok_inv _ _ _ traced
            obtain ⟨assembled, hassembled, traced⟩ := bind_ok_inv _ _ _ traced
            by_cases negative : first = 45#u8
            · simp only [negative, if_true] at traced
              obtain ⟨result, hresult, traced⟩ := bind_ok_inv _ _ _ traced
              cases traced
              obtain ⟨wordSpec, wordBound⟩ :=
                ParserSelectedMagnitudeSign
                  (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have exponentBound := ParserSelectedExponent
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have mantissaBound := ParserSelectedMantissaBound
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              change DecimalGoalVocabularyDefault.assembledWord selected word at wordSpec
              change word.val < 2 ^ 63 at wordBound
              have hwordNonNan := ParserAssembledPairNonNan selected word
                exponentBound.1 exponentBound.2 mantissaBound
                hselectedInfinity wordSpec wordBound
              obtain ⟨canonical, hcanonical, canonicalSpec⟩ :=
                AssemblyCorrespondence selected
              rw [hassembled] at hcanonical
              cases hcanonical
              have assembledVal : assembled.val = word.val := by
                dsimp only [DecimalGoalVocabularyDefault] at wordSpec canonicalSpec
                exact canonicalSpec.trans wordSpec.symm
              have assembledEq : assembled = word :=
                UScalar.eq_of_val_eq assembledVal
              subst assembled
              change ModelF64Neg word = ok f at hresult
              cases hresult
              dsimp only [DecimalGoalVocabularyDefault] at hwordNonNan ⊢
              intro hnan
              apply hwordNonNan
              rcases hnan with ⟨hexponent, hfraction⟩
              refine ⟨?_, ?_⟩
              · change (((word.bv ^^^ BitVec.ofNat 64 (2 ^ 63)).toNat) %
                    2 ^ 63) / 2 ^ 52 = 2047 at hexponent
                rw [BitVec.toNat_xor] at hexponent
                have hbit : (BitVec.ofNat 64 (2 ^ 63)).toNat = 2 ^ 63 := by
                  norm_num
                rw [hbit] at hexponent
                change (word.val ^^^ (2 ^ 63)) % (2 ^ 63) /
                    (2 ^ 52) = 2047 at hexponent
                have hxor : word.val ^^^ (2 ^ 63) = word.val + 2 ^ 63 := by
                  have hor := Nat.two_pow_add_eq_or_of_lt wordBound 1
                  have hx : word.val ^^^ (2 ^ 63) =
                      (2 ^ 63) ||| word.val := by
                    apply Nat.eq_of_testBit_eq
                    intro k
                    rw [Nat.testBit_xor, Nat.testBit_or, Nat.testBit_two_pow]
                    by_cases hk : k = 63
                    · subst k
                      rw [Nat.testBit_lt_two_pow wordBound]
                      decide
                    · have hk' : 63 ≠ k := Ne.symm hk
                      simp [hk, hk']
                  exact hx.trans (by simpa [Nat.add_comm] using hor.symm)
                rw [hxor, Nat.add_mod] at hexponent
                norm_num at hexponent
                exact hexponent
              · change (((word.bv ^^^ BitVec.ofNat 64 (2 ^ 63)).toNat) %
                    2 ^ 52) ≠ 0 at hfraction
                rw [BitVec.toNat_xor] at hfraction
                have hbit : (BitVec.ofNat 64 (2 ^ 63)).toNat = 2 ^ 63 := by
                  norm_num
                rw [hbit] at hfraction
                change (word.val ^^^ (2 ^ 63)) % (2 ^ 52) ≠ 0 at hfraction
                have hxor : word.val ^^^ (2 ^ 63) = word.val + 2 ^ 63 := by
                  have hor := Nat.two_pow_add_eq_or_of_lt wordBound 1
                  have hx : word.val ^^^ (2 ^ 63) =
                      (2 ^ 63) ||| word.val := by
                    apply Nat.eq_of_testBit_eq
                    intro k
                    rw [Nat.testBit_xor, Nat.testBit_or, Nat.testBit_two_pow]
                    by_cases hk : k = 63
                    · subst k
                      rw [Nat.testBit_lt_two_pow wordBound]
                      decide
                    · have hk' : 63 ≠ k := Ne.symm hk
                      simp [hk, hk']
                  exact hx.trans (by simpa [Nat.add_comm] using hor.symm)
                rw [hxor, Nat.add_mod] at hfraction
                norm_num at hfraction
                exact hfraction
            · simp only [negative, if_false] at traced
              cases traced
              obtain ⟨wordSpec, wordBound⟩ :=
                ParserSelectedMagnitudeSign
                  (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have exponentBound := ParserSelectedExponent
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              have mantissaBound := ParserSelectedMantissaBound
                (⟨first :: tail, source_bound⟩ : Str) f _ hsource hout
              change DecimalGoalVocabularyDefault.assembledWord selected word at wordSpec
              change word.val < 2 ^ 63 at wordBound
              have hwordNonNan := ParserAssembledPairNonNan selected word
                exponentBound.1 exponentBound.2 mantissaBound
                hselectedInfinity wordSpec wordBound
              obtain ⟨canonical, hcanonical, canonicalSpec⟩ :=
                AssemblyCorrespondence selected
              rw [hassembled] at hcanonical
              cases hcanonical
              have resultVal : f.val = word.val := by
                dsimp only [DecimalGoalVocabularyDefault] at wordSpec canonicalSpec
                exact canonicalSpec.trans wordSpec.symm
              dsimp only [DecimalGoalVocabularyDefault] at hwordNonNan ⊢
              simpa [resultVal] using hwordNonNan

end dec2flt_model

Proof structure

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

Uses

All 50 entries

Used by

No other declaration in this version lists this one as a dependency.

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 187 entries
Technical checking records
Local closure summary
{
  "node": "ParserNonNanResults",
  "closure_version": "patch_c_v1",
  "active_decl_hash": "fd5163805484e0f358f113d2c7d40cf25a27a873eb3daffd909fef24b5cc24b1",
  "active_statement_hash": "508da2fae6fcede85d303ff05d1a299a8e83316244dadb8d4840c30259c8656b",
  "kernel_axioms": [
    "Classical.choice",
    "Quot.sound",
    "propext"
  ],
  "toolchain_hash": "ce4c4e3d87434b9663f46de25ce34b48a0cf0d392e0a320a0787b4674a2d7b61",
  "lean_executable_hash": "3e0d0d3d801675359f2d4cf9815bfdb417b20b92fdd9d48b3b14c95bbae28bbf",
  "checker_script_hash": "c8e4a03273e23b9a8f2e141020652a4e0b7b0a8ab0883366ea9d031ca3f37aa1",
  "approved_axioms_hash": "ab64d13f256386ee0e494a5abcc6a5db49512cf3d90bbdfcabd6327793a31f95",
  "axcheck_status": "Agreed",
  "accepted_at_snapshot_id": "worker-result-local-closure-issuance-cycle-136",
  "boundary_theorems": {},
  "strict_theorem_deps": {
    "AssemblyCorrespondence": "e3495a6647394e20",
    "DecimalGoalVocabularyDefault": "94cb4c406f8efb78",
    "NativeCorrectOrDefer": "4eb7d1b8e4ed1a56",
    "ParserAssembledPairNonNan": "5be7fbb4c365e47d",
    "ParserComputeFloatInfinityMantissa": "3d5b3a671765d393",
    "ParserSelectedExponent": "2d4e5f8c99bf68c7",
    "ParserSelectedMagnitudeSign": "70c47baac228615a",
    "ParserSelectedMantissaBound": "8c0433452b441220",
    "ParserSlowInfinityMantissa": "35810a563a0faf15",
    "SpecialHelperInfinity": "4124e26dd85ce114",
    "SpecialHelperRejection": "e1e229c5dd3ecf3c",
    "num_imp_dec2flt_dec2flt_with_trace": "f3e7d4ffbf9b4d68",
    "num_imp_traits_Float_SIG_BITS_default": "9ab622d85ef04d94"
  },
  "strict_definition_deps": {
    "DecimalGoalVocabulary": "91e42e6d78c02c8e",
    "DecimalGoalVocabularyDefault": "512f8d0aea894250",
    "F64": "ec4e25fbaf4e11d4",
    "F64_Insts_CoreOpsArithDivF64F64": "dc44e13a99fc6bed",
    "F64_Insts_CoreOpsArithMulF64F64": "1ae1a9021a654abd",
    "F64_Insts_CoreOpsArithNegF64": "2d9be310c546ea2e",
    "F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64": "30963b4ef656cc79",
    "F64_Insts_Dec2flt_modelNumImpTraitsFloatExtU64": "60afe26c6a80cf0f",
    "F64_Insts_Dec2flt_modelNumImpTraitsFloatU64": "94095c9bf79da164",
    "F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SIG_TOTAL_BITS": "887b52d84a3fc9c4",
    "ModelF64Neg": "78a021de99eb373b",
    "ModelSliceFirst": "a31394b3c1080f71",
    "Preamble": "86dc391ab250c79b",
    "SourceValidByteSlice": "3dc42716a6378d26",
    "core_ops_arith_Neg": "0ff07135a60bcbf9",
    "num_float_parse_ParseFloatError": "c43614ff2149ecf2",
    "num_imp_dec2flt_Dec2FltAssemblyTrace": "7bda5de02611ad76",
    "num_imp_dec2flt_Dec2FltTrace": "644abe66cec8ac98",
    "num_imp_dec2flt_Lemire": "1923f90c53d323e6",
    "num_imp_dec2flt_biased_fp_to_float": "acdde060e8d35ca7",
    "num_imp_dec2flt_common_BiasedFp": "31d81cf1cf22709f",
    "num_imp_dec2flt_common_BiasedFp_Insts_CoreCmpPartialEqBiasedFp_eq": "fbbf553e3c502a05",
    "num_imp_dec2flt_dec2flt": "f9f7d93449a25efa",
    "num_imp_dec2flt_dec2flt_with_trace": "5665189e0304a27e",
    "num_imp_dec2flt_decimal_Decimal": "fe99f3f976739f2d",
    "num_imp_dec2flt_decimal_Decimal_try_fast_path": "2e4888f65a06b49f",
    "num_imp_dec2flt_lemire_compute_float": "39d89e3f0a8a9d4c",
    "num_imp_dec2flt_parse_parse_inf_nan": "85655c19a8791b54",
    "num_imp_dec2flt_parse_parse_number": "f73f8bc11faa6db3",
    "num_imp_dec2flt_pfe_empty": "89046d1da5ac1ce2",
    "num_imp_dec2flt_pfe_invalid": "21db875427d92c6d",
    "num_imp_dec2flt_slow_parse_long_mantissa": "cd8af64c3688b60f",
    "num_imp_traits_Float": "02acccb9db3e30f2",
    "num_imp_traits_FloatExt": "f996e5400649797d"
  }
}
Prose assessment
{
  "label": "Recorded Sound: VerifierPass",
  "assessment_status": "VerifierPass",
  "fingerprint_relation": "matches current fingerprint",
  "assessment_fingerprint": "sound-v2:dfd3c70b8df8e62ea62844da2c916902cdb5760ea6c811598421b32d3e226cb4",
  "current_fingerprint": "sound-v2:dfd3c70b8df8e62ea62844da2c916902cdb5760ea6c811598421b32d3e226cb4",
  "superseded_for_theorem_closure": false
}
Review verdicts
{
  "corr_status": "Pass",
  "sound_status": "Pass",
  "substantiveness_status": "Pass"
}