Design By Contract for Rust
Annotate functions and methods with "contracts", using invariants, pre-conditions and post-conditions.
Design by contract is a popular method to augment code with formal interface specifications. These specifications are used to increase the correctness of the code by checking them as assertions at runtime.
(For a more complete example see the RangedInt test)
Set-up
At the moment, contracts
is not on crates.io, so it has to be added as a git-dependency.
[dependencies]
contracts = { git = "https://gitlab.com/karroffel/contracts" }
To bring all procedural macros into scope, you can add use contracts::*;
in all files you plan
to use the contract attributes.
Alternative use the "old-style" of importing macros to have them available in project-wide.
extern crate contracts;
TODOs
- add
test_pre
/test_post
/test_invariant
attributes which are only used in test configurations. This is useful to test implementations for "slow but obviously correct" alternative implementations. - add
debug_pre
/debug_post
/debug_invariant
attributes which usedebug_assert!
instead ofassert!
- add a static analyzer à la SPARK for whole-projects using the contracts to make static assertions.