P529_T1_LeftShiftCertificate

Lean checked

Statement

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

Lemma · Constructed left shift with positive shape and fixed endpoints

For a record a put D(a)=\operatorname{map}(\mathit{val}, \operatorname{take}(a.n,a.\mathit{digits})), I(a)=\operatorname{fold}_{10}(D(a),0) and V(a)=I(a)10^{a.p-a.n}, where n is the natural count and p the signed decimal point. Let d have count at most 768, decimal retained cells, and D(d)=h::t of length d.n with 1\le h<10. Suppose -324\le d.p\le0, k\le60, and
X=V(d)+\eta,\quad Y=V(d)+u,\quad 0\le\eta<u,\quad d.\mathit{truncated}\iff\eta>0.
Then there are an actual normal left-shift result d' and an actual normal digit-growth result g\le19 for that same shift, with d'.p=d.p+g and -324\le d'.p\le19. The output has count at most 768, decimal retained cells, a positive head in [1,9], retained length equal to its count, and a nonzero last retained cell. There are 0\le\eta'<u' with
2^kX=V(d')+\eta',\quad 2^kY=V(d')+u',\quad d'.\mathit{truncated}\iff\eta'>0.
The Lean statement records both successful calls, not just value equations.

Lean statement

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

import Tablet.DecimalLeftShiftLoop1Execution
import Tablet.DecimalLeftShiftFirstLoopSemantics
import Tablet.DecimalLeftShiftSecondLoopSemantics
import Tablet.DecimalLeftShiftDigitGrowth
import Tablet.DecimalLeftShiftTableCertificate
import Tablet.DecimalSeqTrimSemantics
import Tablet.P472_T1_DecimalSeqDyadicShiftSemantics
import Tablet.P804_T1_LeftShiftPointGrowth
import Tablet.P472_T1_DecimalValueBounds

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false
namespace dec2flt_model

-- [TABLET NODE: P529_T1_LeftShiftCertificate]
theorem P529_T1_LeftShiftCertificate (X Y : Real)
    (d : num.imp.dec2flt.decimal_seq.DecimalSeq) (shift : Std.Usize)
    (hshift : shift.val <= 60)
    (hpointLo : -324 <= d.decimal_point.val)
    (hpointHi : d.decimal_point.val <= 0)
    (hinput : d.num_digits.val <= 768 /\
      (forall b, b ∈ d.digits.val.take d.num_digits.val -> b.val < 10) /\
      (exists h tail,
        (d.digits.val.take d.num_digits.val).map (fun b => b.val) = h :: tail /\
        1 <= h /\ h < 10 /\ (h :: tail).length = d.num_digits.val)) :
    let V := fun a : num.imp.dec2flt.decimal_seq.DecimalSeq =>
      ((((a.digits.val.take a.num_digits.val).map (fun b => b.val)).foldl
        (fun n z => 10 * n + z) 0 : Nat) : Real) *
        (10 : Real) ^ (a.decimal_point.val - (a.num_digits.val : Int))
    (exists eta u : Real, X = V d + eta /\ Y = V d + u /\
      0 <= eta /\ eta < u /\ (d.truncated = true <-> 0 < eta)) ->
    exists (d' : num.imp.dec2flt.decimal_seq.DecimalSeq) (growth : Std.Usize),
      num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift d shift = ok d' /\
      num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift
        d shift = ok growth /\
      growth.val <= 19 /\
      d'.decimal_point.val = d.decimal_point.val + (growth.val : Int) /\
      -324 <= d'.decimal_point.val /\ d'.decimal_point.val <= 19 /\
      d'.num_digits.val <= 768 /\
      (forall b, b ∈ d'.digits.val.take d'.num_digits.val -> b.val < 10) /\
      (exists h tail,
        (d'.digits.val.take d'.num_digits.val).map (fun b => b.val) = h :: tail /\
        1 <= h /\ h < 10 /\ (h :: tail).length = d'.num_digits.val) /\
      d'.digits.val[d'.num_digits.val - 1]? ≠ some 0#u8 /\
      (exists eta' u' : Real,
        (2 : Real) ^ shift.val * X = V d' + eta' /\
        (2 : Real) ^ shift.val * Y = V d' + u' /\
        0 <= eta' /\ eta' < u' /\ (d'.truncated = true <-> 0 < eta')) := 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

Write n=d.n, I=I(d) and B=2^k. The list hypothesis gives 1\le n\le768. By DecimalValueBounds, V(d)>0; equivalently the decimal fold satisfies 10^{n-1}\le I<10^n. Apply DecimalLeftShiftLoop1Execution with the stated point, shift and list hypotheses. It constructs a normal complete left shift and a nonempty result d'. This is an existence application before any use of an enclosing slow call.
We establish the extra shape clauses from the constructed call. For k=0, direct evaluation of the zero table entry in num imp dec2flt decimal seq DecimalSeq left shift gives growth zero. For k>0, DecimalLeftShiftTableCertificate supplies 10^{a-1}<B<10^a; DecimalLeftShiftDigitGrowth gives a normal growth g=a or a-1 according as IB\ge10^{n+a-1} or not. In both cases
10^{n+g-1}\le IB<10^{n+g},\qquad 0\le g\le19.
For the a-1 case the lower bound follows from I\ge10^{n-1} and B>10^{a-1}; for the a case the upper bound follows from I<10^n and B<10^a. The bound on a follows from B\le2^{60}<10^{19}. The k=0 case uses the original fold bounds.
Unfold the normal complete call to expose its two normal carry loops. A failed or divergent bind cannot produce its normal result. The first checked width is L=n+g\le787. DecimalLeftShiftFirstLoopSemantics, at read n, write L and carry zero, gives a length-n decimal word v, final cursor g and carry c, with
IB=c10^n+F(v),\qquad 0\le F(v)<10^n.
The stated loop cell clauses store v_j at g+j when g+j<768. The fold bounds above imply c<10^g. If g>0, they also imply c\ge10^{g-1}: otherwise IB<(c+1)10^n\le10^{n+g-1}, a contradiction. Consequently the zero-padding premise of DecimalLeftShiftSecondLoopSemantics is vacuous for g=0 and has impossible antecedent for every j<g when g>0. That principal gives a length-g decimal word w with F(w)=c, stores w below cursor g, and preserves every first-loop cell at or beyond g. Therefore the pre-trim retained array is exactly the first \min(L,768) digits of w\mathbin{++}v, whose fold is c10^n+F(v)=IB and whose length is L. Its first digit is nonzero: a zero head of a length-L decimal word would make its fold less than 10^{L-1}. Thus the capped prefix is positive, all its cells are decimal, and its count lies in [1,768].
The normal call's final operation is trim on this capped record. DecimalSeqTrimSemantics preserves the array and point, reduces the count, removes only terminal zero cells and leaves either zero count or a nonzero last cell. Zero count is impossible because the preserved first cell is nonzero. Its smaller retained prefix therefore still has the same positive head, only decimal cells, exact list length, and count at most 768. The cast of g\le19 to I32 is exact. LeftShiftPointGrowth identifies the actual point as d.p+g; this lies in [-324,19] and is within I32 bounds.
Finally apply the left half of DecimalSeqDyadicShiftSemantics to the same normal call, positive V(d), digit bounds, and the given \eta,u. It supplies the ordered new errors and exact sticky equivalence, with V(d')+u'=2^k(V(d)+u)=2^kY. This proves all claimed clauses for the one constructed result. No initial terminal-trim premise was used.

Lean proof


  dsimp only
  intro htransport
  rcases hinput with ⟨hncap, hdigit, hhead⟩
  rcases hhead with ⟨head, tail, hdigits, hheadLo, hheadHi, hlen⟩
  rcases htransport with ⟨eta, u, hX, hY, hetaLo, hetau, hsticky⟩
  let digits := (d.digits.val.take d.num_digits.val).map (fun b => b.val)
  let I := digits.foldl (fun n z => 10 * n + z) 0
  have hdigitsLen : digits.length = d.num_digits.val := by
    simp [digits, d.digits.property,
      min_eq_left (show d.num_digits.val <= 768 by omega)]
  have hdigitsHead : digits = head :: tail := hdigits
  have hdigitsDec : forall z, z ∈ digits -> z < 10 := by
    intro z hz
    simp only [digits, List.mem_map] at hz
    rcases hz with ⟨b, hb, rfl⟩
    exact hdigit b hb
  have hvalueBounds := P472_T1_DecimalValueBounds digits head tail
    hdigitsHead hheadLo hdigitsDec d.decimal_point.val
  have hvaluePos : 0 < (I : Real) * (10 : Real) ^
      (d.decimal_point.val - (d.num_digits.val : Int)) := by
    have hp : 0 < (10 : Real) ^ (d.decimal_point.val - 1) :=
      zpow_pos (by norm_num) _
    have hz : 0 < (head : Real) * (10 : Real) ^ (d.decimal_point.val - 1) :=
      mul_pos (by exact_mod_cast hheadLo) hp
    dsimp [I] at hvalueBounds
    rw [hdigitsLen] at hvalueBounds
    exact lt_of_lt_of_le hz hvalueBounds.1
  obtain ⟨d', q, hcall, hqbound, hpointExec, hpointLo', hpointHi', hnonempty⟩ :=
    DecimalLeftShiftLoop1Execution d shift hshift hpointLo hpointHi
      (by refine ⟨hncap, hdigit, ?_⟩
          exact ⟨head, tail, hdigits, hheadLo, hheadHi, hlen⟩)
  have hne : d.num_digits.val != 0 := by
    rw [← hdigitsLen, hdigitsHead]
    simp
  have hneProp : d.num_digits.val ≠ 0 := by
    simpa [bne_iff_ne] using hne
  have zeroGrowthTotal (d0 : num.imp.dec2flt.decimal_seq.DecimalSeq)
      (sh : Std.Usize) (hsh : sh.val = 0) :
      exists gr : Std.Usize,
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift
          d0 sh = ok gr /\ gr.val = 0 := by
    have hseq : sh = 0#usize := UScalar.eq_of_val_eq (by simpa using hsh)
    subst sh
    let kfin : Fin 61 := ⟨0, by omega⟩
    have cert := DecimalLeftShiftTableCertificate kfin
    dsimp only at cert
    rcases cert with ⟨hloidx, hhiidx, hlenTable, _, hzero, _⟩
    have hz := hzero (by simp [kfin])
    rcases hz with ⟨hhiZero, hdsZero⟩
    let table := num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
    let pow5Table := num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE_POW5
    let x := table.val.get ⟨0, by simp [table]⟩
    let y := table.val.get ⟨1, by simp [table]⟩
    let hi := x.val / 2048
    let lo := x.val % 2048
    let hiNext := y.val % 2048
    let dsU := pow5Table.val.extract lo hiNext
    let ds := dsU.map (fun q => q.val)
    have hloidx' : lo <= hiNext := by
      simpa [lo, hiNext, x, y, table, kfin] using hloidx
    have hhiidx' : hiNext <= 1308 := by
      simpa [hiNext, y, table, kfin] using hhiidx
    have hlen' : ds.length = hiNext - lo := by
      simpa [ds, dsU, pow5Table, lo, hiNext, x, y, table, kfin] using hlenTable
    have hhiZero' : hi = 0 := by
      simpa [hi, x, table, kfin] using hhiZero
    have hdsZero' : ds = [] := by
      simpa [ds, dsU, pow5Table, lo, hiNext, x, y, table, kfin] using hdsZero
    have hloEq : lo = hiNext := by
      rw [hdsZero'] at hlen'
      simp at hlen'
      omega
    have hmask : (0#usize &&& 63#usize) = 0#usize := by decide
    obtain ⟨xa, hxa, hxaVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (Array.index_usize_spec
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
        0#usize (by simp [Array.length]))
    have hxaEq : xa = x := by
      apply UScalar.eq_of_val_eq
      simpa [x, table] using congrArg UScalar.val hxaVal
    subst xa
    obtain ⟨next, hnext, hnextVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (UScalar.add_spec (x := 0#usize) (y := 1#usize) (by scalar_tac))
    norm_num at hnextVal
    obtain ⟨yb, hyb, hybVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (Array.index_usize_spec
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
        next (by simp [Array.length]; omega))
    have hybEq : yb = y := by
      apply UScalar.eq_of_val_eq
      simpa [y, table, hnextVal] using congrArg UScalar.val hybVal
    subst yb
    obtain ⟨high16, hhigh16, hhigh16Val⟩ := Aeneas.Std.WP.spec_imp_exists
      (U16.ShiftRight_IScalar_spec x 11#i32 (by norm_num) (by norm_num))
    have hhigh16Eq : high16.val = hi := by
      rw [hhigh16Val.1, Nat.shiftRight_eq_div_pow]
      norm_num [hi, Int.toNat]
    let numNew : Std.Usize := UScalar.cast .Usize high16
    have hnumNewVal : numNew.val = 0 := by simp [numNew, hhigh16Eq, hhiZero']
    let low16 := 2047#u16 &&& x
    let pow5a : Std.Usize := UScalar.cast .Usize low16
    have hpow5aVal : pow5a.val = lo := by
      simp [pow5a, low16, lo, UScalar.val_and]
      rw [show 2047 = 2 ^ 11 - 1 by decide, Nat.and_comm,
        Nat.and_two_pow_sub_one_eq_mod]
    let next16 := 2047#u16 &&& y
    let pow5b : Std.Usize := UScalar.cast .Usize next16
    have hpow5bVal : pow5b.val = hiNext := by
      simp [pow5b, next16, hiNext, UScalar.val_and]
      rw [show 2047 = 2 ^ 11 - 1 by decide, Nat.and_comm,
        Nat.and_two_pow_sub_one_eq_mod]
    have hlo1308 : pow5a.val <= 1308 := by rw [hpow5aVal]; exact hloidx'.trans hhiidx'
    let slice : Slice Std.U8 := pow5Table.to_slice.drop pow5a
    have hslice :
        core.array.Array.index
          (core.ops.index.IndexSlice
            (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8))
          pow5Table { start := pow5a } = ok slice := by
      rw [Array.index_SliceIndexRangeFromUsizeSlice]
      unfold core.slice.index.SliceIndexRangeFromUsizeSlice.index
      simp [hlo1308, slice]
    have hsubBound : pow5a.val <= pow5b.val := by
      rw [hpow5aVal, hpow5bVal]
      exact hloidx'
    obtain ⟨span, hspan, hspanVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (UScalar.sub_spec (x := pow5b) (y := pow5a) hsubBound)
    have hspanZero : span.val = 0 := by
      rw [hspanVal.1, hpow5aVal, hpow5bVal, ← hloEq]
      simp
    have hspanEq : span = 0#usize :=
      UScalar.eq_of_val_eq (by simpa using hspanZero)
    subst span
    refine ⟨numNew, ?_, hnumNewVal⟩
    unfold num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift
    simp only [hmask, lift, Bind.bind, Aeneas.Std.bind, hxa, bind_tc_ok,
      hnext, hyb, hhigh16]
    rw [hxaEq, hybEq]
    simp only [hhigh16, bind_tc_ok]
    rw [show UScalar.cast .Usize (2047#u16 &&& x) = pow5a by rfl]
    rw [show UScalar.cast .Usize (2047#u16 &&& y) = pow5b by rfl]
    rw [show UScalar.cast .Usize high16 = numNew by rfl]
    rw [hslice]
    simp only [bind_tc_ok]
    unfold core.slice.Slice.iter
    simp only [bind_tc_ok]
    unfold core.slice.iter.IteratorSliceIter.enumerate
    simp only [bind_tc_ok, hspan]
    unfold core.iter.adapters.enumerate.IteratorEnumerate.take
    simp only [bind_tc_ok]
    unfold num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift_loop
    rw [Aeneas.Std.loop.eq_def]
    unfold num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift_loop.body
    unfold core.iter.adapters.take.IteratorTake.next
    simp
  have hgrowthCall :
      exists growth : Std.Usize,
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift d shift = ok growth := by
    have hcall' := hcall
    unfold num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift at hcall'
    have hneWord : d.num_digits ≠ 0#usize := by
      intro hz
      have hv := congrArg UScalar.val hz
      simp at hv
      apply hneProp
      simpa using hv
    simp only [hneWord, if_false] at hcall'
    cases hg : num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift d shift with
    | fail e => simp [hg] at hcall'
    | div => simp [hg] at hcall'
    | ok growth => exact ⟨growth, by simpa [hg]⟩
  rcases hgrowthCall with ⟨growth, hgrowth⟩
  have hgrowthBound : growth.val <= 19 := by
    by_cases hk0 : shift.val = 0
    · have hs : shift = 0#usize :=
        UScalar.eq_of_val_eq (by simpa using hk0)
      subst shift
      obtain ⟨gr, hgr, hgrVal⟩ := zeroGrowthTotal d 0#usize (by simp)
      rw [hgr] at hgrowth
      cases hgrowth
      simpa [hgrVal]
    · have hkpos : 0 < shift.val := by omega
      let kfin : Fin 61 := ⟨shift.val, by omega⟩
      have cert := DecimalLeftShiftTableCertificate kfin
      dsimp only at cert
      rcases cert with ⟨_, _, _, _, _, hpositiveTable⟩
      have hp := hpositiveTable (by simpa [kfin] using hkpos)
      rcases hp with ⟨_, _, _, _, hlo, hhi⟩
      let table :=
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
      let entry := table.val.get ⟨shift.val, by simp [table]; omega⟩
      let h := entry.val / 2048
      have hlo' : 10 ^ (h - 1) < 2 ^ shift.val := by
        simpa [h, entry, table, kfin] using hlo
      have hhi' : 2 ^ shift.val < 10 ^ h := by
        simpa [h, entry, table, kfin] using hhi
      have hpos : 0 < h := by
        by_contra hz
        have hz' : h = 0 := by omega
        rw [hz'] at hhi'
        norm_num at hhi'
      have hle : h <= 19 := by
        by_contra hn
        have hp19 : 10 ^ 19 <= 10 ^ (h - 1) :=
          Nat.pow_le_pow_right (by omega) (by omega)
        have hBle : 2 ^ shift.val <= 2 ^ 60 :=
          Nat.pow_le_pow_right (by omega) hshift
        have hnum : 2 ^ 60 < 10 ^ 19 := by norm_num
        exact (not_lt_of_ge hp19)
          (lt_of_lt_of_le hlo' (le_trans hBle (Nat.le_of_lt hnum)))
      obtain ⟨growth', hgrowth', hformula⟩ :=
        DecimalLeftShiftDigitGrowth d shift h hshift hlo' hhi' hncap hdigit
      rw [hgrowth] at hgrowth'
      cases hgrowth'
      have hformula' : growth.val =
          if 10 ^ (d.num_digits.val + h - 1) <= I * 2 ^ shift.val
          then h else h - 1 := by
        simpa [digits, I] using hformula
      rw [hformula']
      split <;> omega
  have hgrowthExec := P804_T1_LeftShiftPointGrowth d d' shift growth
    hne hgrowth hgrowthBound hcall
  have hqEq : q = growth.val := by omega
  have hpoint : d'.decimal_point.val = d.decimal_point.val + (growth.val : Int) := by
    simpa [hqEq] using hpointExec
  have hdyadic := (P472_T1_DecimalSeqDyadicShiftSemantics).1
    d d' shift X eta u hshift hvaluePos
    (by intro b hb; exact hdigit b hb) hcall hX hetaLo hetau hsticky
  rcases hdyadic with ⟨eta', u', hscaledX, heta'Lo, heta'u', hsticky', hscaledY, _⟩
  have hcallStruct := hcall
  unfold num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift at hcallStruct
  have hneWord : d.num_digits ≠ 0#usize := by
    intro heq
    have hv := congrArg UScalar.val heq
    apply hneProp
    simpa using hv
  simp only [hneWord, if_false, hgrowth, bind_tc_ok] at hcallStruct
  cases hwidth : d.num_digits + growth with
  | fail e => simp [hwidth] at hcallStruct
  | div => simp [hwidth] at hcallStruct
  | ok width =>
    simp only [hwidth, bind_tc_ok] at hcallStruct
    cases hloop0 : num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift_loop0
        d.truncated d.digits shift d.num_digits width 0#u64 with
    | fail e => simp [hloop0] at hcallStruct
    | div => simp [hloop0] at hcallStruct
    | ok out0 =>
      rcases out0 with ⟨b0, a0, cursor, carry⟩
      simp only [hloop0, bind_tc_ok] at hcallStruct
      change (do
        let (b1, a1) ←
          num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift_loop1
            b0 a0 cursor carry
        let i1 ←
          if width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
          then ok num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS else ok width
        let i2 ← lift (UScalar.hcast .I32 growth)
        let i3 ← d.decimal_point + i2
        num.imp.dec2flt.decimal_seq.DecimalSeq.trim
          { num_digits := i1, decimal_point := i3, truncated := b1, digits := a1 }) =
          ok d' at hcallStruct
      cases hloop1 : num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift_loop1
          b0 a0 cursor carry with
      | fail e => simp [hloop1] at hcallStruct
      | div => simp [hloop1] at hcallStruct
      | ok out1 =>
        rcases out1 with ⟨b1, a1⟩
        rw [hloop1] at hcallStruct
        let delta : Std.I32 := UScalar.hcast .I32 growth
        simp only [lift, bind_tc_ok] at hcallStruct
        rw [show UScalar.hcast .I32 growth = delta by rfl] at hcallStruct
        cases hpointCall : d.decimal_point + delta with
        | fail e =>
          by_cases hc : width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
        | div =>
          by_cases hc : width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
        | ok point =>
          simp only [hpointCall, bind_tc_ok] at hcallStruct
          let count : Std.Usize :=
            if width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
            then num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS else width
          have hcount :
              (if width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
                then ok num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
                else ok width) = ok count := by
            unfold count
            split <;> rfl
          rw [hcount] at hcallStruct
          simp only [bind_tc_ok] at hcallStruct
          let pre : num.imp.dec2flt.decimal_seq.DecimalSeq :=
            { num_digits := count, decimal_point := point,
              truncated := b1, digits := a1 }
          change num.imp.dec2flt.decimal_seq.DecimalSeq.trim pre = ok d' at hcallStruct
          cases htrim : num.imp.dec2flt.decimal_seq.DecimalSeq.trim pre with
          | fail e => simp [pre, htrim] at hcallStruct
          | div => simp [pre, htrim] at hcallStruct
          | ok out =>
            rw [htrim] at hcallStruct
            cases hcallStruct
            have hcountBound : count.val <= a1.val.length := by
              rw [a1.property]
              dsimp [count]
              split
              · simp [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def]
              · simp only [gt_iff_lt, UScalar.lt_equiv,
                  num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def] at *
                omega
            have htrimSem := DecimalSeqTrimSemantics pre d' hcountBound htrim
            dsimp only at htrimSem
            rcases htrimSem with
              ⟨hdigitsOut, hpointOut, htruncOut, hnumLe, hzeros, hlast, hvalueOut⟩
            let B := 2 ^ shift.val
            have hfoldBounds := P804_T1_DecimalFoldBounds digits hdigitsDec
              head tail hdigitsHead hheadLo
            have foldBound (xs : List Nat) (hs : forall z, z ∈ xs -> z < 10) :
                xs.foldl (fun n z => 10 * n + z) 0 < 10 ^ xs.length := by
              let F := fun ys : List Nat =>
                ys.foldl (fun n z => 10 * n + z) 0
              have foldlFrom (ys : List Nat) (acc : Nat) :
                  ys.foldl (fun n z => 10 * n + z) acc =
                    acc * 10 ^ ys.length + F ys := by
                induction ys generalizing acc with
                | nil => simp [F]
                | cons y ys ih =>
                  simp only [List.foldl_cons, List.length_cons]
                  rw [ih, pow_succ]
                  change (10 * acc + y) * 10 ^ ys.length + F ys =
                    acc * (10 ^ ys.length * 10) +
                      (y :: ys).foldl (fun n z => 10 * n + z) 0
                  simp only [List.foldl_cons]
                  rw [ih]
                  ring
              induction xs with
              | nil => simp
              | cons z xs ih =>
                have hz : z < 10 := hs z (by simp)
                have hxs : forall q, q ∈ xs -> q < 10 := by
                  intro q hq
                  exact hs q (by simp [hq])
                have hi := ih hxs
                have hform : (z :: xs).foldl (fun n a => 10 * n + a) 0 =
                    z * 10 ^ xs.length + xs.foldl (fun n a => 10 * n + a) 0 := by
                  simp only [List.foldl_cons]
                  simpa [F] using foldlFrom xs z
                rw [hform, List.length_cons, pow_succ]
                have hm := Nat.mul_le_mul_right (10 ^ xs.length) (show z <= 9 by omega)
                nlinarith
            have hproductBounds :
                10 ^ (d.num_digits.val + growth.val - 1) <= I * B /\
                I * B < 10 ^ (d.num_digits.val + growth.val) := by
              by_cases hk0 : shift.val = 0
              · obtain ⟨gr, hgr, hgrVal⟩ := zeroGrowthTotal d shift hk0
                rw [hgrowth] at hgr
                cases hgr
                have hIlo := hfoldBounds.1
                have hIhi := hfoldBounds.2
                rw [hdigitsLen] at hIlo hIhi
                have hB : B = 1 := by simp [B, hk0]
                rw [hgrVal, hB]
                simpa [I] using And.intro hIlo hIhi
              · have hkpos : 0 < shift.val := by omega
                let kfin : Fin 61 := ⟨shift.val, by omega⟩
                have cert := DecimalLeftShiftTableCertificate kfin
                dsimp only at cert
                rcases cert with ⟨_, _, _, _, _, hpositiveTable⟩
                have hp := hpositiveTable (by simpa [kfin] using hkpos)
                rcases hp with ⟨_, _, _, _, hlo, hhi⟩
                let table :=
                  num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
                let entry := table.val.get ⟨shift.val, by simp [table]; omega⟩
                let h := entry.val / 2048
                have hlo' : 10 ^ (h - 1) < B := by
                  simpa [h, entry, table, kfin, B] using hlo
                have hhi' : B < 10 ^ h := by
                  simpa [h, entry, table, kfin, B] using hhi
                have hpos : 0 < h := by
                  by_contra hz
                  have hz' : h = 0 := by omega
                  rw [hz'] at hhi'
                  norm_num at hhi'
                  have hBpos : 0 < B := by simp [B]
                  omega
                obtain ⟨gr, hgr, hformula⟩ :=
                  DecimalLeftShiftDigitGrowth d shift h hshift hlo' hhi' hncap hdigit
                rw [hgrowth] at hgr
                cases hgr
                have hformula' : growth.val =
                    if 10 ^ (d.num_digits.val + h - 1) <= I * B
                    then h else h - 1 := by
                  simpa [digits, I, B] using hformula
                rw [hformula']
                split
                · rename_i ht
                  constructor
                  · exact ht
                  · have hIhi := hfoldBounds.2
                    rw [hdigitsLen] at hIhi
                    have hmul1 : I * B < 10 ^ d.num_digits.val * B :=
                      (Nat.mul_lt_mul_right (by positivity : 0 < B)).2 hIhi
                    have hmul2 : 10 ^ d.num_digits.val * B <
                        10 ^ d.num_digits.val * 10 ^ h :=
                      (Nat.mul_lt_mul_left (by positivity : 0 < 10 ^ d.num_digits.val)).2 hhi'
                    calc
                      I * B < 10 ^ d.num_digits.val * B := hmul1
                      _ < 10 ^ d.num_digits.val * 10 ^ h := hmul2
                      _ = 10 ^ (d.num_digits.val + h) := by rw [Nat.pow_add]
                · rename_i ht
                  have hmul1 :
                      10 ^ (h - 1) * 10 ^ (d.num_digits.val - 1) <
                        B * 10 ^ (d.num_digits.val - 1) :=
                    (Nat.mul_lt_mul_right (by positivity)).mpr hlo'
                  have hIlo := hfoldBounds.1
                  rw [hdigitsLen] at hIlo
                  have hmul2 : B * 10 ^ (d.num_digits.val - 1) <= B * I :=
                    Nat.mul_le_mul_left B hIlo
                  have he : d.num_digits.val + (h - 1) - 1 =
                      (h - 1) + (d.num_digits.val - 1) := by omega
                  constructor
                  · rw [he, Nat.pow_add]
                    exact Nat.le_of_lt (lt_of_lt_of_le hmul1 (by simpa [Nat.mul_comm] using hmul2))
                  · have hlt : I * B <
                        10 ^ (d.num_digits.val + h - 1) := by omega
                    have hexp' : d.num_digits.val + h - 1 =
                        d.num_digits.val + (h - 1) := by omega
                    simpa only [show d.num_digits.val + h - 1 =
                      d.num_digits.val + (h - 1) by omega] using hlt
            have haddBound : d.num_digits.val + growth.val <= UScalar.max .Usize := by
              scalar_tac
            obtain ⟨widthSpec, hwidthSpec, hwidthVal⟩ :=
              Aeneas.Std.WP.spec_imp_exists
                (UScalar.add_spec (x := d.num_digits) (y := growth) haddBound)
            have hwidthEq : widthSpec = width := by
              rw [hwidth] at hwidthSpec
              cases hwidthSpec
              rfl
            subst widthSpec
            have hreadwrite : d.num_digits.val <= width.val := by
              rw [hwidthVal]
              omega
            have hfirst := DecimalLeftShiftFirstLoopSemantics
              d.digits a0 d.truncated b0 shift d.num_digits width cursor carry
              hshift (by simpa using hncap) hreadwrite hdigit hloop0
            dsimp only at hfirst
            rcases hfirst with
              ⟨lowDigits, hlowLen, hlowDigit, hcursorEq, hcarryB, hproduct,
                hlowArray, houtside0, hsticky0⟩
            have hprod : B * I =
                carry.val * 10 ^ d.num_digits.val +
                  lowDigits.foldl (fun n z => 10 * n + z) 0 := by
              simpa [B, I, digits] using hproduct
            have hcursorVal : cursor.val = growth.val := by
              rw [hwidthVal] at hcursorEq
              omega
            have hlowBound : lowDigits.foldl (fun n z => 10 * n + z) 0 <
                10 ^ d.num_digits.val := by
              have := foldBound lowDigits hlowDigit
              simpa [hlowLen] using this
            have hcarryWidth : carry.val < 10 ^ cursor.val := by
              rw [hcursorVal]
              have hle : carry.val * 10 ^ d.num_digits.val <= B * I := by
                rw [hprod]
                exact Nat.le_add_right _ _
              have hpow : 10 ^ growth.val * 10 ^ d.num_digits.val =
                  10 ^ (d.num_digits.val + growth.val) := by
                rw [Nat.mul_comm, ← Nat.pow_add]
              have hm : carry.val * 10 ^ d.num_digits.val <
                  10 ^ growth.val * 10 ^ d.num_digits.val := by
                rw [hpow]
                exact lt_of_le_of_lt hle (by simpa [Nat.mul_comm] using hproductBounds.2)
              exact Nat.lt_of_mul_lt_mul_right hm
            have hcarryLower : 0 < growth.val -> 10 ^ (growth.val - 1) <= carry.val := by
              intro hgpos
              by_contra hnot
              have hcsmall : carry.val < 10 ^ (growth.val - 1) := by omega
              have hu : carry.val * 10 ^ d.num_digits.val +
                  lowDigits.foldl (fun n z => 10 * n + z) 0 <
                    10 ^ (growth.val - 1) * 10 ^ d.num_digits.val := by
                have hc1 : carry.val + 1 <= 10 ^ (growth.val - 1) := by omega
                have hm := Nat.mul_le_mul_right (10 ^ d.num_digits.val) hc1
                rw [Nat.add_mul] at hm
                have hF : 0 <=
                    lowDigits.foldl (fun n z => 10 * n + z) 0 := Nat.zero_le _
                omega
              rw [← hprod] at hu
              have hexp : d.num_digits.val + growth.val - 1 =
                  (growth.val - 1) + d.num_digits.val := by omega
              have hlow := hproductBounds.1
              rw [hexp, Nat.pow_add] at hlow
              exact (not_lt_of_ge (by simpa [Nat.mul_comm] using hlow)) hu
            have hpad : forall j, j < cursor.val -> j < 768 ->
                carry.val < 10 ^ (cursor.val - j - 1) ->
                  a0.val[j]? = some 0#u8 := by
              intro j hj _ hjcarry
              have hgpos : 0 < growth.val := by omega
              have hlow := hcarryLower hgpos
              have hexp : cursor.val - j - 1 <= growth.val - 1 := by
                rw [hcursorVal]
                omega
              have hp : 10 ^ (cursor.val - j - 1) <= 10 ^ (growth.val - 1) :=
                Nat.pow_le_pow_right (by omega) hexp
              exact False.elim
                (not_lt_of_ge hlow (lt_of_lt_of_le hjcarry hp))
            have hsecond := DecimalLeftShiftSecondLoopSemantics a0 a1 b0 b1
              cursor carry hcarryWidth hpad hloop1
            rcases hsecond with
              ⟨highDigits, hhighLen, hhighDigit, hcarryDigits,
                hhighArray, houtside1, hsticky1⟩
            have headPositive (ys : List Nat) (hy : forall z, z ∈ ys -> z < 10)
                (hpos : 0 < ys.length)
                (hlower : 10 ^ (ys.length - 1) <=
                  ys.foldl (fun n z => 10 * n + z) 0) :
                exists q qs, ys = q :: qs /\ 0 < q := by
              cases hys : ys with
              | nil =>
                rw [hys] at hpos
                simp at hpos
              | cons q qs =>
                refine ⟨q, qs, rfl, ?_⟩
                by_contra hq
                have hqzero : q = 0 := by omega
                have hy' : forall z, z ∈ q :: qs -> z < 10 := by
                  simpa [hys] using hy
                have htailDigit : forall a, a ∈ qs -> a < 10 := by
                  intro a ha
                  exact hy' a (List.mem_cons_of_mem q ha)
                have htailBound := foldBound qs htailDigit
                have htailLower : 10 ^ qs.length <=
                    qs.foldl (fun n z => 10 * n + z) 0 := by
                  simpa [hys, hqzero] using hlower
                omega
            have hcountPos : 0 < count.val := by
              have hnpos : 0 < d.num_digits.val := by
                have := hdigitsLen
                simp only [hdigitsHead, List.length_cons] at this
                omega
              unfold count
              split
              · simp [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def]
              · have hw : width.val = d.num_digits.val + growth.val := hwidthVal
                omega
            have hcell0 : exists q : Nat,
                (a1.val.map (fun z => z.val))[0]? = some q /\ 1 <= q /\ q < 10 := by
              by_cases hgzero : growth.val = 0
              · have hcursorZero : cursor.val = 0 := by rw [hcursorVal, hgzero]
                have hcarryZero : carry.val = 0 := by
                  rw [hcursorZero] at hcarryWidth
                  simp at hcarryWidth
                  omega
                have hlowLower : 10 ^ (lowDigits.length - 1) <=
                    lowDigits.foldl (fun n z => 10 * n + z) 0 := by
                  have hl := hproductBounds.1
                  rw [hgzero] at hl
                  have hprod' : B * I =
                      lowDigits.foldl (fun n z => 10 * n + z) 0 := by
                    rw [hprod, hcarryZero]
                    simp
                  have hl' : 10 ^ (d.num_digits.val - 1) <=
                      lowDigits.foldl (fun n z => 10 * n + z) 0 := by
                    have hl'' : 10 ^ (d.num_digits.val - 1) <= I * B := by
                      simpa [hgzero] using hl
                    calc
                      10 ^ (d.num_digits.val - 1) <= I * B := hl''
                      _ = B * I := by rw [Nat.mul_comm]
                      _ = lowDigits.foldl (fun n z => 10 * n + z) 0 := hprod'
                  simpa [hlowLen] using hl'
                obtain ⟨q, qs, hlowEq, hqpos⟩ :=
                  headPositive lowDigits hlowDigit (by rw [hlowLen]; omega) hlowLower
                have hmap := hlowArray 0 (by rw [hlowEq]; simp) (by omega)
                have hmap' :
                    (a1.val.map (fun z => z.val))[0]? = some q := by
                  have hkeep := houtside1 0 (by omega) (by simpa [hcursorZero])
                  have hmapKeep := congrArg
                    (Option.map (fun z : Std.U8 => z.val)) hkeep
                  calc
                    (a1.val.map (fun z => z.val))[0]? =
                        Option.map (fun z : Std.U8 => z.val) a1.val[0]? := by
                          simp
                    _ = Option.map (fun z : Std.U8 => z.val) a0.val[0]? := hmapKeep
                    _ = (a0.val.map (fun z => z.val))[0]? := by simp
                    _ = some q := by
                      simpa [hcursorZero, hlowEq] using hmap
                refine ⟨q, hmap', ?_, ?_⟩
                · omega
                · exact hlowDigit q (by rw [hlowEq]; simp)
              · have hgpos : 0 < growth.val := by omega
                have hhighLower : 10 ^ (highDigits.length - 1) <=
                    highDigits.foldl (fun n z => 10 * n + z) 0 := by
                  rw [hhighLen, hcursorVal]
                  simpa [hcarryDigits] using hcarryLower hgpos
                obtain ⟨q, qs, hhighEq, hqpos⟩ :=
                  headPositive highDigits hhighDigit
                    (by rw [hhighLen, hcursorVal]; omega) hhighLower
                have hmap := hhighArray 0 (by rw [hhighEq]; simp) (by omega)
                have hmap' : (a1.val.map (fun z => z.val))[0]? = some q := by
                  simpa [hhighEq] using hmap
                refine ⟨q, hmap', ?_, ?_⟩
                · omega
                · exact hhighDigit q (by rw [hhighEq]; simp)
            have hcountLe : count.val <= 768 := by
              rw [a1.property] at hcountBound
              simpa using hcountBound
            have hnumLe768 : d'.num_digits.val <= 768 := by
              change d'.num_digits.val <= count.val at hnumLe
              exact hnumLe.trans hcountLe
            have houtLength :
                ((d'.digits.val.take d'.num_digits.val).map (fun b => b.val)).length =
                  d'.num_digits.val := by
              simp [hdigitsOut, pre, d'.digits.property,
                min_eq_left hnumLe768]
            have houtLenEq :
                ((d'.digits.val.take d'.num_digits.val).map (fun b => b.val)).length =
                  d'.num_digits.val := by
              simp only [List.length_map, List.length_take]
              have hArrayLen : d'.digits.val.length = 768 := by
                simpa using d'.digits.property
              rw [hArrayLen]
              exact Nat.min_eq_left hnumLe768
            have hnumPos : 0 < d'.num_digits.val := by
              have hne' : d'.num_digits.val ≠ 0 := by
                simpa [bne_iff_ne] using hnonempty
              omega
            have hshape :
                exists hd tl,
                  (d'.digits.val.take d'.num_digits.val).map (fun b => b.val) = hd :: tl /\
                  1 <= hd /\ hd < 10 /\ (hd :: tl).length = d'.num_digits.val := by
              let outDigits := (d'.digits.val.take d'.num_digits.val).map (fun b => b.val)
              cases hout : outDigits with
              | nil =>
                change outDigits.length = d'.num_digits.val at houtLenEq
                rw [hout] at houtLenEq
                simp at houtLenEq
                omega
              | cons hd tl =>
                refine ⟨hd, tl, hout, ?_, ?_, ?_⟩
                · have hq := hcell0
                  rcases hq with ⟨q, hqcell, hqlo, hqhi⟩
                  have hmapOut :
                      outDigits[0]? = some q := by
                    simpa [outDigits, hdigitsOut, pre, hnumPos,
                      List.getElem?_take] using hqcell
                  simp [hout] at hmapOut
                  have : hd = q := hmapOut
                  simpa [this] using hqlo
                · have hq := hcell0
                  rcases hq with ⟨q, hqcell, hqlo, hqhi⟩
                  have hmapOut :
                      outDigits[0]? = some q := by
                    simpa [outDigits, hdigitsOut, pre, hnumPos,
                      List.getElem?_take] using hqcell
                  simp [hout] at hmapOut
                  have : hd = q := hmapOut
                  simpa [this] using hqhi
                · have hlenOut : outDigits.length = d'.num_digits.val := by
                    simp [outDigits, d'.digits.property,
                      Nat.min_eq_left hnumLe768]
                  rw [hout] at hlenOut
                  simpa using hlenOut
            have hdigitsOutBound : forall byte,
                byte ∈ d'.digits.val.take d'.num_digits.val -> byte.val < 10 := by
              intro byte hbyte
              rcases List.mem_take_iff_getElem.mp hbyte with ⟨j, hjmin, hbyteEq⟩
              have hj : j < d'.num_digits.val := by omega
              have hjarr : j < d'.digits.val.length := by
                have hlenArr : d'.digits.val.length = 768 := by
                  simpa using d'.digits.property
                rw [hlenArr]
                omega
              have hbyteVal : byte.val = a1.val[j].val := by
                have hbyteEq' : pre.digits.val[j] = byte := by
                  simpa [hdigitsOut] using hbyteEq
                simpa [pre] using congrArg (fun z : Std.U8 => z.val) hbyteEq'.symm
              have hjwidth : j < width.val := by
                by_cases hc : width >
                    num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
                · have hmax :
                    num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.val = 768 := by
                    norm_num [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def]
                  have hwide : 768 < width.val := by
                    simpa [UScalar.lt_equiv, hmax] using hc
                  have hj768 : j < 768 := Nat.lt_of_lt_of_le hj hnumLe768
                  omega
                · have hcountWidth : count.val = width.val := by
                    simp [count, hc]
                  change d'.num_digits.val <= count.val at hnumLe
                  omega
              by_cases hjhigh : j < cursor.val
              · have hidx := hhighArray j (by simpa [hhighLen] using hjhigh)
                  (by omega)
                have hidxArr : j < (a1.val.map (fun z => z.val)).length := by
                  simp [a1.property]
                  omega
                have hidxHigh : j < highDigits.length := by
                  simpa [hhighLen] using hjhigh
                have hjA1 : j < a1.val.length := by
                  simpa [a1.property] using hidxArr
                rw [List.getElem?_eq_getElem hidxArr,
                  List.getElem?_eq_getElem hidxHigh] at hidx
                simp only [List.getElem_map] at hidx
                have hval : (a1.val[j]'hjA1).val = highDigits[j] :=
                  Option.some.inj hidx
                rw [hbyteVal, hval]
                exact hhighDigit _ (List.getElem_mem _)
              · have hjcursor : cursor.val <= j := by omega
                have hidxKeep := houtside1 j (by omega) hjcursor
                have hidxKeep' : a1.val[j]? = a0.val[j]? := hidxKeep
                have hjlow : j - cursor.val < lowDigits.length := by
                  rw [hlowLen]
                  omega
                have hidxLow := hlowArray (j - cursor.val) hjlow (by omega)
                have hidxLow' :
                    (a0.val.map (fun z => z.val))[j]? =
                      lowDigits[j - cursor.val]? := by
                  simpa only [Nat.add_sub_of_le hjcursor] using hidxLow
                have hjA0 : j < a0.val.length := by
                  simpa [a0.property] using Nat.lt_of_lt_of_le hj hnumLe768
                have hidxA0 :
                    (a0.val.map (fun z => z.val))[j]? =
                      some (a0.val[j]'hjA0).val := by
                  rw [List.getElem?_eq_getElem (by simpa using hjA0)]
                  simp [List.getElem_map]
                have hidxLowElem :
                    lowDigits[j - cursor.val]? =
                      some lowDigits[j - cursor.val] := by
                  simpa using List.getElem?_eq_getElem hjlow
                rw [hidxA0, hidxLowElem] at hidxLow'
                have hjA0 : j < a0.val.length := by
                  simpa [a0.property] using Nat.lt_of_lt_of_le hj hnumLe768
                have hjA1 : j < a1.val.length := by
                  simpa [a1.property] using Nat.lt_of_lt_of_le hj hnumLe768
                have hvalKeep : a1.val[j]'hjA1 = a0.val[j]'hjA0 := by
                  have heq := hidxKeep
                  rw [List.getElem?_eq_getElem hjA1,
                    List.getElem?_eq_getElem hjA0] at heq
                  exact Option.some.inj heq
                have hvalKeep' : (a1.val[j]'hjA1).val =
                    (a0.val[j]'hjA0).val := congrArg (fun z : Std.U8 => z.val) hvalKeep
                have hval : (a0.val[j]'hjA0).val = lowDigits[j - cursor.val] :=
                  Option.some.inj hidxLow'
                have hlowDig : lowDigits[j - cursor.val] < 10 :=
                  hlowDigit _ (List.getElem_mem (n := j - cursor.val) hjlow)
                have hbyteLow : byte.val = lowDigits[j - cursor.val] := by
                  rw [hbyteVal, hvalKeep', hval]
                rw [hbyteLow]
                exact hlowDig
            have hlastOut :
                d'.digits.val[d'.num_digits.val - 1]? ≠ some 0#u8 := by
              rcases hlast with hzero | hlastBool
              · have hne' : d'.num_digits.val ≠ 0 := by
                  simpa [bne_iff_ne] using hnonempty
                omega
              · have hnot :
                    pre.digits.val[d'.num_digits.val - 1]? ≠ some 0#u8 := by
                  simpa [bne_iff_ne] using hlastBool
                simpa [hdigitsOut] using hnot
            refine ⟨d', growth, hcall, hgrowth, hgrowthBound, hpoint,
              hpointLo', hpointHi', hnumLe768, hdigitsOutBound, hshape,
              hlastOut, ?_⟩
            refine ⟨eta', u', ?_, ?_, heta'Lo, heta'u', hsticky'⟩
            · exact hscaledX
            · simpa [hY] using hscaledY.symm

end dec2flt_model

Download Lean source · Download TeX source

Complete Lean module
import Tablet.DecimalLeftShiftLoop1Execution
import Tablet.DecimalLeftShiftFirstLoopSemantics
import Tablet.DecimalLeftShiftSecondLoopSemantics
import Tablet.DecimalLeftShiftDigitGrowth
import Tablet.DecimalLeftShiftTableCertificate
import Tablet.DecimalSeqTrimSemantics
import Tablet.P472_T1_DecimalSeqDyadicShiftSemantics
import Tablet.P804_T1_LeftShiftPointGrowth
import Tablet.P472_T1_DecimalValueBounds

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false
namespace dec2flt_model

-- [TABLET NODE: P529_T1_LeftShiftCertificate]
theorem P529_T1_LeftShiftCertificate (X Y : Real)
    (d : num.imp.dec2flt.decimal_seq.DecimalSeq) (shift : Std.Usize)
    (hshift : shift.val <= 60)
    (hpointLo : -324 <= d.decimal_point.val)
    (hpointHi : d.decimal_point.val <= 0)
    (hinput : d.num_digits.val <= 768 /\
      (forall b, b ∈ d.digits.val.take d.num_digits.val -> b.val < 10) /\
      (exists h tail,
        (d.digits.val.take d.num_digits.val).map (fun b => b.val) = h :: tail /\
        1 <= h /\ h < 10 /\ (h :: tail).length = d.num_digits.val)) :
    let V := fun a : num.imp.dec2flt.decimal_seq.DecimalSeq =>
      ((((a.digits.val.take a.num_digits.val).map (fun b => b.val)).foldl
        (fun n z => 10 * n + z) 0 : Nat) : Real) *
        (10 : Real) ^ (a.decimal_point.val - (a.num_digits.val : Int))
    (exists eta u : Real, X = V d + eta /\ Y = V d + u /\
      0 <= eta /\ eta < u /\ (d.truncated = true <-> 0 < eta)) ->
    exists (d' : num.imp.dec2flt.decimal_seq.DecimalSeq) (growth : Std.Usize),
      num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift d shift = ok d' /\
      num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift
        d shift = ok growth /\
      growth.val <= 19 /\
      d'.decimal_point.val = d.decimal_point.val + (growth.val : Int) /\
      -324 <= d'.decimal_point.val /\ d'.decimal_point.val <= 19 /\
      d'.num_digits.val <= 768 /\
      (forall b, b ∈ d'.digits.val.take d'.num_digits.val -> b.val < 10) /\
      (exists h tail,
        (d'.digits.val.take d'.num_digits.val).map (fun b => b.val) = h :: tail /\
        1 <= h /\ h < 10 /\ (h :: tail).length = d'.num_digits.val) /\
      d'.digits.val[d'.num_digits.val - 1]? ≠ some 0#u8 /\
      (exists eta' u' : Real,
        (2 : Real) ^ shift.val * X = V d' + eta' /\
        (2 : Real) ^ shift.val * Y = V d' + u' /\
        0 <= eta' /\ eta' < u' /\ (d'.truncated = true <-> 0 < eta')) := by
-- BODY
  dsimp only
  intro htransport
  rcases hinput with ⟨hncap, hdigit, hhead⟩
  rcases hhead with ⟨head, tail, hdigits, hheadLo, hheadHi, hlen⟩
  rcases htransport with ⟨eta, u, hX, hY, hetaLo, hetau, hsticky⟩
  let digits := (d.digits.val.take d.num_digits.val).map (fun b => b.val)
  let I := digits.foldl (fun n z => 10 * n + z) 0
  have hdigitsLen : digits.length = d.num_digits.val := by
    simp [digits, d.digits.property,
      min_eq_left (show d.num_digits.val <= 768 by omega)]
  have hdigitsHead : digits = head :: tail := hdigits
  have hdigitsDec : forall z, z ∈ digits -> z < 10 := by
    intro z hz
    simp only [digits, List.mem_map] at hz
    rcases hz with ⟨b, hb, rfl⟩
    exact hdigit b hb
  have hvalueBounds := P472_T1_DecimalValueBounds digits head tail
    hdigitsHead hheadLo hdigitsDec d.decimal_point.val
  have hvaluePos : 0 < (I : Real) * (10 : Real) ^
      (d.decimal_point.val - (d.num_digits.val : Int)) := by
    have hp : 0 < (10 : Real) ^ (d.decimal_point.val - 1) :=
      zpow_pos (by norm_num) _
    have hz : 0 < (head : Real) * (10 : Real) ^ (d.decimal_point.val - 1) :=
      mul_pos (by exact_mod_cast hheadLo) hp
    dsimp [I] at hvalueBounds
    rw [hdigitsLen] at hvalueBounds
    exact lt_of_lt_of_le hz hvalueBounds.1
  obtain ⟨d', q, hcall, hqbound, hpointExec, hpointLo', hpointHi', hnonempty⟩ :=
    DecimalLeftShiftLoop1Execution d shift hshift hpointLo hpointHi
      (by refine ⟨hncap, hdigit, ?_⟩
          exact ⟨head, tail, hdigits, hheadLo, hheadHi, hlen⟩)
  have hne : d.num_digits.val != 0 := by
    rw [← hdigitsLen, hdigitsHead]
    simp
  have hneProp : d.num_digits.val ≠ 0 := by
    simpa [bne_iff_ne] using hne
  have zeroGrowthTotal (d0 : num.imp.dec2flt.decimal_seq.DecimalSeq)
      (sh : Std.Usize) (hsh : sh.val = 0) :
      exists gr : Std.Usize,
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift
          d0 sh = ok gr /\ gr.val = 0 := by
    have hseq : sh = 0#usize := UScalar.eq_of_val_eq (by simpa using hsh)
    subst sh
    let kfin : Fin 61 := ⟨0, by omega⟩
    have cert := DecimalLeftShiftTableCertificate kfin
    dsimp only at cert
    rcases cert with ⟨hloidx, hhiidx, hlenTable, _, hzero, _⟩
    have hz := hzero (by simp [kfin])
    rcases hz with ⟨hhiZero, hdsZero⟩
    let table := num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
    let pow5Table := num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE_POW5
    let x := table.val.get ⟨0, by simp [table]⟩
    let y := table.val.get ⟨1, by simp [table]⟩
    let hi := x.val / 2048
    let lo := x.val % 2048
    let hiNext := y.val % 2048
    let dsU := pow5Table.val.extract lo hiNext
    let ds := dsU.map (fun q => q.val)
    have hloidx' : lo <= hiNext := by
      simpa [lo, hiNext, x, y, table, kfin] using hloidx
    have hhiidx' : hiNext <= 1308 := by
      simpa [hiNext, y, table, kfin] using hhiidx
    have hlen' : ds.length = hiNext - lo := by
      simpa [ds, dsU, pow5Table, lo, hiNext, x, y, table, kfin] using hlenTable
    have hhiZero' : hi = 0 := by
      simpa [hi, x, table, kfin] using hhiZero
    have hdsZero' : ds = [] := by
      simpa [ds, dsU, pow5Table, lo, hiNext, x, y, table, kfin] using hdsZero
    have hloEq : lo = hiNext := by
      rw [hdsZero'] at hlen'
      simp at hlen'
      omega
    have hmask : (0#usize &&& 63#usize) = 0#usize := by decide
    obtain ⟨xa, hxa, hxaVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (Array.index_usize_spec
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
        0#usize (by simp [Array.length]))
    have hxaEq : xa = x := by
      apply UScalar.eq_of_val_eq
      simpa [x, table] using congrArg UScalar.val hxaVal
    subst xa
    obtain ⟨next, hnext, hnextVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (UScalar.add_spec (x := 0#usize) (y := 1#usize) (by scalar_tac))
    norm_num at hnextVal
    obtain ⟨yb, hyb, hybVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (Array.index_usize_spec
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
        next (by simp [Array.length]; omega))
    have hybEq : yb = y := by
      apply UScalar.eq_of_val_eq
      simpa [y, table, hnextVal] using congrArg UScalar.val hybVal
    subst yb
    obtain ⟨high16, hhigh16, hhigh16Val⟩ := Aeneas.Std.WP.spec_imp_exists
      (U16.ShiftRight_IScalar_spec x 11#i32 (by norm_num) (by norm_num))
    have hhigh16Eq : high16.val = hi := by
      rw [hhigh16Val.1, Nat.shiftRight_eq_div_pow]
      norm_num [hi, Int.toNat]
    let numNew : Std.Usize := UScalar.cast .Usize high16
    have hnumNewVal : numNew.val = 0 := by simp [numNew, hhigh16Eq, hhiZero']
    let low16 := 2047#u16 &&& x
    let pow5a : Std.Usize := UScalar.cast .Usize low16
    have hpow5aVal : pow5a.val = lo := by
      simp [pow5a, low16, lo, UScalar.val_and]
      rw [show 2047 = 2 ^ 11 - 1 by decide, Nat.and_comm,
        Nat.and_two_pow_sub_one_eq_mod]
    let next16 := 2047#u16 &&& y
    let pow5b : Std.Usize := UScalar.cast .Usize next16
    have hpow5bVal : pow5b.val = hiNext := by
      simp [pow5b, next16, hiNext, UScalar.val_and]
      rw [show 2047 = 2 ^ 11 - 1 by decide, Nat.and_comm,
        Nat.and_two_pow_sub_one_eq_mod]
    have hlo1308 : pow5a.val <= 1308 := by rw [hpow5aVal]; exact hloidx'.trans hhiidx'
    let slice : Slice Std.U8 := pow5Table.to_slice.drop pow5a
    have hslice :
        core.array.Array.index
          (core.ops.index.IndexSlice
            (core.slice.index.SliceIndexRangeFromUsizeSlice Std.U8))
          pow5Table { start := pow5a } = ok slice := by
      rw [Array.index_SliceIndexRangeFromUsizeSlice]
      unfold core.slice.index.SliceIndexRangeFromUsizeSlice.index
      simp [hlo1308, slice]
    have hsubBound : pow5a.val <= pow5b.val := by
      rw [hpow5aVal, hpow5bVal]
      exact hloidx'
    obtain ⟨span, hspan, hspanVal⟩ := Aeneas.Std.WP.spec_imp_exists
      (UScalar.sub_spec (x := pow5b) (y := pow5a) hsubBound)
    have hspanZero : span.val = 0 := by
      rw [hspanVal.1, hpow5aVal, hpow5bVal, ← hloEq]
      simp
    have hspanEq : span = 0#usize :=
      UScalar.eq_of_val_eq (by simpa using hspanZero)
    subst span
    refine ⟨numNew, ?_, hnumNewVal⟩
    unfold num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift
    simp only [hmask, lift, Bind.bind, Aeneas.Std.bind, hxa, bind_tc_ok,
      hnext, hyb, hhigh16]
    rw [hxaEq, hybEq]
    simp only [hhigh16, bind_tc_ok]
    rw [show UScalar.cast .Usize (2047#u16 &&& x) = pow5a by rfl]
    rw [show UScalar.cast .Usize (2047#u16 &&& y) = pow5b by rfl]
    rw [show UScalar.cast .Usize high16 = numNew by rfl]
    rw [hslice]
    simp only [bind_tc_ok]
    unfold core.slice.Slice.iter
    simp only [bind_tc_ok]
    unfold core.slice.iter.IteratorSliceIter.enumerate
    simp only [bind_tc_ok, hspan]
    unfold core.iter.adapters.enumerate.IteratorEnumerate.take
    simp only [bind_tc_ok]
    unfold num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift_loop
    rw [Aeneas.Std.loop.eq_def]
    unfold num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift_loop.body
    unfold core.iter.adapters.take.IteratorTake.next
    simp
  have hgrowthCall :
      exists growth : Std.Usize,
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift d shift = ok growth := by
    have hcall' := hcall
    unfold num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift at hcall'
    have hneWord : d.num_digits ≠ 0#usize := by
      intro hz
      have hv := congrArg UScalar.val hz
      simp at hv
      apply hneProp
      simpa using hv
    simp only [hneWord, if_false] at hcall'
    cases hg : num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift d shift with
    | fail e => simp [hg] at hcall'
    | div => simp [hg] at hcall'
    | ok growth => exact ⟨growth, by simpa [hg]⟩
  rcases hgrowthCall with ⟨growth, hgrowth⟩
  have hgrowthBound : growth.val <= 19 := by
    by_cases hk0 : shift.val = 0
    · have hs : shift = 0#usize :=
        UScalar.eq_of_val_eq (by simpa using hk0)
      subst shift
      obtain ⟨gr, hgr, hgrVal⟩ := zeroGrowthTotal d 0#usize (by simp)
      rw [hgr] at hgrowth
      cases hgrowth
      simpa [hgrVal]
    · have hkpos : 0 < shift.val := by omega
      let kfin : Fin 61 := ⟨shift.val, by omega⟩
      have cert := DecimalLeftShiftTableCertificate kfin
      dsimp only at cert
      rcases cert with ⟨_, _, _, _, _, hpositiveTable⟩
      have hp := hpositiveTable (by simpa [kfin] using hkpos)
      rcases hp with ⟨_, _, _, _, hlo, hhi⟩
      let table :=
        num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
      let entry := table.val.get ⟨shift.val, by simp [table]; omega⟩
      let h := entry.val / 2048
      have hlo' : 10 ^ (h - 1) < 2 ^ shift.val := by
        simpa [h, entry, table, kfin] using hlo
      have hhi' : 2 ^ shift.val < 10 ^ h := by
        simpa [h, entry, table, kfin] using hhi
      have hpos : 0 < h := by
        by_contra hz
        have hz' : h = 0 := by omega
        rw [hz'] at hhi'
        norm_num at hhi'
      have hle : h <= 19 := by
        by_contra hn
        have hp19 : 10 ^ 19 <= 10 ^ (h - 1) :=
          Nat.pow_le_pow_right (by omega) (by omega)
        have hBle : 2 ^ shift.val <= 2 ^ 60 :=
          Nat.pow_le_pow_right (by omega) hshift
        have hnum : 2 ^ 60 < 10 ^ 19 := by norm_num
        exact (not_lt_of_ge hp19)
          (lt_of_lt_of_le hlo' (le_trans hBle (Nat.le_of_lt hnum)))
      obtain ⟨growth', hgrowth', hformula⟩ :=
        DecimalLeftShiftDigitGrowth d shift h hshift hlo' hhi' hncap hdigit
      rw [hgrowth] at hgrowth'
      cases hgrowth'
      have hformula' : growth.val =
          if 10 ^ (d.num_digits.val + h - 1) <= I * 2 ^ shift.val
          then h else h - 1 := by
        simpa [digits, I] using hformula
      rw [hformula']
      split <;> omega
  have hgrowthExec := P804_T1_LeftShiftPointGrowth d d' shift growth
    hne hgrowth hgrowthBound hcall
  have hqEq : q = growth.val := by omega
  have hpoint : d'.decimal_point.val = d.decimal_point.val + (growth.val : Int) := by
    simpa [hqEq] using hpointExec
  have hdyadic := (P472_T1_DecimalSeqDyadicShiftSemantics).1
    d d' shift X eta u hshift hvaluePos
    (by intro b hb; exact hdigit b hb) hcall hX hetaLo hetau hsticky
  rcases hdyadic with ⟨eta', u', hscaledX, heta'Lo, heta'u', hsticky', hscaledY, _⟩
  have hcallStruct := hcall
  unfold num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift at hcallStruct
  have hneWord : d.num_digits ≠ 0#usize := by
    intro heq
    have hv := congrArg UScalar.val heq
    apply hneProp
    simpa using hv
  simp only [hneWord, if_false, hgrowth, bind_tc_ok] at hcallStruct
  cases hwidth : d.num_digits + growth with
  | fail e => simp [hwidth] at hcallStruct
  | div => simp [hwidth] at hcallStruct
  | ok width =>
    simp only [hwidth, bind_tc_ok] at hcallStruct
    cases hloop0 : num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift_loop0
        d.truncated d.digits shift d.num_digits width 0#u64 with
    | fail e => simp [hloop0] at hcallStruct
    | div => simp [hloop0] at hcallStruct
    | ok out0 =>
      rcases out0 with ⟨b0, a0, cursor, carry⟩
      simp only [hloop0, bind_tc_ok] at hcallStruct
      change (do
        let (b1, a1) ←
          num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift_loop1
            b0 a0 cursor carry
        let i1 ←
          if width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
          then ok num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS else ok width
        let i2 ← lift (UScalar.hcast .I32 growth)
        let i3 ← d.decimal_point + i2
        num.imp.dec2flt.decimal_seq.DecimalSeq.trim
          { num_digits := i1, decimal_point := i3, truncated := b1, digits := a1 }) =
          ok d' at hcallStruct
      cases hloop1 : num.imp.dec2flt.decimal_seq.DecimalSeq.left_shift_loop1
          b0 a0 cursor carry with
      | fail e => simp [hloop1] at hcallStruct
      | div => simp [hloop1] at hcallStruct
      | ok out1 =>
        rcases out1 with ⟨b1, a1⟩
        rw [hloop1] at hcallStruct
        let delta : Std.I32 := UScalar.hcast .I32 growth
        simp only [lift, bind_tc_ok] at hcallStruct
        rw [show UScalar.hcast .I32 growth = delta by rfl] at hcallStruct
        cases hpointCall : d.decimal_point + delta with
        | fail e =>
          by_cases hc : width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
        | div =>
          by_cases hc : width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
          · simp [hc, hpointCall, bind_tc_ok] at hcallStruct
        | ok point =>
          simp only [hpointCall, bind_tc_ok] at hcallStruct
          let count : Std.Usize :=
            if width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
            then num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS else width
          have hcount :
              (if width > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
                then ok num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
                else ok width) = ok count := by
            unfold count
            split <;> rfl
          rw [hcount] at hcallStruct
          simp only [bind_tc_ok] at hcallStruct
          let pre : num.imp.dec2flt.decimal_seq.DecimalSeq :=
            { num_digits := count, decimal_point := point,
              truncated := b1, digits := a1 }
          change num.imp.dec2flt.decimal_seq.DecimalSeq.trim pre = ok d' at hcallStruct
          cases htrim : num.imp.dec2flt.decimal_seq.DecimalSeq.trim pre with
          | fail e => simp [pre, htrim] at hcallStruct
          | div => simp [pre, htrim] at hcallStruct
          | ok out =>
            rw [htrim] at hcallStruct
            cases hcallStruct
            have hcountBound : count.val <= a1.val.length := by
              rw [a1.property]
              dsimp [count]
              split
              · simp [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def]
              · simp only [gt_iff_lt, UScalar.lt_equiv,
                  num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def] at *
                omega
            have htrimSem := DecimalSeqTrimSemantics pre d' hcountBound htrim
            dsimp only at htrimSem
            rcases htrimSem with
              ⟨hdigitsOut, hpointOut, htruncOut, hnumLe, hzeros, hlast, hvalueOut⟩
            let B := 2 ^ shift.val
            have hfoldBounds := P804_T1_DecimalFoldBounds digits hdigitsDec
              head tail hdigitsHead hheadLo
            have foldBound (xs : List Nat) (hs : forall z, z ∈ xs -> z < 10) :
                xs.foldl (fun n z => 10 * n + z) 0 < 10 ^ xs.length := by
              let F := fun ys : List Nat =>
                ys.foldl (fun n z => 10 * n + z) 0
              have foldlFrom (ys : List Nat) (acc : Nat) :
                  ys.foldl (fun n z => 10 * n + z) acc =
                    acc * 10 ^ ys.length + F ys := by
                induction ys generalizing acc with
                | nil => simp [F]
                | cons y ys ih =>
                  simp only [List.foldl_cons, List.length_cons]
                  rw [ih, pow_succ]
                  change (10 * acc + y) * 10 ^ ys.length + F ys =
                    acc * (10 ^ ys.length * 10) +
                      (y :: ys).foldl (fun n z => 10 * n + z) 0
                  simp only [List.foldl_cons]
                  rw [ih]
                  ring
              induction xs with
              | nil => simp
              | cons z xs ih =>
                have hz : z < 10 := hs z (by simp)
                have hxs : forall q, q ∈ xs -> q < 10 := by
                  intro q hq
                  exact hs q (by simp [hq])
                have hi := ih hxs
                have hform : (z :: xs).foldl (fun n a => 10 * n + a) 0 =
                    z * 10 ^ xs.length + xs.foldl (fun n a => 10 * n + a) 0 := by
                  simp only [List.foldl_cons]
                  simpa [F] using foldlFrom xs z
                rw [hform, List.length_cons, pow_succ]
                have hm := Nat.mul_le_mul_right (10 ^ xs.length) (show z <= 9 by omega)
                nlinarith
            have hproductBounds :
                10 ^ (d.num_digits.val + growth.val - 1) <= I * B /\
                I * B < 10 ^ (d.num_digits.val + growth.val) := by
              by_cases hk0 : shift.val = 0
              · obtain ⟨gr, hgr, hgrVal⟩ := zeroGrowthTotal d shift hk0
                rw [hgrowth] at hgr
                cases hgr
                have hIlo := hfoldBounds.1
                have hIhi := hfoldBounds.2
                rw [hdigitsLen] at hIlo hIhi
                have hB : B = 1 := by simp [B, hk0]
                rw [hgrVal, hB]
                simpa [I] using And.intro hIlo hIhi
              · have hkpos : 0 < shift.val := by omega
                let kfin : Fin 61 := ⟨shift.val, by omega⟩
                have cert := DecimalLeftShiftTableCertificate kfin
                dsimp only at cert
                rcases cert with ⟨_, _, _, _, _, hpositiveTable⟩
                have hp := hpositiveTable (by simpa [kfin] using hkpos)
                rcases hp with ⟨_, _, _, _, hlo, hhi⟩
                let table :=
                  num.imp.dec2flt.decimal_seq.number_of_digits_decimal_left_shift.TABLE
                let entry := table.val.get ⟨shift.val, by simp [table]; omega⟩
                let h := entry.val / 2048
                have hlo' : 10 ^ (h - 1) < B := by
                  simpa [h, entry, table, kfin, B] using hlo
                have hhi' : B < 10 ^ h := by
                  simpa [h, entry, table, kfin, B] using hhi
                have hpos : 0 < h := by
                  by_contra hz
                  have hz' : h = 0 := by omega
                  rw [hz'] at hhi'
                  norm_num at hhi'
                  have hBpos : 0 < B := by simp [B]
                  omega
                obtain ⟨gr, hgr, hformula⟩ :=
                  DecimalLeftShiftDigitGrowth d shift h hshift hlo' hhi' hncap hdigit
                rw [hgrowth] at hgr
                cases hgr
                have hformula' : growth.val =
                    if 10 ^ (d.num_digits.val + h - 1) <= I * B
                    then h else h - 1 := by
                  simpa [digits, I, B] using hformula
                rw [hformula']
                split
                · rename_i ht
                  constructor
                  · exact ht
                  · have hIhi := hfoldBounds.2
                    rw [hdigitsLen] at hIhi
                    have hmul1 : I * B < 10 ^ d.num_digits.val * B :=
                      (Nat.mul_lt_mul_right (by positivity : 0 < B)).2 hIhi
                    have hmul2 : 10 ^ d.num_digits.val * B <
                        10 ^ d.num_digits.val * 10 ^ h :=
                      (Nat.mul_lt_mul_left (by positivity : 0 < 10 ^ d.num_digits.val)).2 hhi'
                    calc
                      I * B < 10 ^ d.num_digits.val * B := hmul1
                      _ < 10 ^ d.num_digits.val * 10 ^ h := hmul2
                      _ = 10 ^ (d.num_digits.val + h) := by rw [Nat.pow_add]
                · rename_i ht
                  have hmul1 :
                      10 ^ (h - 1) * 10 ^ (d.num_digits.val - 1) <
                        B * 10 ^ (d.num_digits.val - 1) :=
                    (Nat.mul_lt_mul_right (by positivity)).mpr hlo'
                  have hIlo := hfoldBounds.1
                  rw [hdigitsLen] at hIlo
                  have hmul2 : B * 10 ^ (d.num_digits.val - 1) <= B * I :=
                    Nat.mul_le_mul_left B hIlo
                  have he : d.num_digits.val + (h - 1) - 1 =
                      (h - 1) + (d.num_digits.val - 1) := by omega
                  constructor
                  · rw [he, Nat.pow_add]
                    exact Nat.le_of_lt (lt_of_lt_of_le hmul1 (by simpa [Nat.mul_comm] using hmul2))
                  · have hlt : I * B <
                        10 ^ (d.num_digits.val + h - 1) := by omega
                    have hexp' : d.num_digits.val + h - 1 =
                        d.num_digits.val + (h - 1) := by omega
                    simpa only [show d.num_digits.val + h - 1 =
                      d.num_digits.val + (h - 1) by omega] using hlt
            have haddBound : d.num_digits.val + growth.val <= UScalar.max .Usize := by
              scalar_tac
            obtain ⟨widthSpec, hwidthSpec, hwidthVal⟩ :=
              Aeneas.Std.WP.spec_imp_exists
                (UScalar.add_spec (x := d.num_digits) (y := growth) haddBound)
            have hwidthEq : widthSpec = width := by
              rw [hwidth] at hwidthSpec
              cases hwidthSpec
              rfl
            subst widthSpec
            have hreadwrite : d.num_digits.val <= width.val := by
              rw [hwidthVal]
              omega
            have hfirst := DecimalLeftShiftFirstLoopSemantics
              d.digits a0 d.truncated b0 shift d.num_digits width cursor carry
              hshift (by simpa using hncap) hreadwrite hdigit hloop0
            dsimp only at hfirst
            rcases hfirst with
              ⟨lowDigits, hlowLen, hlowDigit, hcursorEq, hcarryB, hproduct,
                hlowArray, houtside0, hsticky0⟩
            have hprod : B * I =
                carry.val * 10 ^ d.num_digits.val +
                  lowDigits.foldl (fun n z => 10 * n + z) 0 := by
              simpa [B, I, digits] using hproduct
            have hcursorVal : cursor.val = growth.val := by
              rw [hwidthVal] at hcursorEq
              omega
            have hlowBound : lowDigits.foldl (fun n z => 10 * n + z) 0 <
                10 ^ d.num_digits.val := by
              have := foldBound lowDigits hlowDigit
              simpa [hlowLen] using this
            have hcarryWidth : carry.val < 10 ^ cursor.val := by
              rw [hcursorVal]
              have hle : carry.val * 10 ^ d.num_digits.val <= B * I := by
                rw [hprod]
                exact Nat.le_add_right _ _
              have hpow : 10 ^ growth.val * 10 ^ d.num_digits.val =
                  10 ^ (d.num_digits.val + growth.val) := by
                rw [Nat.mul_comm, ← Nat.pow_add]
              have hm : carry.val * 10 ^ d.num_digits.val <
                  10 ^ growth.val * 10 ^ d.num_digits.val := by
                rw [hpow]
                exact lt_of_le_of_lt hle (by simpa [Nat.mul_comm] using hproductBounds.2)
              exact Nat.lt_of_mul_lt_mul_right hm
            have hcarryLower : 0 < growth.val -> 10 ^ (growth.val - 1) <= carry.val := by
              intro hgpos
              by_contra hnot
              have hcsmall : carry.val < 10 ^ (growth.val - 1) := by omega
              have hu : carry.val * 10 ^ d.num_digits.val +
                  lowDigits.foldl (fun n z => 10 * n + z) 0 <
                    10 ^ (growth.val - 1) * 10 ^ d.num_digits.val := by
                have hc1 : carry.val + 1 <= 10 ^ (growth.val - 1) := by omega
                have hm := Nat.mul_le_mul_right (10 ^ d.num_digits.val) hc1
                rw [Nat.add_mul] at hm
                have hF : 0 <=
                    lowDigits.foldl (fun n z => 10 * n + z) 0 := Nat.zero_le _
                omega
              rw [← hprod] at hu
              have hexp : d.num_digits.val + growth.val - 1 =
                  (growth.val - 1) + d.num_digits.val := by omega
              have hlow := hproductBounds.1
              rw [hexp, Nat.pow_add] at hlow
              exact (not_lt_of_ge (by simpa [Nat.mul_comm] using hlow)) hu
            have hpad : forall j, j < cursor.val -> j < 768 ->
                carry.val < 10 ^ (cursor.val - j - 1) ->
                  a0.val[j]? = some 0#u8 := by
              intro j hj _ hjcarry
              have hgpos : 0 < growth.val := by omega
              have hlow := hcarryLower hgpos
              have hexp : cursor.val - j - 1 <= growth.val - 1 := by
                rw [hcursorVal]
                omega
              have hp : 10 ^ (cursor.val - j - 1) <= 10 ^ (growth.val - 1) :=
                Nat.pow_le_pow_right (by omega) hexp
              exact False.elim
                (not_lt_of_ge hlow (lt_of_lt_of_le hjcarry hp))
            have hsecond := DecimalLeftShiftSecondLoopSemantics a0 a1 b0 b1
              cursor carry hcarryWidth hpad hloop1
            rcases hsecond with
              ⟨highDigits, hhighLen, hhighDigit, hcarryDigits,
                hhighArray, houtside1, hsticky1⟩
            have headPositive (ys : List Nat) (hy : forall z, z ∈ ys -> z < 10)
                (hpos : 0 < ys.length)
                (hlower : 10 ^ (ys.length - 1) <=
                  ys.foldl (fun n z => 10 * n + z) 0) :
                exists q qs, ys = q :: qs /\ 0 < q := by
              cases hys : ys with
              | nil =>
                rw [hys] at hpos
                simp at hpos
              | cons q qs =>
                refine ⟨q, qs, rfl, ?_⟩
                by_contra hq
                have hqzero : q = 0 := by omega
                have hy' : forall z, z ∈ q :: qs -> z < 10 := by
                  simpa [hys] using hy
                have htailDigit : forall a, a ∈ qs -> a < 10 := by
                  intro a ha
                  exact hy' a (List.mem_cons_of_mem q ha)
                have htailBound := foldBound qs htailDigit
                have htailLower : 10 ^ qs.length <=
                    qs.foldl (fun n z => 10 * n + z) 0 := by
                  simpa [hys, hqzero] using hlower
                omega
            have hcountPos : 0 < count.val := by
              have hnpos : 0 < d.num_digits.val := by
                have := hdigitsLen
                simp only [hdigitsHead, List.length_cons] at this
                omega
              unfold count
              split
              · simp [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def]
              · have hw : width.val = d.num_digits.val + growth.val := hwidthVal
                omega
            have hcell0 : exists q : Nat,
                (a1.val.map (fun z => z.val))[0]? = some q /\ 1 <= q /\ q < 10 := by
              by_cases hgzero : growth.val = 0
              · have hcursorZero : cursor.val = 0 := by rw [hcursorVal, hgzero]
                have hcarryZero : carry.val = 0 := by
                  rw [hcursorZero] at hcarryWidth
                  simp at hcarryWidth
                  omega
                have hlowLower : 10 ^ (lowDigits.length - 1) <=
                    lowDigits.foldl (fun n z => 10 * n + z) 0 := by
                  have hl := hproductBounds.1
                  rw [hgzero] at hl
                  have hprod' : B * I =
                      lowDigits.foldl (fun n z => 10 * n + z) 0 := by
                    rw [hprod, hcarryZero]
                    simp
                  have hl' : 10 ^ (d.num_digits.val - 1) <=
                      lowDigits.foldl (fun n z => 10 * n + z) 0 := by
                    have hl'' : 10 ^ (d.num_digits.val - 1) <= I * B := by
                      simpa [hgzero] using hl
                    calc
                      10 ^ (d.num_digits.val - 1) <= I * B := hl''
                      _ = B * I := by rw [Nat.mul_comm]
                      _ = lowDigits.foldl (fun n z => 10 * n + z) 0 := hprod'
                  simpa [hlowLen] using hl'
                obtain ⟨q, qs, hlowEq, hqpos⟩ :=
                  headPositive lowDigits hlowDigit (by rw [hlowLen]; omega) hlowLower
                have hmap := hlowArray 0 (by rw [hlowEq]; simp) (by omega)
                have hmap' :
                    (a1.val.map (fun z => z.val))[0]? = some q := by
                  have hkeep := houtside1 0 (by omega) (by simpa [hcursorZero])
                  have hmapKeep := congrArg
                    (Option.map (fun z : Std.U8 => z.val)) hkeep
                  calc
                    (a1.val.map (fun z => z.val))[0]? =
                        Option.map (fun z : Std.U8 => z.val) a1.val[0]? := by
                          simp
                    _ = Option.map (fun z : Std.U8 => z.val) a0.val[0]? := hmapKeep
                    _ = (a0.val.map (fun z => z.val))[0]? := by simp
                    _ = some q := by
                      simpa [hcursorZero, hlowEq] using hmap
                refine ⟨q, hmap', ?_, ?_⟩
                · omega
                · exact hlowDigit q (by rw [hlowEq]; simp)
              · have hgpos : 0 < growth.val := by omega
                have hhighLower : 10 ^ (highDigits.length - 1) <=
                    highDigits.foldl (fun n z => 10 * n + z) 0 := by
                  rw [hhighLen, hcursorVal]
                  simpa [hcarryDigits] using hcarryLower hgpos
                obtain ⟨q, qs, hhighEq, hqpos⟩ :=
                  headPositive highDigits hhighDigit
                    (by rw [hhighLen, hcursorVal]; omega) hhighLower
                have hmap := hhighArray 0 (by rw [hhighEq]; simp) (by omega)
                have hmap' : (a1.val.map (fun z => z.val))[0]? = some q := by
                  simpa [hhighEq] using hmap
                refine ⟨q, hmap', ?_, ?_⟩
                · omega
                · exact hhighDigit q (by rw [hhighEq]; simp)
            have hcountLe : count.val <= 768 := by
              rw [a1.property] at hcountBound
              simpa using hcountBound
            have hnumLe768 : d'.num_digits.val <= 768 := by
              change d'.num_digits.val <= count.val at hnumLe
              exact hnumLe.trans hcountLe
            have houtLength :
                ((d'.digits.val.take d'.num_digits.val).map (fun b => b.val)).length =
                  d'.num_digits.val := by
              simp [hdigitsOut, pre, d'.digits.property,
                min_eq_left hnumLe768]
            have houtLenEq :
                ((d'.digits.val.take d'.num_digits.val).map (fun b => b.val)).length =
                  d'.num_digits.val := by
              simp only [List.length_map, List.length_take]
              have hArrayLen : d'.digits.val.length = 768 := by
                simpa using d'.digits.property
              rw [hArrayLen]
              exact Nat.min_eq_left hnumLe768
            have hnumPos : 0 < d'.num_digits.val := by
              have hne' : d'.num_digits.val ≠ 0 := by
                simpa [bne_iff_ne] using hnonempty
              omega
            have hshape :
                exists hd tl,
                  (d'.digits.val.take d'.num_digits.val).map (fun b => b.val) = hd :: tl /\
                  1 <= hd /\ hd < 10 /\ (hd :: tl).length = d'.num_digits.val := by
              let outDigits := (d'.digits.val.take d'.num_digits.val).map (fun b => b.val)
              cases hout : outDigits with
              | nil =>
                change outDigits.length = d'.num_digits.val at houtLenEq
                rw [hout] at houtLenEq
                simp at houtLenEq
                omega
              | cons hd tl =>
                refine ⟨hd, tl, hout, ?_, ?_, ?_⟩
                · have hq := hcell0
                  rcases hq with ⟨q, hqcell, hqlo, hqhi⟩
                  have hmapOut :
                      outDigits[0]? = some q := by
                    simpa [outDigits, hdigitsOut, pre, hnumPos,
                      List.getElem?_take] using hqcell
                  simp [hout] at hmapOut
                  have : hd = q := hmapOut
                  simpa [this] using hqlo
                · have hq := hcell0
                  rcases hq with ⟨q, hqcell, hqlo, hqhi⟩
                  have hmapOut :
                      outDigits[0]? = some q := by
                    simpa [outDigits, hdigitsOut, pre, hnumPos,
                      List.getElem?_take] using hqcell
                  simp [hout] at hmapOut
                  have : hd = q := hmapOut
                  simpa [this] using hqhi
                · have hlenOut : outDigits.length = d'.num_digits.val := by
                    simp [outDigits, d'.digits.property,
                      Nat.min_eq_left hnumLe768]
                  rw [hout] at hlenOut
                  simpa using hlenOut
            have hdigitsOutBound : forall byte,
                byte ∈ d'.digits.val.take d'.num_digits.val -> byte.val < 10 := by
              intro byte hbyte
              rcases List.mem_take_iff_getElem.mp hbyte with ⟨j, hjmin, hbyteEq⟩
              have hj : j < d'.num_digits.val := by omega
              have hjarr : j < d'.digits.val.length := by
                have hlenArr : d'.digits.val.length = 768 := by
                  simpa using d'.digits.property
                rw [hlenArr]
                omega
              have hbyteVal : byte.val = a1.val[j].val := by
                have hbyteEq' : pre.digits.val[j] = byte := by
                  simpa [hdigitsOut] using hbyteEq
                simpa [pre] using congrArg (fun z : Std.U8 => z.val) hbyteEq'.symm
              have hjwidth : j < width.val := by
                by_cases hc : width >
                    num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
                · have hmax :
                    num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.val = 768 := by
                    norm_num [num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def]
                  have hwide : 768 < width.val := by
                    simpa [UScalar.lt_equiv, hmax] using hc
                  have hj768 : j < 768 := Nat.lt_of_lt_of_le hj hnumLe768
                  omega
                · have hcountWidth : count.val = width.val := by
                    simp [count, hc]
                  change d'.num_digits.val <= count.val at hnumLe
                  omega
              by_cases hjhigh : j < cursor.val
              · have hidx := hhighArray j (by simpa [hhighLen] using hjhigh)
                  (by omega)
                have hidxArr : j < (a1.val.map (fun z => z.val)).length := by
                  simp [a1.property]
                  omega
                have hidxHigh : j < highDigits.length := by
                  simpa [hhighLen] using hjhigh
                have hjA1 : j < a1.val.length := by
                  simpa [a1.property] using hidxArr
                rw [List.getElem?_eq_getElem hidxArr,
                  List.getElem?_eq_getElem hidxHigh] at hidx
                simp only [List.getElem_map] at hidx
                have hval : (a1.val[j]'hjA1).val = highDigits[j] :=
                  Option.some.inj hidx
                rw [hbyteVal, hval]
                exact hhighDigit _ (List.getElem_mem _)
              · have hjcursor : cursor.val <= j := by omega
                have hidxKeep := houtside1 j (by omega) hjcursor
                have hidxKeep' : a1.val[j]? = a0.val[j]? := hidxKeep
                have hjlow : j - cursor.val < lowDigits.length := by
                  rw [hlowLen]
                  omega
                have hidxLow := hlowArray (j - cursor.val) hjlow (by omega)
                have hidxLow' :
                    (a0.val.map (fun z => z.val))[j]? =
                      lowDigits[j - cursor.val]? := by
                  simpa only [Nat.add_sub_of_le hjcursor] using hidxLow
                have hjA0 : j < a0.val.length := by
                  simpa [a0.property] using Nat.lt_of_lt_of_le hj hnumLe768
                have hidxA0 :
                    (a0.val.map (fun z => z.val))[j]? =
                      some (a0.val[j]'hjA0).val := by
                  rw [List.getElem?_eq_getElem (by simpa using hjA0)]
                  simp [List.getElem_map]
                have hidxLowElem :
                    lowDigits[j - cursor.val]? =
                      some lowDigits[j - cursor.val] := by
                  simpa using List.getElem?_eq_getElem hjlow
                rw [hidxA0, hidxLowElem] at hidxLow'
                have hjA0 : j < a0.val.length := by
                  simpa [a0.property] using Nat.lt_of_lt_of_le hj hnumLe768
                have hjA1 : j < a1.val.length := by
                  simpa [a1.property] using Nat.lt_of_lt_of_le hj hnumLe768
                have hvalKeep : a1.val[j]'hjA1 = a0.val[j]'hjA0 := by
                  have heq := hidxKeep
                  rw [List.getElem?_eq_getElem hjA1,
                    List.getElem?_eq_getElem hjA0] at heq
                  exact Option.some.inj heq
                have hvalKeep' : (a1.val[j]'hjA1).val =
                    (a0.val[j]'hjA0).val := congrArg (fun z : Std.U8 => z.val) hvalKeep
                have hval : (a0.val[j]'hjA0).val = lowDigits[j - cursor.val] :=
                  Option.some.inj hidxLow'
                have hlowDig : lowDigits[j - cursor.val] < 10 :=
                  hlowDigit _ (List.getElem_mem (n := j - cursor.val) hjlow)
                have hbyteLow : byte.val = lowDigits[j - cursor.val] := by
                  rw [hbyteVal, hvalKeep', hval]
                rw [hbyteLow]
                exact hlowDig
            have hlastOut :
                d'.digits.val[d'.num_digits.val - 1]? ≠ some 0#u8 := by
              rcases hlast with hzero | hlastBool
              · have hne' : d'.num_digits.val ≠ 0 := by
                  simpa [bne_iff_ne] using hnonempty
                omega
              · have hnot :
                    pre.digits.val[d'.num_digits.val - 1]? ≠ some 0#u8 := by
                  simpa [bne_iff_ne] using hlastBool
                simpa [hdigitsOut] using hnot
            refine ⟨d', growth, hcall, hgrowth, hgrowthBound, hpoint,
              hpointLo', hpointHi', hnumLe768, hdigitsOutBound, hshape,
              hlastOut, ?_⟩
            refine ⟨eta', u', ?_, ?_, heta'Lo, heta'u', hsticky'⟩
            · exact hscaledX
            · simpa [hY] using hscaledY.symm

end dec2flt_model

Proof structure

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

Explore this dependency tree

Inspect related source (117)
More program dependencies (84)
Standard-library dependencies (30)

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 30 entries
Technical checking records
Local closure summary
{
  "node": "P529_T1_LeftShiftCertificate",
  "closure_version": "patch_c_v1",
  "active_decl_hash": "14d75b96fabc1e5315c68d9d288af0d1fdada2edca2eb85052f82aa5c101026a",
  "active_statement_hash": "13e2070c7d80a9200942f3cb2d62076d0b70c977e61f7220d8a879d0852876cc",
  "kernel_axioms": [
    "Classical.choice",
    "Quot.sound",
    "propext"
  ],
  "toolchain_hash": "ce4c4e3d87434b9663f46de25ce34b48a0cf0d392e0a320a0787b4674a2d7b61",
  "lean_executable_hash": "3e0d0d3d801675359f2d4cf9815bfdb417b20b92fdd9d48b3b14c95bbae28bbf",
  "checker_script_hash": "c8e4a03273e23b9a8f2e141020652a4e0b7b0a8ab0883366ea9d031ca3f37aa1",
  "approved_axioms_hash": "576e6bf9480cfd32f53c309c7ac8fb115c1ba6e413f299ed5ff9fa7c647e6769",
  "axcheck_status": "Agreed",
  "accepted_at_snapshot_id": "worker-result-local-closure-issuance-cycle-181",
  "boundary_theorems": {},
  "strict_theorem_deps": {
    "DecimalLeftShiftDigitGrowth": "6dcf8858df4713eb",
    "DecimalLeftShiftFirstLoopSemantics": "d126fe9b83dfc5f3",
    "DecimalLeftShiftLoop1Execution": "c945a26c8d67077b",
    "DecimalLeftShiftSecondLoopSemantics": "ccbfee7a0aef7445",
    "DecimalLeftShiftTableCertificate": "3c85f76c60cebc6c",
    "DecimalSeqTrimSemantics": "e4b2cbb62f7171af",
    "P472_T1_DecimalSeqDyadicShiftSemantics": "9d844d655b9f8a27",
    "P472_T1_DecimalValueBounds": "4b5c924b5d52bc9d",
    "P804_T1_DecimalFoldBounds": "9af7ca1186664411",
    "P804_T1_LeftShiftPointGrowth": "6a9a6c7c27a2ac4e",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS": "0eb6fb2627d0ff5c",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_left_shift": "adfe9a4161cd7fd6",
    "num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift": "3703c132ca68c95c"
  },
  "strict_definition_deps": {
    "num_imp_dec2flt_decimal_seq_DecimalSeq": "b0286c42454b158d",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS": "39f6cb231ef80388",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_left_shift": "4aaaec2c6526e3a6",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_right_shift": "1aaf1bb11c0b6a49",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_trim": "faa9fd92b8c29c14",
    "num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift": "889854c120bac844",
    "num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift_TABLE": "e68bec96fec99700",
    "num_imp_dec2flt_decimal_seq_number_of_digits_decimal_left_shift_TABLE_POW5": "4dda92c1af5f2c9e"
  }
}
Prose assessment
{
  "label": "Recorded Sound: VerifierPass",
  "assessment_status": "VerifierPass",
  "fingerprint_relation": "matches current fingerprint",
  "assessment_fingerprint": "sound-v2:dbd86f44cc53e5878bcd74a7f1c1e096ba210d5f0eafdd4c1cde559e6b9f409f",
  "current_fingerprint": "sound-v2:dbd86f44cc53e5878bcd74a7f1c1e096ba210d5f0eafdd4c1cde559e6b9f409f",
  "superseded_for_theorem_closure": false
}
Review verdicts
{
  "corr_status": "Pass",
  "sound_status": "Pass",
  "substantiveness_status": "Pass"
}