Repository navigation
Keep loop attributes on rewritten for loops and add loop-only locals to loop_modifies - #4947
Conversation
tautschnig
left a comment
There was a problem hiding this comment.
I built this PR merged onto current main (c846403), on its own and together with #4937, and compared it with #4938, which fixes the same problem (#4906) and conflicts with it in loop_contracts.rs. CBMC 6.11.0.
expectedsuite,loop-contractfilter: all pass (64 here, 67 with #4937's three tests; 6 fixme ignored).kani/Quantifiers/gcd_invariantpasses. Thekani_macrosunit test passes. fmt and both CI clippy invocations are clean. Theloop_modifiesexample in the documentation verifies.- Which locals get added: the
kani_index/__kani_prev_varlocals of this loop's id, the nth-pattern bindings, the locals whoseStorageLiveis in this loop's body and whichmove_storagelive_assign_to_loopheadmatches, and the temporaries assigned by the moved call blocks of a user variable declared in this loop's body. Each one only grants writes to the local's own storage. I checked that the following still fail as they should:- a write through a reference declared in the body;
- a write through a pointer created before the loop;
- a write through a
forbinding that points into the iterated array; a[k] = ..withanot listed;- a write to a variable declared before the loop that the loop writes before reading (
Check that y is assignable; #4938 accepts this one); - a read of a body local after its scope ended (
dereference failure: dead object; #4938 reports SUCCESS).
- #4938's tests against this PR:
loop_assigns_body_temp_and_carried_fail,loop_assigns_nested_body_tempsandloop_assigns_mixed_fat_thinpass.loop_assigns_write_only_outerfails, which I think is correct.loop_assigns_body_local_tempsandloop_assigns_multiple_body_temps(a binary search calling a closure onget_unchecked(mid)) still fail withCheck that mid is assignableandRust intrinsic assumption failed. The second check fails on main even without aloop_modifiesclause. The reason is thatmove_storagelive_call_to_loopheadcopies thecmp = f(..)call, which readsmid, to the loop head. That is pre-existing and should get its own issue. A body local set by checked arithmetic without such a call (let mid = base + half;) verifies here. - #4938's approach, with #4930 and this PR's macro change applied, verifies none of the 9
for_loop_modifies.rsharnesses I could run (it never addskani_index_*), andwith_prevfails there too. - With #4937 merged in as well, a
whileloop withprev, a body local and a complete clause verifies.
No prior review threads.
Overlaps: this PR contains #4930's three commits (head 36ea4cf), so #4930 should merge first, and this PR then reduces to c5bd2fd. It merges cleanly with #4937. #4938 must drop its transform (see my review there). Once this PR is in, #4938's loop_assigns_body_temp_and_carried_fail would be a useful extra test.
Inline comment:
- loop_modifies_loop_locals.rs:79: add a failing test for what must not be added.
Assessment: this is the one I would merge. The added set is limited to locals that exist only for the loop, and the MIR is left as it is.
One more case from reviewing #4930 (reproduced on main + this PR): a second #[kani::loop_invariant] on a for loop now fails to compile with "Kani could not find the loop head of this for loop with a loop contract". On main the second invariant is silently dropped, so a compile error is safer, but the message does not say what is wrong. Please either support it, as while loops do, or reject it with a message that names the second invariant:
#[kani::proof]
fn for_second_invariant() {
let a = [1u8, 2, 3];
let c: u8 = 0;
#[kani::loop_invariant(true)]
#[kani::loop_invariant(c == 1)]
for _x in a {}
}|
Thanks for the thorough review, and for comparing it with #4938. About a second
Since the documentation says that a loop contract is composed of "one or more loop invariants", I made I opened #4949 for the |
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Explicit empty or ZST-only modifies clauses are still mistaken for absent clauses, allowing CBMC to infer a broader write set.
Review effort: Balanced
Findings: 1
What changed in this PR
Preserves for-loop contract attributes and automatically includes loop-generated locals in explicit modifies clauses.
Changes:
- Preserves loop labels, attributes, and multiple invariants during macro rewriting.
- Tracks generated loop locals through MIR transformation into code generation.
- Adds documentation and comprehensive loop-contract regression tests.
| File | Description |
|---|---|
library/kani_macros/src/sysroot/loop_contracts/mod.rs |
Preserves attributes/labels and combines invariants. |
kani-compiler/src/kani_middle/transform/mod.rs |
Stores generated modifies metadata. |
kani-compiler/src/kani_middle/transform/loop_contracts.rs |
Finds loop heads and records loop-local writes. |
kani-compiler/src/codegen_cprover_gotoc/overrides/hooks.rs |
Adds generated locals to modifies clauses. |
docs/src/reference/experimental/loop-contracts.md |
Documents invariants and loop-local handling. |
tests/expected/loop-contract/while_let_loop_modifies_fail.rs |
Tests while-let attribute ordering. |
tests/expected/loop-contract/while_let_loop_modifies_fail.expected |
Records expected assigns failures. |
tests/expected/loop-contract/loop_modifies_not_added_fail.rs |
Tests excluded outer writes and lifetimes. |
tests/expected/loop-contract/loop_modifies_not_added_fail.expected |
Records expected safety failures. |
tests/expected/loop-contract/loop_modifies_loop_locals.rs |
Tests while-loop generated locals. |
tests/expected/loop-contract/loop_modifies_loop_locals.expected |
Records successful verification. |
tests/expected/loop-contract/loop_invariant_multiple.rs |
Tests multiple invariants. |
tests/expected/loop-contract/loop_invariant_multiple.expected |
Records invariant outcomes. |
tests/expected/loop-contract/loop_contract_labeled_loops.rs |
Tests preserved labels. |
tests/expected/loop-contract/loop_contract_labeled_loops.expected |
Records successful label tests. |
tests/expected/loop-contract/for_loop_on_entry_call.rs |
Tests CFG-based loop-head discovery. |
tests/expected/loop-contract/for_loop_on_entry_call.expected |
Records successful verification. |
tests/expected/loop-contract/for_loop_modifies.rs |
Tests complete for-loop modifies clauses. |
tests/expected/loop-contract/for_loop_modifies.expected |
Records successful harnesses. |
tests/expected/loop-contract/for_loop_modifies_fail.rs |
Tests rejected writes outside clauses. |
tests/expected/loop-contract/for_loop_modifies_fail.expected |
Records expected assigns failures. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…to loop_modifies `#[kani::loop_invariant]` rewrites a `for` loop into a `while` loop, and the rewrite dropped the attributes written after the invariant, so a `#[kani::loop_modifies]` or `#[kani::loop_decreases]` written there was silently ignored. Keep them on the rewritten loop. Carrying them over exposed two problems, the first of which also affects clauses written before the invariant: - A complete `loop_modifies` clause failed the assigns check on locals that the user cannot name in the clause: the index and the pattern bindings that the `for` loop rewrite generates, the variables generated for `prev`, and the variables and temporaries declared in the loop body whose initialization the loop contract pass copies to the loop head. The pass now records these locals for each loop, by the instance of the register function that the loop latch calls, and `BodyTransformation` keeps them by the instance of the body and of the register function (new `TransformPass::take_generated_loop_modifies` with an empty default). The codegen hook of that call adds them to the assigns clause of the loop if the user wrote one. The body is not changed for this, so later passes such as the uninitialized memory checks do not instrument anything for it. The locals only exist for the loop, so writes to any other memory are still checked against the user's clause. - `replace_first_pat_by_nth_pat` assumed that the loop head is the second block after the call to `KaniIter::first`, and panicked with `not a loop head` when an expression evaluated in between needed a block of its own (e.g. `#[kani::loop_modifies(&out[0])]` written after the invariant, or `on_entry(v.len())`). It now finds the loop head in the control flow graph, redirects the uses of the first pattern in all blocks before it, and emits an error instead of panicking if the loop head cannot be found.
A variable declared before the loop that the loop writes before reading it must still fail the assigns check, and a variable declared in the loop body must still be dead after its scope. Suggested in review.
Each `#[kani::loop_invariant]` attribute of a loop added its own call to a register function. On a `while` loop, only the call of the last attribute is the loop head, so the other invariants were silently dropped: they were neither checked nor assumed. On a `for` loop, whose attributes after the invariant are now kept on the rewritten loop, a second invariant made the loop contract pass fail with "Kani could not find the loop head of this `for` loop with a loop contract". The documentation says that a loop contract is composed of one or more loop invariants. Make the first `#[kani::loop_invariant]` attribute take the other ones out of the loop and use the conjunction of all their invariants, for `while`, `loop`, `while let` and `for` loops.
A loop whose `#[kani::loop_modifies]` clause had no target got an inferred write set, so the loop could write anything: codegen only attached a clause with at least one target, and CBMC infers the write set of a loop whose assigns clause has no target. This happened with an empty clause (`#[kani::loop_modifies()]`, whose `()` binding MIR optimizations also remove), and with a clause whose targets all have zero size, since codegen drops those targets (it also did not drop a single zero-sized target, which made CBMC report pointer failures). Track whether a loop has a clause separately from its targets (`current_loop_modifies` is now an `Option`), drop a single zero-sized target as well, and when a clause has no target left (also after adding the locals that only exist for the loop), use an object that no code writes as its only target. For an empty clause, the macro now binds a reference to a zero-sized local, which MIR optimizations keep.
1b5b14d to
f6388e0
Compare
feliperodri
left a comment
There was a problem hiding this comment.
Requesting changes, for one regression. On main, a complete loop_modifies clause on a for loop fails on variables the user can't name (#4940), and a clause written after the invariant is dropped or crashes the compiler. This PR fixes all three without changing the MIR, which is what made the #4938 transform unsound.
What I checked (the rebased head has the same tree as my merge of the previous head with main):
- The new tests fail on
mainfor the reasons the description gives, and pass here. The fullexpected,kanianduisuites pass apart from two solver out-of-memory failures that also happen onmainwith my 6 GB cap. fmt and both clippy gates are clean. - Both probes from my #4930 review now verify:
loop_modifies(&out[0])after the invariant, and a completeloop_modifies(&s)in both orders. - I tried to make the added locals hide an assigns violation, using call temporaries that borrow outer variables, reborrows, and an outer variable written before it is read. Everything that should fail still fails with the expected check.
Before merging:
- Thanks for the rebase. The description still says the PR is based on #4930 and will be rebased, and it doesn't mention a99b57c (several
loop_invariantattributes become their conjunction) or f6388e0 (empty and zero-sized clauses). PRs are squash-merged, so the description becomes the commit message. Please add a paragraph for each, and the new tests to the Testing section. Both are behavior changes users can notice: awhileloop whose second invariant used to be silently dropped can now fail. - See the inline comment on nested loops. Carrying
forattributes over means an outerforclause written after the invariant now goes to the inner loop, and that fails programs that verify onmain. The single-slot clause handling that causes it is older, but this PR is what makesforloops reach it, so I'd like it fixed here rather than in a follow-up. It's the same bar I used for #4930.
Thanks for writing loop_modifies_not_added_fail.rs and the generic and closure cases in loop_modifies_loop_locals.rs. Those tests pin down what must not be added, which is exactly what #4938 got wrong.
Codegen kept the user clause in a single slot: it was set when codegen reached the
`kani_loop_modifies` binding and taken by the next loop latch that codegen generated. The latch
of an inner loop is generated before the latch of its outer loop, so an inner loop without a
clause got the clause of its outer loop, and an inner loop with a clause replaced it, leaving the
outer loop with an inferred write set. Since the attributes of a `for` loop are now kept, an
outer clause written after the invariant of a `for` loop reached this as well. The clause of a
loop that does not iterate (e.g. `loop { break; }`), whose latch is not generated, went to the
next loop.
The loop contract pass now finds the `kani_loop_modifies` binding of each loop, by walking up
the dominator tree from the loop head and stopping at the head of another loop or at a binding
of another loop, and records it with the instance of the register function of the loop, like the
locals that only exist for the loop. Codegen keeps the targets of each clause by that instance,
and the hook of each loop takes its own clause. A binding that does not belong to a loop with a
loop invariant is not attached to any loop. The decreases clause is not changed.
The binding of a `#[kani::loop_modifies]` clause was assigned where the attribute expanded: before all the code that `#[kani::loop_invariant]` generates for the loop when the clause is written first, and right before the loop otherwise. The loop contract pass, which looks for the binding of a loop by walking up the dominator tree from the loop head, stopped at the head of any loop. So the clause was dropped, and CBMC inferred the write set of the loop, when a loop without a loop contract was in between: a loop in the iterable expression of a `for` loop or in an `on_entry` expression, with the clause written first, or a loop around the loop whose body starts with it, whose head then holds the binding. `#[kani::loop_invariant]` now takes the `#[kani::loop_modifies]` attributes of its loop and binds their targets right before the loop, after the code that it generates for the loop. A `#[kani::loop_modifies]` written before the invariant moves itself after it. The walk now also searches the head of the loop where it stops. In addition: - The targets of several `#[kani::loop_modifies]` attributes on one loop are combined. Only the attribute closest to the loop was applied. - A clause on a loop without `#[kani::loop_invariant]` is ignored with a warning. It was applied to the next loop when its own loop does not iterate. - The binding is a tuple, even for a single target. MIR optimizations merged the binding of a single variable (e.g. `#[kani::loop_modifies(p)]`) with that variable: if the variable is an argument, the clause was dropped, and codegen also skipped the writes through the variable, taking them for the binding; if it is a local, Kani panicked.
`move_storagelive_assign_to_loophead` copies the initialization of a variable declared in a loop body to the loop head, and records the variable as a local of that loop, which codegen adds to its write set. The binding of a `#[kani::loop_modifies]` clause of an inner loop is such a variable when it has a single target or no target, so it was added to the write set of the loop around it. With three nested loops, the write set of the middle loop then had a local that is not in the write set of the outer loop, since it is only declared at the head of the middle loop, and `Check assigns clause inclusion` failed for the middle loop. Codegen does not generate the assignments of the bindings, so they are not moved anymore.
… found Codegen skipped every assignment to a local whose name contains `kani_loop_modifies`, including assignments through it (e.g. `*p = ..`). Now it only skips the assignment of a binding itself, when the loop contract pass found the loop of that binding, and the pass ignores assignments through a binding. Codegen also keeps the targets of a clause by the instance of the function that contains the loop as well as the register function of the loop, as the locals of the loop are, so that a loop whose latch is not generated does not leave its clause to another function.
Codegen generated the tuple that binds the targets of a clause, and paired its fields with the operands of the tuple. The fields are in the order of the layout of the tuple, which rustc can change, e.g. a slice and two references, so a target could get the type of another one: Kani panicked on `#[kani::loop_modifies(slice_from_raw_parts_mut(a.as_mut_ptr(), 2), &i, &j)]`, and with slices of different element sizes the target of a slice covered the wrong number of bytes, which could miss a write outside of the clause. Each operand is now generated on its own. This already happened on `main` for clauses with several targets, and is more likely now that the targets of several `#[kani::loop_modifies]` attributes are combined.
|
Thanks for the review. Changes since then:
Locally, the |
feliperodri
left a comment
There was a problem hiding this comment.
Thanks for the rework. The clause attachment now holds up: I reran the shapes from my first review (nested for loops with the clause after the invariant, an outer loop writing an unlisted variable under an inner clause, an empty clause on loop { break; }, a single &mut parameter target) and added probes for a loop in a branch or a match arm followed by another loop. Each one either verifies or fails on exactly the unlisted variable, and the three that were wrong on main are right here. Combining several invariants works too: a loop that needs both of them now verifies, and a false one fails wherever it is.
Two pre-existing problems, inline, neither blocking. The first is worth your attention: at -Zmir-opt-level=2 and above the clause binding is optimized away and the loop gets an inferred write set, so writes outside the clause verify. The keep-alive from #4946 fixes it in my test; it costs some expected-file churn. The second is that #[kani::loop_modifies(t)] moves a &mut parameter.
This PR and #4946 conflict in statement.rs, goto_ctx.rs and loop_contracts.rs, so whichever lands second needs a rebase.
An explicit `#[kani::loop_modifies]` must cover every local that the loop writes. model-checking#4947 adds the loop-only locals that Kani generates, but MIR temporaries (e.g. the scrutinee of a `match` with `return` arms) and variables of the loop body that are still live when a `return` leaves the loop cannot be named by the user, and still fail with `Check that var_N is assignable`. Add to the write set the locals that are dead at the loop head where the write set is havocked (by a MIR liveness analysis), are not storage-local to the loop, and are temporaries or declared inside the loop's span, for loops that are not nested in another contracted loop. Emit `StorageLive` for them at the latch, so that havocking an address-taken temporary whose storage the last iteration ended is not a write to a dead object. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
) ## Summary Fix loop contract attribute parsing for loop expressions used directly as match arms. Previously, the token stream passed to `#[kani::loop_invariant]`, `#[kani::loop_modifies]`, or `#[kani::loop_decreases]` could include the match arm's trailing comma. Parsing it as a `syn::Stmt` failed, and the macro could panic instead of expanding the loop or reporting a useful diagnostic. ## Changes - Introduce a shared `LoopInput` parser for `loop`, `while`, and `for` expressions, supporting an optional statement semicolon or match-arm trailing comma. - Use the parser consistently in all three loop contract attributes. - Return normal compile errors for malformed input instead of panicking. - Add regression tests for match-arm loops, different attribute orders, and invalid attribute placement. - Add a negative termination-check regression to ensure a nondecreasing measure is actually rejected. ## Testing - Targeted `loop-contract` expected tests pass, including positive and negative decreases checks. - Loop attribute UI tests and `kani_macros` unit tests pass. - The standalone branch builds successfully; Clippy and formatting checks pass. - Full repository CI has not been run locally. ## Related work This fixes match-arm attribute parsing, independently of the loop transformation and modifies-clause fixes in model-checking#4930, model-checking#4947, model-checking#5068, and model-checking#5071. By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.

Description
Follow-up to #4930, which kept the label of rewritten
forloops but left their attributes for a separate PR (see the review there).#[kani::loop_invariant]rewrites aforloop into awhileloop (transform_for_to_loop). The rewrite dropped the attributes written after the invariant, so a#[kani::loop_modifies]or#[kani::loop_decreases]written there was silently ignored. This PR keeps them on the rewritten loop, as #4930 does forwhile letloops.As found in the review of #4930, carrying the attributes over made two programs that verify on
mainfail. This PR fixes both:A complete
loop_modifiesclause failed the assigns check on locals that the user cannot name in the clause. This already happened onmainwhen the clause is written before the invariant, and forwhileloops (Loop contracts: explicitloop_modifiesrejects writes to temporaries declared in the loop body (Check that var_N is assignable) #4906, Loop contracts: an explicitloop_modifieson aforloop fails the assigns check on Kani's generated variables #4940). With an explicit clause, CBMC checks every write in the loop to a local that is also used outside of it. The loop contract transformation creates such locals:kani_index_...) and the pattern bindings that theforloop rewrite generates (afterreplace_first_pat_by_nth_patmerges the first and the nth pattern, the bindings are assigned before the loop and in each iteration), and the temporary that holds the item for patterns such as(i, j),&xor_;prev(..);move_storagelive_assign_to_loopheadandmove_storagelive_call_to_loophead), e.g.var_14,var_15andvar_16in Loop contracts: explicitloop_modifiesrejects writes to temporaries declared in the loop body (Check that var_N is assignable) #4906.The loop contract pass now records these locals for each loop, keyed by the instance of the register function that the new loop latch calls. This instance is unique to the loop, and it is the instance that the codegen hook of that call (
LoopInvariantRegister) receives. The pass hands the locals toBodyTransformationthrough a newTransformPass::take_generated_loop_modifiesmethod (empty by default), which keeps them by the instance of the transformed body and of the register function, and the hook adds them to the assigns clause of the loop if the user wrote one. Without a user clause, CBMC still infers the clause. The body itself is not changed for this, so the passes that run after the loop contract pass (e.g. the uninitialized memory checks) do not instrument anything for it, and nothing depends on the name of a binding that MIR optimizations could remove (as happens tokani_loop_decreasesin#[kani::loop_decreases]with a plain variable measure generates no decreases check #4942). The index andprevvariables are found by their generated names, which start with the id of the loop; they are borrowed by the loop invariant closure or assigned in the loop, so they are not optimized away.This does not let the loop write to memory outside the user's clause: every added local only exists for the loop (it is generated by the rewrite or declared in the loop body), so the user could not name it in the clause anyway. Adding a local to the write set only allows writes to that local's own storage. A write through a pointer stored in such a local, or a write to any variable declared before the loop, is still checked against the user's clause (see
for_loop_modifies_fail.rsandloop_modifies_not_added_fail.rsbelow).A clause whose expression needs a basic block of its own crashed the compiler with
not a loop head, e.g.#[kani::loop_modifies(&out[0])]written after the invariant (the bounds check ofout[0]).replace_first_pat_by_nth_patassumed that the loop head is the second block after the call toKaniIter::first. The same crash already happens onmainfor anon_entryexpression that calls a function in aforloop invariant, e.g.on_entry(v.len()). The pass now finds the loop head in the control flow graph (the first loop head reachable from that call whose body callsKaniIter::nth), redirects the uses of the first pattern (reads, borrows and index operands) in all blocks before it, not only the borrows in the loop head, and emits a compile error instead of panicking if no loop head is found.Each
loop_modifiesclause now goes to its own loop. Codegen used to keep the user clause in a single slot: it was set when codegen reached thekani_loop_modifiesbinding and taken by the next loop latch that codegen generated. With nested loops, the latch of the inner loop is generated before the latch of the outer loop, so an outer clause written after the invariant of aforloop now went to the inner loop, which made programs that verify onmainfail. This already happened onmainwith the clause written before the invariant, and withwhileloops: an inner loop without a clause got the clause of the outer loop, and an inner loop with a clause replaced it, so the outer loop got an inferred write set and its writes were not checked. Likewise, the clause of a loop that does not iterate (e.g.loop { break; }), whose latch is never generated, went to the next loop. Now:#[kani::loop_invariant]takes the#[kani::loop_modifies]attributes of its loop and binds their targets right before the loop, after the code that it generates for the loop (theon_entryvariables, the initialization of aforloop, the first iteration forprev). A#[kani::loop_modifies]written before the invariant leaves itself on the loop as#[kanitool::loop_modifies], for the invariant to take. Both macros recognize these attributes by the last segment of their path, so that re-exports such askani_core::loop_invariantwork.#[kani::loop_decreases]expression), and the binding of a loop that is the first statement in the body of aloopis in the head of thatloop. The pass records the binding with the instance of the register function of the loop, like the locals above. Codegen keeps the targets of each clause by that instance and the instance of the function, and the hook of each loop takes its own clause.kani_loop_modifies, including writes through it.move_storagelive_assign_to_loophead) anymore. That added them to the write set of the enclosing loop, which failedCheck assigns clause inclusionwith three nested loops.The decreases clause is not changed here (see #4946).
Other
loop_modifieschanges that come with the new binding. They can change the result of a program:#[kani::loop_modifies]attributes on one loop are combined. Only the attribute closest to the loop used to be applied.#[kani::loop_modifies]on a loop without#[kani::loop_invariant]is ignored with a warning, as Check#[kani::loop_decreases]clauses whose measure is a variable #4946 does for a decreases clause. It used to be applied to the next loop with a loop invariant.#[kani::loop_modifies(p)]with a raw pointerp, ortwitht: &mut u8) with that variable, which then had the name of the binding. When the variable is an argument, the clause was dropped (the case from the review of this PR), and codegen took the writes through the variable for the binding, so it skipped them (e.g. after the loop) or panicked (in the loop). When the variable is a local, Kani panicked.main, and combining attributes makes such tuples more likely.Several
#[kani::loop_invariant]attributes on one loop are now combined into their conjunction. Each attribute added its own call to a register function, but only one of them was the loop head: on awhileloop, the invariants of all but the last attribute were silently neither checked nor assumed, and on aforloop, whose attributes after the invariant are now kept, a second invariant failed to compile with "Kani could not find the loop head of thisforloop with a loop contract". The documentation says that a loop contract is composed of one or more loop invariants, so the first attribute now takes the others out of the loop and uses the conjunction of all invariants, forwhile,loop,while letandforloops. This changes the result of some programs: awhileloop whose dropped invariant was false now failsCheck invariant before entryorCheck invariant after step, and a loop that needs all of its invariants now verifies.A
loop_modifiesclause without targets is now applied. A loop whose clause had no target got an inferred write set, so it could write anything: codegen only attached a clause with at least one target, and CBMC infers the write set of a loop whose assigns clause has no target. This happened onmainwith an empty clause (#[kani::loop_modifies()], whose()binding MIR optimizations also removed), and with a clause whose targets all have zero size, since codegen drops those targets (it did not drop a single zero-sized target, which made CBMC report pointer failures). Codegen now tracks whether a loop has a clause separately from its targets, drops a single zero-sized target as well, and when a clause has no target left (also after adding the locals above), uses an object that no code writes as its only target. For an empty clause, the macro binds a reference to a zero-sized local, which MIR optimizations keep. This can also change results: a loop with an empty or zero-sized clause that writes a variable declared before it now fails its assigns check.A
#[kani::loop_decreases]written after the invariant on aforloop is now carried over as well, but its measure is not checked yet: a plain variable measure produces no decreases check because of #4942 (fix in #4946), and an arithmetic measure runs into #4585. So this PR has no verification test forloop_decreases.The loop contracts documentation now says which variables do not need to be listed in a
loop_modifiesclause, when its targets are evaluated, that several invariants or severalloop_modifiesattributes of a loop are combined, and that aloop_modifieson a loop without an invariant is ignored.Resolves #4929.
Resolves #4906.
Resolves #4940.
Testing
All the new tests are in
tests/expected/loop-contract.for_loop_modifies.rs: completeloop_modifiesclauses onforloops, which only list variables declared before the loop. It covers both attribute orders, the patternsx,(i, j),&x,_and(k, x)overenumerate(), a variable declared in the loop body,prev, nestedforloops, and the indexed place&out[0]in both orders (the two cases from the review of Keep loop attributes and labels when rewritingwhile letandforloops with a loop invariant #4930). Onmain, three harnesses fail withCheck that x is assignable,Check that kani_index_... is assignableorCheck that var_25 is assignable, and the harnesses with the clause after the invariant pass only because the clause is dropped. With the attributes carried over but without the other changes,indexed_place_invariant_then_modifiescrashes withnot a loop head. With this PR, all 11 harnesses verify.for_loop_modifies_fail.rs, the test removed from Keep loop attributes and labels when rewritingwhile letandforloops with a loop invariant #4930, with six harnesses that must each fail exactly their assigns check: two loops writej, which is not in the clause, one per attribute order; one writesjthrough a reference declared in the loop body; one writesout[1]with a clause for&out[0]; and two nestedforloops (one per attribute order of the outer clause) whose outer loop writesy, which its clause does not list, while the inner loop has a clause of its own. Onmain, onlymodifies_then_invariantfails, and it also reports the generated locals; the nested ones verify because the clause of the outer loop is replaced by that of the inner loop.for_loop_on_entry_call.rs: aforloop invariant withon_entry(v.len()). Onmain, Kani panics withnot a loop head. With this PR, it verifies.loop_modifies_loop_locals.rs:whileloops with complete clauses, one with a call in the body (the example from Loop contracts: explicitloop_modifiesrejects writes to temporaries declared in the loop body (Check that var_N is assignable) #4906), one withprev, and the first one again in a generic function instantiated twice and in a closure (each loop has its own register function instance). Onmain, they fail withCheck that var_15 is assignable(andvar_14,var_16,x) orCheck that __kani_prev_var_... is assignable. With this PR, all four verify.loop_modifies_not_added_fail.rs(suggested in review): a variable declared before the loop that the loop writes before reading it must still fail its assigns check, and a variable declared in the loop body must still be dead after its scope.loop_modifies_own_loop.rs(the two cases from the review, plus variants): nested loops whose outer clause must not go to the inner loop, which writes a variable declared in the body of the outer loop, forforandwhileloops and both attribute orders; and a clause (empty or not) on aloop { break; }, which must not go to the next loop. All six verify. Onmain, thewhileversions, the clause-before-invariantforversion and the non-empty clause onloop { break; }fail.loop_modifies_own_loop_fail.rs: loops that write abadthat their clause does not list, with a loop without a loop contract between the clause and the loop (in the iterable expression of aforloop or in anon_entryexpression with the clause written first, or in aloop_decreasesexpression) or around the loop (the loop is the first statement in the body of aloop), and with the invariant or the clause written with another path (a re-export). Each must fail withCheck that bad is assignable.loop_modifies_nested.rsandloop_modifies_nested_fail.rs: nestedwhileloops with complete clauses on both loops, on the outer one only and on the inner one only, an inner counter declared in the body of the outer loop, a labeledcontinue 'outer, and three levels of loops (one with a single-target innermost clause, one with an empty clause on an innermostloop { break; }), which verify; and loops that write atthat their clause does not list (outer loops with a clause on both loops, on the outer one only, and with a branch between the outer binding and the outer loop head; aforloop with its clause written first followed by a loop without a clause; the middle one of three loops), which must each fail withCheck that t is assignable. Onmain, where the outer clause is attached to the inner loop,outer_loop_with_clauseandlabeled_continuefail, andboth_loops_with_clauseandjoin_before_outer_loopverify.loop_modifies_multiple.rs: twoloop_modifiesattributes on one loop, in each order relative to the invariant and on aforloop, verify; with an empty clause as the second attribute, a write towmust fail its assigns check. Onmain, thewhileloops fail withCheck that i is assignable. It also has clauses whose first target is a slice, which Kani used to pair with the wrong target types: one with two references verifies (Kani panicked on it), and one with a slice ofu8, a slice ofu64and a reference must fail its assigns check for a write outside of theu8slice (it verified).loop_modifies_no_invariant.rs: aloop_modifieson a loop without an invariant, which iterates or not, is reported with a warning and is not applied to the next loop. Onmain, both harnesses fail withCheck that j is assignable.loop_modifies_pointer_target.rs: clauses whose only target is a raw pointer argument, a&mutargument or a raw pointer local. The loops that only write through the target verify; the loops that also write another variable, and a write through the target after the loop that the assertion relies on, must fail. Onmain,mut_ref_argument_fail(the case from the review) andwrite_after_loop_failverify, and Kani panics on the others.loop_invariant_multiple.rs: two invariants onwhileandforloops. Every false invariant failsCheck invariant before entry, whichever its position, and loops that need both invariants (one usingprev, one usingkani::index) verify. Onmain, awhileloop with a false first invariant and aforloop with a false second invariant verify, and the loops that need both invariants fail.loop_modifies_empty.rsandloop_modifies_empty_fail.rs: an empty clause, one or two zero-sized targets, and an empty clause on aforloop. With a write to a variable declared before the loop, each must fail its assigns check (onmain, the empty and two-target cases verify); loops that only write their own variables verify.kani_macroscheck that the rewrittenforloop keeps its label and attributes, that the otherloop_invariantattributes and theloop_modifiesattributes of a loop (with any path, and the#[kanitool::loop_modifies]that a clause written first leaves) are taken out of it, and that the binding of a single target is a tuple.--keep-temps, a#[kani::loop_decreases]written after the invariant on aforloop now produces thekani_loop_decreaseslocal.RUSTFLAGS=--cfg=kani_sysroot cargo test -p kani_macros --features syn/extra-traits --lib,cargo clippy --workspace --tests -- -D warnings,RUSTFLAGS="--cfg=kani_sysroot" cargo clippy --workspace -- -D warnings,cargo test -p kani-compiler,cargo fmt --checkandscripts/kani-fmt.sh --checkpass, and so do theexpected(519 passed, 15 ignored),ui(153 passed),kani(620 passed, 23 ignored) andscript-based-pre(91 passed) suites.By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.