[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/kapabl/cppfront/main/docs/cpp2/contracts.md [Back]  [Original]

# Contracts

## Overview

Cpp2 currently supports three kinds of contracts:

- **Preconditions and postconditions.** A function declaration can include `pre(condition)` and `post(condition)` before the `= /* function body */`. Before entering the function body, preconditions are fully evaluated and postconditions are captured as function expressions to be evaluated later (and perform their captures of values on entry, if any). Immediately before exiting the function body via a normal return, postconditions are evaluated. If the function exits via an exception, postconditions are not evaluated.

- **Assertions.** A function body can write `assert(condition)` assertion statements. Assertions are evaluated when control flow passes through them.

Notes:

- `condition` is an expression that evaluates to `#!cpp true` or `#!cpp false`. It will not be evaluated unless checking for this contract group is enabled (`group.is_active()` is `true`).

- Optionally, `condition` may be followed by `, "message"`, a message to include if a violation occurs. For example, `pre(condition, "message")`.

- Optionally, a `` can be written inside `` angle brackets immediately before the `(`, to designate that this test is part of the [contract group](#groups) named `group` and (also optionally) [contract predicates](#predicates) `pred1` and `pred2`. If a violation occurs, `Group.report_violation()` will be called. For example, `pre(condition)`. If no contract group is specified, the contract defaults to being part of the `default` group (spelled `cpp2_default` when used from Cpp1 code).

The order of evaluation is:

- First, if the contract group is `unevaluated` then the contract is ignored; `condition` is never evaluated. This special group designates conditions intended for use by static analyzers only, and the only requirement is that the condition be grammatically valid.

- Next, predicates are evaluated in order. If any predicate evaluates to `#!cpp false`, stop.

- Next, `group.is_active()` is evaluated. If that evaluates to `#!cpp false`, stop.

- Next, `condition` is evaluated. If that evaluates to `#!cpp true`, stop.

- Finally, if all the predicates were true and the group is active and the condition was false, `group.report_violation()` is called.

For example:

``` cpp title="Precondition and postcondition examples" hl_lines="2 3"
insert_at: (container, where: int, val: int)
    pre( 0 

Web Proxy Viewer  |  New URL  |  Original Page