<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html;charset=US-ASCII">

<style type="text/css">

body { color: #000000; background-color: #FFFFFF; }
del { text-decoration: line-through; color: #8B0040; }
ins { text-decoration: underline; color: #005100; }

p.example { margin-left: 2em; }
pre.example { margin-left: 2em; }
div.example { margin-left: 2em; }

code.extract { background-color: #F5F6A2; }
pre.extract { margin-left: 2em; background-color: #F5F6A2;
  border: 1px solid #E1E28E; }

p.function { }
.attribute { margin-left: 2em; }
.attribute dt { float: left; font-style: italic;
  padding-right: 1ex; }
.attribute dd { margin-left: 0em; }

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: #FFEBFF;
  border: 1px solid #ECD7EC;
  padding-left: 0.5empadding-right: 0.5em; ; }

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

table { border: 1px solid black; border-spacing: 0px;
  margin-left: auto; margin-right: auto; }
th { text-align: left; vertical-align: top;
  padding-left: 0.8em; border: none; }
td { text-align: left; vertical-align: top;
  padding-left: 0.8em; border: none; }

</style>

<title>N4248 Library Preconditions are a Language Feature</title>
</head>
<body>
<h1>N4248 Library Preconditions are a Language Feature</h1>

<p>
ISO/IEC JTC1 SC22 WG21 N4248 - 2014-10-12
</p>

<address>
Alisdair Meredith, public@alisdairm.net
</address>

<h2>Table of Contents</h2>
<ul>
<li><a href="#1.0">Introduction</a></li>
<li><a href="#2.0">What are Library Contracts?</a></li>
<ul>
  <li><a href="#2.1">Contract Violations</a></li>
  <li><a href="#2.3">Contract Violations are not Undefined Behavior</a></li>
</ul>
<li><a href="#3.0">Contracts as a Programming Construct</a></li>
<ul>
  <li><a href="#3.1">A Simple Proposition</a></li>
  <li><a href="#3.2">Concern with Complexity</a></li>
  <li><a href="#3.3">Benefits of Language Support</a></li>
</ul>
<li><a href="#4.0">Proposed Solution</a></li>
<ul>
  <li><a href="#4.1">Straw Man Syntax</a></li>
  <li><a href="#4.2">Multiple Build Modes</a></li>
  <li><a href="#4.3">Checking From The Caller</a></li>
  <li><a href="#4.4">Interaction With <tt>noexcept</a></tt></li>
  <ul>
    <li><a href="#4.4">Preconditions are always <tt>noexcept(false)</tt></a></li>
    <li><a href="#4.4">Preconditions are ignored</a></li>
    <li><a href="#4.4">Precondition checks depend on build mode</a></li>
  </ul>
  <li><a href="#4.5">Let The <del>Wookie</del><ins>User</ins> Win</a></li>
</ul>
<li><a href="#5.0">Further Issues</a></li>
<ul>
  <li><a href="#5.1">One Definition Rule</a></li>
  <li><a href="#5.2">Declaration vs. Definition</a></li>
  <li><a href="#5.3">Querying for Contracts</a></li>
  <li><a href="#5.4">Cost of Evaluation</a></li>
  <li><a href="#5.5">Simple and Elegant Syntax</a></li>
  <li><a href="#5.6">Not All Preconditions Are Amenable To Checking</a></li>
</ul>
<li><a href="#6.0">Summary</a></li>
<li><a href="#7.0">Appendix A: Existing Support for Contracts in C++14</a></li>
<ul>
  <li><a href="#7.1"><tt>const</tt> Correctness</a></li>
  <li><a href="#7.2">Non-null Pointers</a></li>
  <li><a href="#7.3"><tt>unsigned</tt> Integer Types</a></li>
  <li><a href="#7.4">Ownership Patterns And RAII</a></li>
  <li><a href="#7.5">Pure Virtual Functions</a></li>
  <li><a href="#7.6"><tt>override</tt> Specifier In C++11</a></li>
  <li><a href="#7.7"><tt>static_assert</tt></a></li>
  <li><a href="#7.8">Concepts</a></li>
  <li><a href="#7.9"><tt>noexcept</tt></a></li>
  <li><a href="#7.10"><tt>[[noreturn]]</tt></a></li>
</ul>
<li><a href="#8.0">Acknowledgements</a></li>
</ul>


<h2><a name="1.0">Introduction</a></h2>
<p>
This paper is motivated by the confluence of several discussions over
the last few years, and draws together several ideas trying to find
the best point in the (language) design space given competing tensions.
The most obvious inspiration is the ongoing debate over appropriate use
of <tt>noexcept</tt> specifications in the standard library, but this
also draws on the experience of the recent paper on a better
<tt>assert</tt> facility,
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4075.pdf">N4075</a>,
and the early work in the area of contract programming by Thorsten Ottosen
and Lawrence Crowl,
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2006/n1962.html">N1962</a>.
</p>

<p>
The key recommendation of this paper is to add support for a feature
to declare preconditions on function parameters that is visible to
the compiler, and address the most important design constraints on
that feature.  It does not provide formal wording yet, nor even a
preferred syntax.  For the sake of exposition, the keywords from the
concepts TS are overloaded to suggest what this might look like, but
are not intended to be a formal suggestion for the final syntax.
</p>

<h2><a name="2.0">What are Library Contracts?</a></h2>
<p>
For the sake of this paper, Contracts are the agreement between a
library and its callers, that describe the outcome of a function
call given <i>valid</i> inputs.  One of the important aspects of a
contract is to define which subset of inputs are valid.  When all
possible inputs for the function parameter data types are valid,
a contract is said to be <i>wide</i>, otherwise there is some
notion of out-of-contract behavior and the contract is said to be
<i>narrow</i>.  Commonly, some subset of valid inputs can produce
error conditions, and the contract describes how such error
conditions are reported, commonly through exceptions or error
codes.
</p>

<p>
In addition to defining the range of values permissible for function
parameters, a contract for a template must also call out the requirements
on the template parameter types.  Often, such a contract will mandate that
some failures to satisfy these requirements will be met with a compilation
failure, such as by a <tt>static_assert</tt>, and my go further to indicate
that such failures would cause a failure subject to SFINAE.
</p>

<p>
In the ideal world, all aspects of a contract are documented and available
for users to rely on.  In common practice, documentation frequently does
not keep up with evolving software, and for some projects the code itself
is deemed documentation enough, where the contracts must be inferred from
the current implementation, making it difficult to diagnose bugs when it
is not clear which side of the contract has been violated.
</p>

<p>
One particularly relevant case for WG21 is the C++ Standard Library which
is entirely defined by contract, and has multiple implementations all
trying to satisfy the same set of contracts.
</p>

<h3><a name="2.1">Contract Violations</a></h3>
<p>
There are several categories of contract violation.  The simplest to
describe is the case that the implementation does not deliver the contracted
behavior.  This is generally a bug by the implementor of the library, and
ideally would be caught and reported by their test suite.  There are two
simple ways to resolve such violations:
</p>
<ul>
<li>Correct the code to satisfy the contract</li>
<li>Amend the contract to agree with the code</li>
</ul>

<p>
Generally speaking, it is preferable to correct the code once a library has
been deployed, as it is difficult for existing customers to audit all of
their code to be sure it conforms to the amended contract.  However, if the
library has not yet been deployed and the incongruence if reported by a test
suite, for example, then amending the contract may indeed be a viable
approach.
</p>

<p>
The second kind of violation is when a caller of the libraries supplies
function arguments that are outside the range of contracted behavior.
This is an error on the part of the library user, and will frequently
result in undefined behavior.  Indeed, the standard library specification
uses exactly that phrase, and for all intents and purposes, for a library
customer, violating the library contract should be treated as invoking
undefined behavior.
</p>

<p>
However, a contract violation is <b>not</b> undefined behavior as far as
the compiler is concerned, as the compiler cannot see the library contract.
A common feature of high quality libraries is some sort of diagnostic or
debug mode that will help users find their own violations of library
contracts.  These often involve redundant checks on function arguments that
are disabled in <i>release</i> builds for production, but enabled in
<i>debug</i> builds for testing and validation.  The C++ Standard Library
provides the <tt>&lt;cassert&gt;</tt> header to support this library
practice, and the proposal 
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4075.pdf">N4075</a>
and its successors seek to enhance this approach, based on existing practice.
</p>

<h3><a name="2.2">Contract Violations are not Undefined Behavior</a></h3>
<p>
One of the key observations of this paper is that contract violations are
<b>not</b> undefined behavior, as the core language means the term, but will
often result in such undefined behavior.  After a contract violation, the
library author is still in control, and has the option to detect and report
that violation in any manner they choose, including using only well-defined
behavior as far as the compiler is concerned.
</p>

<p>
This distinction becomes clearest when considering a <tt>constexpr</tt>
function where the language is required to diagnose all undefined behavior
in a <tt>constexpr</tt> evaluation:
</p>

<pre><code>
auto divide(double a, double b)
  // Return a/b.  The behavior is undefined if 0.0 == b
{
  if (0.0 == b) {
    // out-of-contract, return a NaN for now but subject to change
    return numeric_limits<double>::quiet_NaN();
  }
  return a / b;
}

constexpr double d = divide(1.0, 0.0);  // error?
</code></pre>

<p>
If a contract violation is undefined behavior, then the compiler is required
to diagnose the error in definition of <tt>d</tt>.  However, as this particular
implementation does not rely on any core undefined behavior, then the compiler
has no way to see that the contract has been violated, regardless of whether
the library documents undefined behavior - unless this is seen as a contractual
requirement on the library to ensure core undefined behavior in such a call.
</p>

<h2><a name="3.0">Contracts as a Programming Construct</a></h2>
<h3><a name="3.1">A Simple Proposition</a></h3>
<p>
This paper makes a simple proposition - that we should introduce a syntax so
that libraries can more clearly declare their contracts in a manner visible
to the compiler.  In practice, the details are rarely as simple as the
proposition.  For example, the concepts TS is a detailed attempt to introduce
a language to declare contracts on type parameters in function templates.
</p>

<p>
Appendix A gives several examples where C++ already has explicit support for
several common kinds of contracts that we deemed such important special cases,
they got their own specific support in the language.
</p>

<p>
Previous motivation for an elaborate feature was presented by Ottosen/Crowl in
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2004/n1613.pdf">N1613</a>,
and
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1800.pdf">N1800</a>.
</p>

<h3><a name="3.2">Concern with Complexity</a></h3>
<p>
My main concern with the original proposal is that the complexity of the feature,
especially use of the feature, outweighs the benefit.  My standard example for
this comes from Kevlin Henney, who asked me to define the contract for a simple
<tt>sort</tt> function.  Almost everyone describes the basic post-condition that
the destination range is sorted according to the predicate supplied to the function
(or the default predicate, usually <tt>operator&lt;</tt>).  Most people miss the
important post-condition that the output range is a permutation of the input range.
This is the kind of precision that is necessary for the language of post-conditions
and invariants to pay off, and we have not even talked about validating the
is-permutation postcondition without violating the algorithmic complexity constraint
of a good <tt>sort</tt> algorithm.
</p>

<h3><a name="3.3">Benefits of Language Support</a></h3>
<p>
There are real benefits to including language support for contracts, and specifically
for pre-condition contracts.  While invariants and post-conditions are the
responsibility of the library implementer, and can be adequately checked with a good
test suite, pre-condition violations are the responsibility of the library caller.
Anything we can do to make it easier for library users to find their own errors in
calling 3rd party code should lead to more reliable software.
</p>

<p>
In addition, by exposing (selected) contract details to the compiler, they become
accessible to the optimizer.  While the effect is not as significant without the
benefit of post-conditions and invariants to eliminate redundant code and checks,
some progress is still to be expected.  For example (see appendix A) the relatively
common case of non-null pointers is inferred in compilers today for parameters that
pass by reference.
</p>

<p>
If we can move the pre-condition checks to the caller's side of the function call,
then they become amenable to additional optimizations, from simple instruction
reordering to dead code elimination and beyond.
</p>

<p>
A further benefit of exposing contract details directly in the language is that they
become accessible to a wider variety of tools than just the compiler.  Such tools
could help the user find errors in their code, provide hints in IDEs and text editors,
help direct test coverage tools, and more.
</p>

<h2><a name="4.0">Proposed Solution</a></h2>
<p>
The solution formally proposed here is to add a simple syntactic extension to
support declaring pre-conditions in function contracts, and specifically to
<b>not</b> extend that syntax to support post-conditions and invariants.  If a
contract violation is detected at runtime, a user-installable violation handler
will be called, using the facility already documented in
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4075.pdf">N4075</a>.
</p>


<h3><a name="4.1">Straw Man Syntax</a></h3>
<p>
For the sake of the design discussion, I propose the simplest syntax that I can
imagine, but expect both simpler and more details variants will emerge if this
direction is deemed worth pursuing.  For now, I suggest extending the <tt>requires</tt>
clauses from the Concepts Lite TS to allow additional non-constexpr expressions that
depend on function parameters, including the implicit <tt>this</tt> pointer.
</p>
<pre><code>
template &lt;class T, class Alloc&gt;
class vector {
   // ...

   bool empty();

   T&amp; front() <ins>requires !empty()</ins>;
};
</code></pre>

<h3><a name="4.2">Multiple Build Modes</a></h3>
<p>
One of the key assumptions of this feature is that there will be multiple build
modes in the compiler.  In the <i>checked</i> build mode, then all preconditions
are checked on each function invocation, and if any check failed, then the user
supplied (or default) contract violation handler is called.  In an <i>unchecked</i>
build mode, then violating a checked precondition is core undefined behavior. It
is expected that this will lead to optimizing away the checks, in addition to
allowing additional inferences to be drawn for further optimization.
</p>

<p>
The Core Working Group have long been resistant to formalizing build modes in the
standard and for good reason.  A proliferation of build modes yields a much more
complex language, as we actually have multiple languages according to all valid
combinations of build modes.  However, I believe the existing <tt>assert</tt>
facility has already challenged that notion through the preprocessor changing the
user's code underneath them.  This proposal merely attempts to make those existing
build modes accessible to the compiler, so that they can be reasoned about more
effectively.
</p>

<h3><a name="4.3">Checking From The Caller</a></h3>
<p>
The intent is to move the pre-condition check out of the function body where it
would be today as an <tt>assert</tt>, and evaluate before the function from the
user's calling context.  Hence, if an error is detected, the file and line number
supplied to the violation handler will be those of the user's code, and not the
library, greatly simplifying bug tracking.
</p>

<p>
The author imagines at least two techniques that could be used to accomplish this.
The first is to inline the precondition checks directly into each call site, much
like expanding an inline function.  This is expected to yield the best opportunity
to the optimizer to efficiently handle the code, at the expense of potential code
bloat. The second technique would be to add a second entry point to each function
having a precondition and having the caller pick the entry point appropriate to
their build mode.  Note that <tt>__FILE__</tt>, <tt>__func__</tt> and
<tt>__LINE__</tt> need to be captured before calling the pre-amble in this case.
</p>

<h3><a name="4.4">Interaction With <tt>noexcept</tt></a></h3>
<p>
One of the motivating factors to produce this paper now is the ongoing discussion
in the Library Working Groups about appropriate use of <tt>noexcept</tt> in the
standard library specification.  My hope is that this paper gives most folks, most
of the features they want, while not granting absolutely everything to any one
direction.
</p>

<p>
The heart of the issue is that <tt>noexcept</tt> is actually a post-condition
contract built into the language.  The use of <tt>noexcept</tt> in a library
specification constrains how a library implementer may respond to a contract
violation, as they cannot (easily) go outside the core language to deliver their
effect.  This leads to a natural tension between those who value marking up
their contracts for the benefit of the compiler/tools/readers, and those who
value their ability to respond to contract violations in the manner most helpful
to their own users.  The current status quo is that use of <tt>noexcept</tt> on
<i>narrow</i> contracts in the library is a quality of implementation feature,
and not specified by the library standard. 
</p>

<p>
Once we add preconditions to function declarations though, move a large part of
detecting are reporting contract violations to the caller's side of the equation,
where they are visible to the compiler.  This still begs the question: How do
precondition clauses interact with <tt>noexcept</tt>.  There are three common
suggestions.
</p>

<h4><a name="4.4.1">Preconditions are always <tt>noexcept(false)</tt></a></h4>
<p>
In this variation, the existing of any precondition clauses signifies that there
are some build modes where a precondition violation will be detected and handled
by a user supplied callback, that may in turn throw exceptions.  To guarantee
predictable behavior in all build modes, any call to such a function should always
be treated as-if marked with <tt>noexcept(false)</tt>, even if the function itself
is decorated with <tt>noexcept(true)</tt>.
</p>

<h4><a name="4.4.2">Preconditions are ignored</a></h4>
<p>
In this variation, the question considers where the precondition checks are inserted
in the expression being queried by the <tt>noexcept</tt> operator.  For example:
</p>
<pre><code>
template &lt;class T, class Alloc&gt;
class vector {
   // ...

   bool empty();

   T&amp; front() <ins>noexcept</ins>
      <ins>requires !empty()</ins>;
};

vector&lt;int&gt; v;
constexpr bool b = noexcept(v.front());
</code></pre>
<p>
In this example, the <tt>noexcept</tt> expression evaluates whether the call to
<tt>v.front()</tt> can throw exceptions.  We know that the definition of this
function does not throw, but where are the additional checks for the contract
inserted?  If they are inserted <i>before</i> the <tt>noexcept</tt> check, then
they have no bearing on the result in any build mode, and so can be completely
ignored.</p>

<h4><a name="4.4.3">Precondition checks depend on build mode</a></h4>
<p>
In the third variation, we ask the same question as in the second - where do the
precondition checks go in relation to the <tt>noexcept</tt> operator, and pick
the other response.  In this view, the precondition checks do affect whether or
not exceptions can be thrown, but are an artifact of the build mode.  This allows
a <i>release</i> build to realize library optimizations in addition to compiler
optimizations at the risk of taking different code paths than are validated in the
instrumented test environment.
</p>


<h3><a name="4.5">Let The <del>Wookie</del><ins>User</ins> Win</a></h3>
<p>
The recommendation of the author is that trying to pick between these three options
is wasted effort.  Different software development efforts will want to pick different
answers based on their own prevailing design philosophy.  There are different groups
where each of the three answers may be preferable, and groups that may even want
different answers in different parts of their project.  By putting this behavior
under another compiler switch, the library owner does not need to pick a single
answer as the choice is made by the end user building their own software.
</p>

<h2><a name="5.0">Further Issues</a></h2>
<p>
There remain a number of issues not yet addressed by this paper that will need more
effort if this paper is to go forward, with expert input from others more informed
on the specific topics.
</p>

<h3><a name="5.1">One Definition Rule</a></h3>
<p>
The most obvious problem with any conditional code is violation of the ODR, the One
Definition Rule - see ISO 14882 section <b>3.5 [basic.link]</b>.  This is true of
code using the <tt>assert</tt> macro today and would be true for any code relying on
a new precondition language feature.
</p>

<p>
The simplest way to manage the problem, as today, is for users to guarantee that all
of their code is compiled and linked in the same build mode, with the same compiler
flags and predefined macros.  This is not always practical though, and as ODR violations
are not required to be diagnosed, the typical result is that code will build and link
fine, but some translation units might be missing expected checks, or have additional
checks inserted, depending on which definition is selected by the linker.
</p>

<p>
The problem is more serious for inline function and function templates, as use of macros
will clearly violate the token-for-token identical requirement for multiple definitions.
The language feature described about would satisfy the token-for-token requirement, but
may reintroduce the problem that the token-for-token requirement was intended to solve.
This topic needs discussion with experts from the core working group to see if there is
a way to define this notion of 'benign' ODR violation in the special cases of concern to
contract validation.
</p>

<h3><a name="5.2">Declaration vs. Definition</a></h3>
<p>
Is a precondition a part of the function type?  Must it be repeated at both declaration
and definition, or even at every declaration?
</p>
<p>
This topic needs a little more research before nailing down an answer.  Provisionally,
requiring consistency everywhere seems the simplest choice, and easiest for users to
understand as well.  However, I suspect we probably don't want to mangle this into the
type system, leaving a result similar to the old-style exception specifications, which
do not appear a successful precedent to follow.
</p>
<p>
I believe that the key difference with the old exception specifications comes down to
how the feature is expected to be used.  The exception specifications were a post-
condition check that pessimized code for the sake of catching library misuse, and
could not be disabled in a conforming build.  The proposed pre-condition checks are
finding problems in the caller's code, which is of much more interest to the library
consumer, and can optionally be disabled.
</p>
<p>
Encoding the precondition expressions into the function type would solve link-time
issues with the ODR, but mangling arbitrary expressions may cost more in terms of
complexity and symbol name than the feature buys us.
</p>
<p>
The other problem in this space is function pointers and function references.  With
the old exception specifications, the specification applied to a specific function
pointer object, rather than the type of that object, and restricted functions that
could be assigned to that function pointer/reference as having compatible exception
specifications.  Determining arbitrary compatibility for functions with preconditions
could be a complex problem (although perhaps no worse than exception inference) and
again, might not be information that is deemed semantically meaningful in this
context.  It may be that the best design really is to ignore the preconditions when
dealing with function pointers and references, or to bind the such pointer/references
to a call point that performs the precondition check before evaluating the function.
(I.e., to adopt the second suggested implementation strategy, at least when binding
to function pointers or references.)
</p>

<h3><a name="5.3">Querying for Contracts</a></h3>
<p>
Much like the <tt>noexcept</tt> operator for exception specifications, there have
been suggestions that there should be an operator to query if a function has a
<i>wide</i> or <i>narrow</i> contract, and in some cases to query the details of
the compiler-visible contract.  The author does not believe this feature would be
helpful, but it would significantly increase the complexity of the proposal.  There
is no suggestion (at this time) to add such a feature.
</p>

<h3><a name="5.4">Cost of Evaluation</a></h3>
<p>
one of the important features of
<a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4075.pdf">N4075</a>
was a recognition that not all checks are equally desirable in all build modes, and
some users can afford a greater level of checking in some build modes, such as when
trying to track down a particularly difficult to find bug.  This initial proposal
does not include a feature to vary which set of preconditions are evaluated in
different build modes, other than a binary on/off.  It would be simply enough to use
the macro techniques suggested in that paper to implement a similar costing mechanism
using the proposed new facility, but one of the benefits of this approach is to move
away from conditional compilation through macros, and directly express the ideas to
the compiler.  One idea might be to mark up precondition expressions with attributes
reflecting cost, another might be a richer syntax that simply hijacking
<tt>requires</tt> as in the straw-man syntax example presented here.  This remains a
topic for future discussion.
</p>

<h3><a name="5.5">Simple and Elegant Syntax</a></h3>
<p>
The straw man syntax is deliberately simple, using an existing reserved keyword in a
manner similar to how it is already planned to be exploited in the Concepts Lite TS.
One concern with the straw-man is that whether or not an expression is a precondition
or a concepts comes down to whether the evaluation is <tt>constexpr</tt> or not, which
is a very subtle, yet significant, change of meaning.  This may turn out to be less of
a concern than is feared, much like the terse notation of the Concepts Lite TS appears
to overload plain functions with types, and function templates with concepts.
</p>
<p>
Another feature that might be desired is a simpler syntax for expressing simple
constraints on a single function parameter, that might be expressed directly on that
parameter in the function parameter list.  A common example would be the <i>not null</i>
constraint on pointer-like arguments.
</p>

<h3><a name="5.6">Not All Preconditions Are Amenable To Checking</a></h3>
<p>
There remain categories of preconditions that must still be handled by documentation,
and may yield better to traditional <tt>assert</tt>-like treatment in their function
definitions.
</p>
<p>
One classic problem that does not yield to either approach is the notion of an invalid
object.  Good examples are invalidated iterators (passed by reference) or stale pointers.
There is nothing a library author can do to easily validate the state of such objects,
so the contractual preconditions are typically not verified.
</p>
<p>
A second category of precondition is those that leak implementation details.  Declaring
preconditions exposes a certain amount of information in the header where a function
signature is declared.  It may be that the library author wishes to avoid introducing
a dependency on an expensive header, or wishes to preserve their freedom to change an
implementation at a later date without changing the contract.  In such cases, they
would use traditional <tt>assert</tt> like techniques in the function implementation.
Note that this was one of the problems with the early experience of concepts for C++0x.
Constrained function templates typically leaked all of their implementation details
through concepts describing all of the expressions that must be valid when a template
is instantiated.  That is less of a problem for this proposal, as the library author
chooses with parts of their contract to expose to the compiler, rather than being
forced to expose the whole implementation.
</p>

<h2><a name="6.0">Summary</a></h2>
<p>
Contracts form the basic interaction between a library and their users.  As such,
it is valuable to be able to annotate functions in a way that can expose contract
information to the compiler and other tools.  However, the final arbiter of what
contract checking is performed, if any, at runtime and how that interacts with
other contracts expressed in the language should be ultimately decided by the end
user assembling the final software product, who can pick a set of options that
conform with their particular development philosophy.  There is no single approach
this rings true for all.
</p>

<h2><a name="7.0">Appendix A: Existing Support for Contracts in C++14</a></h2>
<p>
There are a number of features in the language that already convey contractual
information from the library to the compiler, to help the user find errors early
in their development.
</p>

<h3><a name="7.1"><tt>const</tt> Correctness</a></h3>
<p>
The most obvious example is <tt>const</tt> correctness.  This provides a compile-
time check at the call site that a non-modifiable object is not passed into a
function that is declared to take a pointer or reference that may modify the
referenced argument.  This also comes with some post-condition (compile-time)
checking, as any attempt to modify an object from a <tt>const</tt> function member
will be caught as an error.
</p>

<h3><a name="7.2">Non-null Pointers</a></h3>
<p>
One of the most commonly encountered narrow contracts is that a pointer not be
null.  This case is supported directly in the C++ language (but not C) through
the use of references, which are not allowed to bind to null pointers.  A function
written with references in its interface clearly advertises that it must be passed
a valid object, and the compiler can optimize based on the knowledge that the hidden
pointer cannot be null.
</p>

<h3><a name="7.3"><tt>unsigned</tt> Integer Types</a></h3>
<p>
A function that cannot handle negative values can indicate this by taking its arguments
as unsigned parameters.  Often this is merely simplifying a contract to have a single
upper bound, rather than both upper and lower bounds, but may be sufficient to widen a
contract completely.
</p>
<p>
Note that there is still a strong school of thought that it is easier to detect misuse
of passing a negative value through an asserted precondition than specifying a single
large upper bound.  The <tt>unsigned</tt> quantity is mostly a valuable hint for tools
examining functions for inferred contracts.
</p>

<h3><a name="7.4">Ownership Patterns And RAII</a></h3>
<p>
One of the key contracts built into the language is that for any successfully constructed
object, unless it has dynamic storage duration, it destructor is guaranteed to be called.
This is commonly exploited in library design.  A common idiom used in library contracts is
the notion of a <i>smart-pointer</i>, where the class confers additional ownership semantics
on the owned pointer, allowing ownership of dynamic objects to be easily tracked across
function boundaries by users and tools alike.
</p>

<h3><a name="7.5">Pure Virtual Functions</a></h3>
<p>
Declaring a pure <tt>virtual</tt> function guarantees that objects of a functionally
incomplete base class cannot be accidentally created.  This catches a category of user
error at compile time, early in the development cycle.
</p>

<h3><a name="7.6"><tt>override</tt> Specifier In C++11</a></h3>
<p>
The <tt>override</tt> specifier in C++11 allows a library user to inform the compiler that
they believe they are implementing a contract on a supplied library by correctly overriding
a specific virtual function.  This allows the compiler to check and flag an error to the
user, granting greater confidence in the client code, and catching unexpected changes to the
underlying library in a fast-evolving code base.
</p>

<h3><a name="7.7"><tt>static_assert</tt></a></h3>
<p>
The <tt>static_assert</tt> language feature was a direct result of some of the early work on
contracts for C++11.  This declares to the compiler a condition that must always be true.  It
can be used to track problems building on different architectures (e.g., size or alignment of
a type is not as expected) or when instantiating templates with user-supplied types.
</p>

<h3><a name="7.8">Concepts</a></h3>
<p>
The pending Concepts Lite TS provides a rich feature that is all about defining contracts in
the type system for generic code and templates.
</p>

<h3><a name="7.9"><tt>noexcept</tt></a></h3>
<p>
The <tt>noexcept</tt> exception specification is a post-condition contract that the compiler
can query through the <tt>noexcept</tt> operator.  By understanding this important post-condition,
generic code can be tuned to take an optimal choice of library implementation.  In addition, the
compiler can perform some mechanical optimizations when it sees no expression inside a block can
throw.
</p>

<h3><a name="7.10"><tt>[[noreturn]]</tt></a></h3>
<p>
The <tt>[[noreturn]]</tt> attribute is another post-condition contract that the compiler can
use to perform certain local optimizations, but mostly to better inform tools when a code-path
will not return without requiring it to solve the halting problem.  This leads to better
diagnostics, helping the user find problems earlier, or at least have confidence that the
tools are not reporting false-positives on impossible conditions.
</p>

<h2><a name="8.0">Acknowledgements</a></h2>
<p>
The author would like to thank John Lakos for explaining the importance of contracts to
libraries, and in particular for coining the terms for <i>narrow</i> and <i>wide</i> contracts
that simplify an important aspect of discussions in this area.  Thanks also to Chandler Carruth
who helped clarify why a library contract violation is a distinct category from general
undefined behavior.  Additional thanks to Thorsten Ottosen and Lawrence Crowl for their
pioneering work bringing this topic to the attention of the committee almost a decade ago!
Finally, thanks to Kevlin Henney for showing me that proof-checking detailed contracts in the
language, while great in principle, rarely works as well in practice.  While they are all
sources of great inspiration, this paper in no way attempts to characterize their own opinions
on the subject, and should not be read as an implicit endorsement on their part!
</p>
</body>
</html>

