Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 63 additions & 17 deletions library/kani_macros/src/sysroot/loop_contracts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,9 +720,29 @@ fn loop_modifies_binding(targets: &[Expr]) -> Vec<Stmt> {
}
}

// An attributed match-arm loop can include its trailing comma.
struct LoopInput(Stmt);

impl syn::parse::Parse for LoopInput {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let expr: Expr = input.parse()?;
if !matches!(expr, Expr::Loop(_) | Expr::While(_) | Expr::ForLoop(_)) {
return Err(syn::Error::new_spanned(
expr,
"loop contract attribute must be applied to a loop expression",
));
}
let semi: Option<Token![;]> = input.parse()?;
if semi.is_none() {
let _: Option<Token![,]> = input.parse()?;
}
Ok(Self(Stmt::Expr(expr, semi)))
}
}

pub fn loop_invariant(attr: TokenStream, item: TokenStream) -> TokenStream {
// parse the stmt of the loop
let mut loop_stmt: Stmt = syn::parse(item.clone()).unwrap();
let LoopInput(mut loop_stmt) = parse_macro_input!(item as LoopInput);
// The invariants of the other `#[kani::loop_invariant]` attributes of the loop, if any.
let other_invariants = match take_other_loop_invariants(&mut loop_stmt) {
Ok(invariants) => invariants,
Expand All @@ -749,7 +769,7 @@ pub fn loop_invariant(attr: TokenStream, item: TokenStream) -> TokenStream {
inv_name.push_str(&loop_id);

// expr of the loop invariant
let mut inv_expr: Expr = syn::parse(attr).unwrap();
let mut inv_expr: Expr = parse_macro_input!(attr as Expr);
let original_span = inv_expr.span();
for other_invariant in other_invariants {
inv_expr = parse_quote! { (#inv_expr) && (#other_invariant) };
Expand Down Expand Up @@ -1023,7 +1043,8 @@ pub fn loop_modifies(attr: TokenStream, item: TokenStream) -> TokenStream {
let targets = proc_macro2::TokenStream::from(attr.clone());
// Check that the targets parse.
let _ = parse_macro_input!(attr with Punctuated::<Expr, Token![,]>::parse_terminated);
let mut loop_stmt: Stmt = syn::parse(item.clone()).unwrap();
let original_item = item.clone();
let LoopInput(mut loop_stmt) = parse_macro_input!(item as LoopInput);
match loop_attrs_mut(&mut loop_stmt) {
Some(attrs) if attrs.iter().any(is_loop_invariant_attr) => {
attrs.push(parse_quote!(#[kanitool::loop_modifies(#targets)]));
Expand All @@ -1036,7 +1057,7 @@ pub fn loop_modifies(attr: TokenStream, item: TokenStream) -> TokenStream {
`#[kani::loop_invariant]`. The modifies clause will be ignored."
.to_string(),
)
.emit_as_item_tokens_or(item.into())
.emit_as_item_tokens_or(original_item.into())
.into(),
}
}
Expand Down Expand Up @@ -1081,19 +1102,7 @@ pub fn loop_decreases(attr: TokenStream, item: TokenStream) -> TokenStream {
const fn kani_keep_loop_decreases_binding<T>(_binding: &T) {}
kani_keep_loop_decreases_binding(&#loop_decreases_ident);
};
let loop_stmt: Stmt = syn::parse(item.clone()).unwrap();
// Validate that the attribute is applied to a loop statement.
match &loop_stmt {
Stmt::Expr(Expr::While(_) | Expr::Loop(_) | Expr::ForLoop(_), _) => {}
_ => {
return syn::Error::new_spanned(
proc_macro2::TokenStream::from(item),
"`#[kani::loop_decreases]` must be applied to a loop statement",
)
.to_compile_error()
.into();
}
}
let LoopInput(loop_stmt) = parse_macro_input!(item as LoopInput);
let ret: TokenStream = quote!(
{
#loop_decreases_stmt
Expand All @@ -1108,6 +1117,43 @@ pub fn loop_decreases(attr: TokenStream, item: TokenStream) -> TokenStream {
mod tests {
use super::*;

#[test]
fn loop_input_accepts_match_arm_separator() {
let parsed: LoopInput = syn::parse2(quote! {
#[kani::loop_modifies(&x)]
loop { break x; },
})
.unwrap();
assert!(matches!(parsed.0, Stmt::Expr(Expr::Loop(_), None)));
let stmt = parsed.0;
assert!(!quote!(#stmt).to_string().ends_with(','));
}

#[test]
fn loop_input_accepts_statement_and_tail_expression() {
for tokens in [
quote!(loop {}),
quote!(while x > 0 { x -= 1; };),
quote!(while x > 0 {
x -= 1;
},),
quote!(for x in a {
consume(x);
},),
quote!(for x in a { consume(x); };),
] {
let parsed: LoopInput = syn::parse2(tokens).unwrap();
assert!(matches!(parsed.0, Stmt::Expr(_, _)));
}
}

#[test]
fn loop_input_rejects_invalid_input() {
for tokens in [quote!(loop {};,), quote!(42), quote!({ loop {} }), quote!(loop {}, extra)] {
assert!(syn::parse2::<LoopInput>(tokens).is_err());
}
}

fn attr_paths(attrs: &[syn::Attribute]) -> Vec<String> {
attrs
.iter()
Expand Down
2 changes: 2 additions & 0 deletions tests/expected/loop-contract/loop_match_expression.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VERIFICATION:- SUCCESSFUL
Complete - 5 successfully verified harnesses, 0 failures, 5 total.
94 changes: 94 additions & 0 deletions tests/expected/loop-contract/loop_match_expression.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT

// kani-flags: -Z loop-contracts

#![feature(stmt_expr_attributes, proc_macro_hygiene)]

// Keep the loop directly in the match arm to exercise the trailing comma.
#[rustfmt::skip]
fn count_to(n: u32, run: bool) -> u32 {
let mut i = 0;
match run {
true =>
#[kani::loop_modifies(&i)]
#[kani::loop_invariant(i <= n)]
loop {
if i == n {
return i;
}
i += 1;
},
false => 0,
}
}

#[kani::proof]
fn match_loop_returns_count() {
let n: u32 = kani::any();
let run: bool = kani::any();
assert_eq!(count_to(n, run), if run { n } else { 0 });
}

#[kani::proof]
#[kani::should_panic]
fn match_loop_detects_wrong_result() {
let n: u32 = kani::any();
kani::assume(n > 0);
assert_eq!(count_to(n, true), 0);
}

#[rustfmt::skip]
fn countdown(mut n: u8, order: bool) -> u8 {
match order {
true =>
#[kani::loop_decreases(n)]
#[kani::loop_invariant(n <= 3)]
#[kani::loop_modifies(&n)]
while n > 0 { n -= 1; },
false =>
#[kani::loop_modifies(&n)]
#[kani::loop_invariant(n <= 3)]
#[kani::loop_decreases(n)]
while n > 0 { n -= 1; },
}
n
}

#[kani::proof]
fn match_decreases_attribute_orders() {
let n: u8 = kani::any();
kani::assume(n <= 3);
assert_eq!(countdown(n, kani::any()), 0);
}

#[rustfmt::skip]
#[kani::proof]
fn match_for_loop() {
let mut count = 0u8;
match true {
true =>
#[kani::loop_invariant(count == kani::index as u8)]
#[kani::loop_modifies(&count)]
for _ in 0..3 { count += 1; },
false => (),
}
assert_eq!(count, 3);
}
Comment thread
feliperodri marked this conversation as resolved.
Resolved

#[rustfmt::skip]
#[kani::proof]
fn match_labeled_loop() {
let mut count = 0u8;
match true {
true =>
#[kani::loop_invariant(count <= 3)]
#[kani::loop_modifies(&count)]
'outer: loop {
if count == 3 { break 'outer; }
count += 1;
},
false => (),
}
assert_eq!(count, 3);
}
4 changes: 4 additions & 0 deletions tests/expected/loop-contract/match_decreases_stale.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
match_decreases_detects_stale_measure.loop_decreases.1\
- Status: FAILURE\
- Description: "Check variant decreases after step for loop match_decreases_detects_stale_measure.0"
VERIFICATION:- FAILED
19 changes: 19 additions & 0 deletions tests/expected/loop-contract/match_decreases_stale.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
// kani-flags: -Z loop-contracts
#![feature(stmt_expr_attributes, proc_macro_hygiene)]

#[rustfmt::skip]
#[kani::proof]
fn match_decreases_detects_stale_measure() {
let mut n = 3u8;
let measure = n;
match true {
true =>
#[kani::loop_decreases(measure)]
#[kani::loop_modifies(&n)]
#[kani::loop_invariant(n <= 3)]
while n > 0 { n -= 1; },
false => (),
}
}
5 changes: 5 additions & 0 deletions tests/ui/loop-contract-attributes/expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
error: loop contract attribute must be applied to a loop expression
error: loop contract attribute must be applied to a loop expression
error: loop contract attribute must be applied to a loop expression
error: unexpected end of input, expected an expression
error: aborting due to 4 previous errors
19 changes: 19 additions & 0 deletions tests/ui/loop-contract-attributes/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
// kani-flags: -Z loop-contracts
#![feature(stmt_expr_attributes, proc_macro_hygiene)]
extern crate core;

#[kani::proof]
fn invalid_attributes() {
#[kani::loop_invariant(true)]
1;
#[kani::loop_modifies()]
2;
#[kani::loop_decreases(0u8)]
3;
#[kani::loop_invariant(1 +)]
loop {
break;
}
}
Loading