Skip to content

Add hooks for handling pre and post conditions in function contracts. - #1511

Merged
monal merged 4 commits into
model-checking:features/function-contractsfrom
monal:contract-hooks
Aug 18, 2022
Merged

monal merged 4 commits into
model-checking:features/function-contractsfrom
monal:contract-hooks

Conversation

@monal

@monal monal commented Aug 11, 2022

Copy link
Copy Markdown

Description of changes:

Background: During macro expansion (yet to be implemented), #[kani::requires(x)] will get inlined as kani::precondition(x) in the function body before the actual function body begins. Similarly, #[kani::ensures(x)] will get inlined as kani::postcondition(x) at the end of the function body. The actual function body will get wrapped in an inner function that gets called and the corresponding return value is returned from the wrapper function.

This change includes -

  1. Hooks for replacing precondition(x) calls into assert or assume statements depending on whether a function contract is being checked or if a function is being replaced by its contract.
  2. Similarly, add hooks for replacing postcondition(x) calls into assert or assume statements.
  3. Add Kani flag --enforce-contracts to checks all function contracts.
  4. Add Kani flag --replace-with-contracts for replacing functions with their contracts, if a contract exists.

Resolved issues:

Resolves #1501

Call-outs:

Testing:

  • How is this change tested?
    By running Kani regression tests. Need to have end-to-end pipeline before adding additional test cases. Will not merge into main until we have these tests.

  • Is this a refactor change?
    No

Checklist

  • Each commit message has a non-empty body, explaining why the change was made
  • Methods or procedures are documented
  • Regression or unit tests are included, or existing tests cover the modified code
  • My PR is restricted to a single feature or bugfix

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

…gs for checking contracts and replacing functions with contracts
@monal
monal requested a review from a team as a code owner August 11, 2022 20:04
@monal monal self-assigned this Aug 11, 2022

@celinval celinval left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a question about usability. What will happen by default? Are we going to check the contracts or ignore them?

Do you have any documentation on how all the pieces fit together? What exactly happens when the user annotates their function with a contract annotation? A bit more context will help figuring out what you are trying to accomplish.

span: Option<Span>,
) -> Stmt {
assert_eq!(fargs.len(), 1);
let cond = fargs.remove(0).cast_to(Type::bool());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest you to implement something like:

struct PostCondition {
  // Should we apply this hook (i.e.: either enforce or check precondition).
  enabled: bool,
}

impl<'tcx> GotocHook<'tcx> for Postcondition {
  fn hook_applies(&self, tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
    self.enabled && matches_function(tcx, instance, "KaniPostcondition")
  }

  fn handle (/*args*/) {
    if tcx.queries.get_enforce_contracts() {
      fargs.add(Expr::string_constant("Post-condition failed");
      Assert::handle(tcx, instance, fargs, assign_to, target, span);
    } else {
      Assume::handle(tcx, instance, fargs, assign_to, target, span);
    }
  }
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to convert the postcondition as follows -

  1. to an assert when a function is being checked against its contract (calling Kani with the --enforce-contracts flag)
  2. to an assume if the function is being replaced with its contract (calling Kani with the --replace-with-contracts flag)
  3. To an empty statement, otherwise (calling Kani without any flags)

In this snippet, enabled must be set to true if tcx.queries.get_enforce_contracts() == true or tcx.queries.get_replace_with_contracts() == true. Where can I set this value? Also, how do I ensure that in the last case (that is call Kani normally without any contract checking/replacing flags) the inlined kani::postcondition gets converted to an empty line?

@monal monal Aug 17, 2022 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've refactored my code to use Assert.handle(..) and Assume.handle(..) within the same if-else statement for now.


impl<'tcx> GotocHook<'tcx> for ReplaceFunctionBody {
fn hook_applies(&self, tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
matches_function(tcx, instance, "KaniReplaceFunctionBody")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure I understand how this hook would work. Who is calling this function? Note that the hooks get applied at a function call level not function body code generation.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The macro expansion stage would call this function. The code would look something like this -

if kani::replace_function_body() {
  let ret = kani::any();
} else {
  let ret = .... //call body closure.
}

// } else {
// // The function contract is being ignored in this case.
// Stmt::block(vec![Stmt::goto(tcx.current_fn().find_label(&target), loc)], loc)
// }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you commit commented code intentionally?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, didn't mean to do that. I've removed them now, thanks! 👍

@celinval celinval left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Just one comment. Please address before pushing.

let target = target.unwrap();
let pe = unwrap_or_return_codegen_unimplemented_stmt!(tcx, tcx.codegen_place(&assign_to))
.goto_expr;
if tcx.queries.get_replace_with_contracts() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe replace this by:

let value = if tcx.queries.get_replace_with_contracts() { Expr::c_true() } else { Expr::c_false() };
Stmt::block(
    vec![
       pe.assign(value, loc),
       Stmt::goto(tcx.current_fn().find_label(&target), loc),
    ],
    loc,
)
        

@monal

monal commented Aug 18, 2022

Copy link
Copy Markdown
Author

Thanks for reviewing, @celinval! ❤️ I've made the last change you suggested.

@monal
monal merged commit 8df214f into model-checking:features/function-contracts Aug 18, 2022
@monal
monal deleted the contract-hooks branch August 18, 2022 21:55
zhassan-aws pushed a commit to zhassan-aws/kani that referenced this pull request May 26, 2023
…model-checking#1511)

* Add hooks for handling preconditions and postconditions; Add kani flags for checking contracts and replacing functions with contracts

* Rewrite using Assert, Assume

* Remove comment

* Refactor if-else statement

Co-authored-by: Monal Narasimhamurthy <[email protected]>
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.

3 participants