LEVIATHAN vd52e79c4 · d52e79c486

Statements

assert

The assert statement, which checks a condition where it stands, raises a ContractViolation with the operand values when it fails, and narrows the code after it.

since 0.1.0-alpha.1linuxwindowswasm

Description

assert(expr); checks that expr is true at the place where it is written. If it is false the program raises a ContractViolation of kind Assertion. assert(expr, message); also carries a string message, which is evaluated only when the assertion fails.

assert is a statement and is legal wherever a statement is, including the top level of a script. It is always on unless it is written @Debug assert(...), which is dropped by --profile release and runs again under --profile release --debug-checks (lang.contracts).

The violation carries the predicate text, the function it is in and the position of the predicate, and the value of each operand of the predicate. Operands are the sides of a comparison, the receiver and arguments of a call, and the operand of a !; for an && or || chain only the parts that were reached are reported.

Operands and the user message

use io::console;

void main() {
    int x = 3;
    try {
        assert(x > 5, "x must be big");
    } catch (ContractViolation v) {
        console.writeln(v.predicate);
        console.writeln(v.userMessage);
        for (ContractOperand o in v.operands) if (o.text != o.value) console.writeln(o.text + " = " + o.value);
    }
}
main();
x > 5
x must be big
x = 3

A non-@Debug assert(c) narrows the statements after it exactly as if (!(c)) throw ...; does, so assert(u != None); makes u a non-optional value after it.

Rules

  1. assert(expr); and assert(expr, message); are statements. expr must be a bool; the error otherwise is assertion has type 'int', expected 'bool'. message must be a string.

  2. assert is a reserved word. It cannot name a variable, parameter, function, field, member or type, and cannot follow . or :::

    error: 'assert' is a reserved word
    
  3. The predicate cannot assign or await. An @Debug assert must be pure.

  4. The message is evaluated only on failure. An exception it throws propagates instead of the violation.

  5. A non-@Debug assert(c) applies c's then-facts to the statements after it. An @Debug assert never narrows.

  6. An exception thrown while the predicate is evaluated is a violation of the assertion, with the exception in attached and no operand values.

  7. An assertion reports at its own site: the reporter bound there is called with the violation (lang.contracts), and then the violation propagates. It is reported once.

  8. The report of an assertion reads:

    assertion failed: x > 5
      in main at assert_basic.lev:13:18
      x = 3
      message: x must be big
    
  9. The ContractViolation is an IException, not an Exception: catch (IException e) catches it, catch (Exception e) does not.

Examples

Assertions, operands and short-circuit

use io::console;

int parseNumber(string s) => s == "7" ? 7 : 21;

string? pick(bool b) => b ? "yes" : None;

void report(ContractViolation v) {
    console.writeln(v.predicate);
    for (ContractOperand o in v.operands) if (o.text != o.value) console.writeln("  " + o.text + " = " + o.value);
    if (v.userMessage != "") console.writeln("  message: " + v.userMessage);
}

void main() {
    int x = 3;
    assert(x == 3);
    try { assert(parseNumber("12") == 12); } catch (ContractViolation v) { report(v); }
    try { assert(x > 5, "x must be big"); } catch (ContractViolation v) { report(v); }
    string? none = pick(false);
    try { assert(x > 10 && none != None); } catch (ContractViolation v) { report(v); }
    try { assert(x > 1 && none != None); } catch (ContractViolation v) { report(v); }
    string? some = pick(true);
    assert(some != None);
    console.writeln(some.length());
}
main();
parseNumber("12") == 12
  parseNumber("12") = 21
x > 5
  x = 3
  message: x must be big
x > 10 && none != None
  x = 3
x > 1 && none != None
  x = 3
  none = None
3

The second and third assertions show &&: when x > 10 is already false, none != None is never reached, so it is not reported.

Notes

  • assert replaces the usual hand-written if (!cond) throw ...; guard and gives the failure a uniform report, the operand values and a reporter hook. A test runner such as Sonar reports a failed assert as a failed test and a violated pre in the code under test as an error.
  • In a comptime evaluation, a failed assert is a compile error carrying the report text, without operands or location.

See also

  • Contracts: pre, post, old — Preconditions and postconditions written after a parameter list, the old(...) capture, how violations are raised and reported, and how contracts are inherited, proven and used to narrow types.
  • Invariants — invariant(expr) members of a class or struct, when they are checked, and the access rules that make them reliable.
  • ContractViolation — A violated contract: a failed pre, post, assert or invariant.
  • IContractReporter — Receives every contract violation before it is thrown.