Skip to content

Commit 670d1d1

Browse files
Fix the bug: Loop contracts are not composable with function contracts (#3979)
This PR fixes the bug of loop contracts are not composable with function contracts. Previously, using loop-contract inside a function with contract may result in unwinding the loop instead of contracting it. Resolves #3910 By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses. --------- Co-authored-by: Carolyn Zech <[email protected]>
1 parent 5b42a48 commit 670d1d1

File tree

8 files changed

+172
-34
lines changed

8 files changed

+172
-34
lines changed

docs/src/reference/experimental/loop-contracts.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,13 +139,36 @@ In proof path 1, we prove properties inside the loop and at last check that the
139139
In proof path 2, we prove properties after leaving the loop. As we leave the loop only when the loop guard is violated, the post condition of the loop can be expressed as
140140
`!guard && inv`, which is `x <= 1 && x >= 1` in the example. The postcondition implies `x == 1`—the property we want to prove at the end of `simple_loop_with_loop_contracts`.
141141

142+
## Loop contracts inside functions with contracts
143+
Kani supports using loop contracts together with function contracts, as demonstrated in the following example:
144+
``` Rust
145+
#![feature(proc_macro_hygiene)]
146+
#![feature(stmt_expr_attributes)]
147+
148+
#[kani::requires(i>=2)]
149+
#[kani::ensures(|ret| *ret == 2)]
150+
pub fn has_loop(mut i: u16) -> u16 {
151+
#[kani::loop_invariant(i>=2)]
152+
while i > 2 {
153+
i = i - 1
154+
}
155+
i
156+
}
157+
158+
#[kani::proof_for_contract(has_loop)]
159+
fn contract_proof() {
160+
let i: u16 = kani::any();
161+
let j = has_loop(i);
162+
}
163+
```
142164

165+
When loop contracts and function contracts are both enabled (by flags `-Z loop-contracts -Z function-contracts`),
166+
Kani automatically contracts (instead of unwinds) all loops in the functions that we want to prove contracts for.
143167
## Limitations
144168

145169
Loop contracts comes with the following limitations.
146170

147-
1. Only `while` loops are supported. The other three kinds of loops are not supported: [`loop` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#infinite-loops)
148-
, [`while let` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops), and [`for` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops).
171+
1. `while` loops and `loop` loops are supported. The other kinds of loops are not supported: [`while let` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops), and [`for` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops).
149172
2. Kani infers *loop modifies* with alias analysis. Loop modifies are those variables we assume to be arbitrary in the inductive hypothesis, and should cover all memory locations that are written to during
150173
the execution of the loops. A proof will fail if the inferred loop modifies misses some targets written in the loops.
151174
We observed this happens when some fields of structs are modified by some other functions called in the loops.

kani-compiler/src/kani_middle/transform/loop_contracts.rs

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -103,39 +103,10 @@ impl TransformPass for LoopContractPass {
103103
let run = Instance::resolve(self.run_contract_fn.unwrap(), args).unwrap();
104104
(true, run.body().unwrap())
105105
} else {
106-
let mut new_body = MutableBody::from(body);
107-
let mut contain_loop_contracts: bool = false;
108-
109-
// Visit basic blocks in control flow order (BFS).
110-
let mut visited: HashSet<BasicBlockIdx> = HashSet::new();
111-
let mut queue: VecDeque<BasicBlockIdx> = VecDeque::new();
112-
// Visit blocks in loops only when there is no blocks in queue.
113-
let mut loop_queue: VecDeque<BasicBlockIdx> = VecDeque::new();
114-
queue.push_back(0);
115-
116-
while let Some(bb_idx) = queue.pop_front().or_else(|| loop_queue.pop_front()) {
117-
visited.insert(bb_idx);
118-
119-
let terminator = new_body.blocks()[bb_idx].terminator.clone();
120-
121-
let is_loop_head = self.transform_bb(tcx, &mut new_body, bb_idx);
122-
contain_loop_contracts |= is_loop_head;
123-
124-
// Add successors of the current basic blocks to
125-
// the visiting queue.
126-
for to_visit in terminator.successors() {
127-
if !visited.contains(&to_visit) {
128-
if is_loop_head {
129-
loop_queue.push_back(to_visit);
130-
} else {
131-
queue.push_back(to_visit)
132-
};
133-
}
134-
}
135-
}
136-
(contain_loop_contracts, new_body.into())
106+
self.transform_body_with_loop(tcx, body)
137107
}
138108
}
109+
RigidTy::Closure(_, _) => self.transform_body_with_loop(tcx, body),
139110
_ => {
140111
/* static variables case */
141112
(false, body)
@@ -194,6 +165,43 @@ impl LoopContractPass {
194165
))
195166
}
196167

168+
/// This function transform the function body as described in fn transform.
169+
/// It is the core of fn transform, and is separated just to avoid code repetition.
170+
fn transform_body_with_loop(&mut self, tcx: TyCtxt, body: Body) -> (bool, Body) {
171+
let mut new_body = MutableBody::from(body);
172+
let mut contain_loop_contracts: bool = false;
173+
174+
// Visit basic blocks in control flow order (BFS).
175+
let mut visited: HashSet<BasicBlockIdx> = HashSet::new();
176+
let mut queue: VecDeque<BasicBlockIdx> = VecDeque::new();
177+
// Visit blocks in loops only when there is no blocks in queue.
178+
let mut loop_queue: VecDeque<BasicBlockIdx> = VecDeque::new();
179+
queue.push_back(0);
180+
181+
while let Some(bb_idx) = queue.pop_front().or_else(|| loop_queue.pop_front()) {
182+
visited.insert(bb_idx);
183+
184+
let terminator = new_body.blocks()[bb_idx].terminator.clone();
185+
186+
let is_loop_head = self.transform_bb(tcx, &mut new_body, bb_idx);
187+
contain_loop_contracts |= is_loop_head;
188+
189+
// Add successors of the current basic blocks to
190+
// the visiting queue.
191+
for to_visit in terminator.successors() {
192+
if !visited.contains(&to_visit) {
193+
if is_loop_head {
194+
loop_queue.push_back(to_visit);
195+
} else {
196+
queue.push_back(to_visit)
197+
};
198+
}
199+
}
200+
}
201+
202+
(contain_loop_contracts, new_body.into())
203+
}
204+
197205
/// Transform loops with contracts from
198206
/// ```ignore
199207
/// bb_idx: {
@@ -316,7 +324,7 @@ impl LoopContractPass {
316324
for stmt in &new_body.blocks()[bb_idx].statements {
317325
if let StatementKind::Assign(place, rvalue) = &stmt.kind {
318326
match rvalue {
319-
Rvalue::Ref(_,_,rplace) => {
327+
Rvalue::Ref(_,_,rplace) | Rvalue::CopyForDeref(rplace) => {
320328
if supported_vars.contains(&rplace.local) {
321329
supported_vars.push(place.local);
322330
} }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
has_loop::{closure#2}::{closure#1}.loop_invariant_step.1\
2+
- Status: SUCCESS\
3+
- Description: "Check invariant after step for loop has_loop::{closure#2}::{closure#1}.0"\
4+
in function has_loop::{closure#2}::{closure#1}
5+
6+
7+
8+
has_loop::{closure#2}::{closure#1}.precondition_instance.1\
9+
- Status: SUCCESS\
10+
- Description: "free argument must be NULL or valid pointer"\
11+
in function has_loop::{closure#2}::{closure#1}
12+
13+
VERIFICATION:- SUCCESSFUL
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Copyright Kani Contributors
2+
// SPDX-License-Identifier: Apache-2.0 OR MIT
3+
4+
// kani-flags: -Z loop-contracts -Z function-contracts
5+
6+
//! Test that we can prove a function contract and a loop contract in tandem.
7+
8+
#![feature(proc_macro_hygiene)]
9+
#![feature(stmt_expr_attributes)]
10+
11+
#[kani::requires(i>=2)]
12+
#[kani::ensures(|ret| *ret == 2)]
13+
pub fn has_loop(mut i: u16) -> u16 {
14+
#[kani::loop_invariant(i>=2)]
15+
while i > 2 {
16+
i = i - 1
17+
}
18+
i
19+
}
20+
21+
#[kani::proof_for_contract(has_loop)]
22+
fn contract_proof() {
23+
let i: u16 = kani::any();
24+
let j = has_loop(i);
25+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
has_loop::{closure#3}::{closure#0}.loop_invariant_base.1\
2+
- Status: SUCCESS\
3+
- Description: "Check invariant before entry for loop has_loop::{closure#3}::{closure#0}.0"\
4+
in function has_loop::{closure#3}::{closure#0}
5+
6+
has_loop::{closure#3}::{closure#0}.precondition_instance.5\
7+
- Status: SUCCESS\
8+
- Description: "free called for new[] object"\
9+
in function has_loop::{closure#3}::{closure#0}
10+
11+
Failed Checks: i>=2
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Copyright Kani Contributors
2+
// SPDX-License-Identifier: Apache-2.0 OR MIT
3+
4+
// kani-flags: -Z loop-contracts -Z function-contracts
5+
6+
//! Calling a function that contains loops and test that using a #[kani::proof] harness fails because the function's precondition gets asserted.
7+
8+
#![feature(proc_macro_hygiene)]
9+
#![feature(stmt_expr_attributes)]
10+
11+
#[kani::requires(i>=2)]
12+
#[kani::ensures(|ret| *ret == 2)]
13+
pub fn has_loop(mut i: u16) -> u16 {
14+
#[kani::loop_invariant(i>=2)]
15+
while i > 2 {
16+
i = i - 1
17+
}
18+
i
19+
}
20+
21+
#[kani::proof]
22+
fn call_has_loop() {
23+
let i: u16 = kani::any();
24+
let j = has_loop(i);
25+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
has_loop.loop_invariant_base.1\
2+
- Status: SUCCESS\
3+
- Description: "Check invariant before entry for loop has_loop.0"\
4+
in function has_loop
5+
6+
7+
8+
VERIFICATION:- SUCCESSFUL
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Copyright Kani Contributors
2+
// SPDX-License-Identifier: Apache-2.0 OR MIT
3+
4+
// kani-flags: -Z loop-contracts -Z function-contracts --no-assert-contracts
5+
6+
//Call a function with loop without checking the contract.
7+
8+
#![feature(proc_macro_hygiene)]
9+
#![feature(stmt_expr_attributes)]
10+
11+
#[kani::requires(i>=2)]
12+
#[kani::ensures(|ret| *ret == 2)]
13+
pub fn has_loop(mut i: u16) -> u16 {
14+
#[kani::loop_invariant(i>=2)]
15+
while i > 2 {
16+
i = i - 1
17+
}
18+
i
19+
}
20+
21+
#[kani::proof]
22+
fn contract_proof() {
23+
let i: u16 = kani::any();
24+
let j = has_loop(i);
25+
}

0 commit comments

Comments
 (0)