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
-
Clauses go after the parameter list and before the body, on free and namespace functions, methods, static methods, constructors, accessors (
get,set, typedget), operators, interface methods and expression-bodied forms. Several may be written, in any order; each kind is checked in written order. -
Every predicate must be a
bool, under the rule anifcondition follows:error: precondition has type 'int', expected 'bool'The same holds for
postcondition,assertionandinvariant. -
No predicate may assign or
await:error: a contract predicate cannot assign error: a contract predicate cannot await -
A
presees the parameters and, outside constructors,thisand its fields. A constructor'sprecannot readthisor its fields, because they are not assigned yet:error: a constructor's precondition cannot read 'this' or its fields -
A
postsees the parameters,thisand, withpost(r: ...), the result under the namer. 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 nothingThe second error is for a
voidfunction, a constructor and asetaccessor. -
old(e)inside apostis the value ofeat 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 lambdaTo use an entry value in a lambda, pass the captured value to a helper function:
post(r: allAbove(r, old(limit))). Outside apost,oldis an ordinary name:old(x)in apre, anassertor aninvariantcalls a function namedoldif 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 (writeold(obj.field)to capture state); of a string, the string. -
A parameter named anywhere in a
post, including insideold(...), is read-only in the body. Every way of writing to it is rejected: assignment, compound assignment, element store, struct field store, amutatingcall and a write from a lambda.error: cannot assign to parameter 'x': a postcondition names it -
A forward declaration cannot carry clauses. A bodiless callable that is not an interface method (a native function, an
@externdeclaration) 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 -
A function whose declared return type is
Promise<...>cannot have apost. It may havepres:error: a postcondition on a Promise-returning function is not supported yet
Tiers and evaluation
-
Every clause is always on unless written with
@Debug. Nothing turns an always-on check off. -
@Debugchecks run in the default build (--profile debug), are dropped by--profile releaseand run again under--profile release --debug-checks. A dropped check is not evaluated. -
A
@Debugcheck never narrows and never makes a call skippable. Its predicate must be pure:error: a '@Debug' predicate must be pure: <reason>@Debugis allowed only directly beforepre,post,assertorinvariant; anywhere else it is'@Debug' marks a contract clause: write it directly before 'pre', 'post', 'assert' or 'invariant'. -
Each predicate is evaluated exactly once per check, left to right, with
&&and||short-circuiting.
When checks run
- A
preruns on entry, after the arguments are bound, in written order. The first false one raises. A call the compiler proved satisfied skips the always-onpres;@Debugpres still run. - The
oldcaptures run after thepres and before the body, in the order theoldexpressions appear. An exception during a capture is a violation of thepostthat contains it, with the exception attached, and it is raised before the body runs. - A
postruns on every normal return, falling off the end included, after the function'susingcleanups, in written order with inherited postconditions first. It never runs when an exception leaves the function. - Object invariants are checked by the caller after a call returns normally; see
lang.invariants. Anassertchecks where it stands; seelang.assert.
Inheritance and interfaces
-
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' -
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.
-
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.
-
The effective postcondition is the AND of every base's effective postconditions, in base order, followed by the callable's own.
-
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).
-
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' -
Dynamic dispatch reaches the run-time target's effective contracts.
Compile-time outcomes
-
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
prewith 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' -
If every always-on clause is definitely true, a call of a function, a static method, a method on implicit
thisor a constructor skips those checks. A call on an explicit receiver (obj.m(x)) keeps its checks.@Debugpres,oldcaptures,posts and invariants are unchanged either way. If the compiler cannot decide, the call is checked. -
Known values are literal expressions (literals, negated literals, literal arithmetic),
trueandfalse, string literals,None, aconstglobal orconstlocal initialized by a literal expression, and type facts: a parameter compared withNoneis decided by the argument's static type, and a parameter tested withis Tby its static class. Aconstglobal 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, andunknown || trueis unknown, because the left side may raise. Acomptimename, a call, a field,thisor a non-constname is unknown. A call through dynamic dispatch is always unknown.leviathan --contract-auditlists every outcome (lang.compiler-cli).
Narrowing
- The non-
@Debugpres of a callable narrow its body, in order: afterpre(s != None),sis astringin the body. The usual narrowing rules apply (an assignment ends the fact; a mutable field never narrows). - A non-
@Debugassert(c)narrows the statements after it byc's facts (lang.assert). - A call whose target has a non-
@Debugpost(r: r != None)orpost(r: r is T), alone or in an&&chain, has the narrowed type. A caller'sf() != Noneis then the usualcan never be Noneerror. - A call
p(a1, ..., an)in a condition (anif, awhile, apre, anassert, an&&or||operand) whose target is a non-generic callable with a body of one expression built only from its parameters,None,istests,==and!=againstNone,!,&&and||, gives the facts that expression gives, with each parameter replaced by its argument.
Violations, reporting and the reporter
-
A failed check raises
ContractViolation, anIExceptionand anILogicException, not anException. Ordinary code catchesException; a boundary (a test runner, a request loop, a top-level reporter) catchesIException. -
An exception thrown while a predicate is evaluated is a violation of that clause, with the exception in
attachedand no operand values. -
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, callsreport(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 thebind: a local, parameter or field at the call site that shadows one of them does not change it. -
The binding is
bind IContractReporter => ...;, withuse std::IContractReporter;in the file. A top-levelbindin any file of the program is program-wide, dependencies included. Abindinside 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. -
reportreturnsvoid. When it returns, the violation continues. An exception it throws is added toattachedand the violation continues. A violation raised while a binding is evaluated orreportruns calls no reporter: it is added toattachedtoo. A reporter that must stop the process callsenv::exit, which ends it with no unwinding: nousingcleanup, nocatch. -
An uncaught violation prints
Uncaught ContractViolation: <message>on standard output and exits with status1, like every exception. The message has the formprecondition violated: cents > 0 in withdraw at pre_basic.lev:4:9 called from pre_basic.lev:29:9 cents = -5Locations are
file:line:columnwith the file's base name. Operands whose text equals their value (0 = 0) are left out. A user message fromassert(e, message)adds amessage:line, and each attached exception anattached: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 catchesIException. A violation is not anExceptionon purpose, so acatch (Exception e)meant for a failed file read cannot swallow a broken contract. pre,postandoldare contextual words.pre(andpost(directly after a parameter list or after another clause are always clauses; anywhere elsepre,postandoldare ordinary names (a function, a local or a parameter may be calledpre). A one-statement body that calls a function namedpreorpostmust be written with braces:void f() { pre(1); }.assertandinvariantare reserved (lang.keywords).- Rule 31 is not limited to programs that use contracts. It applies in a plain
iforwhiletoo, 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 onx. - Limits you may meet:
- Contracts cannot be written on lambdas.
- A function returning
Promise<...>cannot have apost. - 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
comptimeevaluation, a violation of thepres andposts written on the called function, and ofasserts, 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()andnext()), theclose()of ausing, a bare accessor read on implicitthisand 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. Afor-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,assertorinvariant. - IContractReporter — Receives every contract violation before it is thrown.