This chapter describes the mechanisms for defining and enforcing contracts introduced in Ada 2012. The general idea is that we add aspects defining certain requirements on the behaviour of an entity such as a subprogram and then, when the subprogram is executed, if any of these requirements are not met, an exception is raised.
As well as specifying pre- and postconditions on subprograms, we can also specify invariant properties of private types, and additional restrictions on the values of subtypes. These properties are all given by the use of aspect specifications briefly mentioned in Section 5.6.
Indeed, it was the introduction of pre- and postconditions that triggered the introduction of aspect specifications into Ada 2012. Moreover, as mentioned in Chapter 9, these in turn triggered the introduction of conditional and quantified expressions.
We start by giving further details of the rules regarding aspect specifications.
Aspect specifications
As we saw in Section 15.5 we can apply an aspect such as No_Return to a procedure using an aspect specification. We can supply several aspects by a series of aspect specifications as follows
procedure Do_It( … )
with Inline, No_Return;
In the general case an aspect specification supplies an expression for the aspect following =>. In the case of both Inline and No_Return, these aspects take a Boolean value so we could pedantically write
procedure Do_It ( … )
with No_Return => True,
Inline => True;
There is a general rule that if an aspect requires a Boolean value then it can be omitted and by default is taken to be true. But this does not apply to the aspects Default_Value and Default_Component_Value, see Sections 6.8 and 8.2.
As we see, aspect specifications are introduced by the reserved word with and if there are several they are separated by commas. The word with is used for a number of purposes (we have already met with clauses and type extensions) and this might be considered confusing. However, with a sensible layout there should be no problems.
In the case of a subprogram without a distinct specification, the aspect specification goes in the subprogram body before is thus
procedure Do_It( … )
with Inline is
…
begin
…
end Do_It;
This arrangement is because the aspect specification is very much part of the specification of the subprogram.