LEVIATHAN vd52e79c4 · d52e79c486

Declarations

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.

since 0.1.0-alpha.1linuxwindowswasm

Description

A contract states what a function needs and what it promises. pre(expr) is a precondition: it must be true when the function is entered. post(expr) is a postcondition: it must be true when the function returns normally. Both are written after the parameter list and before the body, on any callable: free and namespace functions, methods, static methods, constructors (new), accessors (get/set), operators and interface methods, in block-bodied and => forms alike.

int withdraw(int balance, int cents)
    pre(cents > 0)
    pre(cents <= balance)
    post(r: r >= 0)
    => balance - cents;

Several pre and post clauses may be written, in any order. Each kind is checked in written order. Every predicate is an ordinary bool expression, evaluated once per check, left to right, with && and || short-circuiting. A predicate cannot assign and cannot await.

A pre sees the parameters and, except in a constructor, this and its fields. A post sees the parameters, this (in a constructor, the built object) and, when written post(r: ...), the function's result under the name r (any identifier that is not a parameter name). Inside a post, old(e) is the value of e as it was when the function was entered.

Every contract is always on unless it is written with @Debug in front (@Debug pre(...), @Debug post(...)). A @Debug check runs in the default build, is dropped entirely by --profile release and runs again under --profile release --debug-checks. A dropped check is not evaluated at all, so its predicate must be pure (it must not do anything that could be observed), and a @Debug check never narrows a type and never lets the compiler skip a call's checks.

When a check fails, the program raises a ContractViolation. The violation says which kind of check failed, the predicate text, the function, where the predicate is written, where the call was made, and the value of each operand of the predicate. A violation is reported, then it propagates like any exception. Reporting calls the IContractReporter that is bound at the call site, if there is one; with no binding nothing is called and the violation simply propagates.

A violation is an IException and an ILogicException, but not an Exception, so catch (Exception e) does not catch it and catch (IException e) does.

When the compiler can see that a call breaks a pre (a literal argument that makes the predicate false), it refuses the program instead. When it can see that a call satisfies every always-on pre, it skips those checks for that call. A pre that is true for the types involved (pre(s != None) and the argument is known not to be None) is skipped the same way. Contracts also feed type narrowing: after pre(s != None) the body can treat s as a non-optional string.

Rules

Where clauses go

  1. Clauses go after the parameter list and before the body, on free and namespace functions, methods, static methods, constructors, accessors (get, set, typed get), operators, interface methods and expression-bodied forms. Several may be written, in any order; each kind is checked in written order.

  2. Every predicate must be a bool, under the rule an if condition follows:

    error: precondition has type 'int', expected 'bool'
    

    The same holds for postcondition, assertion and invariant.

  3. No predicate may assign or await:

    error: a contract predicate cannot assign
    error: a contract predicate cannot await
    
  4. A pre sees the parameters and, outside constructors, this and its fields. A constructor's pre cannot read this or its fields, because they are not assigned yet:

    error: a constructor's precondition cannot read 'this' or its fields
    
  5. A post sees the parameters, this and, with post(r: ...), the result under the name r. The result name must not be a parameter name, and the function must return something:

    error: the result name 'r' is also a parameter of 'f'
    error: 'post(r: ...)' names a result, but 'f' returns nothing
    

    The second error is for a void function, a constructor and a set accessor.

  6. old(e) inside a post is the value of e at entry. It cannot be nested, cannot read the result and cannot appear inside a lambda:

    error: 'old' cannot be nested
    error: 'old(...)' cannot read the result 'r'
    error: 'old(...)' cannot appear inside a lambda
    

    To use an entry value in a lambda, pass the captured value to a helper function: post(r: allAbove(r, old(limit))). Outside a post, old is an ordinary name: old(x) in a pre, an assert or an invariant calls a function named old if one is in scope, and is otherwise the error 'old(...)' is allowed only inside a 'post' clause. The capture of an array, map or set shares the value with the usual copy-on-write rules; of a value struct, it is a copy taken on every call; of a class reference, it is the reference (write old(obj.field) to capture state); of a string, the string.

  7. A parameter named anywhere in a post, including inside old(...), is read-only in the body. Every way of writing to it is rejected: assignment, compound assignment, element store, struct field store, a mutating call and a write from a lambda.

    error: cannot assign to parameter 'x': a postcondition names it
    
  8. A forward declaration cannot carry clauses. A bodiless callable that is not an interface method (a native function, an @extern declaration) cannot carry clauses either:

    error: a forward declaration cannot carry contracts; put them on the definition of 'f'
    error: contracts need a body: 'f' has none
    
  9. A function whose declared return type is Promise<...> cannot have a post. It may have pres:

    error: a postcondition on a Promise-returning function is not supported yet
    

Tiers and evaluation

  1. Every clause is always on unless written with @Debug. Nothing turns an always-on check off.

  2. @Debug checks run in the default build (--profile debug), are dropped by --profile release and run again under --profile release --debug-checks. A dropped check is not evaluated.

  3. A @Debug check never narrows and never makes a call skippable. Its predicate must be pure:

    error: a '@Debug' predicate must be pure: <reason>
    

    @Debug is allowed only directly before pre, post, assert or invariant; anywhere else it is '@Debug' marks a contract clause: write it directly before 'pre', 'post', 'assert' or 'invariant'.

  4. Each predicate is evaluated exactly once per check, left to right, with && and || short-circuiting.

When checks run

  1. A pre runs on entry, after the arguments are bound, in written order. The first false one raises. A call the compiler proved satisfied skips the always-on pres; @Debug pres still run.
  2. The old captures run after the pres and before the body, in the order the old expressions appear. An exception during a capture is a violation of the post that contains it, with the exception attached, and it is raised before the body runs.
  3. A post runs on every normal return, falling off the end included, after the function's using cleanups, in written order with inherited postconditions first. It never runs when an exception leaves the function.
  4. Object invariants are checked by the caller after a call returns normally; see lang.invariants. An assert checks where it stands; see lang.assert.

Inheritance and interfaces

  1. An override (a method, accessor or operator that overrides a base member) cannot write pre. It inherits the base's:

    error: an override cannot declare 'pre'; 'f' inherits the preconditions of 'Base.f'
    
  2. An implementation of an interface method inherits that method's contracts. The link is the signature: the parameter types and the result, seen through the type arguments of the base clause. A member with the same name and a different signature is an overload and inherits nothing. There is one exception: when the signatures differ, the contracts still link if the interface has one requirement of that name and parameter count and the class has one member of that name and count (an implementation with a narrower result, for example). Operators and indexers always need the signature.

  3. The effective precondition of a callable is the OR of its bases' effective preconditions, each base contributing the AND of its own clauses. If any base contributes no clause at all, nothing is checked, so no caller of any base is broken. A callable with no base has one group, its own clauses.

  4. The effective postcondition is the AND of every base's effective postconditions, in base order, followed by the callable's own.

  5. Inherited predicates bind the callable's parameters by position and are evaluated in the context of the base that declared them (its field names, its private members).

  6. A class that inherits from a base class a method that satisfies an interface requirement carrying contracts, without inheriting the requirement itself, is an error:

    error: 'B.f' implements 'I.f' for 'C' but does not carry its contracts; override 'f' in 'C'
    

    A data field that satisfies an interface accessor carrying contracts is the same mistake, because a field has nowhere to run them:

    error: 'C.v' implements 'I.v' for 'C' but does not carry its contracts; write an accessor 'v' in 'C'
    
  7. Dynamic dispatch reaches the run-time target's effective contracts.

Compile-time outcomes

  1. For a call whose target is known at compile time and whose always-on preconditions form exactly one group, the compiler evaluates each always-on, pure pre with the call's arguments. A clause that is definitely false is a compile error at the call, unless the call is written in the body of a declaration marked @Violates (lambdas in it included), where it is checked at run time instead:

    error: this call violates the precondition 'c > 0' of 'withdraw'
    
  2. If every always-on clause is definitely true, a call of a function, a static method, a method on implicit this or a constructor skips those checks. A call on an explicit receiver (obj.m(x)) keeps its checks. @Debug pres, old captures, posts and invariants are unchanged either way. If the compiler cannot decide, the call is checked.

  3. Known values are literal expressions (literals, negated literals, literal arithmetic), true and false, string literals, None, a const global or const local initialized by a literal expression, and type facts: a parameter compared with None is decided by the argument's static type, and a parameter tested with is T by its static class. A const global is not a known value inside a global initializer, and not anywhere if an initializer that runs before its own is not a literal, because that initializer may call a function that reads it. (Automatic constructions run first, then namespace variables and static fields in source order, then top-level variables in source order.) Arithmetic uses the run-time rules (wrapping integers). An evaluation error such as division by zero makes the clause violated. &&, || and ! short-circuit, and unknown || true is unknown, because the left side may raise. A comptime name, a call, a field, this or a non-const name is unknown. A call through dynamic dispatch is always unknown. leviathan --contract-audit lists every outcome (lang.compiler-cli).

Narrowing

  1. The non-@Debug pres of a callable narrow its body, in order: after pre(s != None), s is a string in the body. The usual narrowing rules apply (an assignment ends the fact; a mutable field never narrows).
  2. A non-@Debug assert(c) narrows the statements after it by c's facts (lang.assert).
  3. A call whose target has a non-@Debug post(r: r != None) or post(r: r is T), alone or in an && chain, has the narrowed type. A caller's f() != None is then the usual can never be None error.
  4. A call p(a1, ..., an) in a condition (an if, a while, a pre, an assert, an && or || operand) whose target is a non-generic callable with a body of one expression built only from its parameters, None, is tests, == and != against None, !, && and ||, gives the facts that expression gives, with each parameter replaced by its argument.

Violations, reporting and the reporter

  1. A failed check raises ContractViolation, an IException and an ILogicException, not an Exception. Ordinary code catches Exception; a boundary (a test runner, a request loop, a top-level reporter) catches IException.

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

  3. Reporting happens before any user handler sees the violation, at the innermost call site that can know. That site fills in callerLocation, evaluates the reporter binding active there, calls report(v), marks the violation reported and lets it propagate. A violation is reported once. A check that passes constructs nothing. The binding's names mean what they mean at the bind: a local, parameter or field at the call site that shadows one of them does not change it.

  4. The binding is bind IContractReporter => ...;, with use std::IContractReporter; in the file. A top-level bind in any file of the program is program-wide, dependencies included. A bind inside a function body covers the calls written in that body, lambdas written there included, and not the calls the callee makes. With no active binding nothing is called; use std::IContractReporter; alone activates nothing.

  5. report returns void. When it returns, the violation continues. An exception it throws is added to attached and the violation continues. A violation raised while a binding is evaluated or report runs calls no reporter: it is added to attached too. A reporter that must stop the process calls env::exit, which ends it with no unwinding: no using cleanup, no catch.

  6. An uncaught violation prints Uncaught ContractViolation: <message> on standard output and exits with status 1, like every exception. The message has the form

    precondition violated: cents > 0
      in withdraw at pre_basic.lev:4:9
      called from pre_basic.lev:29:9
      cents = -5
    

    Locations are file:line:column with the file's base name. Operands whose text equals their value (0 = 0) are left out. A user message from assert(e, message) adds a message: line, and each attached exception an attached: line.

Examples

A function with two preconditions. The first false one is reported, and it carries the operands of the predicate. catch (Exception e) does not catch it; catch (IException e) does:

Preconditions, the violation and what it carries

use io::console;

int withdraw(int balance, int cents)
    pre(cents > 0)
    pre(cents <= balance)
    => balance - cents;

void show(ContractViolation v) {
    console.writeln(v.predicate);
    console.writeln(v.function);
    for (ContractOperand o in v.operands) console.writeln(o.text + " = " + o.value);
}

void main() {
    int big = 500;
    int neg = -5;
    console.writeln(withdraw(100, 30));
    try {
        withdraw(100, big);
    } catch (Exception e) {
        console.writeln("wrong: Exception caught it");
    } catch (IException e) {
        console.writeln("IException caught it");
        if (e is ContractViolation) show(e);
    }
    try {
        withdraw(100, neg);
    } catch (ContractViolation v) {
        console.writeln(v.kind == ContractKind::Precondition);
        show(v);
    }
}
main();
70
IException caught it
cents <= balance
withdraw
cents = 500
balance = 100
true
cents > 0
withdraw
cents = -5
0 = 0

A call the compiler can see breaks a precondition is rejected, and the message names the clause and the function. Put the argument behind a variable, or write the call in a declaration marked @Violates (in a test), when the violation is intended:

int withdraw(int balance, int cents) pre(cents > 0) => balance - cents;
int left = withdraw(100, -5);
// error: this call violates the precondition 'cents > 0' of 'withdraw'

Postconditions run after the function's cleanups and never when an exception leaves the function. old(...) reads the entry value:

Postconditions and old

use io::console;

int closes = 0;

class Res : IDisposable {
    void close() { closes = closes + 1; }
}

int addTo(int a, int b)
    post(r: r >= a)
    => a + b;

class Box {
private:
    int items = 0;
public:
    int count() => items;
    void add(int k)
        post(items == old(items) + k)
    {
        items = items + k;
        if (k == 13) items = items + 1;
    }
}

int afterClose()
    post(closes == 1)
{
    using Res res = Res();
    return 7;
}

int leavesEarly(int x)
    post(r: r > 1000)
{
    if (x > 0) throw RuntimeException("left early");
    return x;
}

void show(ContractViolation v) {
    console.writeln(v.predicate + " in " + v.function);
    for (ContractOperand o in v.operands) console.writeln("  " + o.text + " = " + o.value);
}

void main() {
    int two = 2;
    int minus = -5;
    console.writeln(addTo(1, two));
    try { addTo(1, minus); } catch (ContractViolation v) { show(v); }
    Box b = Box();
    b.add(2);
    console.writeln(b.count());
    try { b.add(13); } catch (ContractViolation v) { show(v); }
    console.writeln(afterClose());
    try {
        leavesEarly(5);
    } catch (ContractViolation v) {
        console.writeln("wrong: post checked");
    } catch (RuntimeException e) {
        console.writeln("post not checked: " + e.message);
    }
}
main();
3
r >= a in addTo
  r = -4
  a = 1
2
items == old(items) + k in Box.add
  items = 16
  old(items) + k = 15
7
post not checked: left early

Contracts narrow types. pre(s != None) makes s a string in the body, post(r: r != None) makes the call's result non-optional and assert(u != None) narrows the statements after it; a predicate function such as isPresent narrows through its one-expression body:

Narrowing through contracts

use io::console;

int len(string? s) pre(s != None) => s.length();

string? find(int k) post(r: r != None) => k > 0 ? "found" : "zero";

bool isPresent(string? s) => s != None;

int len2(string? s) pre(isPresent(s)) => s.length();

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

void main() {
    string? t = find(1);
    console.writeln(len(t));
    console.writeln(find(2).length());
    string? u = pick(true);
    assert(u != None);
    console.writeln(u.length());
    string? w = pick(true);
    console.writeln(len2(w));
    if (isPresent(w)) console.writeln(w.length());
}
main();
5
5
3
3
3

Contracts are inherited. An override keeps the base's pre, an implementation of an interface method keeps the interface's, and postconditions add up:

Inherited contracts

use io::console;

class Shape {
    int scale(int k) pre(k > 0) => k * 2;
    int area() post(r: r >= 0) => 0;
}

class Square : Shape {
    int side = 3;
    int scale(int k) => k * side;
    int area() post(r: r < 100) => side * side;
}

interface ISized {
    int resize(int n) pre(n <= 10);
}

class Panel : ISized {
    int resize(int n) => n + 1;
}

void main() {
    Shape s = Square();
    int bad = -1;
    console.writeln(s.scale(2));
    try { s.scale(bad); } catch (ContractViolation v) { console.writeln(v.function + ": " + v.predicate); }
    ISized p = Panel();
    int big = 11;
    console.writeln(p.resize(1));
    try { p.resize(big); } catch (ContractViolation v) { console.writeln(v.function + ": " + v.predicate); }
    Square q = Square();
    q.side = 20;
    try { q.area(); } catch (ContractViolation v) { console.writeln(v.function + ": " + v.predicate); }
}
main();
6
Square.scale: k > 0
2
Panel.resize: n <= 10
Square.area: r < 100

@Debug clauses run in the default build only. This program prints the following in the default build; with --profile release the @Debug check is dropped and checkedHalf(3) prints 1, and with --profile release --debug-checks it is back:

A debug-tier and an always-on precondition

use io::console;

int checkedHalf(int n)
    @Debug pre(n % 2 == 0)
    pre(n >= 0)
    => n / 2;

void main() {
    int three = 3;
    int neg = -2;
    try { console.writeln(checkedHalf(three)); } catch (ContractViolation v) { console.writeln("debug check: " + v.predicate); }
    try { console.writeln(checkedHalf(neg)); } catch (ContractViolation v) { console.writeln("always check: " + v.predicate); }
}
main();
debug check: n % 2 == 0
always check: n >= 0

A reporter sees every violation before any handler does. Float operands print in the language's float format, shortest round-trip digits in scientific notation:

A reporter bound for the whole file

use io::console;
use std::IContractReporter;

class Logger : IContractReporter {
    void report(ContractViolation v) {
        console.writeln("report: " + v.predicate + " in " + v.function);
    }
}

bind IContractReporter => Logger();

float half(float x) pre(x >= 0.0) => x / 2.0;

void main() {
    float neg = -1.5;
    try {
        half(neg);
    } catch (IException e) {
        if (e is ContractViolation) {
            for (ContractOperand o in e.operands) console.writeln(o.text + " = " + o.value);
        }
    }
}
main();
report: x >= 0.0 in half
x = -1.5e0
0.0 = 0.0e0

Notes

  • Ordinary code catches Exception; a boundary catches IException. A violation is not an Exception on purpose, so a catch (Exception e) meant for a failed file read cannot swallow a broken contract.
  • pre, post and old are contextual words. pre( and post( directly after a parameter list or after another clause are always clauses; anywhere else pre, post and old are ordinary names (a function, a local or a parameter may be called pre). A one-statement body that calls a function named pre or post must be written with braces: void f() { pre(1); }. assert and invariant are reserved (lang.keywords).
  • Rule 31 is not limited to programs that use contracts. It applies in a plain if or while too, and a narrowed argument can change which overload a later call picks, as writing the test inline would. A fact ends when a later argument of the same call writes the path: q(x, x = v) gives no fact on x.
  • Limits you may meet:
    • Contracts cannot be written on lambdas.
    • A function returning Promise<...> cannot have a post.
    • The compiler does not prove anything about calls through dynamic dispatch: they are always checked.
    • A call written inside the standard library checks only invariants declared in the standard library, which declares none, so an invariant of your own class is checked at every boundary written in your program, including your call into a library function that is handed the object, but not at a call the library makes itself.
    • A violation raised under a standard-library call site propagates to the nearest call site in your program, and is reported there, with that site's location and reporter.
    • A failed multi-group precondition (an override whose bases disagree) reports the first group's failing clause and no operand values.
    • Inside a comptime evaluation, a violation of the pres and posts written on the called function, and of asserts, is a compile error carrying the report text with no operands and no location; inherited contracts and invariants are not checked at compile time.
    • The implicit calls of a for-in loop (iterator() and next()), the close() of a using, a bare accessor read on implicit this and a static accessor are not call sites: the function they call still checks its own contracts, and a violation is reported at the next call site up the stack. A for-in loop does not check the invariants of the object it iterates.

See also

  • 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.
  • 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.