\newcommand\labelcolor{OliveGreen}


\newcommand\trefc[4]{
\ensuremath{
  \langle
	\texttt{\{#1:} #2  \texttt{|} #3 \texttt{\}}
  \rangle
	^{\color{\labelcolor}#4}
}}

\newcommand\mklabel[1]{\color{\labelcolor}{#1}}

\definecolor{colorint}{rgb}{0.71,0.33,0.14}

\newcommand\trefint[2]{\trefc{v}{{\color{colorint}\texttt{Int}}}{#1}{#2}}
\newcommand\trefpos[1]{\trefint{v>0}{#1}}

\newcommand\tyint{{\color{colorint}\texttt{Int}}}
\newcommand\ttpos{
\texttt{\{v:{\color{colorint}Int}|v > 0\}}
}

\newcommand\ttpred[1]{
\texttt{\{v:{\color{colorint}Int}|v = #1 - 1\}}
}

\newcommand\tteq[1]{
\texttt{\{v:{\color{colorint}Int}|v = #1\}}
}

\newcommand\tlabel{\rulename{T-Label}}
\newcommand\tcast{\rulename{T-Cast}}

\newcommand\cbase{\rulename{C-Base}}
\newcommand\cfunction{\rulename{C-Fun}}


\newcommand\predname{{\color{blue}\texttt{pred}}}
\newcommand\prednamep{{\color{blue}\texttt{pred'}}}

\newcommand\elabel[1]{\ensuremath{\Uparrow {\mklabel{#1}}}}
\newcommand\ecast[3]{\ensuremath{\langle #1 \Rightarrow #2 \rangle^{{\mklabel{#3}}}}}

\newcommand\isCompatible[2]{\ensuremath{ #1 \Vert #2 }}

\chapter{Undecidable Systems}\label{sec:undec}

In systems where the refinement language can have arbitrary program expressions,
higher order predicates can be expressed, thus the verification procedure is undecidable.
%
There are many alternatives to reason in such languages;
in this section we will present two of them.
Firstly, we present \textit{Interactive theorem proving},
where the proofs are statically provided by the user.
Secondly, we present \textit{Contracts Calculi},
where the specifications are checked at run time.
%Finally, we present \textit{Hybrid Type Checking}; 
%where the assertions are checked statically whenever possible
%and dynamically when necessary.

\section{Interactive theorem Proving}
% intro
One approach to verify that a program satisfies some 
specifications is for the user to statically prove them.
% 
This approach is used by \textit{interactive theorem provers}, 
such as 
NuPRL \cite{Constable86},
Coq \cite{coq-book}, F$^\star$ \cite{SwamyCFSBY11}, Agda \cite{norell07}
and Isabelle \cite{NPW2002}
that can express mathematical assertions, 
mechanically check proofs of these assertions, 
help to find formal proofs, 
and extract a certified program from 
the constructive proof of its formal specification.

% overview 

As an example, consider once again the @pred@ function
that computes the predecessor of a positive number.
$$\centering
\begin{tabular}{c}
\begin{codeCoq}
pred :: s:{n : nat | n > 0}  -> {v:nat | s = S v}
\end{codeCoq}
\end{tabular}
$$
This type signature says that if @pred@ is called with a 
positive number @s@, it will return @s@'s predecessors. 
There are two different assertions that should be proved:
\begin{itemize}
\item The result of the function is the predecessor of the argument.
At @pred@'s definitions the programmer should provide a proof
that this assertion is indeed satisfied.
\item The argument is a positive number.
At each call site of @pred@, 
the user should provide a proof that 
its argument is positive.
\end{itemize}

% implementation
\begin{figure}
$$\centering
\begin{tabular}{c}
\begin{codeCoq}
Inductive sig (A : Type) (P : A -> Prop) : Type :=
    exist : forall x : A, P x -> sig P
Notation
  "{ x : A | P }" := sig (fun x : A => P)

Definition pred (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
  match s return {m : nat | proj1_sig s = S m} with
    | exist 0 pf => match zgtz pf with end
    | exist (S n') pf => exist _ n' (eq_refl (S n'))
  end.
\end{codeCoq}
\end{tabular}
$$
\caption{The pred function in Coq}
\label{fig:coq}
\end{figure}

To illustrate programming with refinement types in Coq, 
we define the @pred@ function,
as presented in Figure \ref{fig:coq}, following \cite{cpdt}.
%
In Coq
the refinement type 
is defined in the standard library, 
and is syntactic sugar,
for the type family @sig@.
The function @pred@ takes an argument @s@ which has two components:
a natural number @n@
and a proof @pf@ that this number is positive.
There is a case analysis on @s@:
if @n@ is zero, then 
the proof @pf@ is used to construct a proof that zero is greater that zero (using a lemma @zgtz@)
and thus reach a contradiction; so this case can not occur.
Otherwise, @n@ has a predecessor, say @n'@ and 
the function returns @n'@ combined with a proof that its successor is 
equal to @n@. This proof is constructed by applying @eq_refl@, the only constructor
of equality to @S n'@.


\begin{comment}
where zgtz

\begin{verbatim}
Lemma zgtz : 0 > 0 -> False.
  crush.
Qed.

Inductive eq (A:Type) (x:A) : A -> Prop :=
    eq_refl : x = x :>A
\end{verbatim}
\end{comment}

In the call site of @pred@, the programmer should provide
both the argument and a proof that it is positive.
As an example,
if @two_gt0@ is a proof that two is greater than zero, we can have

$$\centering
\begin{tabular}{c}
\begin{code}
pred (exist _ 2 two_gt0)
\end{code}
\end{tabular}
$$
 
This application typechecks, as Coq verifies that 
the argument satisfies @pred@'s precondition, i.e., that  
@two_gt0@ is indeed a proof that @2@ is greater than 0. 

\begin{comment}
Theorem two_gt0 : 2 > 0.
  crush.
Qed.
\end{comment}

Even though this example seems tedious, 
interactive theorem proving can be simplified
using inference and tactics. 
%
However, the user still needs to provide proofs.
%
We discuss other systems, which remove this burden from the user.

\section{Contracts}
% intro
Another approach to verify that a program satisfies some 
assertions is to dynamically check them.
% 
These assertions are called \textit{contracts}, i.e., 
dynamically enforced pre- and post-assertions that
define formal, precise, and verifiable interface specifications 
for software components.
%	
Their use in programming languages dates back to the 1970s,
when Eiffel \cite{Eiffel}, an object-oriented programming language,
totally adopted assertions and developed the 
``Design by Contract'' philosophy \cite{Meyer92}.

%In many systems contracts consist of a refinement type with a supersript:
Contracts are of the form:
\trefc{v}{\tau}{p}{l}.
The refinement part, as usual,  describes the values $v$, of type $\tau$
that satisfy the predicate $p$. 
The $\mklabel{l}$ superscript is a \textit{blame label}, used to
identify the source of failures.
%
As an example, 
consider a contract for positive integers \trefpos{l}
applied to two values, $2$ and $0$: 
\begin{align*}
\trefpos{l'}\ 2 &\rightarrow	 2 \\
\trefpos{l}\ 0 &\rightarrow\ \elabel{l}
\end{align*}
%
If the check succeeds, as in the case for $2$,
then the application will return the value, so the first 
application just returns $2$.
If it fails, then the entire program will ``blame'' the label $\mklabel{l}$,
raising an uncatchable exception  \elabel{l}, pronounced ``blame $l$''.

% higher-order 
\begin{comment}
Assigning blame for contractual violations in higher-order languages
is complex:
%
The boundaries between cooperating components are more obscure 
than in the world with only first-order functions. 
A function may invoke a function passed to it at its call site.
Accordingly, the blame for a corresponding contract violation must 
lie with the supplier of the bad value, 
no matter if the bad value was passed by directly applying 
a function or by applying a base value.
%
\end{comment}
In 2002, Findler and Felleisen \cite{Findler02} were the first to
create a system for higher order languages with contracts.
%
In their system, the blame is properly assigned in the 
higher-order components of the program via a
``variance-contravariance'' rule.
% Other features
Moreover,
they allow dependent contracts, i.e., 
contracts that have the form of a refinement function type, 
where the result can depend on the argument.
Finally,
they treat contracts as first class values, 
i.e., contracts are values that can be passed to and from functions.
%
In 2004, Blume and McAllester \cite{BlumeM06} 
formally defined contract satisfaction on Findler and Felleisen's system,
and they proved that their system is indeed
sound and complete.
%
The contract system is sound if whenever
the algorithm blames a contract declaration, 
that contract declaration is actually wrong.
%
Conversely, it is complete if blame on an expression is explained
by the fact that the expression violates one of it contract interfaces.

% Contracts and refinement types 
Since Findler and Felleisen's work 
a variety of contract calculi systems have been studied. 
Broadly, these come in two different sorts. 
%
In systems with \textit{latent contracts}, types and contracts
are orthogonal features. Examples of these systems include Findler
and Felleisen's original system, Hinze \etal \cite{Hinze06}, Blume and
McAllester \cite{BlumeM06}, Chitil and Huch \cite{ChitilH07}, Guha \etal \cite{GuhaMFK07},
and Tobin-Hochstadt and Felleisen \cite{Tobin-HochstadtF08}. 
By contrast, \textit{manifest contracts} are integrated into the type system, 
which tracks, for each value, the most recently checked contract. 
Hybrid types \cite{flanagan06} are a well-known example in this style; others include the
work of Ou \etal \cite{Ou2004}, Wadler and Findler \cite{WadlerF09}, Gronski
\etal \cite{Gronski06}, Belo \etal \cite{Greenberg11}, and Grennberg \etal \cite{Greenberg12}.
%
In the rest of this subsection we discuss manifest contracts and
present a core calculus for them.

\subsection{Manifest Contracts}

Manifest Contracts Systems~\cite{Greenberg12}, use casts
\ecast{\tau_s}{\tau_t}{l}
to convert values from the source type $\tau_s$ 
to the target type $\tau_t$ and raise \elabel{l}
if the cast fails.

As an example, consider a cast from integers to positives:
$$
\ecast{\tyint}{\ttpos}{l} \ \texttt{n}
$$
The system should statically verify that the value @n@ is 
of the source type @Int@.
After the cast, this value is treated as
if it has the target type \ttpos.
At run-time, a check will be made that @n@ 
is actually a positive integer and if it fails it will raise \elabel{l}.

To generalize, for base contracts a cast will behave just like a check on the target type: 
applied to @n@, the cast either returns @n@ or raises \elabel{l} . 
%
A function application cast 
$(\ecast{\tau_{11} \texttt{ -> } \tau_{12}}{\tau_{21} \texttt{ -> } \tau_{22}}{l} \ \texttt{f} ) \ \texttt{v}$
will reduce to 
$\ecast{\tau_{12}}{\tau_{22}}{l}\ (
	\texttt{f} \ 
	(
		\ecast{\tau_{21}}{\tau_{11}}{l} 
		\ \texttt{v}
	)
)$
wrapping the argument @v@ in a (contravariant) cast between the domain types
and wrapping the result of the application in a (covariant) cast between the
range types.

To illustrate how function casts work let's once more consider 
the \predname\ example.
%
To get the desired type signature for \predname, 
we have to wrap the function's definition 
in a type cast:
\begin{align*}
& \prednamep\ x= x - 1 \\
& \predname  = \ecast{\tyint \texttt{->} \tyint}{x:\ttpos \texttt{->} \ttpred{x}}{l} \ \prednamep
\end{align*}
If we apply a positive number, say @2 :: {v:Int | v > 0}@, we will have the following computation:
%
\begin{align*}
&\predname\ \texttt{2}\\
&=(\ecast{\tyint \texttt{->} \tyint}{x:\ttpos \texttt{->} \ttpred{x}}{l} \ \prednamep)\ \texttt{2} \\
&\rightarrow^\star (\ecast{\tyint}{\ttpred{2}}{l}) \ (\prednamep(\ecast{\ttpos}{\tyint}{l}\texttt{2})) \\ 
&\rightarrow^\star (\ecast{\tyint}{\ttpred{2}}{l}) \ (\prednamep\ \texttt{2}) \\ 
&\rightarrow^\star (\ecast{\tyint}{\ttpred{2}}{l}) \ \texttt{1} \\ 
&\rightarrow^\star \texttt{1} \\ 
\end{align*}

The first line is @pred@'s definition. In the second line the rule for functional cast is applied.
Then, the check that @2@ is an integer succeeds, and @2@ is applied to \prednamep
so, we get @1@.
Finally, this result is checked to be @1@ and since this check succeeds the value is returned.
%
If \prednamep was not returning the correct value, the program would raise a blame:
\begin{align*}
&\prednamep\ x= 0 \\
&\predname\ \texttt{2} \\
&=(\ecast{\tyint \texttt{->} \tyint}{x:\ttpos \texttt{->} \ttpred{x}}{l} \ \prednamep)\ \texttt{2} \\
&\rightarrow^\star (\ecast{\tyint}{\ttpred{2}}{l}) \ (\prednamep(\ecast{\ttpos}{\tyint}{l}\texttt{2})) \\ 
&\rightarrow^\star (\ecast{\tyint}{\ttpred{2}}{l}) \ (\prednamep\ \texttt{2}) \\ 
&\rightarrow^\star (\ecast{\tyint}{\ttpred{2}}{l}) \ \texttt{0} \\ 
&\rightarrow^\star \elabel{l} \\ 
\end{align*}
The evaluation is the same as in the previous example, 
up to the point where the \prednamep application returns.
Here, the application returns @0@, thus the final check fails 
and the program raises the blame {\mklabel{l}}.

% testing the argument
You may notice that in both cases \prednamep is applied to a 
positive integer.
Since a positive integer is not a primitive type, 
the only way to get such a type is via a cast.
Thus, for this application to statically typecheck, the argument should 
be wrapped in a cast.
But, if we cast a non-positive value to be positive,
then the cast will fail:

\begin{align*}
\predname \ ((\ecast{\tyint}{\ttpos}{zero})\ \texttt{0}) &\rightarrow^\star \elabel{zero}
\end{align*}

We saw that two distinct casts should be used to satisfy the functions pre- and post-conditions.
These casts use different labels, with which we can track the source of failure, if any.

\subsection{Formal Language}
Lets now extend our core calculus $\lambda_c$ to $\lambda_{cc}$,
so that it supports manifest contracts.
%
In the expressions of our language we add a blaming expression
and a type cast.
The refinement language includes any core expression.
Everything else remains unchanged.


In the typing judgements we add two rules:
a blame expression can have any well-formed type, 
while a type cast expression behaves as a function from the 
source to the target type.
For a casting expression to typecheck, both types should be 
well-formed and compatible, i.e., their unrefined types should be 
the same. We check this with a new compatibility judgement.

\begin{figure}[ht!]
\centering
$$
\begin{array}{rrcl}
\emphbf{Expressions} \quad 
  & e 
  & ::= 
  & 		 \dots
  \spmid \elabel{l} 
  \spmid \ecast{\tau}{\tau}{l} 
  \\[0.05in] 

\emphbf{Predicates} \quad 
  & p
  & ::= 
  &		e
  \\[0.05in] 

\end{array}
$$
\caption{\textbf{Syntax} from $\lambda_C$ to $\lambda_{CC}$}
\label{fig:syntax}
\end{figure}


\begin{figure}[ht!]

\medskip \judgementHead{Compatibility}{$\isCompatible{\tau_1}{\tau_2}$}
$$\begin{array}{cc}

\inference
  {}
  {\isCompatible{\tref{b}{p_1}}{\tref{b}{p_2}}}
  [\cbase]

&

\inference
  {\isCompatible{\tau_{x_1}}{\tau_{x_2}} &&
   \isCompatible{\tau_1}{\tau_2}}
  {\isCompatible{\tfun{x_1}{\tau_{x_1}}{\tau_1}}{\tfun{x_2}{\tau_{x_2}}{\tau_2}}}
  [\cfunction]
\end{array}$$



\medskip \judgementHead{Type Checking}{$\hastype{\Gamma}{e}{\tau}$}
$$\begin{array}{cc}

\inference
  {\isWellFormed{\Gamma}{\tau}}
  {\hastype{\Gamma}{\elabel{l}}{\tau}}
  [\tlabel]
&
\inference
  {\isWellFormed{\Gamma}{\tau_1} &&
   \isWellFormed{\Gamma}{\tau_2} && 
   \isCompatible{\tau_1}{\tau_2}}
  {\hastype{\Gamma}{\ecast{\tau_1}{\tau_2}{l}}{(\tfun{x}{\tau_1}{\tau_2})}}
  [\tcast]
\end{array}$$


\caption{\textbf{Static Semantics} from $\lambda_C$ to $\lambda_{CC}$}
\label{fig:rules}
\end{figure}

\begin{comment}
\section{Hybrid Type Checking}

The great disadvantage of contract calculi is that all contracts are checked in runtime, 
so type checking consumes cycles that otherwise would perform useful computation.
Moreover limited coverage is provided: contracts are checked only for data values and
code paths of actual execution.
This disadvantages are eliminated in Flanagan's Hybrid Type Checking \cite{flanagan06}.
%

Apart from type casting, Flanagan used syntactic subtyping to convert values from one type to another.
As an example, we know that @2@ is an integer exactly equal to @2@
and we want to deduce that it is a positive number.
We write :
$$\tteq{2} \preceq \ttpos $$
This relation means that every value that has the left-hand side type
should also have the right-hand side type. 
Subtyping reduces to implication checking, as discussed in \ref{subsec:formal}.
In our example, we get the implication:
$$ v = 2 \Rightarrow v > 0$$
which is easy to prove with some algorithm that uses linear arithmetic.

Flanagan's type system checks implications statically, whenever possible
and dynamically, only when necessary.
He assumes that 
there exists an algorithm that within limited time can
conservatively approximate implications between predicates.
Say that we know that %in an environment $\Gamma$, 
$e :: \tau_s$ and we want to use $e$ as if it had a target type $\tau_t$, %that $e :: \tau_t$, 
then we have to prove that the source type is subtype of the target, 
or $\tau_s\preceq \tau_t$. 
Subtyping is reduced to implication checking, thus implications of the form
$e_s \Rightarrow e_t$ are created.
If we apply the algorithm to each implication, there are three cases:
\begin{itemize}
\item The algorithm proves that all implications hold, 
 $\vdash e_s \Rightarrow e_t$, 
which implies that $\tau_s\preceq \tau_t$ always holds.
\item The algorithm proves that some implication does not hold, 
$\nvdash e_s \Rightarrow e_t$, 
which implies that the subtyping does not hold %the related contract
%will always fail 
and the program is rejected as unsafe.
\item The algorithm can not prove any of the above.
Thus, the expression $e$ is annotated with a type cast \ecast{\tau_s}{\tau_t}{}
to dynamically ensure that values returned by $e$ are actually of the desired type $\tau_t$.
\end{itemize}

So the program is transformed to include all required type casts, 
i.e., the ones that can neither be statically proved nor rejected.


Compared to manifest contacts, Hybrid type system has two advantages:
First, type casts are automatically created, thus the annotation burden is lower for
the programmer.
Moreover, whenever possible, subtyping is statically checked, which leads to both
limiting the run-time checks and broader coverage of the contract checks.

As an application, Sage\cite{Gronski06} is 
a purely functional programming language that performs hybrid type checking
and queries the Simplify \cite{Simplify} Theorem Prover for implication checking.

\subsection{Formal Language}
We will extend our core language $\lambda_{CC}$ to $\lambda_{CH}$,
so as to support hybrid type checking. 
The syntax of the language is not extended, but we need to add the subtyping rules.
As we stated, the source program goes through a transformation and the necessary casts are added.
Thus, every time the \tsub rule is used, 
it is guaranteed that the algorithm can either prove or reject
the subtyping relation.
Thus, the subtyping relation is decidable.

The rule \tsub is the one defined in the \ref{subsec:formal}
where the \texttt{Valid} predicate refers to the algorithm used 
for implications checking.

\begin{figure}[ht!]
\medskip \judgementHead{Type Checking}{$\hastype{\Gamma}{e}{\tau}$}

$$\begin{array}{cc}

\inference
  {  \hastype{\Gamma}{e}{\tau_2} && \isSubType{\Gamma}{\tau_2}{\tau_1} 
  && \isWellFormed{\Gamma}{\tau_1}
  }
  {\hastype{\Gamma}{e}{\tau_1}}
  [\tsub]
\end{array}$$

\caption{\textbf{Static Semantics} from $\lambda_{CC}$ to $\lambda_{CH}$}
\label{fig:rules}
\end{figure}
\end{comment}
 
