Skip to content

Add pure expression inliner infrastructure for quantifier bodies - #4567

Merged
feliperodri merged 6 commits into
model-checking:mainfrom
feliperodri:inline-pure-expressions
Apr 19, 2026
Merged

feliperodri merged 6 commits into
model-checking:mainfrom
feliperodri:inline-pure-expressions

Conversation

@feliperodri

Copy link
Copy Markdown
Member

What

Adds Expr::substitute_symbol() and inline_as_pure_expr() — infrastructure for inlining function calls as side-effect-free expression trees. This is a prerequisite for generating CBMC quantifier bodies without StatementExpression nodes, which will enable nested quantifier support.

Why

CBMC rejects side effects inside quantifier expressions (forall/exists). Today, Kani's handle_quantifiers post-pass inlines function calls into StatementExpression nodes, which CBMC accepts via convert_statement_expression, but this breaks for nested quantifiers (inner quantifiers are treated as side effects, causing a CBMC invariant violation crash).

The pure expression inliner resolves this by producing expression trees that contain no statements, no gotos, and no labels; only pure expressions that CBMC can handle directly, including in nested contexts.

How

Expr::substitute_symbol() (cprover_bindings/src/goto_program/expr.rs)

  • Recursively replaces all occurrences of a symbol with a replacement expression across all 25+ ExprValue variants.

inline_as_pure_expr() (kani-compiler/src/codegen_cprover_gotoc/context/goto_ctx.rs)

  • For a function call: looks up the body in the symbol table, collects all assignments, resolves the return expression through the assignment chain, substitutes parameters with arguments, and flattens StatementExpression nodes (e.g., checked arithmetic).
  • Recursively inlines nested function calls.
  • Handles Forall/Exists sub-expressions for future nested quantifier support.

Soundness note

When flattening StatementExpression nodes from checked arithmetic (e.g., %, +), the inliner drops Assert/Assume statements that check for overflow and division by zero. This is a known trade-off documented in docs/dev/pure-expression-inliner.md: CBMC requires pure expressions in quantifier bodies, and runtime checks are inherently side effects. A future improvement could hoist these checks outside the quantifier as preconditions.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.

@github-actions github-actions Bot added Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-CompilerBenchCI Tag a PR to run benchmark CI labels Mar 30, 2026
@feliperodri
feliperodri marked this pull request as ready for review March 30, 2026 04:10
@feliperodri
feliperodri requested a review from a team as a code owner March 30, 2026 04:10
Add Expr::substitute_symbol() and inline_as_pure_expr() for inlining
function calls as side-effect-free expression trees. This infrastructure
is needed to generate CBMC quantifier bodies without StatementExpression
nodes, which will enable nested quantifier support.

Changes:
- cprover_bindings: Expr::substitute_symbol() — recursive symbol
  replacement across all ExprValue variants, with 6 unit tests
- goto_ctx.rs: inline_as_pure_expr() — inlines function calls by
  extracting return expressions, resolving intermediate variables,
  and substituting parameters. Handles StatementExpression flattening
  for checked arithmetic (drops Assert/Assume runtime checks).
- docs/dev/pure-expression-inliner.md — developer documentation
  including soundness implications

Soundness note: The pure inliner drops overflow and division-by-zero
checks when flattening StatementExpression nodes from checked arithmetic.
This is a known trade-off — CBMC requires pure expressions in quantifier
bodies, and runtime checks are side effects.

The existing handle_quantifiers post-pass is NOT modified — this is
purely additive infrastructure.

Signed-off-by: Felipe R. Monteiro <[email protected]>
- substitute_symbol returns (Expr, bool) for reliable change detection
  instead of Debug-format string comparison
- Graceful fallback for recursive functions (tracing::warn + return
  original) instead of assert! panic
- Diagnostics for edge cases: multiple assignments to same variable,
  non-symbol return expressions, unknown UnaryOperator variants
- Public API cleanup: inline_as_pure_expr_toplevel wrapper hides the
  visited set implementation detail
- Document StatementExpression non-recursion in substitute_symbol

Signed-off-by: Felipe R. Monteiro <[email protected]>
@feliperodri
feliperodri force-pushed the inline-pure-expressions branch from 0fcc5c3 to 8b2600a Compare March 30, 2026 04:33
Comment thread docs/dev/pure-expression-inliner.md Resolved
- Replace destructuring assignment with .0 for substitute_symbol calls
- Restore step-by-step 'How It Works' section in dev documentation

Signed-off-by: Felipe R. Monteiro <[email protected]>
@feliperodri feliperodri added [C] Internal Tracks some internal work. I.e.: Users should not be affected. Z-Contracts Issue related to code contracts labels Mar 30, 2026
@feliperodri feliperodri added this to the Contracts milestone Mar 30, 2026
@thanhnguyen-aws

Copy link
Copy Markdown
Contributor

Could you please add some document to explain why this transformation preserves the semantic of Rust (for the return values of functions), especially for the case the code contains aliasing, memory reference ...?

Explain why the substitution-based transformation preserves Rust
semantics for function return values, covering:
- Straight-line code (SSA-form algebraic substitution)
- Aliasing and memory references (symbol substitution preserves
  dereferences; CBMC evaluates them with full alias analysis)
- When the transformation is NOT safe (multi-assignment locals,
  side effects between assignments, mutable aliasing)
- Scope of applicability (quantifier closures are pure single-
  expression functions where substitution equals beta-reduction)

Signed-off-by: Felipe R. Monteiro <[email protected]>
@feliperodri

Copy link
Copy Markdown
Member Author

@thanhnguyen-aws I added a section in the docs/dev/pure-expression-inliner.md doc to document why this transformation preserves the semantic of Rust. Could you take another look?

Comment thread docs/dev/pure-expression-inliner.md Resolved
@feliperodri
feliperodri added this pull request to the merge queue Apr 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Apr 15, 2026
@feliperodri
feliperodri added this pull request to the merge queue Apr 19, 2026
Merged via the queue into model-checking:main with commit 27eaf3b Apr 19, 2026
34 checks passed
@feliperodri
feliperodri deleted the inline-pure-expressions branch April 19, 2026 01:19
wodex1nhaoIeng pushed a commit to wodex1nhaoIeng/kani that referenced this pull request Nov 10, 2026
… checks (model-checking#5136)

## Summary

Fix nested quantifier capture projection while conservatively rejecting
predicates whose checks or function calls could be lost during
extraction.

This improves nested capture handling without relaxing the existing
projection safety restrictions, and replaces several backend failures
with source-located diagnostics.

## Changes

- Add type-checked simplification for captured values and field
projections, restricted to expressions whose evaluation can safely be
elided.
- Improve recursive side-effect detection and scan GOTO statements and
expressions for unsupported checks and calls.
- Conservatively reject checked or call-containing nested predicates,
including default checks, to avoid unsound successful verification.
- Preserve quantifier source spans during recursive inlining and improve
diagnostics for safety checks, missing GOTO bodies, and indirect calls.
- Add explicit termination after fatal diagnostics and extract shared
error messages into constants.
- Document the limitations of `exists!(... *ptr.add(i) == x)` and nested
pointer dereferences.
- Add positive and negative regressions for public-macro captures,
pointer comparisons, nested checks, and unsupported cases.

## Regression evidence

On upstream `main` at `d0b7082524140b889650c4012ca168dd4c462e04`, the
nested-capture semantic tests and the final pointer-comparison capture
tests trigger a `goto-cc` invariant abort (`quantifier must not contain
side effects`). With the PR changes, the corresponding positive and
negative solver tests produce the expected results.

The original reproducer from model-checking#4902 also crashes on `main`. It now
produces an explicit unsupported diagnostic rather than a backend abort.
This does not add general support for nested arithmetic predicates.

An additional nested overflowing-addition case incorrectly verified with
the earlier PR implementation. The follow-up conservatively rejects it,
even without extra UB flags.

Pure existential predicates remain supported, including with both extra
UB options enabled.

## Testing

At tested commit `d2cb6388cb464bfa5a047c348cb2b29b6dfe198a`:

- **120 related test items passed, 0 failed**:
  - 48 compiler unit tests
  - 42 `cprover_bindings` unit tests
  - 14 Quantifiers tests
  - 14 quantifier-safety-checks UI tests
  - 2 quantifier-capture expected tests
- Release development build, formatting, and workspace/tests Clippy (`-D
warnings`) passed.
- Additional targeted probes checked nested overflow, deeper nesting,
user assertions, indirect calls, and generated GOTO/C expressions.

The PR branch was subsequently updated with `main`; the results above
refer to the explicitly tested commit, not an independent rerun of the
latest HEAD.

Full repository CI and the complete Challenge 21 proofs have not been
run locally.

## Limitations

- Nested predicates containing detected checks or function calls,
including pointer dereferences with default null-pointer checks, are
conservatively rejected.
- **Non-nested predicate extraction can still discard default checks and
Rust assertions.** This is tracked separately in model-checking#5141.
- General branching and existential-fallback issues in model-checking#5004 and model-checking#5010
remain unresolved.
- Existing Z3 quantifier backend limitations remain unresolved.

## Related work

Addresses model-checking#4902 by replacing its original backend crash with an explicit
unsupported diagnostic, without claiming support for arbitrary nested
arithmetic.

Related issues: model-checking#5004, model-checking#5010, model-checking#5141.

Builds on model-checking#4567, model-checking#4578, and model-checking#4583.

By submitting this pull request, I confirm that my contribution is made
under the terms of the Apache 2.0 and MIT licenses.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[C] Internal Tracks some internal work. I.e.: Users should not be affected. Z-CompilerBenchCI Tag a PR to run benchmark CI Z-Contracts Issue related to code contracts Z-EndToEndBenchCI Tag a PR to run benchmark CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants