Skip to content

feat(model): add Stmt.forEachWhile early-exit bounded loop (#2916) - #2958

Merged
fricoben merged 2 commits into
mainfrom
model/early-exit-loop
Nov 25, 2026
Merged

fricoben merged 2 commits into
mainfrom
model/early-exit-loop

Conversation

@fricoben

Copy link
Copy Markdown
Member

Refs #2916 (partial: adds the CompilationModel early-exit bounded loop construct Stmt.forEachWhile, proofs, and differential smoke tests; Solidity importer lowering of early-exit for loops is deferred to follow-up PR B).

What changes

1. Stmt.forEachWhile varName count guard body (046387bdf)

  • Model & semantics (Verity/Core/Model/Types.lean, Denote.lean, DenoteFunctionCalls.lean, Compiler/Proofs/IRGeneration/SourceSemantics.lean):
    • Evaluates count once, initializes varName := 0 before iteration check 0, and re-evaluates guard before every iteration check (including the terminal remaining = 0 check, matching Yul's non-short-circuiting condition order).
    • Structural recursion on remaining : Nat (bound from count), stopping immediately on the first check where guard evaluates to 0 with no silent out-of-fuel fallback.
  • Yul lowering (Compiler/CompilationModel/Compile.lean):
    • Lowers to for { let idx := 0 let cnt := <count> let <varName> := 0 } and(lt(idx, cnt), iszero(iszero(<guard>))) { idx := add(idx, 1) } { <varName> := idx <body> }, freshening synthetic counters against inScopeNames, varName, count, guard, and body (forEachWhileUsedNames / forEachWhileBodyScope).
  • Validation & effect analysis (ScopeValidation.lean, Validation.lean, ValidationCalls.lean, ValidationHelpers.lean, ValidationInterop.lean, UsageAnalysis.lean, TrustSurface.lean, Verity/Macro/EffectAnalysis.lean):
    • Validates count in the outer scope and guard/body in the loop scope (varName :: localScope), rejecting varName shadowing of parameters, outer locals, or enclosing loop variables while allowing sequential sibling reuse.
    • Rejects call-like expressions in guard and ADT expressions in count/guard.
    • Tracks count -> guard and cross-iteration body/guard -> guard ordering in CEI and read-after-external-call checkers, with soundness lemmas in EffectAnalysis.lean.
  • Proofs (Compiler/Proofs/IRGeneration/ForEachWhile.lean, DenoteAgreement.lean, SupportedSpec.lean, HelperBodyShape.lean, FunctionBody/Stmt.lean):
    • Conservativity over Stmt.forEach under constant nonzero guards (execStmt_forEachWhile_eq_forEach_of_guard_const, execStmt_forEachWhile_literal_one_eq_forEach).
    • Equivalence with flag-guarded Stmt.forEach loops up to the out-of-scope loop variable (execStmt_forEach_guarded_eq_forEachWhile, execStmt_forEach_flagGuarded_eq_forEachWhile).
    • IR loop-condition evaluation (evalIRExpr_forEachWhile_cond), early-exit step (execIRStmt_forEachWhile_exit), and Denote <-> SourceSemantics agreement (execForEachWhileLoop_rawFree, execForEachWhileLoop_agree).
    • Zero new axioms, sorry, or native_decide; zero weakened theorem statements.
  • Tests (Contracts/Smoke/ForEachWhileSmoke.lean, test/ForEachWhileSmoke.t.sol, SourceSemanticsFeatureTest.lean, CompilationModelFeatureTest.lean, CompileDriverTest.lean):
    • Differential Foundry tests against Solidity break loops covering first/middle/last match, no match, n = 0, empty body, 2^200 / uint256.max with early exit, 2^200 without exit (out-of-gas on both sides), plain forEach negative control, loop-variable reads in guard, even nonzero word (2) guard normalization, and fuzzing.

2. Reuse imported Environment across in-process module loads (ed0a0d1d3)

  • Compiler/ModuleInput.lean: Lean 4.31's interpreter closure cache retains each distinct Environment passed to evalConstCheck (~3 GB for the Contracts import cone), pushing multi-call suites such as CompileDriverTest past a 10 GB cgroup cap. loadSpecsFromModules now reuses the cached Environment when a subsequent in-process call requests a subset of its modules under the same SearchPath.

Verification (on 046387bdf)

  • lake build (7777/7777 jobs) -> PASS
  • lake build Verity Contracts + python3 scripts/check_lean_warning_regression.py (3 baseline warnings) -> PASS
  • python3 scripts/generate_print_axioms.py + lake build PrintAxioms + python3 scripts/check_axioms.py (8922 theorems, 0 project axioms) -> PASS
  • ./.lake/build/bin/verity-compiler --module Contracts.Smoke.ForEachWhileSmoke --output compiler/yul-smoke + FOUNDRY_PROFILE=difftest forge test --match-path test/ForEachWhileSmoke.t.sol -vv (13/13 passed) -> PASS
  • 3 Yul codegen mutants on ForEachWhileSmoke.yul (drop early exit, invert guard, drop iszero(iszero(guard)) normalization) -> all 3 killed
  • make check (1043 unit tests + hygiene, boundary, proof-length, and docsync checks) -> PASS

Each distinct Environment passed to evalConstCheck is retained by Lean's
interpreter closure cache (~3 GB for the Contracts import cone), pushing
multi-call driver suites such as CompileDriverTest past the 10 GB cgroup
memory cap. Reuse the cached Environment when a subsequent in-process call
requests a subset of its modules under the same search path.
Add Stmt.forEachWhile varName count guard body to the CompilationModel,
re-evaluating the guard before every iteration check and lowering the loop
condition to and(lt(idx, cnt), iszero(iszero(guard))) so an early exit runs
no remaining empty iterations.

Includes Denote and SourceSemantics execution, validation (scope rules, CEI,
ADT and call-like guard rejection), constructor-wide analysis/proof-surface
cases, conservativity and guarded-flag-loop equivalence theorems in
Compiler.Proofs.IRGeneration.ForEachWhile, DenoteAgreement proofs, feature
tests, and Foundry differential smoke tests against Solidity break loops.

Refs #2916
@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
veritylang.com Ready Ready Preview Nov 25, 2026 7:38pm UTC

Request Review

@fricoben
fricoben requested a review from Th0rgal as a code owner November 25, 2026 19:37
@fricoben

Copy link
Copy Markdown
Member Author

Looks good to merge on 046387b.

No blocking or non-blocking findings.

What I Ran

  1. Git HEAD, tree cleanliness, and commit/diff audit:

    • git rev-parse HEAD && git status --short && git log --oneline origin/main..HEAD && git diff --stat origin/main...046387bdff65d6f2862e0d315f34a97d7f925929 -> PASS (HEAD = 046387bdff65d6f2862e0d315f34a97d7f925929, clean worktree, 2 commits ed0a0d1d3 and 046387bdf, 36 files changed, 1621 insertions, 19 deletions; zero weakened/deleted theorem statements).
    • git diff origin/main...046387bdf | grep '^+' | grep -v '^+++' | rg -n '\b(sorry|axiom|native_decide|bv_decide|allowUnsafeReducibility)\b' -> PASS (zero matches).
  2. Foundry differential & gas-cap smoke suite (solc --strict-assembly + EVM execution):

    • FOUNDRY_PROFILE=difftest forge test --match-path test/ForEachWhileSmoke.t.sol -vv -> PASS (13/13 passed, 0 failed, including testEvenNonzeroWordGuard, testGuardReadsLoopVariable, testHugeCountWithEarlyExit, testHugeCountWithoutExitRunsOutOfGasOnBothSides, testForEachFlagLoopKeepsIterating, testFirstMatchFuzz (257 runs), and testCountWhileBelowFuzz (256 runs)).
  3. Targeted Lean elaboration, kernel #print axioms, and adversarial #guard / #eval! probes:

    • lake env lean --stdin (#print axioms on all 17 new theorems across Compiler/Proofs/IRGeneration/ForEachWhile.lean, Compiler/Proofs/IRGeneration/DenoteAgreement.lean, and Verity/Macro/EffectAnalysis.lean) -> PASS (only standard Lean axioms [propext, Classical.choice, Quot.sound] or [propext]; zero sorryAx, Lean.ofReduceBool, Lean.trustCompiler, or custom axioms).
    • lake env lean Compiler/Proofs/IRGeneration/ForEachWhile.lean && lake env lean Compiler/Proofs.IRGeneration/SourceSemanticsFeatureTest.lean && lake env lean Compiler/ModuleInputTest.lean -> PASS (all proofs, decide +kernel smoke examples, and ModuleInputTest checks passed).
    • Adversarial #guard and ModuleInput cache order/subset probes (reserved __ prefix and Yul keyword gas on forEachWhile varName, isPure rejecting storage-reading guard, modifies rejecting undeclared writes inside forEachWhile, hasExternalCallBeforeStorageRead flagging call+read guard with empty body, stmtInternalPreciseCEIViolation flagging guard write after prior call, and loadSpecsFromRawModules preserving caller order on reordered/subset cache hits) -> PASS.
  4. Repository hygiene, boundary, Yul, and doc-sync gates:

    • python3 scripts/check_axioms.py -> PASS (0 documented axiom locations ... 0 source axioms).
    • python3 scripts/check_lean_hygiene.py -> PASS (0 debug commands in proofs, 0 allowUnsafeReducibility, 0 sorry, 0 native_decide in proofs).
    • python3 scripts/check_proof_length.py -> PASS (10,089 proofs scanned; 0 new proofs over the 50-line hard limit).
    • python3 scripts/docsync.py --check, check_lake_default_coverage.py, check_compilationmodel_split.py, check_compiler_boundaries.py, check_layer_import_boundaries.py, check_package_import_boundaries.py, check_package_glob_surfaces.py, check_trust_surface_registry.py, check_foundry_yul_dirs.py, check_feature_ownership.py, check_dead_private_decls.py, check_yul.py -> PASS.

What I Read & Verified

  • Round 1 re-verification items:

    1. Post-interaction storage read/write checks (Verity/Macro/EffectAnalysis.lean:526-542, 1018-1081, 1138-1192): Both count -> guard on check 0 and body/guard -> guard across iterations (including empty body) are soundly flagged without false-positive flagging of body -> count (count is evaluated once in for init).
    2. Loop-variable shadowing & sequential reuse (Compiler/CompilationModel/ScopeValidation.lean:531-540, Compiler/CompilationModelFeatureTest.lean:7559-7655): count is validated in outer localScope; varName is rejected if present in paramScope or localScope (parameters, outer locals, and enclosing loop variables); guard and body are validated in varName :: localScope; returning pure localScope preserves sequential sibling reuse.
    3. Even nonzero word (2) guard normalization coverage (Contracts/Smoke/ForEachWhileSmoke.lean:80-87, Compiler/Proofs/IRGeneration/SourceSemanticsFeatureTest.lean:1022-1036, test/ForEachWhileSmoke.t.sol:63-76, 155-200): Directly exercises iszero(iszero(guard)) where raw bitwise and(1, 2) would evaluate to 0.
  • End-to-end semantic agreement (Denote, SourceSemantics, Yul Compile.lean, EVM):

    • Verified Compiler/CompilationModel/Compile.lean:183-196,430-450, Verity/Core/Model/Denote.lean:1864-1889,2217-2226, Verity/Core/Model/DenoteFunctionCalls.lean:497-508, and Compiler/Proofs/IRGeneration/SourceSemantics.lean:960-1017: count evaluated once, varName := 0 bound before check 0, guard re-evaluated before every check including terminal remaining = 0 check, varName := idx rebound on entry, early exit halting remaining iterations, structural recursion on remaining : Nat with no silent out-of-fuel fallback, and collision-free synthetic counter names via forEachWhileBodyScope.
  • Proofs, constructor-wide validation/analysis, and ModuleInput cache:

    • Verified Compiler/Proofs/IRGeneration/ForEachWhile.lean:43-289, Compiler/Proofs/IRGeneration/DenoteAgreement.lean:580-603,749-831, constructor coverage across Types.lean, UsageAnalysis.lean, Validation.lean, ValidationCalls.lean, ValidationHelpers.lean, ValidationInterop.lean, TrustSurface.lean, CompileDriverCommon.lean, SupportedSpec.lean, SurfaceMask.lean, HelperBodyShape.lean, FunctionBody/Stmt.lean, DenoteEquivalence.lean, MetaSpecs.lean, SpecHarness.lean, GeneratedTransition.lean, and SolidityImport barrier/binding helpers.
    • Verified importedEnvCache in Compiler/ModuleInput.lean:106-142: reuses the cached immutable Environment only when cachedPath == effectiveSearchPath and moduleNames.all (. ∈ cachedModules), evaluates constants in caller-supplied moduleNames order, leaves cache untouched on importModules failure, and restores searchPathRef in finally.

@fricoben
fricoben merged commit 8f308e9 into main Nov 25, 2026
27 of 28 checks passed

This branch was successfully deployed

1 active deployment
Preview — 046387bd Deployed Nov 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant