DecimalSeqFractionalFinish

Lean checked

Definition and explanation

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

Definition · Decimal-sequence fractional finalization

For arbitrary modeled slices s and rest and an arbitrary modeled decimal-sequence record d, DecimalSeqFractionalFinish is the following checked monadic computation. It subtracts |\texttt{rest}| from |s| and passes the resulting consumed count to the extracted trailing-zero counter on s. It casts the returned trailing count to I32 and adds it to d.\texttt{decimal\_point}; subtracts trailing from d.\texttt{num\_digits} to obtain kept; casts kept to I32 and adds it to the intermediate point; and then selects
(\texttt{nDigits},\texttt{flag})= \begin{cases}(768,\mathsf{true}),&\texttt{kept}>768,\\ (\texttt{kept},d.\texttt{truncated}),&\texttt{kept}\le768. \end{cases}
It applies DecimalSeqExponentEval to rest and the resulting point. Finally it runs the extracted parser loop~1 on d.\texttt{digits} over the half-open array-index interval [\texttt{nDigits},19), setting exactly those cells to zero and leaving every other cell unchanged, and returns the record made from nDigits, the exponent-adjusted point, flag, and that array. Each failed or divergent checked operation is propagated by its monadic bind.

Lean definition

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

import Tablet.DecimalSeqExponentEval
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq

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

-- [TABLET NODE: DecimalSeqFractionalFinish]
def DecimalSeqFractionalFinish (s rest : Slice Std.U8)
    (d : num.imp.dec2flt.decimal_seq.DecimalSeq) :
    Result num.imp.dec2flt.decimal_seq.DecimalSeq :=
-- BODY
  do
    let consumed <- Slice.len s - Slice.len rest
    let trailing <-
      num.imp.dec2flt.decimal_seq.count_trailing_zeros s consumed
    let p1 <- d.decimal_point + UScalar.hcast .I32 trailing
    let kept <- d.num_digits - trailing
    let point <- p1 + UScalar.hcast .I32 kept
    let (nDigits, flag) <-
      if kept > num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS
      then ok (num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS, true)
      else ok (kept, d.truncated)
    let finalPoint <- DecimalSeqExponentEval rest point
    let a <- num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop1
      { start := nDigits,
        «end» :=
          num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS_WITHOUT_OVERFLOW }
      d.digits
    ok (num.imp.dec2flt.decimal_seq.DecimalSeq.mk nDigits finalPoint flag a)

end dec2flt_model
Preservation and explanation

Natural-language argument

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.

Preservation argument

Claim

Consider an actual execution of crate/dec2flt/decimal_seq.rs:320--363 after the integral and optional fractional scans. Let s_0 be the exact original source slice stored as start, let r be the exact current residual suffix stored as s, and let d be the exact post-scan DecimalSeq. On the branch d.\texttt{num_digits}\ne0, the remainder of that source execution is exactly DecimalSeqFractionalFinish(s_0,r,d): it has the same final record on normal return and fails at the same modeled checked operation on an abnormal return. No claim is made that the source invokes this finalization from an arbitrary state with zero digit count.

Proof

Fix an execution and s_0,r,d satisfying the claim. The branch hypothesis is the source guard at line 320, so the assignments at lines 322--333 execute; it is not an invented premise on the public parser. Compare those assignments and the subsequent exponent and fill code with the corresponding branches of the pinned parse_decimal_seq declaration num imp dec2flt decimal seq parse decimal seq.
First, the source sets consumed_len to |s_0|-|r|. The definition binds the same Usize subtraction Slice.len s_0- Slice.len r. Since r is the exact residual suffix of this execution, |r|\le |s_0| on every source-reachable state. At the model level the two fragments still use the same checked subtraction, so an underflow, if presented outside that source invariant, would be the same first propagated failure rather than a different result.
Next both call the pinned reverse scanner num imp dec2flt decimal seq count trailing zeros on s_0 and that same consumed length. The adaptation record reference/model-evidence/source-adaptation-delta.txt establishes that this indexed helper visits positions consumed_len-1, …, 0 in the same order as the original iter().rev() loop, increments exactly on ASCII zero, passes over a decimal point, and stops at the first byte that is neither zero nor point. Thus its Usize result is exactly the source value n_trailing_zeros; a helper failure is bound and returned before any record update on both model fragments.
Let z be that Usize result, and write \operatorname{cast32}(u) for the signed I32 representative of the low 32 bits of a Usize value u. Rust's narrowing u as i32 and Aeneas's pure UScalar.hcast .I32 u both compute exactly \operatorname{cast32}(u); this operation truncates and cannot fail (the lift surrounding it in the pinned parser merely places that pure value in the Result computation). Thus both fragments first perform the same checked I32 addition d.\texttt{decimal_point}+\operatorname{cast32}(z), which either fails on both sides or produces the same intermediate point. They next perform the same checked Usize subtraction d.\texttt{num_digits}-z; if it succeeds, call its Usize result k. Both then compute the identical pure value \operatorname{cast32}(k) and perform the same checked I32 addition to the intermediate point. Consequently, whenever both additions and the subtraction succeed, the uncapped point on each side is the I32 value d.\texttt{decimal_point}+\operatorname{cast32}(z) +\operatorname{cast32}(k); subtraction and addition failures coincide, and neither narrowing cast contributes a failure.
The next test is the same strict comparison k>\texttt{DecimalSeq::MAX_DIGITS}, whose pinned value is 768 by num imp dec2flt decimal seq DecimalSeq MAX DIGITS. In the true branch both retain 768 digits and set truncated to true. In the false branch both retain k and preserve d.\texttt{truncated}. This establishes the same pair (n,f) of stored digit count and flag, including the equality case k=768.
It remains to justify the residual observation made before the optional exponent computation. The cited pinned parser has four source-reachable copies of this nonzero finalization. When the residual s_2 is empty, the outer Slice.is_empty result is saved across finalization. After a decimal point, the two copies (according as the pre-fractional digit count is zero or nonzero) use the post-scan residual s_6 or s_5 and test it after finalization. In the remaining nonempty, non-decimal-point copy, the parser saves both the false emptiness result and the byte s_2[0] across finalization. In every copy, the intervening consumed-length computation, trailing-zero scan, casts, arithmetic, cap test, and flag update only read the residual slice; none changes that slice. Thus the argument r passed to the factoring is respectively that same s_2, s_6, s_5, or s_2.
By the Aeneas slice semantics, Slice.is_empty is total and returns the deterministic test of whether the slice length is zero. Recomputing it on the unchanged r therefore returns the parser's saved Boolean in the first and fourth copies, and is the identical test already made by the parser in the two post-decimal copies. In the empty case both computations take the empty branch and neither indexes r. In every nonempty case, index zero is in bounds; Slice.index_usize therefore succeeds deterministically and returns the same byte, including the byte saved by the outer parser in the fourth copy. Hence the factoring's extra emptiness and index observations cannot fail or diverge, and both sides select the same nonmarker, lowercase-e, or uppercase-E branch.
Only after that observation equality is established, apply the optional exponent computation DecimalSeqExponentEval to the identical residual r and the identical cast-correct I32 base d.\texttt{decimal_point}+\operatorname{cast32}(z) +\operatorname{cast32}(k). Its empty/marker, optional-sign, decimal-exponent-parser, checked-multiplication, and checked-addition analysis then gives the same final point p or the same first arithmetic or parser failure. Separately, the source/adaptation evidence cited above identifies the guarded nonempty/index tests with the original source's split-first tests; it is used for that source-preservation comparison, not for the saved-versus-recomputed observation equality just proved.
Finally the source loop at lines 361--363 ranges from n to MAX_DIGITS_WITHOUT_OVERFLOW and writes zero to each selected digit cell. Aeneas duplicated this one source loop across control-flow branches as parse_decimal_seq_loop1, loop4, loop6, and loop7 in the pinned node; their range iterator, array update, state, and exit bodies are identical. The factoring calls loop1 with the same range and original d.\texttt{digits}, and hence produces exactly the same filled array a, or propagates the same range/array failure at the same iteration. When all binds succeed, both computations construct DecimalSeq.mk with fields num_digits=n, decimal_point=p, truncated=f, and digits=a. Monadic short-circuiting also shows that any earlier failure prevents this construction on both sides. This proves equality of normal and failure behavior precisely on the source's nonzero-digit post-scan branch, while making no assertion about source use at zero count.

Requirement: parser totality

On every actual nonzero post-scan branch this definition is the pinned parser's own checked finalization, including its first failure; the zero-count branch is left untouched. Factoring therefore adds no public-input premise and changes no termination or panic observation.

Requirement: parser numeric acceptance

Every numeric execution reaching this nonzero branch retains the exact residual, point, digit count, truncation flag, exponent update, and zero-filled array of parse_decimal_seq. The definition adds no grammar condition and assumes no acceptance result.

Requirement: parser invalid rejection

The same residual byte controls the optional-exponent branch, and nonmarker and failure cases are preserved without extra consumption. Thus finalization cannot change a later invalidity decision or impose a new premise.

Requirement: parser nan acceptance

NaN literals are accepted by the special helper and do not enter the numeric decimal-sequence finalization. Restricting this claim to the actual nonzero numeric branch leaves NaN recognition and construction unchanged.

Requirement: parser infinity

Infinity literals also bypass parse_decimal_seq. This factoring changes neither their keyword path nor their lexical sign.

Requirement: parser non nan results

For numeric slow executions, the factored record and every failure coincide with the pinned parser; for special executions it is unused. It therefore neither creates a NaN nor assumes the no-spurious-NaN conclusion.

Requirement: parser numeric sign

The public lexical sign is stored and assembled outside this unsigned decimal-sequence record. Preserving the exact post-scan record leaves the eventual sign application unchanged.

Requirement: parser signed zero

Trailing-zero removal changes only the canonical record exactly as in the pinned parser, while the public sign remains outside it. The zero magnitude and later signed assembly paths are therefore unchanged and unrestricted.

Requirement: parser exact rounding

The slow converter receives the same capped digits, decimal point, sticky/truncation flag, and zero-filled tail as before. This source-branch factoring adds no hypothesis about exact value or rounding and preserves the parser observation used by the goal.

Requirement: parser selected exponent

All downstream raw-pair computations see the identical DecimalSeq or the identical prior failure. No biased-exponent range fact is inserted as a premise.

Requirement: parser selected magnitude sign

The definition neither applies the public sign nor assembles a raw pair; it preserves the magnitude record supplied to the slow converter. Hence selected magnitude words are unchanged.

Requirement: dispatch abstract composition

This definition extensionally factors the actual nonzero finalization inside the slow numeric component while preserving the source's zero-count alternative. It adds no component precondition and does not assume the disputed abstract-composition conclusion.

Requirement: dispatch component compliance

At a real slow-component call, s_0, r, and d are exactly the parser-produced source slice, residual, and state required by the claim; that is a control-flow fact, not a strengthened caller contract. The component's normal and failure behavior remains exact.

Requirement: parser accumulated rounding

Trailing-zero normalization, retained digits, sticky flag, and signed explicit-exponent update determine the same accumulated decimal record as the pinned parser. Factoring adds no premise and does not assume the record is ultimately rounded correctly.

Requirement: parser equal target rounding

Both the parser result and the decimal-sequence input to slow rounding are unchanged on the branch, while exact/accumulated target equality remains the GOAL's own condition. No new equality condition is introduced.

Requirement: number helper acceptance

parse_number returns a Decimal before the optional slow decimal-sequence conversion and never calls this finalizer. Its nonempty-slice domain and Some cases are unaffected.

Requirement: number helper rejection

The number helper's None decision precedes and is independent of parse_decimal_seq. A definition over DecimalSeq states no new condition on that decision.

Requirement: number helper record bounds

The helper-bound fields belong to Decimal, whereas this definition consumes and constructs DecimalSeq. It cannot change the returned mantissa, negative flag, or 10^{19} bound.

Requirement: number helper accumulated value

The mantissa/exponent interval in this goal describes the earlier parse_number record. Post-scan trailing-zero and array finalization occurs only later on the slow path and leaves that record untouched.

Requirement: special helper infinity

parse_inf_nan neither produces nor consumes a DecimalSeq. Its keyword bytes, separate sign argument, and infinity result are noninterfering.

Requirement: special helper nan

The special NaN helper is disjoint from this numeric slow-path finalization. No NaN payload, classification, or sign argument is changed.

Requirement: special helper rejection

Inputs rejected by the special helper are decided by its keyword comparisons, not by decimal-sequence state. Its None cases remain identical.

Requirement: native correct or defer

try_fast_path operates directly on the Decimal record and runs before slow decimal-sequence parsing. This finalizer changes neither a native-path Some value nor a deferral.

Requirement: integer correct or defer

compute_float accepts scalar exponent and mantissa arguments and does not observe any DecimalSeq array. Its returned or deferred BiasedFp is unaffected.

Requirement: slow accumulated rounding

This is the relevant consumer: parse_long_mantissa calls parse_decimal_seq and receives precisely the final record factored here on the actual nonzero branch, with the zero branch preserved separately. No premise is added to unsigned numeric inputs, and no rounding result is assumed.

Requirement: assembly correspondence

biased_fp_to_float consumes only a completed raw pair, not a source slice, residual, or decimal digit array. This finalizer cannot alter the assembly formula quantified over all field values.

Requirement: classification totality

The mathematical classification relation ranges over finite byte strings and is defined before any decimal-sequence execution. Its coverage by numeric, special, or invalid is unchanged.

Requirement: classification determinism

No grammar rule or parsed lexical content is changed by factoring a later source branch. Classification uniqueness and uniqueness of numeric content are therefore noninterfering.

Requirement: classification significand digit

The existence of a significand digit is a property of numeric syntax; the finalizer is entered only after scanning such bytes and does not redefine the grammar. The goal is unchanged.

Requirement: rounding totality

Abstract rounding totality quantifies over nonnegative real numbers, with no parser state or byte slice. The source-branch factoring has no effect on its candidates or domain.

Requirement: rounding determinism

Abstract target uniqueness is likewise independent of the construction of a DecimalSeq. Its real input and binary64 comparison relation remain unchanged.

Requirement: exponent value agreement

The mathematical exact and accumulated exponent values are defined from lexical content, not from this finalizer's implementation. The definition preserves the implementation but neither changes those values nor assumes their stated equality, so the agreement goal is noninterfering.

Download Lean source · Download TeX source

Proof structure

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

Explore this dependency tree

Inspect related source (77)
More program dependencies (44)
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 14 entries
Technical checking records
Local closure summary
{
  "node": "DecimalSeqFractionalFinish",
  "closure_version": "patch_c_v1",
  "active_decl_hash": "8f5b2adac8306a1da3c84006295dd69c558681e78129bcd2abc74195d8e5d96b",
  "active_statement_hash": "c963c56b92bb36ace1752c59ce61ef8fe36f9c1a533bb3ebd435fe2843e8feac",
  "kernel_axioms": [
    "Classical.choice",
    "Quot.sound",
    "propext"
  ],
  "toolchain_hash": "ce4c4e3d87434b9663f46de25ce34b48a0cf0d392e0a320a0787b4674a2d7b61",
  "lean_executable_hash": "3e0d0d3d801675359f2d4cf9815bfdb417b20b92fdd9d48b3b14c95bbae28bbf",
  "checker_script_hash": "c8e4a03273e23b9a8f2e141020652a4e0b7b0a8ab0883366ea9d031ca3f37aa1",
  "approved_axioms_hash": "ab64d13f256386ee0e494a5abcc6a5db49512cf3d90bbdfcabd6327793a31f95",
  "axcheck_status": "Agreed",
  "accepted_at_snapshot_id": "worker-result-local-closure-issuance-cycle-170",
  "boundary_theorems": {},
  "strict_theorem_deps": {},
  "strict_definition_deps": {
    "DecimalSeqExponentEval": "b51b6389c17b6c1f",
    "num_imp_dec2flt_decimal_seq_DecimalSeq": "59bf1ff9fe88fa8d",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS": "39f6cb231ef80388",
    "num_imp_dec2flt_decimal_seq_DecimalSeq_MAX_DIGITS_WITHOUT_OVERFLOW": "65634ac95536dcca",
    "num_imp_dec2flt_decimal_seq_count_trailing_zeros": "7a77bc9e01c1a09b",
    "num_imp_dec2flt_decimal_seq_parse_decimal_seq": "9f2c4f5675cad683"
  }
}
Prose assessment
{
  "label": "Recorded Sound: VerifierPass",
  "assessment_status": "VerifierPass",
  "fingerprint_relation": "matches current fingerprint",
  "assessment_fingerprint": "preservation-v1:883578e52dffe87c7be56336f6809c86e9b47be5df03e0a53d1805c01d74a482",
  "current_fingerprint": "preservation-v1:883578e52dffe87c7be56336f6809c86e9b47be5df03e0a53d1805c01d74a482",
  "superseded_for_theorem_closure": false
}
Review verdicts
{
  "corr_status": "Pass",
  "sound_status": "Pass",
  "substantiveness_status": "Pass"
}