<html>
<head>
 <meta charset="UTF-8">
<title>Support for contract based programming in C++</title>
<style type="text/css">
blockquote.std { color: #000000; background-color: #F1F1F1;
                 border: 1px solid #D1D1D1;
                 padding-left: 0.5em; padding-right: 0.5em; }
blockquote.stddel { text-decoration: line-through;
                    color: #000000; background-color: #FFA0A0;
                    border: 1px solid #ECD7EC;
                    padding-left: 0.5em; padding-right: 0.5em; }

blockquote.stdins { color: #000000; background-color: #A0FFA0;
                    border: 1px solid #B3EBB3; padding: 0.5em; }

blockquote.stdrepl { color: #000000; background-color: #FFFFA0;
                    border: 1px solid #EBEBB3; padding: 0.5em; }


ins { background-color:#A0FFA0; text-decoration: none }
del { background-color:#FFA0A0; text-decoration: line-through; }
#hidedel:checked ~ * del, #hidedel:checked ~ * del * { display:none; visibility:hidden }

tab { padding-left: 4em; }
tab3 { padding-left: 3em; }
</style>
</head>
<body>
<p align=right>
Document number:<b>P0542R5</b><br/>
Date: <b>2018-06-08</b><br/>
Audience: <b>Core Evolution Working Group</b>
<p align=right>
<br/>Reply to: J. Daniel Garcia (josedaniel.garcia@uc3m.es)
</p>

<BR><BR><HR>

<h1>Support for contract based programming in C++</h1>

<h2>G. Dos Reis, J. D. Garcia, J. Lakos, A. Meredith, N. Myers, B. Stroustrup</h2>

<h2>1. Introduction</h2>

This paper is based on P0380 (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf">P0380R1</a> <a href="#bib-contracts-design">[1]</a>).
All changes are relative to latest working draft (
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4727.pdf">N4727</a> <a href="#bib-cpp-draft">[2]</a>).

<h2>2. Summary of wording</h2>

<h3>2.1. A new attributes syntax</h3>

<p>
To simplify the way that contracts are specified, and in line with our previous design paper,
we propose a new syntax that may be used for attributes.
</p>

<p>
We propose this new syntax to be usable by attributes taking a single argument, which is a valid conditional expression.

<pre><b>
[[contract-attribute: conditional-expression]]
</b></pre>
where a <i>contract-attribute</i> is one of the following: <tt><b>expects</b></tt>, <tt><b>ensures</b></tt>, <tt><b>assert</b></tt>.
</p>

<p>
To avoid confusion, 
only the colon syntax for attributes is permitted in contract specifications
</p>

<p>
We also needed to support the idea of assertion levels needed by contracts.
For this reason, we have introduced the concept of an attribute modifier that may appear after the attribute token itself.

<pre><b>
[[contract-attribute modifier: conditional-expression]]
</b></pre>

In this way we may specify contracts with assertion levels easily.
We require that each attribute using the new proposed attribute syntax explicitly lists its accepted modifiers (if any).
</p>

<p>
In the case of contract attributes valid modifiers are:
<b><tt>axiom</tt></b>,
<b><tt>default</tt></b>, and
<b><tt>audit</tt></b>
</p>

<p>
Finally, we needed to introduce the ability to define the return value to be used in postconditions.
We allow, that an <tt>ensures</tt> attribute lists an identifier which is associated with the return value of a function.
<pre><b>
[[ensures modifier identifier: conditional-expression]
</b></pre>
</p>

<p>
With all this changes we can easily specify a contract:
<pre><b>
int f(int x)
  [[expects audit: x>0]]
  [[ensures axiom res: res>1]];

void g() {
  int x = f(5);
  int y = f(12);
  //...
  [[assert: x+y>0]]
</b></pre>
</p>

<p>
Note that while <tt><b>assert(expression)</b></tt> would expand as a function-like macro
with the appropriate header, <tt><b>assert:</b></tt> is not a function-like invocation, so
does not expand.
</p>


<h3>2.2. Functions versus function types</h3>

<p>
The current standard establishes a distinction between an attribute applied to a function and to the function type
(the normative text uses the form <i>"appertain to function type"</i>).
With that approach there would be a difference between the following cases:

<pre><b>
[[attribute]] void f(); // Attribute applied to function
void f [[attribute]] (); // Attribute applied to function
void f() [[attribute]]; // Attribute applied to function type
</b></pre>

Only the third option is interesting for contract attributes as the preconditions and postconditions need make use of function's parameters.

<pre><b>
void f(int x, int y)
  [[expects: x>0]]
  [[expects: y!=0]]
  [[ensures result: result > x+y]];
</b></pre>

Consequently contracts attributes (as any other attribute in that  syntactical location) <i>appertain to the function type</i>. However, they are not part of the function type.
</p>

<p>
Note that this does not solve the issue of being able to use attributes on lambda expressions (see Core issue 2097). 
In fact, until that issue is resolved it will not be possible to specify preconditions and postconditions for  lambda expressions.
</p>

<pre><b>
void f() {
  // Not currently supported
  auto increment = [](int x) [[expects: x>0]] { return x+1; };
  // ...
}
</b></pre>

<h3>2.3 Contracts repetition</h3>

<p>
We require that any redeclaration of a function either has the contract or completely omits it.
</p>
<pre><b>
int f(int x) 
  [[expects: x>0]]
  [[ensures r: r>0]];

int f(int x); // OK. No contract.

int f(int x)
  [[expects: x>=0]]; // Error missing ensures and different expects condition

int f(int x)
  [[expects: x>0]]
  [[ensures r: r>0]]; //OK. Same contract.
</b></pre>

<p>
Different argument names in redeclaration would be usually considered irrelevant.
<pre><b>
int f(int x) 
  [[expects: x>0]]
  [[ensures r: r>0]];

int f(int y)
  [[expects: y>0]]    // Should be OK
  [[ensures z: z>0]]; // Should be OK
</b></pre>
</p>

Consequently, we require that contracts are the same in redeclarations. 
That means that:

<ul>
  <li>Preconditions and postconditions appear in the same order.
  <li>Their modifiers are the same.
  <li>Each conditional expression would satisfy the ODR if it appeared in function definition, except for renaming of parameters and return value identifiers. 
</ul>

However, we do not require this to be diagnosed.

<h3>2.4 Structured bindings and postconditions</h3>

<p>
One might imagine using structured bindings in postconditions:
<pre><b>
std::tuple<int,string> f() 
  [[ensures [x,y]: x>0 && y.size()>0]];
</b></pre>
</p>

<p>
However, we decided that this is something that might be considered for a
future version. The same effect can be achieved currently as follows:

<pre><b>
std::tuple<int,string> f() 
  [[ensures r: get<0>(r)>0 && get<1>(r).size()>0]];
</b></pre>
</p>

<h3>2.5 Information of contract_violation</h3>

<p>
The information in <tt><b>contract_violation</b></tt> could be partially represented
by a <tt><b>source_location</b></tt> object, from the Library Fundamentals V2
Technical Specification.
</p>

<p>
However, we defer this decision for a future version of this proposal.
</p>

<h3>2.6 Name lookup of contracts</h3>

<p>
Name lookup resolution in contracts may interact with the use of different build modes.
</p>

<p>
There are two answers here. The first one would be to make resolution dependent on the
current build mode, requiring that only the contracts that would be evaluated in the
current build mode need to parse correctly and pass the name lookup.
</p>

<p>
A second solution would be to make name lookup independent of build mode. In that case,
all contracts would be required to pass name lookup independently of their assertion level.
We have selected this second solution.
</p>

<h3>2.7 Identical contracts</h3>

<p>
We are also requiring in the wording that a redeclaration of a function that contains
a contract needs to use the same contract (in the sense of ODR)
that was present in the first declaration of the function.
</p>

<p>
The exact meaning would be to require contracts to be lexically the same token by token.
This is a simpler definition, but would require that a redeclaration uses also the same
names for functions parameters (if/when they are used in the contract).
</p>

<p>
A second solution would be to require the contracts to be logically equivalent which seems
to introduce a number of additional implementation challenges.
</p>

<p>
A third option is to say that the functions must be textually equivalent except
for a change of (parameter) variable names, but otherwise having the same
structure. We have selected this option.
</p>

<p>
We have taken the route of requiring contract expressions to be odr-identical,
except for the change of function parameter names. Diagnostic, however, is not required.
</p>

<h3>2.8 Throwing violation handler</h3>

<p>
If a violation handler throws an exception, it is necessary to clarify what is the effect
when the continuation mode is <i>off</i>.
</p>

<p>
One option could be that the exception propagates as the handler did not
<i>return</i>. However, that design option would open the opportunity for continuation
when the continuation has been set to <i>off</i>.
</p>

<p>
Another design alternative would be to unconditionally invoke <tt><b>terminate()</b></tt>.
</p>

<h3>2.9 Additional information in contract violation</h3>

Besides original information in <tt><b>contract_violation</b></tt>, a new member
has been added to store the <tt><b>assertion_level</b></tt>. This value contains
a string with the <i>assertion-level</i> of the contract that has been violated.

<h3>2.10 Invoking the handler</h3>

<p>
The proposal does not support the direct invocation of the violation handler.
Allowing so, would imply access to handler supplied by the user.
</p>

<p>
Previous versions of this proposal included an <tt><b>always</b></tt> assertion
level. That level was introduced as a way to make it possible to invoke the 
violation handler. However, the mechanism seemed to be problematic when used
in interfaces. Addtionally, it resulted to be more controversial and not addressing
exactly initial intent.
</p>

<p>
Consequently, we have removed the <tt><b>always</b></tt> level from the current 
proposal and we may revisit alternative solutions in the future.
</p>

<h3>2.11 Initialization of contract_violation objects</h3>

<p>
When a contract is broken, a <tt><b>contract_violation</b></tt> needs to be created with
the corresponding information. There are several options on how such object should
be populated with information.
</p>

<p>
Among the available options, one could be to leave this details as something to be defined
by implementations. Otherwise, the exact population approach would need to be standardized.
</p>

<p>
This proposal establishes some constraints on the values that a contract violation object
should hold.
</p>

<ul>
<li><b>Information on source location</b>: 
<ul>
<li>In the case of a precondition violation the 
source location is implementation defined, although implementations are encouraged
to report the caller site.</li>
<li>In the case of a postcondition violation
the source location violation will be the one from the callee site.</li>
<li>In the case of an assertion,
the source location will be the one from the assertion itself.</li>
</li>
</ul>

<li><b>Comment</b>: 
It will contain an implementation-defined text relating to the 
<i>conditional-expression</i> of the contract that
was not satisified.
</li>

<li><b>Assertion level</b>: It will contain a string representation of the <i>assertion-level</i>
of the contract that has failed.
</li>
</ul>

<h3>2.12 Side effects in contracts</h3>

In general, contracts conditions are expected to be observable side-effect free.
This implies that any observable effect in a contract condition leads to undefined
behavior.

This was the direction taken by EWG in Jacksonville.

<p/>
<table border="1" cellpadding="5">
<thead>
  <tr>
    <td>Side effect is ill-formed</td>
    <td>Side effect is undefined</td>
  </tr>
</thead>
<tbody>
  <tr>
    <td>8</td>
    <td>16</td>
  </tr>
</tbody>
</table>

<p/>
This means that the modification of a global or a local in a contract expression is
undefined behavior. This also includes reading a volatile object.
<pre><b>
int x;
volatile int y;

void f(int n) [[expects: n&gt;x]]; // OK
void g(int n) [[expects: n&gt;x++]]; // Undefined behavior
void h(int n) [[expects: n++>0]]; // Undefined behavior
void j() {
  int n=3;
  [[assert: ++n&gt;3]]; // Undefined behavior
  //...
}
void k() [[expects: y&gt;0]]; // Undefined behavior
</b></pre>
<p/>

This also includes calling a function that potentially might modify a variable:

<pre><b>
bool might_increment(int & x);

void f(int n) [[expects: might_increment(n)]]; // Undefined behavior

bool is_valid(int x) {
  std::cerr &lt;&lt; "checking x\n";
  return x>0;
}

void g(int n) [[expects: is_valid(n)]]; // Undefined behavior
</b></pre>
<p//>

However, local side effects in functions invoked in the conditional expression are
allowed. Please, note that they would not be observable from outside that function.

<pre><b>
bool is_valid(int x) {
  int a=1;
  while (a&lt;x) {
    if (x % a == 0) return true;
    a++;
  }
  return false;
}

void f(int n) [[expects: is_valid(x)]]
</b></pre>

<h3>2.13 Location of a violation</h3>

The location of a violation belongs logically to the caller site. However,
there is a number of cases where this might be difficult for implementers
and users. Jason Merrill suggested to have an independent mechanism for
obtaining the caller information (such as proposed stack trace in P0881).

We propose that implementations should try to do their best to report the
caller site and otherwise to report the callee site.

<h2>3. Questions about contracts programming</h2>

<h3>What is the effect of violating a contract while evaluating the check for
another expression</h3>

Nothing special needs to be considered. When the first contract is violated the
corresponding action is taken.

<pre><b>
bool positive(const int * p) [[expects: p!=nullptr]] {
  return *p > 0;
}

bool g(int * p) [[expects: positive(p)]];

void test() {
  g(nullptr); // Contract violation when calling positive(nullptr)
}
</b></pre>
</p>

<h3>Contract attribute as identifier</h3>

What happens if you try to use an identifier named as a contract attribute (e.g.
<tt><b>requires</b></tt>, <tt><b>audit</b></tt>, ...)?

Example:

<pre><b>
X f(X & audit) [[ensures audit: audit.valid()]];
</b></pre>
</p>

This is valid code. The first <tt><b>audit</b></tt> is interpreted as a
<i>contract-level</i>. Then, the <i>conditional-expression</i> identifies the
second <tt><b>audit</b></tt> correctly as the function argument.

<h2>4. Proposed Wording</h2>

<p>In 5.10 <tt><b>[lex.name]</b></tt>, modify Table 4:

<table border="1" cellpadding="5" align="center">
<caption>Table 4 &mdash; Identifiers with special meaning</caption>
<tr>
<td><b><tt>override</tt></b></td>
<td><b><tt>final</tt></b></td>
<td><ins><b><tt>axiom</tt></b></ins></td>
<td><ins><b><tt>audit</tt></b></ins></td>
</tr>
</table>

<p>In 6.2/12 <tt><b>[basic.def.odr]</b></tt>, add a new bullet after bullet 12.5:</p>
<blockquote class="stdins">
<ul>
<li>it is implementation-defined the conditions under which
    &mdash;if D contains an assertion, has a postcondition, or invokes a function with a precondition&mdash;
    each definition of D shall be translated using the same build level and violation continuation mode 
    (10.6.11 <tt><b>[dcl.attr.contracts]</b></tt>); and
</li>
<ul>
</blockquote>

<p>Modify clause 6.3.7 <tt><b>[basic.class.scope]</b></tt>, p. 1:</p>

<blockquote>
<p>
The potential scope of a name declared in a class consists not only of the declarative region following the
name’s point of declaration, but also of all function bodies, default arguments, noexcept-specifiers, <del>and</del> default
member initializers (12.2)<ins>, and contract conditions (10.6.11 <tt><b>[dcl.attr.contracts]</tt></b>)</ins> in that class (including such things in nested classes).
</p>
</blockquote>

<p>Modify clause 6.4.1 <tt><b>[basic.lookup.unqual]</b></tt>, p. 7:</p>

<blockquote>
<p>
A name used in the definition of a class X outside of a member function body, default argument, noexcept-
specifier, default member initializer (12.2), <ins>contract condition (10.6.11 <tt><b>[dcl.attr.contracts]</tt></b>),</ins> or nested class definition shall be declared in one of the following
ways:
</p>
</blockquote>

<p>Modify clause 6.4.1 <tt><b>[basic.lookup.unqual]</b></tt>, p. 8:</p>

<blockquote>
<p>
For the members of a class X, a name used in a member function body, in a default argument, in a noexcept-
specifier, in a default member initializer (12.2), <ins>in a contract condition (10.6.11 <tt><b>[dcl.attr.contracts]</tt></b>), </ins>or in the definition of a class member outside of the definition
of X, following the member’s declarator-id, shall be declared in one of the following ways:
<br/>
&hellip;
</p>
</blockquote>

<p>Modify clause 8.6 <tt><b>[expr.const]</b></tt>, p. 2, adding a new bullet</p>
<blockquote class="stdins">
<ul>
<li>A checked contract (10.6.11 <tt><b>[dcl.attr.contracts]</tt></b>) whose predicate evaluates to false.
</li>
</ul>
</blockquote>

<p>In 10.6.1/1 <tt><b>[dcl.attr.grammar]</b></tt>, modify the production for <i>attribute</i> as follows:</p>
<blockquote class="std">
  <blockquote class="grammar">
    &hellip;<br/>
    <i>attribute-specifier:</i><br/>
    <tab><tt><b>[[</b></tt><i>attribute-using-prefix<sub>opt</sub>&nbsp;&nbsp;attribute-list</i><tt><b>]]</b></tt><br/>
    <tab><ins><i>contract-attribute-specifier</i></ins><br/>
    <tab><i>alignment-specifier</i><br/>
    &hellip;<br/>
  </blockquote>
</blockquote>

<p>Add a new section 10.6.11 Contracts attributes <tt><b>[dcl.attr.contracts]</b></tt></p>

<blockquote class="stdins">
<p>
1. Contract attributes are used to specify preconditions, postconditions, and assertions for functions.
</p>

  <blockquote class="grammar">
  <i>contract-attribute-specifier:</i><br/>
    <tab><tt><b>[[ </b>expects</tt> <i>contract-level<sub>opt</sub>&nbsp;&nbsp;<tt>:</tt>&nbsp;conditional-expression</i><tt><b> ]]</b></tt><br/>
    <tab><tt><b>[[ </b>ensures</tt> <i>contract-level<sub>opt</sub>&nbsp;&nbsp;identifier<sub>opt</sub>&nbsp;<tt>:</tt>&nbsp;conditional-expression</i><tt><b> ]]</b></tt><br/>
    <tab><tt><b>[[ </b>assert</tt> <i>contract-level<sub>opt</sub>&nbsp;&nbsp;<tt>:</tt>&nbsp;conditional-expression</i><tt><b> ]]</b></tt><br/>
  </blockquote>

  <blockquote class="grammar">
    <i>contract-level:</i><br/>
    <tab><tt>default</tt><br/>
    <tab><tt>audit</tt><br/>
    <tab><tt>axiom</tt><br/>
  </blockquote>

<p>
An ambiguity between a <i>contract-level</i> and an identifier is resolved in favor of <i>contract-level</i>.
</p>
</blockquote>

<blockquote class="stdins">
<p>
2.
A <i>contract-attribute-specifier</i> using <tt>expects</tt> is a <i>precondition</i>.
It expresses a function's expectation on its arguments 
and/or the state of other objects using a predicate 
that is intended to hold upon entry into the function.
</p>

<p>
3.
A <i>contract-attribute-specifier</i> using <tt>ensures</tt> is a <i>postcondition</i>.
It expresses a condition that a function should ensure for the return value 
and/or the state of objects using a predicate 
that is intended to hold upon exit from the function.
</p>

<p>
4.
A <i>contract-attribute-specifier</i> using <tt>assert</tt> is an <i>assertion</i>.
It expresses a condition that is intended to be satisfied where it appears in a function body.
</p>

<p>
5. 
Preconditions, postconditions, and assertions are collectively called <i>contracts</i>.
The <i>conditional-expression</i> in a contract is contextually converted to bool; 
the converted expression is called the <i>predicate</i> of the contract.
</p>

<p>
6.
A <i>contract condition</i> is a precondition or a postcondition.
A contract condition may be applied to the function type of a function declaration.
The first declaration of a function shall specify all contract conditions (if any) of the function.
Subsequent declarations shall either specify no contract conditions or the same list of contract conditions;
no diagnostic is required if corresponding conditions will always evaluate to the same value. 
The list of contract conditions of a function shall be the same if the declarations of that function 
appear in different translation units; 
no diagnostic required.
If a friend declaration is the first declaration of the function in a translation unit 
and has a contract condition, the declaration shall be a definition 
and shall be the only declaration of the function in the translation unit.
</p>

<p>
7.
Two lists of contract conditions are the same if they consist of the same contract conditions in the same order.
Two contract conditions are the same if their contract levels are the same and their predicates are the same.
Two predicates contained in <i>contract-attribute-specifier</i>s are the same if they would satisfy the one-definition rule (6.2 <tt><b>[basic.def.odr]</b></tt>) were they to appear in function definitions, except for renaming of parameters, return value identifiers (if any), and renaming of template parameters.
</p>

<p>
8.
An assertion is checked by evaluating its predicate.
The predicate of an assertion is potentially evaluated (6.2 [<b><tt>basic.def.odr</tt></b>]). 
The predicate of an assertion is evaluated 
as part of the evaluation of the null statement
(9.2 <b><tt>[stmt.expr]</tt></b>) 
it applies to.
</p>

<p>
9.
The predicate of a contract condition is potentially-evaluated 
(6.2 [<b><tt>basic.def.odr</tt></b>]) and 
has the same semantic restrictions as if it appeared as the first <i>expression-statement</i>
in the body of the function it applies to.
Additional access restrictions apply to 
names appearing in a contract condition of a member function of class <tt>C</tt>:
<ul>
<li>Friendship is not considered (14.3 [<b><tt>class.friend</tt></b>]).</li>
<li>For a contract condition of a public member function, no member of <tt>C</tt> or of an enclosing class of <tt>C</tt> is accessible unless it is a public member of <tt>C</tt>, or a member of a base class accessible as a public member of <tt>C</tt> (14.2 [<b><tt>class.access.base</tt></b>]).</li>
<li>For a contract condition of a protected member function, no member of <tt>C</tt> or of an enclosing class of <tt>C</tt> is accessible unless it is a public or protected member of <tt>C</tt>, or a member of a base class accessible as a public or protected member of <tt>C</tt>.</li>
</ul>
For names appearing in a contract condition of a non-member function,
friendship is not considered.
</p>
<p>
[<i>Example</i>:
<pre><b>
class X {
public:
  int v() const;
  void f() [[expects: x>0]]; // Ill-formed
  void g() [[expects: v()>0]]; // OK
  friend void r(int z) [[expects: z>0]]; // OK
  friend void s(int z) [[expects: z>x]]; // Ill-formed
protected:
  int w();
  void h() [[expects: x>0]]; // Ill-formed
  void i() [[ensures: y>0]]; // OK
  void j() [[ensures: w()>0]]; // OK
  int y;
private:
  void k() [[expects: x>0]]; // OK
  int x;
};

class Y : public X {
public:
  void a() [[expects: v()>0]]; // OK
  void b() [[ensures: w()>0]]; // Ill-formed
protected:
  void c() [[expects: w()>0]]; // OK
};
</b></pre>
&mdash; <i>end example</i>]
</p>

<p>
10.
The only side effects of a predicate 
that are allowed in a <i>contract-attribute-specifier</i>
are modifications of 
non-volatile objects whose lifetime began and ended within 
the evaluation of the predicate 
in functions invoked from
that predicate.
The behavior of any other side effect is undefined.
[<i>Example</i>
<pre><b>
void push(int x, queue &amp; q)
  [[expects: !q.full()]]
  [[ensures: !q.empty()]]
{
  //...
  [[assert: q.is_valid()]];
  //...
}

int min=-42;
constexpr int max=42;

constexpr int g(int x)
  [[expects: min&lt;=x]] // error
  [[expects: x&lt;max]] // OK
{
  //...
  [[assert: 2*x &lt; max]];
  [[assert: ++min > 0]]; // undefined
  //...
}
</b></pre>
&mdash; <i>end example</i>]
</p>

<p>
11.
If the <i>contract-level</i> of a <i>contract-attribute-specifier</i> is absent, it is assumed to be <tt>default</tt>.
[<i>Note:</i>
A <tt>default</tt> <i>contract-level</i> is expected to be used for those contracts where the cost of run-time checking is assumed to be small (or at least not expensive) compared to the cost of executing the function.
An <tt>audit</tt> <i>contract-level</i> is expected to be used for those contracts where the cost of run-time checking is assumed to be large (or at least significant) compared to the cost of executing the function.
An <tt>axiom</tt> <i>contract-level</i> is expected to be used for those contracts that are formal comments and are not evaluated at run-time.
&mdash; <i>end note</i>].
</p>

<p>
12.
A translation may be performed with one of the following <i>build levels</i>:
<i>off</i>, <i>default</i>, or <i>audit</i>.
A translation with build level set to <i>default</i> performs checking for <tt>default</tt> contracts.
A translation with build level set to <i>audit</i> performs checking for <tt>default</tt> and <tt>audit</tt> contracts.
If no build level is explicitly selected, the build level is <i>default</i>.
The mechanism for selecting the build level is implementation-defined.
The translation of a program consisting of translation units where the build level is not the same in all translation units is conditionally supported.
There should be no programmatic way of setting, modifying, or querying the build level of a translation unit.
</p>

<p>
13.
A precondition is checked by evaluating its predicate immediately before starting 
evaluation of the function body. [<i>Note</i>: the function body includes <i>function-try-blocks</i> (18 [<b><tt>except</tt></b>]) and <i>ctor-initializer</i> (15.6.2 [<b><tt>class.base.init</tt></b>]). &mdash; <i>end note</i>.]
A postcondition is checked immediately before returning control to the caller of the function.
[<i>Note</i>: The lifetime of local variables and temporaries has ended. 
Exiting via an exception and <tt>longjmp</tt> (21.112 [<b><tt>csetjmp</tt></b>]) are not considered returning control to the caller of the function. &mdash; <i>end note</i>].
An evaluation of a predicate that exits via an exception invokes <b><tt>std::terminate()</tt></b>.
</p>

<p>
14.
If a function has multiple preconditions,
their evaluation if any will be performed in the order they appear lexically.
If a function has multiple postconditions,
their evaluation if any will be performed in the order they appear lexically.
<pre><b>
void f(int * p)
  [[expects: p!=nullptr]] // #1
  [[ensures: *p == 1]] // #3
  [[expects: *p == 0]] // #2
{
  *p = 1;
}
</b></pre>
</p>

<p>
15.
It is unspecified whether a contract that would not be checked
under the current build level is evaluated. 
If it would evaluate to false the behavior is undefined.
During constant expression evaluation (8.6 [<tt><b>expr.const</b></tt>]),
contract evaluation is performed only for those contracts that are checked.
</p>

<p>
16.
The violation handler of a program is a function of type 
"<b><tt>noexcept<sub>opt</sub></tt></b> function of 
(lvalue reference to <tt><b>const std::contract_violation</b></tt>)
returning <tt><b>void</b></tt>"
specified in an
implementation-defined manner. The violation handler is invoked when the
predicate of a checked contract evaluates to false (called a contract
violation). There should be no programmatic way of setting or modifying the
violation handler.
It is implementation defined how the violation handler is established for a program and how the 
<tt><b>std::contract_violation</b></tt> argument value is set.
If a precondition is violated, the source location of the violation is 
implementation defined [<i>Note</i>: Implementations are encouraged but not required to
report the caller site. &mdash; <i>end note</i>].
If a postcondition is violated, the source location of the violation is the source location
of the function definition.
If an assertion is violated, the source location of the violation is the source location
of the statement to which the assertion is applied.
</p>

<p>
17.
If a user-provided violation handler exits by throwing an exception and a contract
is violated on a call to a function with a non-throwing exception specification,
then the behavior is as if the exception escaped the function body.
[<i>Note:</i>
The function <b><tt>std::terminate()</tt></b> is invoked (18.5.1 <b>[except.terminate]</b>).
&mdash; <i>end note</i>]
<br/>
[<i>Example:</i>
<pre><b>
void f(int x) noexcept [[expects: x>0]];

void g() {
  f(0); // std::terminate() if violation handler throws
  //...
}
</b></pre>
&mdash; <i>end example</i>]
</p>

<p>
18.
A translation may be performed with one of the following <i>violation continuation modes</i>: <i>off</i> or <i>on</i>.
A translation with a violation continuation mode set to </i>off</i> terminates execution by
invoking <b><tt>std::terminate()</tt></b> after completing the execution of the violation handler. 
A translation with a violation continuation mode set to <i>on</i>
continues execution after completing the execution of the violation handler.
If no continuation mode is explicitly selected, the default continuation mode is <i>off</i>.
[<i>Note:</i>
A continuation mode set to <i>on</i> provides the opportunity to install a logging handler to instrument
a pre-existing code base and fix errors before enforcing checks.
&mdash; <i>end note</i>]
[<i>Example:</i>
<pre><b>
void f(int x) [[expects: x > 0]];

void g() {
  f(0); // std::terminate() after handler if continuation mode is off
        // Proceeds after handler if continuation mode is on
  //...
}
</b></pre>
&mdash; <i>end example</i>]
</p>

</blockquote>

<p>Add a new section 10.6.11.1 Interface contracts <tt><b>[dcl.attr.contracts.interface]</b></tt></p>

<blockquote class="stdins">
<p>
1.
Multiple contract conditions may be applied to a function type with the same 
or different <i>contract-level</i>s.
[<i>Example</i>:
<pre><b>
int z;

bool is_prime(int k);

void f(int x)
  [[expects: x>0]]
  [[expects audit: is_prime(x)]]
  [[ensures: z>10]]
{
  //...
}
</b></pre>
&mdash; <i>end example</i>]
</p>

<p>
2.
A postcondition may introduce an identifier to represent the glvalue result or the prvalue result object 
of the function.
[<i>Example:</i>
<pre><b>
int f(char * c)
  [[ensures res: res&gt;0 &amp;&amp; c!=nullptr]];

int g(double * p)
  [[ensures audit res: res!=0 &amp;&amp; p!=nullptr &amp;&amp; *p&lt;=0.0]];
</b></pre>
&mdash; <i>end example</i>]
</p>

<p>
3.
If a postcondition odr-uses a parameter value in its predicate 
and the function body makes direct or indirect modifications
of that value the behavior is undefined.
[<i>Example:</i>
<pre><b>
int f(int x)
  [[ensures r: r==x]] 
{
  return ++x; // Undefined behavior
}

int g(int * p)
  [[ensures r: p!=nullptr]] 
{
  *p = 42; // OK. p is not modified
}

int h(int x)
  [[ensures r: r==x]]
{
  potentially_modify(x); // Undefined behavior if x is modified
  return x;
}
</b></pre>
&mdash; <i>end example</i>]

</p>

<p>
4.
[<i>Note</i>:
A function pointer cannot include contract conditions.
&mdash; <i>end note</i>]
<br/>
[<i>Example</i>:
<pre><b>typedef int (*fpt)() [[ensures r: r!=0]]; // Ill-formed

int g(int x) 
  [[expects: x>=0]] 
  [[ensures r: r>x]]
{
  return x+1;
}

int (*pf)(int) = g; // OK
int x = pf(5); // contract conditions of g are checked
</b></pre>
&mdash; <i>end example</i>]
</p>

<p>
5.
If an overriding function specifies contract conditions, it shall specify the
same list of contract conditions as its overridden functions; no diagnostic is
required if corresponding conditions will always evaluate to the same value.

Otherwise, it is considered to have the list of contract conditions from one of
its overridden functions; the names in the contract conditions are bound, and
the semantic constraints are checked, at the point where the contract
conditions appear.

Given a virtual function <tt>f</tt> with a contract condition that odr-uses
<tt>*this</tt>, the class of which <tt>f</tt> is a direct member shall be be an
unambiguous and accessible base class of any class in which <tt>f</tt> is
overridden.

If a function overrides more than one function, all of the overridden functions
shall have the same list of contract conditions (10.6.11
[<tt><b>dcl.attr.contracts</tt></b>]); no diagnostic is required if
corresponding conditions will always evaluate to the same value.
</p>
[<i>Example</i>:
<pre><b>
struct A {
  virtual void g() [[expects: x==0]];
  int x = 42;
};

int x = 42;
struct B {
  virtual void g() [[expects: x==0]];
}

struct C : A, B {
  virtual void g(); // Ill-formed, no diagnostic required
};
</b></pre>
&mdash; <i>end example</i>]

</blockquote>

<p>Modify clause 12.2 <tt><b>[class.mem]</b></tt>, p. 6:</p>

<blockquote>
<p>
A class is considered a completely-defined object type (6.7) (or complete type) at the closing } of the
class-specifier. Within the class member-specification, the class is regarded as complete within function
bodies, default arguments, noexcept-specifiers, <del>and</del> default member initializers<ins>, and contract conditions (10.6.11 <tt><b>[dcl.attr.contracts]</tt></b>) </ins>(including such things in
nested classes). Otherwise it is regarded as incomplete within its own class member-specification.
</p>
</blockquote>

<p>Add at the end of clause 13.3 <tt><b>[class.virtual]</b></tt>:</p>

<blockquote class="stdins">
<p>
18.
[<i>Note</i>:
For contracts, see 
10.6.11.1 [<tt><b>dcl.attr.contracts.interface</tt></b>].
&mdash; <i>end note</i>]
</p>
</blockquote>

</blockquote>

<p>Modify clause 17.8.2 <tt><b>[temp.explicit]</b></tt>, p. 5</p>

<blockquote>
<p>
The declaration in an explicit-instantiation and the declaration produced by the corresponding substitution into
the templated function, variable, or class are two declarations of the same entity. 
<ins>An <i>explicit-instantiation</i> of a function template shall not specify a contract condition (10.6.11 [<tt><b>dcl.attr.contracts</tt></b>]).</ins>
[ Note: These declarations
are required to have matching types as specified in 6.5, except as specified in 18.4. [ Example:
</p>
</blockquote>

<p>Add a note to 17.8.3 <tt><b>[temp.expl.spec]</tt></b></p>

<blockquote class="stdins">
<p>
[<i>Note</i>:
For an explicit specialization of a function template, the contract conditions (10.6.11 [<tt><b>dcl.attr.contracts</tt></b>]) of the explicit specialization are independent of those of the primary template.
&mdash; <i>end note</i>]
</p>
</blockquote>

<p>Change 18.5.1 [<b><tt>except.terminate</tt></b>] adding a bullet after 1.6</p>

<blockquote class="stdins">
<ul>
<li>
when evaluation of a predicate (10.6.11 [<tt><b>dcl.attr.contracts</tt></b>]) exits via an exception.
</li>
<li>
when the violation handler invoked for a failed contract condition (10.6.11 [<tt><b>dcl.attr.contracts</tt></b>]) check on a noexcept function exits via an exception.
</li>
</ul>
</blockquote>

<p>Modify clause 20.5.1.2/2 <tt><b>[headers]</tt></b>, Table 16</p>

<table border="1" cellpadding="5" align="center">
<caption>Table 16 &mdash; C++ library headers</caption>
<tr><td><tt>&hellip;</tt></td></tr>
<tr><td><tt>&lt;codecvt&gt;</tt></td></tr>
<tr><td><tt><ins>&lt;contract&gt;</ins<</tt></td></tr>
<tr><td><tt>&lt;compare&gt;</tt></td></tr>
<tr><td><tt>&hellip;</tt></td></tr>
</table>


Modify clause 21.1/2 <tt><b>[support.general]</b></tt>:

<blockquote class="std">
<p>
2.
The following subclauses describe common type definitions used throughout the library, characteristics of
the predefined types, functions supporting start and termination of a C++ program, support for dynamic
memory management, support for dynamic type identification, <ins>support for contract violation handling,</ins>
support for exception processing, support for
initializer lists, and other runtime support, as summarized in Table 32.
</p>
<table border="1" cellpadding="5" align="center">
<caption>Table 32 &mdash; Language support library summary</caption>
<thead>
<tr>
<td/>
<td>Subclause</td>
<td>Header(s)</td>
<tr>
</thead>
<tbody>

<tr>
<td>21.2</td>
<td>Common definitions</td>
<td>
<tt>&lt;cstddef&gt;</tt><br/>
<tt>&lt;cstdlib&gt;</tt>
</td>

<tr>
<td>21.3</td>
<td>Implementation properties</td>
<td>
<tt>&lt;limits&gt;</tt><br/>
<tt>&lt;climits&gt;</tt><br/>
<tt>&lt;cfloat&gt;</tt>
</td>
</tr>

<tr>
<td>21.4</td>
<td>Integer types</td>
<td><tt>&lt;cstdint&gt;</tt></td>
</tr>

<tr>
<td>21.5</td>
<td>Start and termination</td>
<td><tt>&lt;cstdlib&gt;</tt></td>
</tr>

<tr>
<td>21.6</td>
<td>Dynamic memory management</td>
<td><tt>&lt;new&gt;</tt></td>
</tr>

<tr>
<td>21.7</td>
<td>Type identification</td>
<td><tt>&lt;typeinfo&gt;</tt></td>
</tr>

<tr>
<td><ins>21.8</ins></td>
<td><ins>Contract violation handling</ins></td>
<td><ins><tt>&lt;contract&gt;</tt></ins></td>
</tr>

<tr>
<td>21.<del>8</del><ins>9</ins></td>
<td>Exception handling</td>
<td><tt>&lt;exception&gt;</tt></td>
</tr>

<tr>
<td>21.<del>9</del><ins>10</ins></td>
<td>Initializer lists</td>
<td><tt>&lt;initializer_list&gt;</tt></td>
</tr>

<tr>
<td>21.<del>10</del><ins>11</ins></td>
<td>Other runtime support</td>
<td>
<tt>&lt;csignal&gt;</tt><br/>
<tt>&lt;csetjmp&gt;</tt><br/>
<tt>&lt;cstdalign&gt;</tt><br/>
<tt>&lt;cstdarg&gt;</tt><br/>
<tt>&lt;cstdbool&gt;</tt><br/>
<tt>&lt;cstdlib&gt;</tt><br/>
</td>
</tr>

</tbody>
</table>
</blockquote>

Add a new section 21.9 <tt><b>[support.contract]</b></tt>, after 21.8 <tt><b>[support.exception]</b></tt>
<blockquote class="stdins">
<h2>21.9 Contract violation handling</h2>

<p>
1.
The header <tt>&lt;contract&gt;</tt> defines a type for reporting information
about contract violations generated by the implementation.
</p>

<h3>21.9.1 Header &lt;contract&gt; synopsys</h3>
<pre>
namespace std {
  class contract_violation;
}
</pre>

<h3>21.9.2 Class <tt>contract_violation</tt></h3>
<pre><b>
namespace std {
  class contract_violation {
  public:
    uint_least32_t line_number() const noexcept;
    string_view file_name() const noexcept;
    string_view function_name() const noexcept;
    string_view comment() const noexcept;
    string_view assertion_level() const noexcept;
  };
}
</b></pre>

<p>
1.
The class <tt>contract_violation</tt> describes information about a contract violation generated by the implementation.
</p>

<pre><b>
uint_least32_t line_number() const noexcept;
</b></pre>
<p>
2.<tab>
<i>Returns:</i>
The source code location where the contract violation happened (10.6.11/15
<tt><b>[dcl.attr.contracts]</b></tt>).
If the location is unknown, 
an implementation may return <tt>0</tt>.
</p>

<pre><b>
string_view file_name() const noexcept;
</b></pre>
<p>
3.<tab>
<i>Returns:</i>
The source file name where the contract violation happened (10.6.11/15
<tt><b>[dcl.attr.contracts]</b></tt>).
If the file name is unknown,
an implementation may return <tt>string_view{}</tt>.
</p>

<pre><b>
string_view function_name() const noexcept;
</b></pre>
<p>
4.<tab>
<i>Returns:</i>
The name of the function where the contract violation happened (10.6.11/15 <tt><b>[dcl.attr.contracts]</b></tt>).
If the function name is unknown, an implementation may return <tt>string_view{}</tt>.
</p>

<pre><b>
string_view comment() const noexcept;
</b></pre>
<p>
5.<tab>
<i>Returns:</i>
Implementation-defined text describing the predicate of the violated contract.
</p>

<pre><b>
string_view assertion_level() const noexcept;
</b></pre>
<p>
6.<tab>
<i>Returns:</i>
Text describing the <i>assertion-level</i> of the violated contract.
</p>
</blockquote>



<h3>Acknowledgements</h3>

<p>
Thanks to Jens Maurer for his gigantic help in the detailed wording.
</p>
<p>
Jason Merrill suggested to express preconditions source location in terms of 
best effort. Hubert Tong helped with better wording for interaction with ODR.
Daveed Vandevoorde made remarks on evaluation of conditional expressions and
side effects.
</p>
<p>
Roger Orr, Andrzej Krzemieński, and Walter Brown reviewed the latest version of this document.
</p>
<p>
Alexander Beels, Andrzej Krzemienski and Melissa Mears reviewed previous versions of this document.
</p>

<h3>References</h3>

<a name="bib-contracts-design">[1]</a>
G. Dos Reis, J. D. Garcia, J. Lakos, A. Meredith, N. Myers, B. Stroustrup.
A contract design. 
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf">P0380R1</a>. 
July, 2016.<br/>

<a name="bib-cpp-draft">
[2]
</a> 
Richard Smith.
Working Draft, Standard for Programming Language C++.
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4727.pdf">N4727</a>
October, 2017.</br>

</body>
</html>



