This chapter describes SWIG's support for software contracts. In the context of SWIG, a contract can be viewed as a constraint that is attached to a declaration. For example, you can easily attach argument checking rules, check the output values of a function and more. When one of the rules is violated by a script, a runtime exception is generated rather than having the program continue to execute.
%contract sqrt(double x) {
require:
x >= 0;
ensure:
sqrt >= 0;
}
...
double sqrt(double);
In this case, a contract is being added to the sqrt() function.
The %contract directive must always appear before the declaration
in question. Within the contract there are two sections, both of which
are optional. The require:
section specifies conditions that must hold before the function is called.
Typically, this is used to check argument values. The ensure: section
specifies conditions that must hold after the function is called. This is
often used to check return values or the state of the program. In both
cases, the conditions that must hold must be specified as boolean expressions.
In the above example, we're simply making sure that sqrt() returns a non-negative number (if it didn't, then it would be broken in some way).
Once a contract has been specified, it modifies the behavior of the resulting module. For example:
>>> example.sqrt(2) 1.4142135623730951 >>> example.sqrt(-2) Traceback (most recent call last): File "", line 1, in ? RuntimeError: Require assertion violation, in function sqrt( arg1>=0) >>>