DEVELOPMENT EDITION · 769442725406
Verification Manual
On this page

Contracts and modular reasoning

A useful contract connects an operation's accepted inputs, effects and outcomes. It lets you verify the operation once and reason about its callers without re-reading its body. This chapter develops that reasoning. The Language Reference owns exact placement, visibility, legality and inherited-contract rules for each syntax.

The call boundary

At a call, establish the callee's parameter subtype conditions, precondition, applicable type invariants and alias/ownership requirements. After normal return, use its result/output subtype facts, effective postcondition, and supported frame/effect facts. Within the callee, the corresponding input premises are assumptions; the implementation proves its output guarantees and internal checks.

Situation Proper specification question
Increment may overflow Which input domain is actually intended, and how is the boundary handled?
Caller needs the answer to equal input plus one Does the postcondition state that relation?
Caller needs an unchanged container length Is length preservation promised?
Operation can reject input by user exception Which exceptional outcomes and consequences are permitted?
Hidden representation must remain valid Which invariant defines valid externally observable values?

Keep responsibilities balanced. A very restrictive precondition may make a body easy to prove while making its API unusable. A weak postcondition can let a body prove while leaving callers unable to establish the required application behavior.

Repair a missing callee guarantee

The contract repair projects contain a correct increment and a client asserting that incrementing 41 returns 42. The unrepaired operation already excludes overflow, but has no result relation in its interface. Its body uses a local next_value then returns it; the caller reasons through an ordinary modular contract, rather than relying on automatic expansion of a single-return expression function.

Select one before project:

veradic prove --no-cache --project docs/manuals/examples/verification/contract/vibe/before/verada.toml

Replace vibe with vada or varc for the other versions. The proof reports B5105 at the client assertion. This is not evidence that an actual call returned the wrong answer. The interface exposes too little to establish that it returned the right one.

The repaired interface adds the same guarantee in all three presentations:

Syntax Precondition Added postcondition
Vada Pre => Value < Natural'Last Post => Increment'Result = Value + 1
Varc requires Value < Natural::Last ensures result == Value + 1
Vibe requires(value < Natural.last) ensures(result == value + 1)

These are contract fragments from complete maintained projects. The implementation remains the same. Prove/run the matching after project; its client now proves and prints answer: 42. This repair strengthens the supplied guarantee instead of excluding an additional application input. It also creates a real obligation on the callee: a later body change returning the wrong value will fail its postcondition.

Preconditions and defined contract expressions

Write a precondition that states what the caller can establish using the public API. Avoid requiring access to private fields or mathematical facts that have no visible model. Every contract expression must itself be defined under the relevant premises. Before indexing array[index], establish valid bounds; before division, establish a nonzero divisor. Use the syntax's short-circuit Boolean form when the later operand requires the earlier fact. Plain non-short-circuit conjunction is not a replacement for guarded evaluation.

The precondition's own arithmetic can overflow too. Prefer a safe comparison such as left <= Natural'Last - right under known nonnegative bounds to an unguarded overflowing left + right <= Natural'Last. Use a mathematical model when the property is genuinely about unbounded arithmetic, and keep the conversion on the correct side of the operation.

Review whether the precondition is satisfiable. An operation that admits no inputs can prove every postcondition vacuously. B8003 is an important review signal even when the command exits successfully.

Old values, results, and frames

A result relation often uses entry state. Old/old(...) snapshots the permitted expression at operation entry, not immediately before the final assignment. A loop-entry snapshot is a different boundary. Snapshot expressions must obey their visibility, entry-known guard, and ownership restrictions; an old copy of an owning structure can create a prohibited alias.

For an operation replacing one element, useful guarantees include unchanged length, the new value at that position, and unchanged values at every other present position. Without a frame statement, “this one element became X” may not tell the caller enough about the rest. Do not infer an entire unchanged representation from a narrow postcondition.

The bounded/unbounded container APIs provide concrete examples of these contracts. Read them precisely: the bounded-vector Find_Index postcondition establishes a valid equal element when the result is nonzero, but does not itself establish completeness of a zero result or first-match minimality. A caller cannot silently use those stronger properties merely because the present implementation scans linearly. See the vector guide.

Contract cases

Cases organize distinct entry situations. Each consequence is required when its guard held on entry. Completeness and disjointness are additional obligations: a collection of overlapping or missing cases is not automatically an adequate specification. others covers the remaining entry situations while preserving the required disjointness of the explicit guards.

The searching corpus illustrates a strong Find: if a key exists, the result is a valid matching index with no earlier match; otherwise it is zero. The corresponding loop invariant states that previously inspected elements differ from the key. Compare its weaker Binary_Search postcondition, which only describes a nonzero answer: it is useful, but it does not promise successful discovery of every existing key. Specification strength is a design decision, not a consequence of the algorithm's name.

Vada and Varc write contract cases directly. In Vibe, state each case as a conditional ensures, or declare the operation in Vada or Varc and import it. A Refined_Post on a body is proved against that body; clients outside the package reason from the visible postcondition alone, so put what they need there.

Type invariants, predicates, and initialization

A subtype predicate describes the permitted values at its checked boundaries. A private type invariant describes the valid representation expected at supported abstraction boundaries. It is not necessarily required after every internal assignment. Temporarily breaking it can be valid inside a package implementation, but it must be restored before calling an operation that assumes it or exposing an output that promises it.

The internal-invariant diagnostic example sets a private counter's step to zero and then calls a ratio operation whose input invariant requires a positive step. The failure is at that call, even though the caller is inside the same package. Privacy is not permission to pass an invalid value into a proved assumption. Functions defining an invariant must not circularly assume the fact they are supposed to establish.

Default_Initial_Condition describes default-created values of a type. A package's Initial_Condition is proved to hold after the package's elaboration (B5110 when it might not). Both are distinct from a constructor's postcondition and from subtype predicates: a constructor should state the visible facts clients need.

Dispatch and callbacks

A dispatching call must be sound for every concrete operation it may invoke through the visible class-wide/interface contract. Pre'Class/Post'Class express the supported substitutability rules; replacing an ordinary specific precondition is not the same operation. Check the inherited rules in the shared reference.

An access-to-subprogram value has an operation-type contract. When designating a target, Verada checks the target against that promised interface, including the relationship between input assumptions and output guarantees. A callback table is not a collection of unchecked function addresses. The callback corpus exercises the generated substitutability obligations. Nested escaping subprogram pointers are not a general closure implementation.

For a foreign callback, also review the external caller's premises and ABI. Proof of a Verada target does not prove the foreign code passes valid pointers or obeys its precondition.

Generics and abstraction

Reason against the generic's formal types and operations, not an accidental property of one instance. If an algorithm needs ordering, a model relation, or a postcondition on a formal operation, that requirement belongs in its supported formal interface. A concrete instance with a familiar name does not make an unstated generic theorem true.

Instance identity and supported inference vary by frontend. Vibe's T: Ordered or supported Protocol bound exposes selected formal operations; it is not unrestricted structural typing. Cross-module containers and generic classes may need defining-module instances. Diagnose such legality/identity failures before attempting to repair proof with stronger assumptions.

Aspects that constrain state and effects

Several aspects add obligations beyond pre- and postconditions. Each is checked:

Aspect What Verada checks
Refined_Post The body establishes it (B5102 when it might not)
Initial_Condition It holds after the package's elaboration (B5110)
Constant_After_Elaboration Nothing changes the object after elaboration (B3024)
Side_Effects Only a function with it may write state, and it is called only as the whole value of an assignment or object declaration (B3006, B2029)
Program_Exit Its condition holds whenever the subprogram ends the program

Extensions_Visible is always true in Verada: a tagged parameter's extension is visible, and Extensions_Visible => False is rejected. Exact declarations and spellings are in aspects and pragmas.

A contract review procedure

Read the operation as a client first. List every assumption needed before the call and every fact used afterward. Then read the implementation against those promises. Check normal, exceptional and resource/ownership exits separately; test representative boundary calls. For each added precondition, explain why excluding the other inputs is acceptable. For each postcondition, ask whether another incorrect implementation could still satisfy it. That question often reveals the missing functional requirement.