import Tablet.DecimalGoalVocabularyDefault
import Tablet.Assumptions
import Tablet.ModelF64MantissaDigits
import Tablet.ModelU64BitAnd
import Tablet.ModelU64BitOr
import Tablet.ModelU64Shl
import Tablet.F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64
import Tablet.F64_Insts_CoreOpsArithDivF64F64
import Tablet.F64_Insts_CoreOpsArithMulF64F64
import Tablet.F64_Insts_CoreOpsArithNegF64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatExtU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_BITS
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_LARGEST_POWER_OF_TEN
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_MAX_EXPONENT_ROUND_TO_EVEN
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_MIN_EXPONENT_ROUND_TO_EVEN
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SIG_TOTAL_BITS
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64_SMALLEST_POWER_OF_TEN
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_Dec2FltTrace
import Tablet.num_imp_dec2flt_dec2flt
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
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_lemire_full_multiplication
import Tablet.num_imp_dec2flt_lemire_power
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_table_LARGEST_POWER_OF_FIVE
import Tablet.num_imp_dec2flt_table_POWER_OF_FIVE_128
import Tablet.num_imp_dec2flt_table_SMALLEST_POWER_OF_FIVE
import Tablet.num_imp_traits_Float_EXP_BIAS_default
import Tablet.num_imp_traits_Float_EXP_BITS_default
import Tablet.num_imp_traits_Float_EXP_MIN_default
import Tablet.num_imp_traits_Float_EXP_SAT_default
import Tablet.num_imp_traits_Float_INFINITE_POWER_default
import Tablet.num_imp_traits_Float_SIG_BITS_default
import Tablet.num_imp_dec2flt_biased_fp_to_float
import Tablet.ParserComputeFloatExponentRange
import Tablet.ParserSlowExponentRange
import Tablet.ParserComputeFloatMantissaBound
import Tablet.ParserSlowMantissaBound
import Tablet.SourceValidByteSlice

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: ParserSelectedMantissaBound]
theorem ParserSelectedMantissaBound :
    ∀ (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) ->
      tr.selected_pair.m.val ≤ 2 ^ 52 := by
-- BODY
  intro s f tr hs h
  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⟩
  let Good := fun (x : num.imp.dec2flt.common.BiasedFp) =>
    x.m.val ≤ 2 ^ 52
  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
    have hbody1Valid : SourceValidByteSlice body1 := by
      have hslen : s.val.length <= 9223372036854775807 := hs.1
      have hbs : body = s := by
        simpa [core.str.Str.as_bytes, ModelStrAsBytes] using hbody.symm
      subst body
      unfold SourceValidByteSlice
      by_cases hminus : c = 45#u8
      · simp only [hminus, if_true] at hbody1
        by_cases hlen : 1 <= s.val.length
        · simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
            Slice.drop, hlen] at hbody1
          cases hbody1
          rw [List.length_tail]
          exact Nat.le_trans (Nat.sub_le _ _) hslen
        · simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
            hlen] at hbody1
      · simp only [hminus, if_false] at hbody1
        by_cases hplus : c = 43#u8
        · simp only [hplus, if_true] at hbody1
          by_cases hlen : 1 <= s.val.length
          · simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
              Slice.drop, hlen] at hbody1
            cases hbody1
            rw [List.length_tail]
            exact Nat.le_trans (Nat.sub_le _ _) hslen
          · simp [core.slice.index.SliceIndexRangeFromUsizeSlice.index,
              hlen] at hbody1
        · simp only [hplus, if_false] at hbody1
          cases hbody1
          exact hslen
    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
          have hfirstGood : Good firstPair :=
            ParserComputeFloatMantissaBound _ _ _ hfirstPair
          obtain ⟨phase1, hphase1, h⟩ := bind_ok_inv _ _ _ h
          rcases phase1 with ⟨many1, many2, firstPair1, fp, guard⟩
          have hfp : fp = firstPair := by
            by_cases hm : r.many_digits
            · simp only [hm, if_true] at hphase1
              cases hphase1
              rfl
            · simp only [hm, if_false] at hphase1
              cases hphase1
              rfl
          subst fp
          obtain ⟨phase2, hphase2, h⟩ := bind_ok_inv _ _ _ h
          rcases phase2 with
            ⟨post, secondExp, secondMant, secondResult, secondEqual, forced⟩
          have hpost : Good post := by
            cases guard with
            | false =>
              simp only [Bool.false_eq_true, if_false] at hphase2
              cases hphase2
              exact hfirstGood
            | true =>
              simp only [if_true] at hphase2
              obtain ⟨mantissa, hmantissa, hphase2⟩ :=
                bind_ok_inv _ _ _ hphase2
              obtain ⟨second, hsecond, hphase2⟩ :=
                bind_ok_inv _ _ _ hphase2
              have hsecondGood : Good second :=
                ParserComputeFloatMantissaBound _ _ _ hsecond
              obtain ⟨equal, hequal, hphase2⟩ :=
                bind_ok_inv _ _ _ hphase2
              obtain ⟨chosen, hchosen, hphase2⟩ :=
                bind_ok_inv _ _ _ hphase2
              rcases chosen with ⟨bf, wasForced⟩
              have hbf : Good bf := by
                by_cases heq : equal = true
                · simp only [heq, if_true] at hchosen
                  cases hchosen
                  exact hfirstGood
                · have heqf : equal = false := Bool.eq_false_of_not_eq_true heq
                  simp only [heqf, if_false] at hchosen
                  cases hchosen
                  exact hfirstGood
              cases hphase2
              exact hbf
          obtain ⟨phase3, hphase3, h⟩ := bind_ok_inv _ _ _ h
          rcases phase3 with ⟨selected, slowGuard, slowResult⟩
          have hselected : Good selected := by
            by_cases hneg : post.p_biased < 0#i32
            · simp only [hneg, if_true] at hphase3
              obtain ⟨replacement, hreplacement, hphase3⟩ :=
                bind_ok_inv _ _ _ hphase3
              have hrange :=
                ParserSlowMantissaBound _ _ hbody1Valid hreplacement
              cases hphase3
              exact Nat.le_of_lt hrange
            · simp only [hneg, if_false] at hphase3
              cases hphase3
              exact hpost
          obtain ⟨i, hi, h⟩ := bind_ok_inv _ _ _ h
          obtain ⟨i1, hi1, h⟩ := bind_ok_inv _ _ _ h
          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 hselected
          · simp only [hnegative, if_false] at h
            cases h
            exact hselected

end dec2flt_model
