NumberHelperRejectionSafeLength

Lean checked

Statement

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

Theorem · Uniform invalid rejection through the sharp safe length

Every source-valid, nonempty byte slice of length at most 9223372036854120459 that is not a complete unsigned numeric literal makes the extracted parse_number return normally with None.

Lean statement

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

import Tablet.Assumptions
import Tablet.DecimalGoalVocabularyDefault
import Tablet.ModelOptionBranch
import Tablet.ModelOptionFromResidual
import Tablet.NumberHelperPartialNumberSafeLength
import Tablet.SourceValidByteSlice
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_offset_from
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_read_u64
import Tablet.num_imp_dec2flt_common_is_8digits
import Tablet.num_imp_dec2flt_parse_MIN_19DIGIT_INT
import Tablet.num_imp_dec2flt_parse_adjust_many_digit_count
import Tablet.num_imp_dec2flt_parse_parse_8digits
import Tablet.num_imp_dec2flt_parse_parse_many_digits
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_partial_number
import Tablet.num_imp_dec2flt_parse_parse_scientific
import Tablet.num_imp_dec2flt_parse_try_parse_19digits
import Tablet.num_imp_dec2flt_parse_try_parse_digits

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: NumberHelperRejectionSafeLength]
theorem NumberHelperRejectionSafeLength :
    forall s : Slice Std.U8,
      SourceValidByteSlice s -> s.val != [] ->
      s.val.length <= 9223372036854120459 ->
      (Not (exists x : DecimalLexeme,
        x.leadingSign = none /\
        DecimalGoalVocabularyDefault.validNumeric x /\
        DecimalGoalVocabularyDefault.bytes s =
          DecimalGoalVocabularyDefault.renderNumeric x)) ->
      num.imp.dec2flt.parse.parse_number s = ok none := 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

Let M=2^{63}-1=9223372036854775807, let B=9223372036854120459=M-655348, and write L for the input length. By Assumptions, usize and isize are both 64-bit. Thus L\leq B<M, every slice length and index used below fits usize, and every length-to-isize cast fits the nonnegative signed range. The premise involving DecimalGoalVocabularyDefault says exactly that the complete input is not a valid unsigned numeric rendering.
We first audit the operations common to every control-flow path. In each eight-byte iteration of num imp dec2flt parse try parse digits, the length guard justifies the eight-byte subslice and SliceU8 Insts Dec2flt modelNumImpDec2fltCommonByteSlice read u64, which returns those eight bytes as one little-endian word; the continuing branch later drops exactly the same eight bytes.
We require a no-false-positive property of the bit test in num imp dec2flt common is 8digits, including the carries and borrows between adjacent bytes. Write the little-endian bytes of its argument v as b_0,\ldots,b_7. The three constants used by the extracted definition are, respectively, eight copies of 0x46, eight copies of 0x30, and eight copies of 0x80. Let c_i be the carry into byte i of the wrapping addition by 0x4646464646464646, and let d_i be the borrow into byte i of the wrapping subtraction by 0x3030303030303030; initially c_0=d_0=0. If the test returns true, the high bit of every byte of both resulting words is zero, because their bitwise OR has zero intersection with 0x8080808080808080.
Induct through the subtraction bytes. Assuming d_i=0, if b_i<48, the result byte is b_i-48+256\in[208,255], whose high bit is one, a contradiction. Hence b_i\geq48, the subtraction produces no outgoing borrow, and its result byte is b_i-48. Its zero high bit further implies b_i-48<128, or b_i\leq175. Starting from d_0=0, this proves 48\leq b_i\leq175 and d_{i+1}=0 successively through all eight bytes. Now induct through the addition bytes. Assuming c_i=0, if b_i\geq58, the preceding upper bound gives b_i+70\in[128,245], again contradicting the zero high bit. Thus b_i\leq57; then b_i+70\leq127, so there is no outgoing carry. Starting from c_0=0, this proves c_i=0 and 48\leq b_i\leq57 for every byte. Consequently the test has no false positive despite cross-byte carries and borrows.
It remains to audit every checked operation in num imp dec2flt parse parse 8digits. On a word accepted by the bit test, its checked subtraction of 0x3030303030303030 has no borrow and produces a word v' whose bytes are all in 0,\ldots,9. Hence v'<\texttt{0x1000000000000000}=2^{60}. The checked multiplication by ten is below 10\cdot2^{60}<2^{64}. The checked shift by eight is defined because 8<64 and gives a value below 2^{52}, so the checked addition is below 10\cdot2^{60}+2^{52}<2^{64}. The subsequent checked shifts by 16 and 32 are also defined because both counts are below 64; the intervening masks, multiplications, and addition are explicitly wrapping. If their final wrapped word is w<2^{64}, then w\mathbin{\mathtt{>>}}32\leq2^{32}-1. The checked cast to u32 therefore succeeds, and its widening back to u64 is exact.
The outer accumulator multiplication and addition are explicitly wrapping. The scalar loop indexes only below the remaining length, casts only a byte to u64, uses wrapping arithmetic for the mantissa, and increments its count to at most that length. Slicing at the final count is consequently in bounds. This proves normal execution of both possible digit scans on arbitrary bytes, not only on numeric input.
Every call to SliceU8 Insts Dec2flt modelNumImpDec2fltCommonByteSlice offset from in the initial parse compares an original slice with one of its suffixes. Both length casts are at most L<M, and their checked difference is in [0,L]. Therefore the integer-digit count, the fractional count, and every ordinary consumed-length offset are exact. If a point is observed, its removal is guarded, the fractional offset F satisfies 0\leq F\leq L, its checked negation lies in the signed range, and the cast of -F to i64 is exact. The checked sum of the two digit counts is the total number D of scanned significand digits and satisfies 0\leq D\leq L. The input is nonempty, so the opening assertion in num imp dec2flt parse parse partial number succeeds. If D=0, that function returns None normally and there is nothing further to check.
Suppose D>0. If the next byte is not e or E, no explicit exponent arithmetic occurs. If it is a marker, unfold num imp dec2flt parse parse scientific. Its optional sign split is guarded. An empty suffix or a nondigit first byte returns None; the option branch and residual operations in ModelOptionBranch and ModelOptionFromResidual then make the partial parser return None normally. Otherwise let q\geq1 be the number of exponent digits consumed. At loop count j\leq q, the index is guarded by the suffix length and the count increment remains at most L. While the accumulator a is below 65536, the checked update obeys 10a+d\leq10\cdot65535+9=655359<2^{63}; afterwards the accumulator is left unchanged. The final optional negation is therefore safe. The result is a value E with |E|\leq655359 and the suffix beginning at the first non-exponent-digit byte.
The only potentially extremal checked operation in this first parse is -F+E. Its upper side is at most 655359. If E\geq0, its lower side is at least -F\geq-B>-2^{63}. If E<0 and F=0, it is at least -655359. It remains to treat E<0 and F>0. If the scientific residual suffix were empty, the already scanned bytes would be exactly: optional integer digits, a point and F fraction digits, an exponent marker, a minus sign, and the q exponent digits. Since D>0, these bytes define a valid complete unsigned lexeme under DecimalGoalVocabularyDefault, contradicting the invalidity premise. Hence at least one byte remains. Counting the point, marker, minus sign, q digits, and that unmatched byte gives F\leq L-(q+4). The decimal loop gives |E|\leq10^q-1 for q\leq5, and |E|\leq655359 for q\geq6. Consequently
F+|E|\leq \begin{cases} L-(q+4)+(10^q-1)\leq L+99990,&q\leq5,\\ L-(q+4)+655359\leq L+655349,&q\geq6. \end{cases}
The second line is extremal at q=6, and L+655349\leq B+655349=M+1=2^{63}. Thus the sum is never below -2^{63}; equality is allowed. This is the required one-byte invalidity margin. All first-pass exponent additions and the following consumed-offset casts are therefore normal at the present bound.
We next audit the many-digit path, including failures that occur after the first exponent calculation. On this path D>19, so the checked subtraction starts the adjustment at D-19\geq1. In num imp dec2flt parse adjust many digit count, every access is guarded by the scan index being below L. The checked constant subtraction 48-1 gives 47; saturating subtraction of 47 from a point byte gives zero, while from a zero digit it gives one, and either result casts exactly to isize. Those are the only two branches that advance the index.
After i index-advancing iterations, let z_i be the number of zero bytes among the i visited bytes and let n_i be the adjusted count. Induction on i using the preceding two branch computations gives
n_i=D-19-z_i,\qquad 0\leq z_i\leq i\leq L.
Indeed a point advances i without changing either z_i or n_i, and a zero advances i and z_i by one while the checked subtraction decreases n_i by one. Since D\geq20, every resulting value satisfies n_i\geq D-19-i\geq1-L. Here 1-L\geq1-B=-9223372036854120458>-2^{63}, while n_i\leq D-19\leq L<2^{63}. Thus each checked signed subtraction is in range, and each guarded index increment is at most L and is in the usize range.
Let z be the final zero count. If the final adjusted value is positive, then D-19-z>0, so z<D-19<D. The scan cannot have advanced past all D digits of the significand found by the initial scans: to advance over every one of those digit bytes, each would have to be zero, which would give z\geq D. It therefore stops on a nonzero digit within that original significand. In particular D-z\geq20, so at least twenty significand digits remain from that first nonzero onward. If the adjusted result is nonpositive, no retry is called.
By num imp dec2flt parse MIN 19DIGIT INT, the retry guard constant is exactly 1000000000000000000=10^{18}. In a retry, num imp dec2flt parse try parse 19digits performs a checked update only while its accumulator is below this exact constant. Each such update is at most 10(10^{18}-1)+9=10^{19}-1<2^{64}; its byte-to-u64 cast is exact, and every split is guarded. If the first retry scan reaches the 10^{18} threshold, its returned suffix precedes the saved end of the integer digits; their offset_from is a nonnegative count at most L, so both casts are safe.
Suppose instead that the first retry returns below 10^{18}. It did not stop at the threshold guard, so it stopped at the first nondigit or at the end. It cannot have consumed all original significand digits without encountering a point. From the first nonzero digit just established there are at least twenty digits; after the exact recurrence a\mapsto10a+d consumes the first nineteen of them, its value is a nineteen-digit integer and hence is at least 10^{18}, the exact cited guard constant. The next guard would therefore stop before the twentieth digit. The low first retry must consequently have stopped at the point saved by the initial scan. Its returned slice is nonempty with that point first, so the one-byte slice in num imp dec2flt parse parse many digits is in bounds and skips exactly the point. The second retry uses the same exact 10^{18} guard and the same checked-update bound. It consumes at most the F fractional digits, so its offset R is in [0,F]; checked negation and the isize-to-i64 cast produce a retry base in [-F,0].
The last operation of parse_many_digits adds the explicit exponent to that base. In the nonnegative integer-offset branch, no explicit exponent gives a base at most L. A negative exponent lowers it by at most 655359. For a positive explicit exponent with q digits, at least nineteen digits, the marker, and those q digits lie outside the nonnegative remaining-digit offset. Thus that offset plus E is at most L-q-20+(10^q-1) for q\leq5, whose maximum is L+99974, and at most L-q-20+655359 for q\geq6, whose maximum is L+655333. At L\leq B both are below M. In the fractional branch the base is -R with R\leq F. Its positive side is at most 655359, and its negative side is bounded by the already proved F+|E|\leq2^{63}. Hence every final retry addition is safe. This exhausts the guarded slices, casts, count arithmetic, negations, mantissa arithmetic, and signed additions in the functions num imp dec2flt parse try parse digits, num imp dec2flt parse parse scientific, num imp dec2flt parse adjust many digit count, num imp dec2flt parse try parse 19digits, num imp dec2flt parse parse many digits, and num imp dec2flt parse parse partial number.
We have shown that the partial parser returns normally. If it returns None, num imp dec2flt parse parse number immediately returns ok none. Otherwise it returns a decimal record together with a consumed length r\leq L. If r=L, the scanned significand has at least one digit; any point is in its unique scanned position; and any exponent has a marker, optional sign, and at least one scanned digit. These components form a valid lexeme with leadingSign = none, and the whole-input equality says its rendering is exactly the input. That contradicts the invalidity premise. Therefore r\ne L, and the final length comparison in parse_number returns ok none, as claimed.

Lean proof


  intro s hvalid hnonempty hlen hinvalid
  obtain ⟨o, hparse, hpartial⟩ :=
    NumberHelperPartialNumberSafeLength s hvalid hnonempty hlen hinvalid
  cases o with
  | none =>
      simpa [num.imp.dec2flt.parse.parse_number, hparse]
  | some p =>
      rcases p with ⟨d, r⟩
      simp [num.imp.dec2flt.parse.parse_number, hparse]
      intro heq
      apply hpartial d r rfl
      apply UScalar.eq_of_val_eq
      simpa [Slice.len, Slice.length] using heq

end dec2flt_model

Download Lean source · Download TeX source

Complete Lean module
import Tablet.Assumptions
import Tablet.DecimalGoalVocabularyDefault
import Tablet.ModelOptionBranch
import Tablet.ModelOptionFromResidual
import Tablet.NumberHelperPartialNumberSafeLength
import Tablet.SourceValidByteSlice
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_offset_from
import Tablet.SliceU8_Insts_Dec2flt_modelNumImpDec2fltCommonByteSlice_read_u64
import Tablet.num_imp_dec2flt_common_is_8digits
import Tablet.num_imp_dec2flt_parse_MIN_19DIGIT_INT
import Tablet.num_imp_dec2flt_parse_adjust_many_digit_count
import Tablet.num_imp_dec2flt_parse_parse_8digits
import Tablet.num_imp_dec2flt_parse_parse_many_digits
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_partial_number
import Tablet.num_imp_dec2flt_parse_parse_scientific
import Tablet.num_imp_dec2flt_parse_try_parse_19digits
import Tablet.num_imp_dec2flt_parse_try_parse_digits

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: NumberHelperRejectionSafeLength]
theorem NumberHelperRejectionSafeLength :
    forall s : Slice Std.U8,
      SourceValidByteSlice s -> s.val != [] ->
      s.val.length <= 9223372036854120459 ->
      (Not (exists x : DecimalLexeme,
        x.leadingSign = none /\
        DecimalGoalVocabularyDefault.validNumeric x /\
        DecimalGoalVocabularyDefault.bytes s =
          DecimalGoalVocabularyDefault.renderNumeric x)) ->
      num.imp.dec2flt.parse.parse_number s = ok none := by
-- BODY
  intro s hvalid hnonempty hlen hinvalid
  obtain ⟨o, hparse, hpartial⟩ :=
    NumberHelperPartialNumberSafeLength s hvalid hnonempty hlen hinvalid
  cases o with
  | none =>
      simpa [num.imp.dec2flt.parse.parse_number, hparse]
  | some p =>
      rcases p with ⟨d, r⟩
      simp [num.imp.dec2flt.parse.parse_number, hparse]
      intro heq
      apply hpartial d r rfl
      apply UScalar.eq_of_val_eq
      simpa [Slice.len, Slice.length] using heq

end dec2flt_model

Proof structure

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

Explore this dependency tree

Inspect related source (69)
More program dependencies (36)
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 64 entries
Technical checking records
Local closure summary
{
  "node": "NumberHelperRejectionSafeLength",
  "closure_version": "patch_c_v1",
  "active_decl_hash": "d20e1b21aa0cd711102d88ebf8bcccb70409ea5a0e12f051666db60df8f03e37",
  "active_statement_hash": "07dcb9e954bf1853468b6068aa899bb4124ea33499f8e169aa72f0c9d899f50f",
  "kernel_axioms": [
    "Quot.sound",
    "propext"
  ],
  "toolchain_hash": "ce4c4e3d87434b9663f46de25ce34b48a0cf0d392e0a320a0787b4674a2d7b61",
  "lean_executable_hash": "3e0d0d3d801675359f2d4cf9815bfdb417b20b92fdd9d48b3b14c95bbae28bbf",
  "checker_script_hash": "c8e4a03273e23b9a8f2e141020652a4e0b7b0a8ab0883366ea9d031ca3f37aa1",
  "approved_axioms_hash": "ab64d13f256386ee0e494a5abcc6a5db49512cf3d90bbdfcabd6327793a31f95",
  "axcheck_status": "Agreed",
  "accepted_at_snapshot_id": "worker-result-local-closure-issuance-cycle-116",
  "boundary_theorems": {},
  "strict_theorem_deps": {
    "NumberHelperPartialNumberSafeLength": "e44fde0977cbf188"
  },
  "strict_definition_deps": {
    "DecimalGoalVocabulary": "4da7f295a9b85b50",
    "DecimalGoalVocabularyDefault": "512f8d0aea894250",
    "DecimalLexeme": "c43614ff2149ecf2",
    "SourceValidByteSlice": "3dc42716a6378d26",
    "num_imp_dec2flt_decimal_Decimal": "c43614ff2149ecf2",
    "num_imp_dec2flt_parse_parse_number": "b8693ec58f01c43c",
    "num_imp_dec2flt_parse_parse_partial_number": "94ed7b2ff71604ef"
  }
}
Prose assessment
{
  "label": "Recorded Sound: VerifierPass",
  "assessment_status": "VerifierPass",
  "fingerprint_relation": "matches current fingerprint",
  "assessment_fingerprint": "sound-v2:3c14aa0a86f2b89a3a1a37d73ca47bbecb55f9e77eff7b0f4428ea7db2a3691f",
  "current_fingerprint": "sound-v2:3c14aa0a86f2b89a3a1a37d73ca47bbecb55f9e77eff7b0f4428ea7db2a3691f",
  "superseded_for_theorem_closure": false
}
Review verdicts
{
  "corr_status": "Pass",
  "sound_status": "Pass",
  "substantiveness_status": "Pass"
}