LEVIATHAN vd52e79c4 · d52e79c486

Declarations

Invariants

invariant(expr) members of a class or struct, when they are checked, and the access rules that make them reliable.

since 0.1.0-alpha.1linuxwindowswasm

Description

invariant(expr); is a member of a class or struct body. It states a condition every object of the type keeps true whenever outside code can see it. @Debug invariant(expr); is dropped by --profile release and runs again under --profile release --debug-checks (lang.contracts).

An invariant is checked at the object's boundary, by the code that called it, after the call returns normally:

  • after a construction of the class: an explicit C(...), a labeled constructor, memberwise construction, and the automatic construction of a bare field, local or global;
  • after a call of any method, accessor (get/set, indexer) or user operator whose receiver is not this, whatever the member's access: other.drop(c) on a private drop checks other;
  • for a struct, only after constructions and mutating calls on a receiver other than this.

A call on a receiver whose type is a type parameter (void g<T>(T x) { x.drain(); }) is a boundary too. Generics are erased, so the call checks the invariants of whichever class the receiver turns out to be.

A call on this (bare this, this.m(), this.Base::m() and a bare m() inside the class) is not a boundary, so a method may break the invariant temporarily and a later call on this may restore it. A local alias of this is not this. An invariant is not checked after a base-constructor call inside a constructor, or when an exception leaves the call.

The invariants checked are those of the receiver's run-time class: every invariant declared by it and its ancestors, base first (depth first over the base list in declaration order, each class once), then its own, in written order.

For this to be reliable an invariant may read only state that outside code cannot change without going through the class. The compiler enforces that.

Rules

  1. invariant(expr); and @Debug invariant(expr); are class and struct body members. They take no access marker, modifier or doc comment:

    error: an invariant takes no access marker or modifier
    

    An interface cannot declare one (an interface cannot declare an invariant), and at statement position invariant is an error ('invariant' declares a class or struct member).

  2. invariant is a reserved word and cannot name a variable, parameter, function, field, member or type ('invariant' is a reserved word).

  3. The predicate must be a bool and cannot assign or await. An @Debug invariant must be pure.

  4. An invariant may read only fields of this (bare or this.f) and constants:

    error: an invariant may read only fields of 'this'
    
  5. Every field an invariant reads must be one that outside code cannot write: private, protected, readonly or const, or a field with a set accessor (an outside write runs the setter, which is a boundary):

    error: an invariant may read only private, protected or readonly fields: 'x' is public and writable
    
  6. The fields an invariant reads include those read by a one-expression method of the class that the invariant calls on this, or a one-expression get accessor it reads on this, followed transitively. Any other method or accessor is not followed.

  7. A field that any invariant reads, its own class's or a base's, may be written only through this. A write whose first field step from another receiver reaches such a field is an error: other.f = v, other.items[i] = v, other.pos.x = v, a mutating call such as other.pos.bump(), and the struct copy form Point p = this; p.x = v;:

    error: field 'f' is read by the invariant of 'C'; assign it through 'this', or call a method on the other object
    

    Reading other.f is allowed.

  8. A generic class's invariant cannot use a member of a type-parameter value (an invariant cannot use a member of type parameter 'T').

  9. Only fields of this are tracked: a deeper step (pos.x where pos is a field) is governed by the invariants of pos's own class.

  10. The standard library declares no invariants.

  11. A violation is a ContractViolation of kind Invariant, reported at the call that returned (lang.contracts):

    invariant violated: balance >= 0
      in Account at invariants.lev:6:15
      called from invariants.lev:36:11
      balance = -4
    

Examples

Invariants at construction, calls and struct mutation

use io::console;

class Account {
private:
    int balance;
    invariant(balance >= 0);
    void drop(int c) { balance = balance - c; }
public:
    new Account(int start) { balance = start; }
    int amount() => balance;
    void withdraw(int c) { balance = balance - c; }
    void withdrawThenRefund(int c) {
        this.drop(c);
        this.drop(0 - c);
    }
    void dropOther(Account other, int c) { other.drop(c); }
    bool richerThan(Account other) => balance > other.balance;
}

struct Meter {
private:
    int v;
    invariant(v <= 10);
public:
    new Meter(int start) { v = start; }
    int value() => v;
    mutating void bump(int k) { v = v + k; }
}

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

void main() {
    Account a = Account(5);
    a.withdrawThenRefund(100);
    console.writeln(a.amount());
    Account b = Account(1);
    console.writeln(a.richerThan(b));
    try { a.withdraw(9); } catch (ContractViolation v) { show(v); }
    try {
        Account bad = Account(-3);
        console.writeln(bad.amount());
    } catch (ContractViolation v) {
        show(v);
    }
    Account c = Account(2);
    Account d = Account(10);
    try { d.dropOther(c, 7); } catch (ContractViolation v) { show(v); }
    console.writeln(d.amount());
    Meter m = Meter(1);
    m.bump(4);
    console.writeln(m.value());
    try { m.bump(20); } catch (ContractViolation v) { show(v); }
}
main();
5
true
balance >= 0 in Account
  balance = -4
balance >= 0 in Account
  balance = -3
balance >= 0 in Account
  balance = -5
10
5
v <= 10 in Meter
  v = 25

withdrawThenRefund breaks the invariant between its two this.drop calls and restores it; nothing is checked until it returns. a.withdraw(9) and Account(-3) are checked and fail. d.dropOther(c, 7) fails with the invariant of c, because the private call is made on a receiver other than this. Reading other.balance in richerThan is allowed.

Writing an invariant field of another object is rejected, since that write would bypass the check:

class Account {
private:
    int balance = 0;
    invariant(balance >= 0);
public:
    void copyFrom(Account other) { other.balance = 3; }
}
// error: field 'balance' is read by the invariant of 'Account'; assign it through 'this', or call a method on the other object

Notes

  • The check runs in the caller, so a class that is subclassed is checked by the run-time class of the object: a subclass with more invariants gets all of them checked.
  • A call written inside the standard library checks only invariants the library declares, which are none. 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 for-in loop performs no invariant check on the object it iterates: the implicit iterator() and next() calls are not boundaries.

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.
  • 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.
  • ContractViolation — A violated contract: a failed pre, post, assert or invariant.
  • Classes — Declare reference types with fields, methods, constructors and accessors, with generics and inheritance from one or more base classes.
  • Value structs — Declare value types that are copied on every assignment, pass and return, with derived equality and explicit mutating methods.