import Tablet.ResultLoopPartial
import Tablet.ParserExponentConstants

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: ParserSlowLoopMinimumExponent]
theorem ParserSlowLoopMinimumExponent
    (d : num.imp.dec2flt.decimal_seq.DecimalSeq) (e : I32)
    (out : num.imp.dec2flt.decimal_seq.DecimalSeq × I32)
    (h : num.imp.dec2flt.slow.parse_long_mantissa_loop2
      F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 d e = ok out) :
    -1022 ≤ out.2.val := by
-- BODY
  rcases ParserExponentConstants with
    ⟨hbits, htotal, hsig, hexpbits, hexpsat, hinf, hbias, hmin,
      hsmall, hlarge, hroundmin, hroundmax⟩
  let Inv := fun (_ : num.imp.dec2flt.decimal_seq.DecimalSeq × I32) => True
  let Post := fun (x : num.imp.dec2flt.decimal_seq.DecimalSeq × I32) =>
    -1022 ≤ x.2.val
  let Body := fun (x : num.imp.dec2flt.decimal_seq.DecimalSeq × I32) =>
    match x with
    | (d, e) => num.imp.dec2flt.slow.parse_long_mantissa_loop2.body
      F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 d e
  have bind_ok_inv : ∀ {α β : Type} (r : Result α) (f : α → Result β) y,
      Bind.bind r f = ok y → ∃ x, r = ok x ∧ f x = ok y := by
    intro α β r f 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 hbody : ∀ x, Inv x → ∀ r, Body x = ok r →
      match r with | done y => Post y | cont x' => Inv x' := by
    intro x hx r hb
    rcases x with ⟨d, e⟩
    simp only [Body] at hb
    unfold num.imp.dec2flt.slow.parse_long_mantissa_loop2.body at hb
    rw [hmin] at hb
    simp only [bind_tc_ok] at hb
    by_cases hgt : (-1022)#i32 > e
    · simp only [hgt, if_true] at hb
      obtain ⟨diff, hdiff, hb⟩ := bind_ok_inv _ _ _ hb
      obtain ⟨n, hn, hb⟩ := bind_ok_inv _ _ _ hb
      obtain ⟨n1, hn1, hb⟩ := bind_ok_inv _ _ _ hb
      obtain ⟨d1, hd1, hb⟩ := bind_ok_inv _ _ _ hb
      obtain ⟨step32, hstep32, hb⟩ := bind_ok_inv _ _ _ hb
      obtain ⟨e', he', hb⟩ := bind_ok_inv _ _ _ hb
      cases hb
      trivial
    · simp only [hgt, if_false] at hb
      cases hb
      change -1022 ≤ e.val
      change ¬ -1022 > e.val at hgt
      omega
  unfold num.imp.dec2flt.slow.parse_long_mantissa_loop2 at h
  refine ResultLoopPartial Inv Post Body ?_ _ _ trivial h
  intro x hx r hr
  cases r with
  | done y => exact hbody x hx (done y) hr
  | cont x' => exact hbody x hx (cont x') hr

end dec2flt_model
