ParserSelectedMagnitudeSign

Lean checked

Statement

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

Theorem

For every normally successful numeric execution whose trace selects a raw pair for final assembly, its recorded assembled word agrees with unrestricted raw-pair assembly and has a clear sign bit.

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.ModelF64MantissaDigits
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.ParserSelectedExponent
import Tablet.ParserSelectedMantissaBound
import Tablet.ParserExponentConstants
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_SIG_TOTAL_BITS
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_dec2flt_with_trace
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_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
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_parse_decimal_seq
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_biased_fp_to_float
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: ParserSelectedMagnitudeSign]
theorem ParserSelectedMagnitudeSign :
    ∀ (s : Str) (f : F64) (tr : num.imp.dec2flt.Dec2FltAssemblyTrace F64),
      DecimalGoalVocabularyDefault.sourceString s ->
      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, num.imp.dec2flt.Dec2FltTrace.Assembled tr) ->
      DecimalGoalVocabularyDefault.assembledWord tr.selected_pair tr.assembled_word ∧ tr.assembled_word.val < 2 ^ 63 := 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

Put U=2^{52}. We first evaluate the significand-width constant used in assembly. Through the traitsFloatExtInst field of F64 Insts Dec2flt modelNumImpDec2fltLemireU64, F64 Insts Dec2flt modelNumImpTraitsFloatExtU64 selects exactly F64 Insts Dec2flt modelNumImpTraitsFloatU64. Its SIG_TOTAL_BITS method is F64 Insts Dec2flt modelNumImpTraitsFloatU64 SIG TOTAL BITS, which calls ModelF64MantissaDigits and returns 53. Therefore the checked subtraction in num imp traits Float SIG BITS default is 53-1=52, with no underflow, and the concrete SIG_BITS call returns the 32-bit word 52.
We next establish the mantissa range which is actually preserved by the integer and slow converters. The required, and strongest uniformly true, integer-converter fact is
\texttt{compute\_float}(F_0,q,w)=\texttt{ok }b \quad\Longrightarrow\quad b.m.\mathit{val}\leq U, \tag{1}
where F_0 is the concrete Float instance just identified. Unfold num imp dec2flt lemire compute float. Each of its three eager sentinels is made by num imp dec2flt common BiasedFp zero pow2, hence has mantissa zero: the zero, infinity, and error pairs are respectively (0,0), (0,i) for the successfully returned infinite-power constant i, and (0,-1). Thus the w=0, lower-decimal-cutoff, upper-decimal-cutoff, approximation-error, severe-underflow, and final infinity exits all satisfy (1).
On either remaining product branch, w\ne0. Its leading-zero count is in 0,\ldots,63, so normalization uses a legal unsigned shift count. The cast of SIG_BITS to usize is exactly 52, and the checked addition gives precision 55. The call to num imp dec2flt lemire compute product approx either fails, which is incompatible with the displayed successful premise, or returns a pair of 64-bit words (lo,hi). Shifting hi right by 63 uses a legal signed nonnegative count and gives upperbit equal to zero or one; its cast to i32 is exact. The checked operations
\texttt{upperbit}+64-52-3
therefore give a shift count 9 or 10. If upperbit=0, then hi<2^{63} and hi\mathbin{\mathtt{>>}}9<2^{54}; if it is one, then hi<2^{64} and hi\mathbin{\mathtt{>>}}10<2^{54}. Hence the local mantissa before rounding always has value less than 2^{54}. The casts of q and of the leading-zero count, and the checked signed additions and subtractions which calculate power2, are monadic predecessors of every remaining return. Any failure propagates; on a successful path they have their displayed integer meanings. The two copies of this calculation, below the two outcomes of the lo test, are identical and so have the same bound.
Suppose first that power2\leq0. Its checked negation and addition form k=-\texttt{power2}+1. If k\geq64, the function returns the zero sentinel. Otherwise the successful checked operations give 1\leq k\leq63. By the exact bounded right-shift semantics,
x=\texttt{mantissa}\mathbin{\mathtt{>>}}k<2^{54-k}\leq2^{53}.
By ModelU64BitAnd, e=x\mathbin{\mathtt{\&}}1 is either zero or one and is the low bit of x. Consequently the checked addition x+e cannot overflow and is at most 2^{53}: its only possible upper endpoint is obtained from x=2^{53}-1 and e=1. The following legal right shift by one therefore produces a returned mantissa at most 2^{52}=U. The shift 1\mathbin{\mathtt{<<}}52 is legal by ModelU64Shl; the Boolean comparison with that value and its exact Boolean-to-i32 cast change only the exponent. This proves (1) on the subnormal/right-shift-and-round return, including its possible endpoint b.m=U.
Suppose instead that power2>0$. The round-to-even tests cast the concrete cutoff constants only after their guards; every such cast and the left-shift equality probe either succeeds or precludes an ok return. The probe's shift count is again 9 or 10. Its only assignment to the mantissa is conjunction with the complement of one, which merely clears the low bit by ModelU64BitAnd. Thus the mantissa remains below 2^{54}. Adding its low bit is at most 2^{54} and cannot overflow, and the subsequent right shift by one is at most 2^{53}. Both scalar shifts 2\mathbin{\mathtt{<<}}52=2^{53} and 1\mathbin{\mathtt{<<}}52=U have legal count 52. If the first threshold is met, the code replaces the value by U and performs the checked exponent increment; otherwise its value is strictly below 2^{53}. In both cases the final conjunction with the complement of U clears bit 52. A value below 2^{53} has no higher set bit, so the resulting ordinary-return mantissa is strictly below U. The final exponent guard either returns the zero-mantissa infinity sentinel or this masked record. This exhausts every successful return of both duplicated blocks and proves (1). Notice that all normalization, product, cast, checked-arithmetic, mask, and scalar-shift failures mentioned above occur inside the result monad; none is silently assigned a value on an ok path.
The corresponding slow-converter fact is the strict bound
\texttt{parse\_long\_mantissa}(F_0,t)=\texttt{ok }b \quad\Longrightarrow\quad b.m.\mathit{val}<U. \tag{2}
Unfold num imp dec2flt slow parse long mantissa. Its eager zero and infinity pairs 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. An empty digit sequence or decimal point below -324 returns zero, while a decimal point at least 310 returns infinity.
For its first loop, use the invariant that the loop-result field is none or some fp_0. It starts as none; the only assignment follows a call through num imp dec2flt slow parse long mantissa closure Insts CoreOpsFunctionFnTupleUsizeUsize call and num imp dec2flt decimal seq DecimalSeq right shift, and assigns exactly fp_0. The other branches preserve the field or terminate. Its positive decimal-point cast to usize, negation of the range constant, shift cast back to i32, checked exponent addition, and called decimal operation all precede the loop result monadically, so any failure rules out the assumed successful outer return. Thus a some exit has zero mantissa. The second loop analogously maintains none or some fp_\infty. Its index-zero read, decimal-point negation and cast, closure call, calls to num imp dec2flt decimal seq DecimalSeq left shift, shift casts, and checked exponent subtractions all propagate failure. Its only assignments to the result field store exactly fp_\infty, so every some exit again has zero mantissa.
If both fields remain none, the third loop either propagates a failure or eventually exits through its done branch. In each continuing iteration it forms the checked positive difference from the minimum exponent, casts it to usize, caps it by num imp dec2flt slow parse long mantissa MAX SHIFT at 60, invokes num imp dec2flt decimal seq DecimalSeq right shift, casts the bounded count back to i32, and performs a checked exponent addition. Thus every cast, subtraction, addition, decimal shift, and loop transition on an eventual successful exit has succeeded.
On the post-loop path, failures of the checked exponent subtraction and addition propagate, and the first exponent guard may return the infinity sentinel. Otherwise 52 casts exactly to usize, the checked addition produces 53, and the call to num imp dec2flt decimal seq DecimalSeq left shift and then num imp dec2flt decimal seq DecimalSeq round must succeed. The checked addition 52+1 in the 32-bit shift count also gives 53, so 1\mathbin{\mathtt{<<}}53 is legal. If the rounding-carry guard is true, the decimal right shift by one, checked exponent increment, second rounding call, subsequent exponent subtractions and additions, and second infinity guard must all succeed; that guard may again return the zero-mantissa infinity pair. On either the carrying or noncarrying ordinary return, the code legally forms 1\mathbin{\mathtt{<<}}52=U, performs the checked subtraction U-1, and conjoins the rounded word with U-1. The exact bounded conjunction from ModelU64BitAnd is at most U-1, hence is strictly below U. These are all sentinel, loop-result, carrying, and noncarrying exits, proving (2).
Now unfold num imp dec2flt dec2flt with trace under the assumed successful Assembled result. By the constructor list in num imp dec2flt Dec2FltTrace, the EmptyInput, SignOnly, Invalid, Special, and FastPath constructors are disjoint from its Assembled constructor. Therefore the calls to num imp dec2flt parse parse number and num imp dec2flt decimal Decimal try fast path returned respectively some r and none; the unsuccessful numeric branch which calls num imp dec2flt parse parse inf nan is not taken. The three concrete arithmetic arguments in this same execution are F64 Insts CoreOpsArithDivF64F64, F64 Insts CoreOpsArithMulF64F64, and F64 Insts CoreOpsArithNegF64; only the last can be reached after assembly, and a failure from it cannot produce the assumed outer ok.
The first integer computation satisfies (1). If many_digits is false, or the first exponent is negative, no second computation occurs and the post-comparison pair is the first pair. Otherwise the checked addition r.\texttt{mantissa}+1 and the second integer computation must succeed, and the second result also satisfies (1). The exact two-field comparison num imp dec2flt common BiasedFp Insts CoreCmpPartialEqBiasedFp eq either retains the first pair or retains its mantissa while replacing its exponent by -1. Thus every post-comparison mantissa is at most U. If its exponent is negative, the definition necessarily replaces the entire pair by the successfully returned slow result, which satisfies the stronger (2); a temporary forced exponent -1 is therefore never assembled. Otherwise the post-comparison pair itself is selected. In all cases the final local pair b obeys
b.m.\mathit{val}\leq U. \tag{3}
The eventual return is Assembled applied to a structure whose selected_pair field, as declared by num imp dec2flt Dec2FltAssemblyTrace, is this same local b. Injectivity of that constructor from num imp dec2flt Dec2FltTrace in the assumed result equality, together with the assembly-record literal in the extracted function and the selected_pair projection declared by num imp dec2flt Dec2FltAssemblyTrace, already identifies b with tr.\texttt{selected\_pair}. Apply ParserSelectedExponent to the same source-string and execution hypotheses. It gives the independent bound
0\leq p=tr.\texttt{selected\_pair}.p_{\rm biased}.\mathit{val} \leq2047. \tag{4}
The assembly cast in num imp dec2flt dec2flt with trace is the signed-to-unsigned bit-vector cast. By (4) its input is nonnegative and below 2^{32}, so its 64-bit value is exactly the natural number p, without sign extension into the upper bits. The already evaluated count 52 is below 64, so ModelU64Shl shows that the checked shift succeeds and has value
E=p2^{52}=pU\leq2047U=2^{63}-U<2^{64}. \tag{5}
There is consequently no truncation and the low 52 bits of E are zero.
Let m be the selected mantissa and let W be the local assembled word. By ModelU64BitOr, the final OR succeeds and is the exact bounded bitwise disjunction of m and E. The local selection argument gives m\leq U. If m<U, it occupies only the low 52 bits, disjoint from E, so
W.\mathit{val}=pU+m\leq2047U+(U-1)=2^{63}-1.
If m=U, split on the low bit of p. For odd p, bit 52 is already set in E, so the OR is pU\leq2047U; for even p, (4) gives p\leq2046 and the OR is (p+1)U\leq2047U. Thus in this endpoint case also W.\mathit{val}\leq2^{63}-U. In every case W.\mathit{val}<2^{63}.
It remains to connect the local computation to the two requested recorded facts. Both sign branches first call num imp dec2flt biased fp to float; any failure there or in the optional final negation would contradict the assumed outer ok. They then construct Assembled from the structure described by the record literal in num imp dec2flt dec2flt with trace. Against the field schema of num imp dec2flt Dec2FltAssemblyTrace, that literal stores the same local b in selected_pair and the same W in assembled_word. Injectivity of the Assembled constructor from num imp dec2flt Dec2FltTrace, followed by the selected_pair and assembled_word projections declared by num imp dec2flt Dec2FltAssemblyTrace, therefore identifies those fields with the corresponding fields of tr and transfers the strict bound on W to tr.\texttt{assembled\_word}.
Finally unfold the assembledWord field of DecimalGoalVocabularyDefault. By (4), the Euclidean remainder of p modulo 2^{64} is p and converting it to a natural number changes nothing. By (5), pU<2^{64}, so the following modulus by 2^{64} also changes nothing. The definition therefore asks precisely for
tr.\texttt{assembled\_word}.\mathit{val} =\operatorname{Nat.lor}(m,pU),
which is the exact value of the extracted OR established above and recorded by constructor injectivity. This proves both the unrestricted assembly agreement and the clear-sign-bit inequality. The sourceString premise is used in the application of ParserSelectedExponent and states the supplied source domain; no stronger lexical property is needed for this model-internal assembly argument.

Lean proof


  intro s f tr hs h
  have hmant := ParserSelectedMantissaBound s f tr hs h
  have hexponent := ParserSelectedExponent s f tr hs h
  obtain ⟨hbits, htotal, hsig, hexpbits, hexpsat, hinf, hbias, hmin,
      hsmall, hlarge, hroundmin, hroundmax⟩ := ParserExponentConstants
  have bind_ok_inv : ∀ {α β : Type} (r : Result α) (g : α → Result β) y,
      Bind.bind r g = ok y → ∃ x, r = ok x ∧ g x = 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 x => exact ⟨x, rfl, hr⟩
  have assemble : ∀ (fp : num.imp.dec2flt.common.BiasedFp)
      (i i2 word : Std.U64),
      0 <= fp.p_biased.val ->
      fp.p_biased.val <= 2047 ->
      fp.m.val <= 2 ^ 52 ->
      lift (IScalar.hcast .U64 fp.p_biased) = ok i ->
      i <<< 52#u32 = ok i2 ->
      lift (fp.m ||| i2) = ok word ->
      DecimalGoalVocabularyDefault.assembledWord fp word ∧
        word.val < 2 ^ 63 := by
    intro fp i i2 word hp0 hp1 hm hi hi2 hword
    have hcast := IScalar.hcast_inBounds_spec .U64 fp.p_biased (by
      constructor
      · exact hp0
      · scalar_tac)
    rw [hi] at hcast
    have hiVal : i.val = fp.p_biased.val.toNat := by
      have hz : (fp.p_biased.val.toNat : Int) = fp.p_biased.val :=
        Int.toNat_of_nonneg hp0
      simp only [WP.spec_ok] at hcast
      omega
    have hshift := UScalar.ShiftLeft_spec i (52#u32) (2 ^ 64)
        (by norm_num) (by simp [U64.size, U64.numBits])
    rw [hi2] at hshift
    have hi2Val : i2.val = i.val * 2 ^ 52 := by
      rcases hshift with ⟨hval, hbv⟩
      rw [Nat.shiftLeft_eq] at hval
      norm_num at hval
      have hip : i.val <= 2047 := by omega
      have hlt : i.val * 2 ^ 52 < 2 ^ 64 := by omega
      omega
    simp only [lift] at hword
    cases hword
    have hpmod : fp.p_biased.val.emod (2 ^ 64) =
        fp.p_biased.val := by
      apply Int.emod_eq_of_lt hp0
      omega
    have hexp :
        (((fp.p_biased.val.emod (2 ^ 64)).toNat * (2 ^ 52)) %
            (2 ^ 64)) = i2.val := by
      rw [hpmod, <- hiVal, hi2Val]
      have hlt : i.val * 2 ^ 52 < 2 ^ 64 := by omega
      exact (Nat.mod_eq_of_lt hlt).trans rfl
    have hassembled :
        DecimalGoalVocabularyDefault.assembledWord fp (fp.m ||| i2) := by
      dsimp only [DecimalGoalVocabularyDefault]
      change (fp.m.bv ||| i2.bv).toNat = _
      rw [BitVec.toNat_or]
      simp only [UScalar.bv_toNat, hexp]
      rfl
    have hwordBound : (fp.m ||| i2).val < 2 ^ 63 := by
      change (fp.m.bv ||| i2.bv).toNat < _
      rw [BitVec.toNat_or]
      simp only [UScalar.bv_toNat]
      have hmant63 : fp.m.val < 2 ^ 63 := by omega
      have hexp63 : i2.val < 2 ^ 63 := by omega
      apply Nat.lt_of_testBit 63
      · rw [Nat.testBit_lor,
          Nat.testBit_eq_false_of_lt hmant63,
          Nat.testBit_eq_false_of_lt hexp63]
        rfl
      · rw [Nat.testBit_two_pow]
        decide
      · intro j hj
        rw [Nat.testBit_lor]
        have hmantj : fp.m.val < 2 ^ j := by
          exact lt_of_lt_of_le hmant63
            (Nat.pow_le_pow_right (by omega) (by omega))
        have hexpj : i2.val < 2 ^ j := by
          exact lt_of_lt_of_le hexp63
            (Nat.pow_le_pow_right (by omega) (by omega))
        rw [Nat.testBit_eq_false_of_lt hmantj,
          Nat.testBit_eq_false_of_lt hexpj]
        rw [Nat.testBit_two_pow]
        simp [hj.ne]
    by_cases hendpoint : fp.m.val = 2 ^ 52
    · by_cases heven : i.val % 2 = 0
      · have hipEven : i.val <= 2046 := by
          have hmodlt := Nat.mod_lt i.val (by norm_num : 0 < 2)
          omega
        exact ⟨hassembled, hwordBound⟩
      · have hodd : i.val % 2 = 1 := by
          have hmodlt := Nat.mod_lt i.val (by norm_num : 0 < 2)
          omega
        exact ⟨hassembled, hwordBound⟩
    · have hmStrict : fp.m.val < 2 ^ 52 := by omega
      exact ⟨hassembled, hwordBound⟩
  unfold num.imp.dec2flt.dec2flt_with_trace at h
  obtain ⟨body, hbody, h⟩ := bind_ok_inv _ _ _ h
  obtain ⟨first, hfirst, h⟩ := bind_ok_inv _ _ _ h
  cases first with
  | none =>
    obtain ⟨pfe, hpfe, h⟩ := bind_ok_inv _ _ _ h
    cases h
  | some c =>
    obtain ⟨body1, hbody1, h⟩ := bind_ok_inv _ _ _ h
    obtain ⟨empty, hempty, h⟩ := bind_ok_inv _ _ _ h
    by_cases he : empty = true
    · simp only [he, if_true] at h
      obtain ⟨pfe, hpfe, h⟩ := bind_ok_inv _ _ _ h
      cases h
    · have hef : empty = false := Bool.eq_false_of_not_eq_true he
      simp only [hef, if_false] at h
      obtain ⟨parsed, hparsed, h⟩ := bind_ok_inv _ _ _ h
      cases parsed with
      | none =>
        obtain ⟨special, hspecial, h⟩ := bind_ok_inv _ _ _ h
        cases special with
        | none =>
          obtain ⟨pfe, hpfe, h⟩ := bind_ok_inv _ _ _ h
          cases h
        | some value => cases h
      | some r =>
        obtain ⟨fast, hfast, h⟩ := bind_ok_inv _ _ _ h
        cases fast with
        | some value => cases h
        | none =>
          obtain ⟨firstPair, hfirstPair, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨phase1, hphase1, h⟩ := bind_ok_inv _ _ _ h
          rcases phase1 with ⟨many1, many2, firstPair1, fp, guard⟩
          obtain ⟨phase2, hphase2, h⟩ := bind_ok_inv _ _ _ h
          rcases phase2 with
            ⟨post, secondExp, secondMant, secondResult, secondEqual, forced⟩
          obtain ⟨phase3, hphase3, h⟩ := bind_ok_inv _ _ _ h
          rcases phase3 with ⟨selected, slowGuard, slowResult⟩
          obtain ⟨i, hi, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨i1, hi1, h⟩ := bind_ok_inv _ _ _ h
          change F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.SIG_BITS =
            ok i1 at hi1
          rw [hsig] at hi1
          cases hi1
          obtain ⟨i2, hi2, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨word, hword, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨assembled, hassembled, h⟩ := bind_ok_inv _ _ _ h
          by_cases hnegative : c = 45#u8
          · simp only [hnegative, if_true] at h
            obtain ⟨result, hresult, h⟩ := bind_ok_inv _ _ _ h
            cases h
            exact assemble selected i i2 word hexponent.1 hexponent.2
              hmant hi hi2 hword
          · simp only [hnegative, if_false] at h
            cases h
            exact assemble selected i i2 word hexponent.1 hexponent.2
              hmant hi hi2 hword

end dec2flt_model

Download Lean source · Download TeX source

Complete Lean module
import Tablet.DecimalGoalVocabularyDefault
import Tablet.ModelF64MantissaDigits
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.ParserSelectedExponent
import Tablet.ParserSelectedMantissaBound
import Tablet.ParserExponentConstants
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_SIG_TOTAL_BITS
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_dec2flt_with_trace
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_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
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_parse_decimal_seq
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_biased_fp_to_float
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: ParserSelectedMagnitudeSign]
theorem ParserSelectedMagnitudeSign :
    ∀ (s : Str) (f : F64) (tr : num.imp.dec2flt.Dec2FltAssemblyTrace F64),
      DecimalGoalVocabularyDefault.sourceString s ->
      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, num.imp.dec2flt.Dec2FltTrace.Assembled tr) ->
      DecimalGoalVocabularyDefault.assembledWord tr.selected_pair tr.assembled_word ∧ tr.assembled_word.val < 2 ^ 63 := by
-- BODY
  intro s f tr hs h
  have hmant := ParserSelectedMantissaBound s f tr hs h
  have hexponent := ParserSelectedExponent s f tr hs h
  obtain ⟨hbits, htotal, hsig, hexpbits, hexpsat, hinf, hbias, hmin,
      hsmall, hlarge, hroundmin, hroundmax⟩ := ParserExponentConstants
  have bind_ok_inv : ∀ {α β : Type} (r : Result α) (g : α → Result β) y,
      Bind.bind r g = ok y → ∃ x, r = ok x ∧ g x = 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 x => exact ⟨x, rfl, hr⟩
  have assemble : ∀ (fp : num.imp.dec2flt.common.BiasedFp)
      (i i2 word : Std.U64),
      0 <= fp.p_biased.val ->
      fp.p_biased.val <= 2047 ->
      fp.m.val <= 2 ^ 52 ->
      lift (IScalar.hcast .U64 fp.p_biased) = ok i ->
      i <<< 52#u32 = ok i2 ->
      lift (fp.m ||| i2) = ok word ->
      DecimalGoalVocabularyDefault.assembledWord fp word ∧
        word.val < 2 ^ 63 := by
    intro fp i i2 word hp0 hp1 hm hi hi2 hword
    have hcast := IScalar.hcast_inBounds_spec .U64 fp.p_biased (by
      constructor
      · exact hp0
      · scalar_tac)
    rw [hi] at hcast
    have hiVal : i.val = fp.p_biased.val.toNat := by
      have hz : (fp.p_biased.val.toNat : Int) = fp.p_biased.val :=
        Int.toNat_of_nonneg hp0
      simp only [WP.spec_ok] at hcast
      omega
    have hshift := UScalar.ShiftLeft_spec i (52#u32) (2 ^ 64)
        (by norm_num) (by simp [U64.size, U64.numBits])
    rw [hi2] at hshift
    have hi2Val : i2.val = i.val * 2 ^ 52 := by
      rcases hshift with ⟨hval, hbv⟩
      rw [Nat.shiftLeft_eq] at hval
      norm_num at hval
      have hip : i.val <= 2047 := by omega
      have hlt : i.val * 2 ^ 52 < 2 ^ 64 := by omega
      omega
    simp only [lift] at hword
    cases hword
    have hpmod : fp.p_biased.val.emod (2 ^ 64) =
        fp.p_biased.val := by
      apply Int.emod_eq_of_lt hp0
      omega
    have hexp :
        (((fp.p_biased.val.emod (2 ^ 64)).toNat * (2 ^ 52)) %
            (2 ^ 64)) = i2.val := by
      rw [hpmod, <- hiVal, hi2Val]
      have hlt : i.val * 2 ^ 52 < 2 ^ 64 := by omega
      exact (Nat.mod_eq_of_lt hlt).trans rfl
    have hassembled :
        DecimalGoalVocabularyDefault.assembledWord fp (fp.m ||| i2) := by
      dsimp only [DecimalGoalVocabularyDefault]
      change (fp.m.bv ||| i2.bv).toNat = _
      rw [BitVec.toNat_or]
      simp only [UScalar.bv_toNat, hexp]
      rfl
    have hwordBound : (fp.m ||| i2).val < 2 ^ 63 := by
      change (fp.m.bv ||| i2.bv).toNat < _
      rw [BitVec.toNat_or]
      simp only [UScalar.bv_toNat]
      have hmant63 : fp.m.val < 2 ^ 63 := by omega
      have hexp63 : i2.val < 2 ^ 63 := by omega
      apply Nat.lt_of_testBit 63
      · rw [Nat.testBit_lor,
          Nat.testBit_eq_false_of_lt hmant63,
          Nat.testBit_eq_false_of_lt hexp63]
        rfl
      · rw [Nat.testBit_two_pow]
        decide
      · intro j hj
        rw [Nat.testBit_lor]
        have hmantj : fp.m.val < 2 ^ j := by
          exact lt_of_lt_of_le hmant63
            (Nat.pow_le_pow_right (by omega) (by omega))
        have hexpj : i2.val < 2 ^ j := by
          exact lt_of_lt_of_le hexp63
            (Nat.pow_le_pow_right (by omega) (by omega))
        rw [Nat.testBit_eq_false_of_lt hmantj,
          Nat.testBit_eq_false_of_lt hexpj]
        rw [Nat.testBit_two_pow]
        simp [hj.ne]
    by_cases hendpoint : fp.m.val = 2 ^ 52
    · by_cases heven : i.val % 2 = 0
      · have hipEven : i.val <= 2046 := by
          have hmodlt := Nat.mod_lt i.val (by norm_num : 0 < 2)
          omega
        exact ⟨hassembled, hwordBound⟩
      · have hodd : i.val % 2 = 1 := by
          have hmodlt := Nat.mod_lt i.val (by norm_num : 0 < 2)
          omega
        exact ⟨hassembled, hwordBound⟩
    · have hmStrict : fp.m.val < 2 ^ 52 := by omega
      exact ⟨hassembled, hwordBound⟩
  unfold num.imp.dec2flt.dec2flt_with_trace at h
  obtain ⟨body, hbody, h⟩ := bind_ok_inv _ _ _ h
  obtain ⟨first, hfirst, h⟩ := bind_ok_inv _ _ _ h
  cases first with
  | none =>
    obtain ⟨pfe, hpfe, h⟩ := bind_ok_inv _ _ _ h
    cases h
  | some c =>
    obtain ⟨body1, hbody1, h⟩ := bind_ok_inv _ _ _ h
    obtain ⟨empty, hempty, h⟩ := bind_ok_inv _ _ _ h
    by_cases he : empty = true
    · simp only [he, if_true] at h
      obtain ⟨pfe, hpfe, h⟩ := bind_ok_inv _ _ _ h
      cases h
    · have hef : empty = false := Bool.eq_false_of_not_eq_true he
      simp only [hef, if_false] at h
      obtain ⟨parsed, hparsed, h⟩ := bind_ok_inv _ _ _ h
      cases parsed with
      | none =>
        obtain ⟨special, hspecial, h⟩ := bind_ok_inv _ _ _ h
        cases special with
        | none =>
          obtain ⟨pfe, hpfe, h⟩ := bind_ok_inv _ _ _ h
          cases h
        | some value => cases h
      | some r =>
        obtain ⟨fast, hfast, h⟩ := bind_ok_inv _ _ _ h
        cases fast with
        | some value => cases h
        | none =>
          obtain ⟨firstPair, hfirstPair, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨phase1, hphase1, h⟩ := bind_ok_inv _ _ _ h
          rcases phase1 with ⟨many1, many2, firstPair1, fp, guard⟩
          obtain ⟨phase2, hphase2, h⟩ := bind_ok_inv _ _ _ h
          rcases phase2 with
            ⟨post, secondExp, secondMant, secondResult, secondEqual, forced⟩
          obtain ⟨phase3, hphase3, h⟩ := bind_ok_inv _ _ _ h
          rcases phase3 with ⟨selected, slowGuard, slowResult⟩
          obtain ⟨i, hi, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨i1, hi1, h⟩ := bind_ok_inv _ _ _ h
          change F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.SIG_BITS =
            ok i1 at hi1
          rw [hsig] at hi1
          cases hi1
          obtain ⟨i2, hi2, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨word, hword, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨assembled, hassembled, h⟩ := bind_ok_inv _ _ _ h
          by_cases hnegative : c = 45#u8
          · simp only [hnegative, if_true] at h
            obtain ⟨result, hresult, h⟩ := bind_ok_inv _ _ _ h
            cases h
            exact assemble selected i i2 word hexponent.1 hexponent.2
              hmant hi hi2 hword
          · simp only [hnegative, if_false] at h
            cases h
            exact assemble selected i i2 word hexponent.1 hexponent.2
              hmant hi hi2 hword

end dec2flt_model

Proof structure

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

Uses

All 34 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 161 entries
Technical checking records
Local closure summary
{
  "node": "ParserSelectedMagnitudeSign",
  "closure_version": "patch_c_v1",
  "active_decl_hash": "db53161dfe96ba245dea28ef56e4321d01485b73662951a6cf2048992b43005b",
  "active_statement_hash": "a09f057fbe6ba692e54ef87a9a04fdff084dde7863a2b59510ea030cf523b017",
  "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-134",
  "boundary_theorems": {},
  "strict_theorem_deps": {
    "ParserExponentConstants": "e2a30a7b0c5e9c91",
    "ParserSelectedExponent": "2d4e5f8c99bf68c7",
    "ParserSelectedMantissaBound": "8c0433452b441220",
    "num_imp_dec2flt_dec2flt_with_trace": "d2b4145772dccc04",
    "num_imp_traits_Float_SIG_BITS_default": "9ab622d85ef04d94"
  },
  "strict_definition_deps": {
    "DecimalGoalVocabulary": "d8d2f621d2f6aa27",
    "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",
    "Preamble": "7a79218b23bce03e",
    "core_ops_arith_Neg": "0ff07135a60bcbf9",
    "num_float_parse_ParseFloatError": "c43614ff2149ecf2",
    "num_imp_dec2flt_Dec2FltAssemblyTrace": "7bda5de02611ad76",
    "num_imp_dec2flt_Dec2FltTrace": "27322b4608129f59",
    "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_with_trace": "d34666730435cdb9",
    "num_imp_dec2flt_decimal_Decimal": "4da4ccbe640ef8e6",
    "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": "94ab5f784cdf5db8",
    "num_imp_traits_FloatExt": "f996e5400649797d"
  }
}
Prose assessment
{
  "label": "Recorded Sound: VerifierPass",
  "assessment_status": "VerifierPass",
  "fingerprint_relation": "matches current fingerprint",
  "assessment_fingerprint": "sound-v2:14f69c347648eef409f749480c886b9b9fe5ddfec0c014a62963af87daf34ba5",
  "current_fingerprint": "sound-v2:14f69c347648eef409f749480c886b9b9fe5ddfec0c014a62963af87daf34ba5",
  "superseded_for_theorem_closure": false
}
Review verdicts
{
  "corr_status": "Pass",
  "sound_status": "Pass",
  "substantiveness_status": "Pass"
}