\documentclass[letterpaper,11pt]{article}
\usepackage{ltcadiz}

%%side margin is 1.0in + oddside, so we're creating a 1 inch margin
\oddsidemargin 0.0in
\topmargin 0.0in
\textwidth 6.5in

\usepackage{fullpage}

\title{Z Example Taken from Some Homework}

\begin{document}

\maketitle

\section*{Introduction}

The Class Manager's Assistant module must provide an interface for dealing
with students enrolling in a class.  Students enroll in a class.  The result
of the enrollment is specified by \emph{EnrollResponse}.  At some point in
time, a student may be tested; it is assumed that a student will pass the
test.  When a student is tested, the Class Manager's Assistant must provide
an appropriate \emph{TestResponse}.

\vspace{1 em}

Given Set [Student]

    $| size: \nat$
    \begin{zed}
    EnrollResponse :: = success | alreadyenrolled \\
    TestResponse ::= success | alreadytested | notenrolled \\
    \end{zed}

\section*{Abstract State Schema}

For a \emph{Class} in the Class Manager's Assistant, a student must enroll in
a class to be considered enrolled.  Once a student is enrolled, the student
may be tested.

    \begin{schema}{Class}
    enrolled: \bbold{P} Student \\
    tested: \bbold{P} Student
    \where
    tested \subseteq enrolled \\
    \# enrolled \leq size
    \end{schema}

\section*{Initialization of Abstract State}

It is initially assumed that a class is empty, and therefore has no students
enrolled.

    \begin{zed}
    [Class' | enrolled' = 0 ]
    \end{zed}

\section*{Operation - Enroll}

When a student requests to be enrolled, that student is added to the Class.

    \begin{schema}{EnrollOK}
    \Delta Class \\
    S? : Student \\
    R! : EnrollResponse \\
    \where
    S? \notin enrolled \\
    enrolled' = enrolled \union \left\{ S? \right\} \\
    R! = success \\
    \end{schema}

If a student has already enrolled, then that student can not enroll in the
Class again.  Please note that this would be regardless of the student's
test status since $tested \subseteq enrolled$.

    \begin{schema}{AlreadyEnrolled}
    \Xi Class \\
    S? : Student \\
    R! : EnrollResponse \\
    \where
    S? \in enrolled \\
    S? = alreadyenrolled \\
    \end{schema}

Therefore, the enroll operation must be the disjunction of EnrollOK and
AlreadyEnrolled.

    \begin{zed}
    Enroll \triangleq EnrollOK \vee AlreadyEnrolled
    \end{zed}

\section*{Operation - Test}

When an enrolled student is tested, the student passes and is now part of the
student population in the class marked as tested.

    \begin{schema}{TestOK}
    \Delta Class \\
    S? : Student \\
    R! : TestResponse \\
    \where
    S? \in enrolled \\
    S? \notin tested \\
    tested' = tested \union \left\{ S? \right\} \\
    enrolled' = enrolled \\
    R! = success \\
    \end{schema}

If a student has not enrolled, then the attempt to test the student must
necessarily fail.

    \begin{schema}{NotEnrolled}
    \Xi Class \\
    S? : Student \\
    R! : TestResponse \\
    \where
    S? \notin enrolled \\
    S? = notenrolled \\
    \end{schema}

In addition, a student can not be tested twice.

    \begin{schema}{AlreadyTested}
    \Xi Class \\
    S? : Student \\
    R! : TestResponse \\
    \where
    S? = tested \\
    R! = alreadytested \\
    \end{schema}

Therefore, the test operation must be the disjunction of TestOK, NotEnrolled,
and AlreadyTested.

    \begin{zed}
    Test \triangleq TestOK \vee NotEnrolled \vee AlreadyTested
    \end{zed}

\end{document}


\documentclass[12pt]{cdblatex}
\usepackage[final]{pdfpages}
\usepackage{bssn-eqtns}

\begin{document}

\input{bssn-eqtns-09.cdbtex}
\input{bssn-eqtns-10.cdbtex}
\input{bssn-eqtns-11.cdbtex}
\input{bssn-eqtns-12.cdbtex}
\input{bssn-eqtns-14.cdbtex}
\input{bssn-eqtns-20.cdbtex}

\input{bssn-constraints.cdbtex}
\input{bssn-ricci-scalar.cdbtex}

\section*{The BSSN evolution equations. Pt.1}

These are the equations as given in the Phys.Rev.D (62) 044034 paper.

\begin{dgroup*}
   \begin{dmath*} \cdb{eq09.00} = \Cdb*{eq09.01} \end{dmath*}
   \begin{dmath*} \cdb{eq10.00} = \Cdb*{eq10.01} \end{dmath*}
   \begin{dmath*} \cdb{eq11.00} = \Cdb*{eq11.01} \end{dmath*}
   \begin{dmath*} \cdb{eq12.00} = \Cdb*{eq12.01} \end{dmath*}
   \begin{dmath*} \cdb{eq20.00} = \Cdb*{eq20.01} \end{dmath*}
   \begin{dmath*} \cdb{eq14.00} = \Cdb*{eq14.01} = \Cdb*{eq14.02} \end{dmath*}
\end{dgroup*}

The next task is to rewrite the right hand sides of this set of equations
in terms of the BSSN variables and their partial derivatives.

The results are summarised on the following page.

\clearpage

\section*{The BSSN evolution equations. Pt.2}

Notice that equation (14) contains $\partial{\bar\Gamma}^i$ but not $\bar\Gamma^i$. This is a consequence of the advice given by Alcubierre, Brugmann etal. (Phys Rev D (67) 084023,
2nd-3rd paragraph on pg. 084023-4)

\begin{quote}
... if one wants to achieve numerical stability. In the computer code we do not use the numerically
evolved ${\bar{\Gamma}}^i$ in all places, but we follow this rule:

Partial derivatives $\partial_j {\bar{\Gamma}}^i$ are computed as finite differences
of the independent variables ${\bar{\Gamma}}^i$ that are evolved using ...
\end{quote}

Compare equation (14) on the previous page and that on this page.

\begin{dgroup*}
   \begin{dmath*} \cdb{eq09.00} = \Cdb*{eq09.99} \end{dmath*}
   \begin{dmath*} \cdb{eq10.00} = \Cdb*{eq10.99} \end{dmath*}
   \begin{dmath*} \cdb{eq11.00} = \Cdb*{eq11.99} \end{dmath*}
   \begin{dmath*} \cdb{eq12.00} = \Cdb*{eq12.99} \end{dmath*}
   \begin{dmath*} \cdb{eq20.00} = \Cdb*{eq20.99} \end{dmath*}
   \begin{dmath*} \cdb{eq14.00} = \Cdb*{eq14.99} \end{dmath*}
\end{dgroup*}

The full details of the above computations can be found on the following pages.

\clearpage

\includepdf[pages=1-]{./bssn-eqtns-09.pdf}
\includepdf[pages=1-]{./bssn-eqtns-10.pdf}
\includepdf[pages=1-]{./bssn-eqtns-11.pdf}
\includepdf[pages=1-]{./bssn-eqtns-12.pdf}
\includepdf[pages=1-]{./bssn-eqtns-14.pdf}
\includepdf[pages=1-]{./bssn-eqtns-20.pdf}
\includepdf[pages=1-]{./bssn-lapse.pdf}
\includepdf[pages=1-]{./bssn-ricci-scalar.pdf}
\includepdf[pages=1-]{./bssn-constraints.pdf}

\end{document}


\documentclass[12pt]{cdblatex}
\usepackage{exercises}
\usepackage{fancyhdr}
\usepackage{footer}

\begin{document}

% --------------------------------------------------------------------------------------------
\section*{Exercise 1.8 Syntax errors -- original code}

\CdbSetup{action=verbatim}

\begin{cadabra}
   {a,b,c,d,e,f#}::Indices.
   C{#}::Symmetric.

   foo := A_{a} B_{b} + C_{ab}.                        # C_{ab} should be C_{a b}
   bah := B_{b} A_{a} + C_{ba}.                        # C_{ba} should be C_{b a}
   meh := @(foo) - @(bah)                              # missing dot or semi-colon terminator

   if meh == 0:
      print ("meh is zero, and all is good")
         success = True.                               # indentation error, drop the dot
   else:
      print ("meh is not zero, oops")
         success = False.                              # indentation error, drop the dot

   canonicalise (meh).                                 # terminate with ; or nothing
   sort_product (meh);

   {\alpha\beta\gamma}::Indices.                       # separate list elements with commas

   foo := Ex ("A_{ab} - A_{a b}");                     # use = for assignment, A_{ab} should be A_{a b}
   bah := Ex ("A_{\alpha\beta} - A_{\alpha \beta}");   # use = for assignment, need raw string in Ex
\end{cadabra}

\clearpage

% --------------------------------------------------------------------------------------------
\section*{Exercise 1.8 Syntax errors -- corrected code}

\CdbSetup{action=show}

\begin{cadabra}
   {a,b,c,d,e,f#}::Indices.
   C{#}::Symmetric.

   foo := A_{a} B_{b} + C_{a b}.                       # cdb (ex-0108.101,foo)
   bah := B_{b} A_{a} + C_{b a}.                       # cdb (ex-0108.102,bah)
   meh := @(foo) - @(bah).                             # cdb (ex-0108.103,meh)

   if meh == 0:
      print ("meh is zero, and all is good")
      success = True
   else:
      print ("meh is not zero, oops")
      success = False

   canonicalise (meh)                                  # cdb (ex-0108.104,meh)
   sort_product (meh);                                 # cdb (ex-0108.105,meh)

   {\alpha,\beta,\gamma}::Indices.

   foo = Ex ("A_{a b} - A_{a b}");                     # cdb (ex-0108.106,foo)
   bah = Ex (r"A_{\alpha\beta} - A_{\alpha \beta}");   # cdb (ex-0108.107,bah)
\end{cadabra}

\begin{align*}
   &\cdb*{ex-0108.101}\\
   &\cdb*{ex-0108.102}\\
   &\cdb*{ex-0108.103}\\
   &\cdb*{ex-0108.104}\\
   &\cdb*{ex-0108.105}\\
   &\cdb*{ex-0108.106}\\
   &\cdb*{ex-0108.107}
\end{align*}

\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 2003-2018 by The University of Queensland
% http://www.uq.edu.au
%
% Primary Business: Queensland, Australia
% Licensed under the Apache License, version 2.0
% http://www.apache.org/licenses/LICENSE-2.0
%
% Development until 2012 by Earth Systems Science Computational Center (ESSCC)
% Development 2012-2013 by School of Earth Sciences
% Development from 2014 by Centre for Geoscience Computing (GeoComp)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Magnetic Inversion With Self-Demagnetisation}\label{sec:forward self demagnetic}
In cases of large susceptibility~\index{susceptibility} $k$ the linear magnetisation assumption
as discussed in the previous Section~\ref{sec:forward magnetic} is not valid and
one assume that magnetisation $M$ is proportional to present magnetic field~\index{magnetic field}
rather than the background magnetic flux
density, see~\cite{Lelievre2006a}.

Analogous to equation~(\ref{ref:MAG:EQU:1}) it is
\begin{equation}\label{ref:SELFREMAG:EQU:1}
B_i = \mu_0 \cdot ( H_i  + M_i )
\end{equation}
where
$B$ is the flux density anomaly, the magnetic field anomaly $H$ and
$\mu_0 = 4 \pi \cdot 10^{-7} \frac{Vs}{Am}$. In extension to equation~(\ref{ref:MAG:EQU:4})
the magnetisation is assumed to be proportional to the
(total) magnetic field $H_i + \frac{1}{\mu_0} B_i^{b}$ in the form
\begin{equation}\label{ref:SELFREMAG:EQU:4}
\mu_0  \cdot M_i = k \cdot ( B_i^{b} + \mu_0  H_i ) \;.
\end{equation}
where $B_i^{(b)}$ is known background geomagnetic flux density $B^b$
(see additional information in Section~\ref{sec:forward magnetic}).

The magnetic field anomaly $H$ can be represented by the gradient of a
magnetic scalar potential\index{scalar potential!magnetic} $\psi$.
We use the form
\begin{equation}\label{ref:SELFREMAG:EQU:6}
\mu_0  \cdot H_i = - \psi_{,i}
\end{equation}
With this notation one gets from Equations~(\ref{ref:SELFREMAG:EQU:1}) and~(\ref{ref:SELFREMAG:EQU:4}):
\begin{equation}\label{ref:SELFREMAG:EQU:7}
B_i = - (1+k) \cdot \psi_{,i}  + k \cdot B^b_i
\end{equation}
As the $B$ magnetic flux density anomaly is divergence free ($B_{i,i}=0$) we obtain the PDE
\begin{equation}\label{ref:SELFREMAG:EQU:8}
- ( (1+k) \cdot \psi_{,i})_{,i} = - (k B^r_i)_{,i}
\end{equation}
with $B^r_i=B^b_i$ which needs to be solved for a given susceptibility $k$.
The magnetic scalar potential is set to zero at the top of the domain
$\Gamma_{0}$.
On all other faces the normal component of the magnetic flux density anomaly
$B_i$ is set to zero, i.e. $(1+k) \cdot  n_i \psi_{,i} = k \cdot n_i  B^b_i$ with outer
normal field $n_i$.

From the magnetic scalar potential we can calculate the magnetic flux density
anomaly via Equation~(\ref{ref:SELFREMAG:EQU:8}) to calculate the defect to the given
data.
If $B^{(s)}_i$ is a measurement of the magnetic flux density anomaly for
survey $s$ and $\omega^{(s)}_i$ is a weighting factor the data defect
$J^{mag}(k)$ in the notation of Chapter~\ref{chapter:ref:inversion cost function} is given as
\begin{equation}\label{ref:SELFREMAG:EQU:9}
J^{mag}(k) = \frac{1}{2}\sum_{s} \int_{\Omega} ( \omega^{(s)}_i \cdot (B_{i}- B^{(s)}_i) ) ^2 dx
\end{equation}
Summation over $i$ is performed.
The cost function kernel\index{cost function!kernel} is given as
\begin{equation}\label{ref:SELFREMAG:EQU:10}
K^{mag}(\psi_{,i},k) = \frac{1}{2}\sum_{s} ( \omega^{(s)}_i \cdot (k \cdot B^b_i - (1+k) \cdot \psi_{,i} - B^{(s)}_i) ) ^2
\end{equation}
Notice that if magnetic flux density is measured in air one can ignore the
$k\cdot B^b_i$ as the susceptibility is zero. See also the remarks on the data defect in Section~\ref{sec:forward magnetic}).

\subsection{Usage}

\begin{classdesc}{SelfDemagnetizationModel}{domain, w, B, background_field,
        \optional{, coordinates=\None}
        \optional{, fixPotentialAtBottom=False},
        \optional{, tol=1e-8},
}
opens a magnetic forward model over the \Domain \member{domain} with
weighting factors \member{w} ($=\omega^{(s)}$) and measured magnetic flux
density anomalies \member{B} ($=B^{(s)}$).
The weighting factors and the  measured magnetic flux density anomalies must be vectors.
\member{background_field} defines the background magnetic flux density $B^b$
as a vector with north, east and vertical components.
\member{tol} sets the tolerance for the solution of the PDE~(\ref{ref:SELFREMAG:EQU:8}).
If \member{fixPotentialAtBottom} is set to  \True, the magnetic potential
at the bottom is set to zero in addition to the potential on the top.
\member{coordinates} set the reference coordinate system to be used. By the default the
Cartesian coordinate system is used.
\end{classdesc}

\begin{methoddesc}[SelfDemagnetizationModel]{rescaleWeights}{
        \optional{scale=1.}
 \optional{k_scale=1.}}
rescale the weighting factors such condition~(\ref{ref:MAG:EQU:12}) holds where
\member{scale} sets the scale $\alpha$
and \member{k_scale} sets $k'$. This method should be called before any inversion is started
in order to make sure that all components of the cost function are appropriately scaled.
\end{methoddesc}

\subsection{Gradient Calculation}
This section briefly explains how the gradient
$\frac{\partial J^{mag}}{\partial k}$ of the cost function $J^{mag}$ with
respect to the susceptibility $k$ is calculated.  We follow the concept as outlined in section~\ref{chapter:ref:inversion cost function:gradient}.

The magnetic potential $\psi$ from PDE~(\ref{ref:SELFREMAG:EQU:8}) is solved in weak form:
\begin{equation}\label{ref:SELFREMAG:EQU:201}
\int_{\Omega}
(1+k) \cdot q_{,i} \psi_{,i} \; dx  = \int_{\Omega}  k \cdot q_{,i}  B^r_i \; dx
\end{equation}
for all $q$ with $q=0$ on $\Gamma_{0}$.
If $\Gamma_{k}$ denotes the region of the domain where the susceptibility is
known and for a given direction $\hat{k}$ with $\hat{k}=0$ on $\Gamma_{k}$ one has
\begin{equation}\label{ref:SELFREMAG:EQU:201aa}
\int_{\Omega}   \frac{\partial J^{mag}}{\partial k} \cdot \hat{k} \; dx  = \int_{\Omega}
\sum_{s} (\omega^{(s)}_j
( B^{(s)}_j-B_{j}))  \cdot ( \omega^{(s)}_i ( (1+k) \cdot \hat{\psi}_{,i} + \hat{k} \cdot \psi_{,i} - \hat{k}  \cdot B^b_i  ) ) \; dx
\end{equation}
with
\begin{equation}\label{ref:SELFREMAG:EQU:201A}
\int_{\Omega} \left(
(1+k) \cdot q_{,i} \hat{\psi}_{,i} +
\hat{k}  \cdot q_{,i} \psi_{,i} \right)
\; dx
= \int_{\Omega} \hat{k} \cdot q_{,i}  B^r_i \; dx
\end{equation}
for all $q$ with $q=0$ on $\Gamma_{0}$. This equation is obtained from equation~(\ref{ref:SELFREMAG:EQU:201})
for $k+\hat{k} \rightarrow  k$ and $\psi+\hat{\psi} \rightarrow \psi$.
With
\begin{equation}\label{ref:SELFREMAG:EQU:202c}
Y_i =   \sum_{s} (\omega^{(s)}_j
(B^{(s)}_j - B_{j}) )  \cdot \omega^{(s)}_i
\end{equation}
Equation~(\ref{ref:SELFREMAG:EQU:201aa}) is written as
\begin{equation}\label{ref:SELFREMAG:EQU:202cc}
\int_{\Omega}   \frac{\partial J^{mag}}{\partial k} \cdot \hat{k} \;  dx  = \int_{\Omega}
(1+k) \cdot  Y_i \hat{\psi}_{,i}  + \hat{k} \cdot  Y_i \psi_{,i} - \hat{k}  \cdot Y_i B^b_i   \; dx
\end{equation}

We then set adjoint function $Y^*$ as the solution of the equation
\begin{equation}\label{ref:SELFREMAG:EQU:202d}
\int_{\Omega} (1+k) \cdot r_{,i} Y^*_{,i} \; dx  =  \int_{\Omega} (1+k) \cdot  r_{,i} Y_i  \; dx  \mbox{ for all } r \mbox{ with } r=0 \mbox{ on } \Gamma_{0}
\end{equation}
with $Y^*=0$ on $\Gamma_{0}$. With $r=\hat{\psi}$ we get
\begin{equation}\label{ref:SELFREMAG:EQU:202dd}
\int_{\Omega} (1+k) \cdot  \hat{\psi}_{,i} Y^*_{,i} \; dx  =  \int_{\Omega}  (1+k)  \cdot \hat{\psi}_{,i} Y_i  \; dx
\end{equation}
and from Equation~(\ref{ref:SELFREMAG:EQU:201A}) with $q=Y^*$ we get
\begin{equation}\label{ref:SELFREMAG:EQU:20e}
\int_{\Omega} (1+k) \cdot  Y^*_{,i}  \hat{\psi}_{,i} \; dx  = \int_{\Omega} \hat{k} \cdot  \left(   Y^*_{,i}  B^r_i - Y^*_{,i} \psi_{,i}  \right) \; dx
\end{equation}
which leads to
\begin{equation}\label{ref:SELFREMAG:EQU:20ee}
\int_{\Omega} (1+k)  \cdot \hat{\psi}_{,i} Y_i   \; dx  =
\int_{\Omega} \hat{k} \cdot  \left(   Y^*_{,i}  B^r_i - Y^*_{,i} \psi_{,i}  \right) \; dx
\end{equation}
and finally
\begin{equation}\label{ref:SELFREMAG:EQU:201a}
\int_{\Omega}   \frac{\partial J^{mag}}{\partial k} \cdot \hat{k} \;  dx  = \int_{\Omega}
\hat{k} \cdot  \left(   Y^*_{,i}  B^r_i - Y^*_{,i} \psi_{,i}
                         + Y_i \psi_{,i} - Y_i B^b_i
 \right)
 \; dx
\end{equation}
or
\begin{equation}\label{ref:SELFREMAG:EQU:201b}
\frac{\partial J^{mag}}{\partial k} =  Y^*_{,i}  B^r_i - Y^*_{,i} \psi_{,i}
                         + Y_i \psi_{,i} - Y_i B^b_i
\end{equation}

\subsection{Geodetic Coordinates }
For geodetic coordinates $(\phi, \lambda, h)$, see Chapter~\ref{Chp:ref:coordinates}, the solution process needs to be slightly modified.
Observations are recorded along the geodetic coordinates axes $\alpha$ rather than the Cartesian axes $i$. In fact we
have in equation~\ref{ref:SELFREMAG:EQU:9}:
\begin{equation}\label{ref:SELFREMAG:EQU:300}
\omega^{(s)}_i \cdot (B_{i}- B^{(s)}_i) = \omega^{(s)}_{\alpha} \cdot (B_{{\alpha}}- B^{(s)}_{\alpha})
\end{equation}
where now $B^{(s)}_{\alpha}$ are the observational data with weighting factors $\omega^{(s)}_{\alpha}$.  Using the
fact that
\begin{equation}
B_{{\alpha}} =
 k \cdot B^b_{{\alpha}} -  (1+k) \cdot  d_{\alpha \alpha} \psi_{,\alpha}
\end{equation}
equation~\ref{ref:SELFREMAG:EQU:10} translates to
\begin{equation}\label{ref:SELFREMAG:EQU:301}
J^{mag}(k) = \frac{1}{2}\sum_{s} \int_{\widehat{\Omega}}
( \omega^{(s)}_{\alpha} \cdot (
(1+k) \cdot  d_{\alpha \alpha} \psi_{,\alpha}
 - k \cdot B^b_{{\alpha}}  + B^{(s)}_{\alpha} ) ) ^2 \; v \; d\widehat{x}
\end{equation}
where $\widehat{\Omega}$ and $d\widehat{x}$ refer to integration over the geodetic coordinates axes. This can be rearranged to
\begin{eqnarray}\label{ref:SELFREMAG:EQU:301bb}
J^{mag}(k)  & = \displaystyle{ \frac{1}{2}\sum_{s} \int_{\widehat{\Omega}}
(  \omega^{(s)}_{\alpha} v^{\frac{1}{2}} d_{\alpha \alpha} \cdot ( (1+k) \cdot
 \psi_{,\alpha} -  k \cdot v_{\alpha \alpha} B^b_{{\alpha}} + v_{\alpha \alpha} B^{(s)}_{\alpha} ) ) ^2 \; d\widehat{x} } \\
  & = \displaystyle{  \frac{1}{2}\sum_{s} \int_{\widehat{\Omega}}
(  {\widehat{\omega}}^{(s)}_{\alpha}\cdot ( (1+k) \cdot  \psi_{,\alpha} -  k \cdot \widehat{B}^b_{{\alpha}}+  \widehat{B}^{(s)}_{\alpha} ) ) ^2 \; d\widehat{x} }
\end{eqnarray}
with
\begin{equation}\label{ref:SELFREMAG:EQU:301b}
 \widehat{\omega}^{(s)}_{\alpha} = \omega^{(s)}_{\alpha} v^{\frac{1}{2}} d_{\alpha \alpha} \mbox{ , }
\widehat{B}^{(s)}_{\alpha}=
\frac{1}{d_{\alpha \alpha}} B^{(s)}_{\alpha}  \mbox{ and } \widehat{B}^b_{{\alpha}} = \frac{1}{d_{\alpha \alpha}}  B^b_{{\alpha}}
\end{equation}
which means one can apply the Cartesian formulation to the geodetic coordinates using modified data.

The magnetic potential is calculated from
\begin{equation}\label{ref:SELFREMAG:EQU:302}
\int_{\widehat{\Omega}} (1+k) \cdot v \; d_{\alpha \alpha}^2 q_{,\alpha} \psi_{,\alpha} \;  d\widehat{x}
=  \int_{\widehat{\Omega}} v \; d_{\alpha \alpha} k \cdot q_{,\alpha}  B^r_{\alpha} \; d\widehat{x}
=  \int_{\widehat{\Omega}}  k \cdot q_{,\alpha}  \widehat{B}^r_{\alpha} \; d\widehat{x}
\end{equation}
with
\begin{equation}\label{ref:SELFREMAG:EQU:302b}
\widehat{B}^r_{\alpha}  =v \; d_{\alpha \alpha} B^r_{\alpha}
\end{equation}
see equation~\ref{ref:SELFREMAG:EQU:201}, and the adjoint function $Y^*$ for $Y_{\alpha}$ (calculated from $\widehat{B}^b$ and $\widehat{B}^{(s)}$ is given from
\begin{equation}\label{ref:SELFREMAG:EQU:303}
\int_{\widehat{\Omega}}(1+k) \cdot  v \; d_{\alpha \alpha}^2 q_{,\alpha} Y^*_{,\alpha } \;d\widehat{x}  =
\int_{\widehat{\Omega}} (1+k) \cdot r_{,{\alpha}} ,Y_{\alpha}  \;d\widehat{x}
\end{equation}
and finally
\begin{equation}\label{ref:SELFREMAG:EQU:310}
\frac{\partial J^{mag}}{\partial k} =
 Y^*_{,\alpha}   \widehat{B}^r_{\alpha} - Y^*_{,\alpha} \psi_{,\alpha}
                         + Y_{\alpha}  \psi_{,\alpha} - Y_{\alpha}   \widehat{B}^b_{\alpha}
\end{equation}
where integration is performed over $\widehat{\Omega}$.


\section{Linearity, Affinity, and Borrows at Work}

\TODO{really good examples. first linearity/affinity (files?), then
  something with borrows (functional arrays), and then something
  really spaced out that pushes the limit}

\subsection{A session on linearity}

A classical example of linearity at work are to control the uses of resources such
as files or network handles.
%
Session types, notably, allow to statically type check protocols.
For instance, the type \lstinline{!int.!int.?int.end} represent a session
where the program must send two integers, receive an integer, then end the session.
%
In this context, it is essential that channels
are used linearly, since every use of the channel
will make the protocol progress and change the type of the channel.

Session types are usually defined with the following operators:

\begin{center}
  \begin{tabular}{r l}
    $\tau ! \mathcal S$ & Send a value of type $\tau$ then continue with protocol $S$.\\
    $\tau ? \mathcal S$& Receive a value of type $\tau$ then continue with protocol $S$.\\
    $\mathcal S \oplus \mathcal S'$& Choose between protocols $S$ and $S'$.\\
    $\mathcal S \operatorname{\&} \mathcal S'$& Offer a choice between protocols $S$ and $S'$.
  \end{tabular}
\end{center}

It is well known that binary session types can be embedded into ML languages
\cite{DBLP:journals/jfp/Padovani17}. We can easily
embed session types in our language and provide the following API:
%
\begin{lstlisting}
type 'S st : lin
val receive: ('a ? 'S) st -> 'a * 'S st
val send : ('a:'k). 'a -> ('a ! 'S) st -{'k}> 'S st
val create : unit -> 'S st * (dual 'S) st
val close : end st -> unit
\end{lstlisting}

\TODO{Explain}

We can then use these primitives to implement a simple addition service.
We do not need any extra linearity annotations in the code: the fact
that the \texttt{st} type is declared as linear is sufficient.
In the case below, \lstinline{add_service} is inferred to be of type
\lstinline{(int ! int ! int ? end) st -> unit}

\begin{lstlisting}
let add_service ep =
  let x, ep = receive ep in
  let y, ep = receive ep in
  let ep = send (x + y) ep in
  close ep
# add_service : (int ! int ! int ? end) st -> unit
\end{lstlisting}

The following code then acts as a client, by sending two messages
and receiving the result.
This code is polymorphic in both argument and return types and could thus
be used to any binary operator.
%
\begin{lstlisting}
let op_client ep x y =
  let ep = send x ep in
  let ep = send y ep in
  let result, ep = receive ep in
  close ep;
  result
# op_client : ('a_1 ? 'a_2 ? 'b ! end) st -> 'a_1 -{lin}> 'a_2 -{lin}> 'b
\end{lstlisting}
% The actual answer from the typechecker looks like this:
% # ('m2:^k2), ('m1:^k1).
% # (^k1 < ^k) & (lin < ^k) =>
% # ('m1 ?'m2 ? 'result ! end) st -> 'm1 -{lin}> 'm2 -{^k}> 'result

In addition, this function can be partially
applied to a channel. Since the closure returned by such a partial
application captures the channel, it can only be used once.
This is reflected by the arrow, \lstinline/-{lin}>/, which is the
type of functions that can only be used once.
The general form of arrows types in \lang is \lstinline/-{k}>/, where
\lstinline/kk/ is an arbitrary kind that describes the behavior of
underlying closure.
For convenience, we shorten \lstinline/-{un}>/ as \lstinline/->/.
Note again that the linearity on the arrows was inferred without
any annotation from the user. In fact, the only difference between the code
presented so far and the examples by
\citet{DBLP:journals/jfp/Padovani17}
is the kind annotation on the type definition of \lstinline/st/.

\TODO{more details?}

Finally, we can compose both server and client.
Failure to fully consume either \lstinline/a/ or \lstinline/b/
would result in a type error.
\begin{lstlisting}
let main1 () =
  let (a, b) = create () in
  add_service a;
  op_client b 1 2
# main : unit -> int
\end{lstlisting}

% \begin{figure}
%   \centering
%   \begin{lstlisting}
% val select : ('S st -{'k}> 'a) -> 'a ot -{'k}> ('S dual) st
% val branch : 'm it -> 'm
%   \end{lstlisting}
%   \caption{Session primitives}
%   \label{api:session}
% \end{figure}

\subsection{Imperative programming}

The programming style used for channels so far is
appropriate for purely functional code.
This style is however fairly bothersome in mutable contexts.
%
To make linearity easier to use for imperative programming, we rely on
{\em borrows}. We present a typical API for mutable affine arrays
in \cref{sig:array} and an example of use in \cref{ex:array}.
We can distinguish three type of operations. Firstly,
function that manipulate the whole
array such as \lstinline/create/ and \lstinline/free/, and behaves exactly
like the functions on channel presented in the previous section.
Second, read-only functions such as \lstinline/get/
manipulates \emph{immutable} borrows. An immutable borrow over array \lstinline/a/
is introduced with \lstinline/&a/ and represent a read-only view of the array.
Finally, mutable functions, such as \lstinline/set/ manipulate
a \emph{mutable borrow}. Mutable borrows, introduced with \lstinline/&!a/
represent a read-write view of the array.

Multiple immutable borrows can be used concurrently and are considered
unrestricted (\lstinline/un/).
A mutable borrow is exclusive, and considered affine (\lstinline/aff/).
Furthermore, any borrow prevents access to the ``raw'' access
as long as they are in use. In \cref{ex:array}, on \cref{ex:array:get},
two immutable borrows are used in the same expression. Once this operation
is done, the borrows are not used anymore, which allows us to take
an exclusive immutable borrow to mutate the array on \cref{ex:array:set}.
Finally we can return the whole array on \cref{ex:array:return} since
none of the borrows are used anymore.

\begin{figure}
  \centering
  \begin{subfigure}{0.48\linewidth}
\begin{lstlisting}
module Array : sig
  type ('a : un) t : aff

  val create : ('a : un) => int -> 'a -> 'a t
  val free : 'a t -> unit

  val length : &('a t) -> int

  val get : &('a t) * int -> 'a
  val set : &!('a t) * int * 'a -> unit
end
\end{lstlisting}
    \caption{Affine primitives}
    \label{sig:array}
  \end{subfigure}\hfill
  \begin{subfigure}{0.5\linewidth}
\begin{lstlisting}
let mk_fib_array n =
  let a = create n 1 in
  for i = 2 to n - 1 do
    let x = get &a (i-1) + get &a (i-2) in(*@\label{ex:array:get}*)
    set &!a i x(*@\label{ex:array:set}*)
  done;
  a(*@\label{ex:array:return}*)
# mk_fib_array : int -> int Array.t
\end{lstlisting}
    \caption{Example of use of affine arrays}
    \label{ex:array}
  \end{subfigure}
\end{figure}

Naturally, \lang also checks that borrows do not escape their point
of use through {\em syntactic regions}. The example
above is reproduce in \cref{ex:array:region} with
regions explicitly delimited by \lstinline/{| ... |}/.
\lang ensures that borrows never escape the smallest enclosing
region.
For instance, On \cref{ex:array:region:get}, \lstinline/&a/ does
not escape the region since the borrow is not captured, and the
region only return integers.
Regions annotations are automatically inserted by \lang using
syntactic information such as borrows and binders.
Users can also annotate regions manually to further restrict the range
of a borrow. In practice, we have found that regions
annotations are very rarely needed in common imperative usage.

\begin{figure}
  \centering
  % \begin{subfigure}{0.6\linewidth}
\begin{lstlisting}
let mk_fib_array n =
  let a = create n 1 in
  for i = 2 to n - 1 do {|
    let x = {| get &a (i-1) + get &a (i-2) |} in(*@\label{ex:array:region:get}*)
    set &!a i x
  |}
  done;
  a(*@\label{ex:array:return}*)
# mk_fib_array : int -> int Array.t
\end{lstlisting}
    \caption{Example from \cref{ex:array} with explicit regions}
    \label{ex:array:region}
  % \end{subfigure}
\end{figure}

\begin{figure}
  \centering
  \begin{subfigure}{0.5\linewidth}
\begin{lstlisting}
let for f a  =
  let n = Array.length &a in
  let rec loop f a i =
    if i < n then (
      f &!a i;
      loop f &!a (i+1)
    )
  in
  loop f &!a 0
# Borrowed m ('a Array.t) tt =>
  (tt -> int -> unit) -> tt -> unit
\end{lstlisting}
    \caption{For loop function for affine arrays}
    \label{ex:array}
  \end{subfigure}
\end{figure}

\section{Hybrid programming styles}

While purely functional data-structure present numerous advantages in term
of correctness and ease of use, they sometimes offer worse performances
than their imperative counterpart. On the other hand, reasoning about imperative
data-structure in the context of sharing is notoriously difficult.
%
In this section, we show how linearity and borrowing allows us to define
a safe API for hybrid arrays that support both immutable and mutable features,
and how it can be used to implement a backtracking sudoku solver.

\begin{figure}
  \centering
  \begin{subfigure}{0.48\linewidth}
\begin{lstlisting}
module type HybArray = sig
  type ('a : un) t : aff

  val create : ('a : un) => int -> 'a -> 'a t
  val free : 'a t -> unit

  val length : &('a t) -> int
  val get : &('a t) * int -> 'a

  val set : &('a t) * int * 'a -> 'a t
  val set_immut : &!('a t) * int * 'a -> unit
end
\end{lstlisting}
    \caption{Signature}
    \label{sig:hybarray}
  \end{subfigure}\hfill
  \begin{subfigure}{0.5\linewidth}
\begin{lstlisting}
module Cow : HybArray = struct
  include Array

  let set (a, i, x) =
    let f k =
      if k = i then x else Array.get (a,k)
    in
    create (length a) f

  let set_mut = Array.set
end
\end{lstlisting}
    \caption{Implementation using copy-on-write}
    \label{ex:cow}
  \end{subfigure}
  \caption{Hybrid arrays -- signature and example implementation}
\end{figure}

\begin{figure}
  \centering
\begin{lstlisting}[multicols=2]
type board = IntSet.t Mat.t

let propagate_line i0 j0 g n =
  for j = j0+1 to size - 1 do
    let cell = Mat.get &g (i0 , j) in
    let cell' = IntSet.remove n cell in
    Mat.set_mut &!g (i0, j) cell'
  done

let propagate i j g n =
  propagate_line i j &!g n;
  propagate_column i j &!g n;
  propagate_square i j &!g n

let rec solve i j g =
  match is_solved &g with
  | true -> Mat.print &g
  | false ->
    let (new_i, new_j) = next_pos (i,j) in
    let try_solution n =
      let new_g =
        Mat.set &g (i,j) (singleton n) in
      propagate i j &!new_g n;
      if is_valid &new_g when
        solve new_i new_j new_g
    in
    let cell = Mat.get &g (i,j) in
    IntSet.iter try_solution cell
\end{lstlisting}
  \caption{Chosen excerpt from the sudoku solver}
  \label{ex:cow}
\end{figure}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:


\chapter{Reflexive Graph Model}
\label{sec:model}

I now present a reflexive graph model of λST. The model is very similar to the
standard set-theoretic models of (dependent) type theories, but it additionally
captures a parametricity property: when we interpret a term $f ∶ \All{n}{T}$,
we get a dependent function
\begin{displaymath}
  ⟦f⟧ ∶ (m ∶ \Size_{<⟦n⟧}) → ⟦T⟧(m)
\end{displaymath}
such that $⟦f⟧(m)$ is independent, in an appropriate sense, of $m$. In other
words, $⟦f⟧$ is size-parametric.

To develop this model, I first introduce its central structure, (propositional)
reflexive graphs and their families. I then show how to interpret each
construct of λST -- sizes, types and terms -- in turn.

\section{Propositional Reflexive Graphs}
\label{sec:model:rgraph}

This section introduces the category of reflexive graphs, which will be used to
interpret sizes and size contexts. The following results are formalised in
\module{Model.\allowbreak RGraph}{Model.RGraph}.

A \Def{reflexive graph} is a tuple $(Δ, ≈_Δ, \refl_Δ)$ where
\begin{AlignAnnot*}
  Δ &∶& \Type \\
  ≈_Δ &∶& Δ → Δ → \Type \\
  \refl_Δ(δ) &∶& δ ≈_Δ δ &\quad ∀ δ ∶ Δ.
\end{AlignAnnot*}
I will generally identify a reflexive graph with its underlying type.

The relation $≈_Δ$ is what distinguishes this model from the standard
set-theoretical model of type theory. As we interpret the constructions of λST
in the next sections, we will define $≈_Δ$ to be \enquote*{equality up to
  sizes}. For example, the interpretation $⟦Δ⟧$ of a size context $Δ$ will have
$δ ≈_{⟦Δ⟧} δ′$ for all $δ$ and $δ′$ because any two interpretations of a size
context should be considered equal up to sizes. This means that we can use
interpretations of sizes internally -- particularly to construct a terminating
interpretation of fixpoints -- but only in such a way that they do not affect
the overall result of a computation.

\begin{remark}
  Each reflexive graph is isomorphic to a presheaf over a particular category.
  Thus, reflexive graphs form a category with families \cite{dybjer1995}, i.e.\ a
  model of Martin-Löf type theory. It is thus not surprising that λST also
  admits a reflexive graph model. Moreover, many of the following results are
  direct consequences of the theory of presheaves, but to keep the presentation
  elementary, I make the constructions explicit.
\end{remark}

A reflexive graph $Δ$ is \Def{propositional} if $≈_Δ$ is a proposition in the
sense of Homotopy Type Theory \cite{hottbook} (i.e.\ for any $δ, δ′ ∶ Δ$ and $p,
q ∶ δ ≈_Δ δ′$, $p = q$) and the underlying type $Δ$ is a set (i.e.\ equality on
$Δ$ is a proposition). We call such a graph a \Def{PRGraph}. These conditions
are trivially fulfilled for all the PRGraphs we consider, so I will silently
omit their proofs.

PRGraphs are simpler than non-propositional reflexive graphs since the proofs
$\refl_Δ(δ)$ are irrelevant. This saves us a lot of effort, particularly in the
formalisation. However, it means that the model probably would not accommodate
theories where the identity type is non-propositional, such as cubical type
theories.

Homomorphisms of PRGraphs are relation-preserving functions. More explicitly, a
\Def{PRGraph morphism} between PRGraphs $Δ$ and $Ω$ is a function $σ$ between
their underlying types such that
\begin{displaymath}
  δ ≈_Δ δ′ ⇒ σ(δ) ≈_Ω σ(δ′) \quad ∀ δ, δ′ ∶ Δ.
\end{displaymath}
Given a proof $p ∶ δ ≈_Δ δ′$, I will occasionally write $σ(p) ∶ σ(δ) ≈_Ω σ(δ′)$.
Not very often, though, since by propositionality of $Ω$ it does not matter
which specific proof of $σ(δ) ≈_Ω σ(δ′)$ we consider. This also means that in
particular $σ(\refl_Δ(δ)) = \refl_Ω(σ(δ))$; for non-propositional reflexive
graphs, we would have to add this condition to the definition of morphisms.

PRGraphs and their morphisms obviously form a category, which we call
$\PRGraphs$.

\section{Families of Propositional Reflexive Graphs}
\label{sec:model:rgraphfam}

To interpret types and type contexts, which are indexed by size contexts, we
need to move from PRGraphs to families of PRGraphs. These may be thought of as
PRGraphs indexed by PRGraphs. The results in this section are formalised in
\module{Model.\allowbreak Type.\allowbreak Core}{Model.Type.Core}.

A \Def{family of PRGraphs} over a given PRGraph $Δ$ is a tuple $(T, ≈_{T,p},
\refl_T)$ where
\begin{AlignAnnot*}
  T &∶& Δ → \Type \\
  ≈_{T,p} &∶& T(δ) → T(δ′) → \Type &\quad ∀ p ∶ δ ≈_Δ δ′ \\
  \refl_T(x) &∶& x ≈_{T,\refl_Δ(δ)} x &\quad ∀ x ∶ T(δ).
\end{AlignAnnot*}
such that $T(δ)$ is a set for any $δ$ and $≈_{T,p}$ is a proposition for any $T$
and $p$.

Note that our \enquote*{equality up to sizes} is now heterogeneous: we can ask
whether an inhabitant of $T(δ)$ is equal to an inhabitant of $T(δ′)$, as long as
$δ$ and $δ′$ are equal up to sizes. In the model, $δ$ and $δ′$ will be
(interpretations of) size valuations, which are always equal up to sizes. We
will thus be able to compare, for example, (interpretations of) terms in
$\Nat{n}$ and $\Nat{m}$ for arbitrary $n$ and $m$. This is necessary as well: if
λST is indeed size-irrelevant and we take a term $t ∶ \All{n}{\Nat{v_0}}$, we
should be able to conclude that $\sapp{t}{m}$ and $\sapp{t}{m′}$ are equal up to
sizes even though these terms have types $\Nat{m}$ and $\Nat{m′}$ respectively.

Morphisms of PRGraph families are again relation-preserving functions; we just
need to carry around some more indices. To be precise, a \Def{morphism between
  PRGraph families $T$ and $U$} over the PRGraph $Δ$ is a family
of functions
\begin{displaymath}
  f_δ ∶ T(δ) → U(δ) \quad ∀ δ ∶ Δ
\end{displaymath}
such that
\begin{displaymath}
  x ≈_{T,p} y ⇒ f(x) ≈_{U,p} f(y) \quad ∀ p ∶ δ ≈_Δ δ′;\; x ∶ T(δ);\; y ∶ T(δ′).
\end{displaymath}
PRGraph families over a given PRGraph $Δ$ and their morphisms form an obvious
category which we call $\PRGraphFams(Δ)$.

The last basic construction on PRGraph families is the interpretation of size
substitution. Size substitutions $σ ∶ Δ ⇒ Ω$ will be modelled as PRGraph
morphisms $⟦σ⟧ ∶ ⟦Δ⟧ → ⟦Ω⟧$, so we must say what it means to apply such a
morphism to a family of PRGraphs over $⟦Ω⟧$. To that end, we define
\Def{semantic substitution}: given a PRGraph morphism $σ ∶ Δ → Ω$ and a family
of PRGraphs $T$ over $Ω$, the application of $σ$ to $T$, $\sub{T}{σ}$, is the
following PRGraph family over $Δ$:
\begin{Align*}
  (\sub{T}{σ})(δ) &≔& T(σ(δ)) \\
  \mathord{≈_{\sub{T}{σ},p}} &≔& \mathord{≈_{T,σ(p)}} \\
  \refl_{\sub{T}{σ}}(x) &≔& \refl_T(x).
\end{Align*}
The last equation is not immediately well-typed: $\refl_T(x)$ proves $x
≈_{T,\refl_Δ(σ(δ))} x$ (assuming $x ∶ T(σ(δ))$) whereas we need to prove $x
≈_{T,σ(\refl_Δ(δ))} x$. However, since $≈_Δ$ is propositional, $\refl_Δ(σ(δ))$
and $σ(\refl_Δ(δ))$ are, in fact, the same.

\section{Properties of PRGraphFams}
\label{sec:model:prgraphfam-properties}

As usual, we will interpret the contexts of λST as finite products of types and
the function space as an exponential. We therefore prove that $\PRGraphFams(Δ)$
admits these constructions. Throughout this section, $Δ$ is an arbitrary
PRGraph.

\subsection{Finite Products}
\label{sec:model:product}

The following results are formalised in \module{Model.\allowbreak
  Terminal}{Model.Terminal} and \module{Model.\allowbreak
  Product}{Model.Product}.

Let $T, U$ be two RGraph families over $Δ$. The \Def{product of $T$ and $U$}, $T
× U$, is defined pointwise. Explicitly, it is the following RGraph family:
\begin{Align*}
  (T × U)(δ) &≔& T(δ) × U(δ) \\
  (x, x′) ≈_{T×U,p} (y, y′) &≔& x ≈_{T,p} y ∧ x′ ≈_{U,p} y′ \\
  \refl_{T×U}(x, y) &≔& (\refl_T(x), \refl_U(y)).
\end{Align*}
In the first equation, the $×$ on the right-hand side is the usual cartesian
product of types. The projections out of $T × U$, $π₁$ and $π₂$, are the usual
projections out of the product type. It is easy to check that this defines a
product in $\PRGraphFams(Δ)$.

To interpret all finite products, we additionally need a \Def{terminal object}.
This is the PRGraph family $⊤$ with
\begin{Align*}
  ⊤(δ) &≔& ⊤ \\
  x ≈_{⊤,p} y &≔& ⊤.
\end{Align*}
On the right-hand sides of the equations, $⊤$ is the unit type. The relation
$≈_⊤$ is trivial and so obviously reflexive.

\subsection{Exponentials}
\label{sec:model:exponential}

The following results are formalised in \module{Model.\allowbreak
  Exponential}{Model.Exponential}.

Before we can construct exponentials, we need an auxiliary definition: given a
family of PRGraphs $T$ over $Δ$ and an object $δ$ of $Δ$, the \Def{application
  of $T$ to $δ$}, $\Ap(T, δ)$, is the following PRGraph:
\begin{Align*}
  \Ap(T, δ) &≔& T(δ) \\
  ≈_{\Ap(T, δ)} &≔& \mathord{≈_{T,\refl_Δ(δ)}} \\
  \refl_{\Ap(T, δ)}(x) &≔& \refl_T(x).
\end{Align*}

Using $\Ap$, we define exponentials. Let $T$ and $U$ be PRGraph families over
$Δ$. The \Def{exponential of $T$ and $U$}, $T ↝ U$, is the following PRGraph
family:
\begin{AlignAnnot*}
  (T ↝ U)(δ) &≔& \Ap(T, δ) → \Ap(U, δ) \\
  f ≈_{T↝U,p} g &≔& ∀ x, y.\; x ≈_{T,p} y ⇒ f(x) ≈_{U,p} g(y) & \qquad (p ∶ δ ≈_Δ δ′).
\end{AlignAnnot*}
$\Ap(T, δ) → \Ap(U, δ)$ is the type of PRGraph morphisms from $\Ap(T, δ)$ to
$\Ap(U, δ)$. The relation of $T ↝ U$ is reflexive because for any such RGraph
morphism $f$, $x ≈_{T,\refl_Δ(δ)} y$ implies $f(x) ≈_{U,\refl_Δ(δ)} f(y)$.

To show that $T ↝ U$ is indeed an exponential, we need currying and evaluation
morphisms. Given a morphism of PRGraph families $f ∶ T × U → V$, we define
\begin{gather*}
  \curry(f) ∶ T → U ↝ V \\
  \curry(f)_δ(t) ≔ \fun{u}{f_δ(t, u)}.
\end{gather*}
It is easy to check that $\curry(f)_δ(t)$ is a PRGraph morphism from
$\Ap(U, δ)$ to $\Ap(V, δ)$ and that $\curry(f)$ is a morphism of PRGraph
families. We also define an evaluation morphism:
\begin{gather*}
  \eval ∶ (T ↝ U) × T → U \\
  \eval_δ(f, t) ≔ f(t).
\end{gather*}
Again, it is easy to check that $\eval$ is a morphism of PRGraph families and
that $T ↝ U$ together with $\curry$ and $\eval$ is an exponential in
$\PRGraphFams(Δ)$.

\section{Sizes}
\label{sec:model:sizes}

With the central notions defined, we can proceed to model λST. We start with
sizes, whose interpretation is formalised in \module{Model.\allowbreak
  Size}{Model.Size}.

A \Def{semantic size} is an ordinal below $ω·2$. These ordinals are either
natural numbers or they have the form $ω + i$ for some $i ∈ ℕ$. They are ordered
by the usual strict order on ordinals, meaning
\begin{displaymath}
  0 < 1 < \dots < ω < ω + 1 < \dots
\end{displaymath}
We write $≤$ for the reflexive closure of $<$, $\Size$ for the type of semantic
sizes and $\Size_{<n}$ for the type of semantic sizes $m$ such that $m < n$.

Syntactic sizes are modelled by semantic sizes as follows. A size context $Δ$ is
interpreted as a set of size tuples. A well-typed size in $Δ$ is interpreted as
a function from $⟦Δ⟧$ to $\Size$. These interpretations are mutually recursively
defined:
\begin{AlignAnnot*}
  ⟦()⟧ &≔& ⊤ &\qquad \text{($⊤$ is the unit type)} \\
  ⟦\ctx{Δ}{n}⟧ &≔& \Sigma_{δ ∶ ⟦Δ⟧}\Size_{<⟦n⟧(δ)} \\
  \\
  ⟦v_0⟧(δ, n) &≔& n \\
  ⟦v_{x+1}⟧(δ, n) &≔& ⟦v_x⟧(δ) \\
  ⟦0⟧(δ) &≔& 0 \\
  ⟦\ssuc{n}⟧(δ) &≔& ⟦n⟧(δ) + 1 \\
  ⟦∞⟧(δ) &≔& ω.
\end{AlignAnnot*}

We will also consider $⟦Δ⟧$ as a PRGraph whose underlying type is $⟦Δ⟧$ and
whose relation is trivial, i.e.\ any two elements are related. A size
interpretation $⟦n⟧$ is then a PRGraph morphism (if we similarly treat the
type $\Size$ as a trivial PRGraph).

\begin{remark}
  We will shortly interpret a type $T$ in a context $Δ$ as a family of PRGraphs
  indexed by the PRGraph $⟦Δ⟧$. However, since $⟦Δ⟧$ is always trivial as a
  PRGraph, we could also interpret $T$ as a family of PRGraphs indexed by the
  \emph{type} $⟦Δ⟧$, which would be a little simpler. I choose not to do so
  because that model would likely not support dependent types (and perhaps other
  interesting features).
\end{remark}

Our interpretation of sizes is well-behaved with respect to size comparison:

\begin{lemma}[Interpretation of $<$]
  \label{lem:⟦<⟧}
  If $Δ ⊢ n < m$ and $δ ∶ ⟦Δ⟧$, then $⟦n⟧(δ) < ⟦m⟧(δ)$.
\end{lemma}

\begin{proof}
  By induction on the derivation of $Δ ⊢ n < m$. In the case where $n$ is a
  variable, we need to use the following fact: given $Δ ⊢ n$, $Δ ⊢ m$ and $(δ,
  o) ∶ ⟦\ctx{Δ}{n}⟧$, we have $⟦\wk(m)⟧(δ, o) = ⟦m⟧(δ)$.
\end{proof}

This concludes the interpretation of sizes. Next, we interpret size
substitutions as functions between interpretations of size contexts. As
explained in \secref{formalisation:sub}, the results presented here are not
exactly those formalised.

Let $σ ∶ Δ ⇒ Ω$ be a well-typed substitution. The interpretation of $σ$ is a
function from $⟦Δ⟧$ to $⟦Ω⟧$ defined by recursion over the derivation of $σ ∶ Δ
⇒ Ω$:
\begin{gather*}
  ⟦()⟧ ∶ ⟦Δ⟧ → ⟦()⟧ \\
  ⟦()⟧(δ) ≔ \mathord{tt} \qquad \text{($\mathord{tt}$ is the unique value of $⊤$)} \\
  \\
  ⟦\ssub{σ}{n}⟧ ∶ ⟦Δ⟧ → \Sigma_{ω ∶ ⟦Ω⟧}\Size_{<⟦m⟧(ω)} \\
  ⟦\ssub{σ}{n}⟧(δ) ≔ ⟦σ⟧(δ), n.
\end{gather*}
The last equation is well-typed because $\ssub{σ}{n} ∶ Δ ⇒ \ctx{Ω}{m}$ implies
$Δ ⊢ n < \sub{m}{σ}$ and thus by Lemma \ref{lem:⟦<⟧} $⟦n⟧ < ⟦\sub{m}{σ}⟧$. The
following Lemma \ref{lem:⟦sub⟧} then lets us conclude $⟦n⟧ < ⟦m⟧(⟦σ⟧(δ))$. (This
means that the present definition and Lemma \ref{lem:⟦sub⟧} are in fact mutually
recursive.)

\begin{lemma}[Interpretation of size substitutions is correct]
  \label{lem:⟦sub⟧}
  If $σ ∶ Δ ⇒ Ω$ and $Ω ⊢ n$, then $⟦\sub{σ}{n}⟧ = ⟦n⟧ ∘ ⟦σ⟧$.
\end{lemma}

We will also need to know the interpretations of some of the specific
substitutions from \secref{source:sub}. The following lemma tells us how they
behave when applied to a size valuation.

\begin{lemma}[Interpretation of specific size substitutions]
  \label{lem:sub-app}
  Let $(ω, m, k) ∶ ⟦\ctx{\ctx{Ω}{n}}{v_0}⟧$, $σ ∶ Δ → Ω$ and $τ ∶ Ω → Ω′$. Then
  we have
  \begin{Align*}
    ⟦\Id⟧(ω) &=& ω \\
    ⟦σ \fcomp τ⟧(ω) &=& ⟦τ⟧(⟦σ⟧(ω)) \\
    ⟦\Wk⟧(ω, m) &=& ω \\
    ⟦\Sing(o)⟧(ω) &=& (ω, ⟦o⟧(ω)) \\
    ⟦\Lift(σ)⟧(ω, m) &=& (⟦σ⟧(ω), m) \\
    ⟦\Skip⟧(ω, m, k) &=& (ω, k).
  \end{Align*}
\end{lemma}

\section{Types}
\label{sec:model:types}

In this section, we model the types of λST. Our results are formalised in
\module{Model.\allowbreak Nat}{Model.Nat}, \module{Model.\allowbreak
  Stream}{Model.Stream} and \module{Model.\allowbreak
  Quantification}{Model.Quantification}.

As foreshadowed, we interpret well-scoped types $T$ in a size context $Δ$ as
families of PRGraphs $⟦T⟧$ over the PRGraph $⟦Δ⟧$. The interpretations of sized
naturals, sized streams and functions are straightforward; only size
quantification will be slightly more complex.

Let $ℕ_{≤n}$ be the type of natural numbers $m$ such that $m ≤ n$ (with $n$
an arbitrary size). The interpretation of $Δ ⊢ \Nat{n}$ is the following
family of PRGraphs:
\begin{Align*}
  ⟦\Nat{n}⟧(δ) &≔& ℕ_{≤ ⟦n⟧(δ)} \\
  i ≈_{⟦\Nat{n}⟧,p} j &≔& i = j.
\end{Align*}
Streams are interpreted in a similar fashion:
\begin{AlignAnnot*}
  ⟦\Stream{n}⟧(δ) &≔& ℕ_{≤ ⟦n⟧(δ)} → ℕ \\
  f ≈_{⟦\Stream{n}⟧,p} g &≔& \all{m ≤ \min(⟦n⟧(δ), ⟦n⟧(δ′))}{f(m) = g(m)} &\quad
    (p ∶ δ ≈_{Δ} δ′).
\end{AlignAnnot*}
The function space is interpreted by the exponential of PRGraph families from
\secref{model:exponential}:
\begin{displaymath}
  ⟦T → U⟧ ≔ ⟦T⟧ ↝ ⟦U⟧.
\end{displaymath}

Size quantification requires a little more effort. We want to think of the terms
of $\All{n}{T}$ as functions which take a size argument, but they should be
parametric in that argument: when we apply such a function to different sizes,
it should return results that are equal up to sizes. To be more precise, let $T$
be a family of PRGraphs over $⟦\ctx{Δ}{n}⟧$ and let $δ ∶ ⟦Δ⟧$. A function
\begin{displaymath}
  f ∶ (m ∶ \Size_{<⟦n⟧(δ)}) → T(δ, m)
\end{displaymath}
is \Def{size-parametric} if
\begin{displaymath}
  f(m) ≈_T f(m′) \quad ∀ m, m′ ∶ \Size_{<⟦n⟧(δ)}.
\end{displaymath}
This equation is well-typed because $≈_{⟦\ctx{Δ}{n}⟧}$ is trivial, so in
particular $(δ, m) ≈_{⟦\ctx{Δ}{n}⟧} (δ, m′)$. We write $\Param(T,δ)$ for the type
of size-parametric functions into $T(δ, ∙)$.

Now we can interpret size quantification: the interpretation of $Δ ⊢ \All{n}{T}$
is the PRGraph family $Π(⟦n⟧, ⟦T⟧)$ with
\begin{AlignAnnot*}
  Π(n, T)(δ) &≔& \Param(T,δ) \\
  f ≈_{Π(n, T)} g &≔& ∀ m, m′.\; f(m) ≈_T g(m′).
\end{AlignAnnot*}
If we think of $≈_T$ as equality up to sizes, $⟦\All{n}{T}⟧$ reflects
the intuition that when we apply a term in $\All{n}{T}$ to a size $m$, it does
not matter -- up to sizes -- which $m$ we choose.

Having interpreted all types, we can now move to type contexts. These are mere
lists of types, so they are, as usual, modelled by finite products:
\begin{Align*}
  ⟦()⟧ &≔& ⊤ \\
  ⟦\Ctx{Γ}{T}⟧ &≔& ⟦Γ⟧ × ⟦T⟧.
\end{Align*}
$⊤$ is the terminal PRGraph family and $×$ is the product of PRGraph families,
both defined in \secref{model:product}.

With this, we have interpreted all type-level constructs of λST. What remains is
to prove a lemma about the correspondence between syntactic and semantic
substitution. To do that, we need some technical lemmas about semantic
substitution first:

\begin{lemma}[Substitution in exponentials]
  Let $T$, $U$ be PRGraph families over $Ω$ and $σ ∶ Δ → Ω$ a PRGraph morphism. Then
  \begin{displaymath}
    \sub{(T ↝ U)}{σ} = \sub{T}{σ} ↝ \sub{U}{σ}.
  \end{displaymath}
\end{lemma}

\begin{lemma}[Substitution in quantifications]
  Let $T$ be a PRGraph family over $⟦\ctx{Ω}{n}⟧$ and $σ ∶ Δ ⇒ Ω$ a well-typed
  substitution. Then
  \begin{displaymath}
    \sub{Π(n, T)}{⟦σ⟧} = Π(\sub{n}{⟦σ⟧}, \sub{T}{⟦\Lift(σ)⟧}).
  \end{displaymath}
\end{lemma}

\begin{remark}
  The correct equality for PRGraph families is isomorphism in $\PRGraphFams(Δ)$,
  so the $=$ above really means $≅$. This abuse of notation is justified because
  in the formalisation, isomorphic PRGraph families are in fact propositionally
  equal (by univalence).
\end{remark}

From the previous two lemmas follows the main substitution lemma for types and
contexts:

\begin{lemma}[Interpretation of substitution in types and contexts is correct]
  \label{lem:⟦subT⟧}
  If $Ω ⊢ T$ and $σ ∶ Δ ⇒ Ω$, then
  \begin{displaymath}
    ⟦\sub{T}{σ}⟧ = \sub{⟦T⟧}{⟦σ⟧}
  \end{displaymath}
  and similar for contexts.
\end{lemma}

\section{Terms}
\label{sec:model:terms}

Well-typed terms (more precisely, judgments $Δ;Γ ⊢ t ∶ T$) are interpreted as
morphisms between the PRGraph families $⟦Γ⟧$ and $⟦T⟧$. In this section, we show
a natural interpretation of each of the terms of λST. Formalisations of these
definitions can be found in \module{Model.\allowbreak Term}{Model.Term}.

\subsection{Functions}
\label{sec:model:terms:functions}

Recall that the function space is modelled by the exponential $⟦T⟧ ↝ ⟦U⟧$ as in
the standard categorical model of the simply-typed lambda calculus. Accordingly,
the interpretations of abstraction and application are also standard.

To interpret $\lam{T}{t}$, we may assume a morphism $⟦t⟧ ∶ ⟦Γ⟧ × ⟦T⟧ → ⟦U⟧$. We
then define
\begin{Align*}
  ⟦\lam{T}{t}⟧ &∶& ⟦Γ⟧ → ⟦T⟧ ↝ ⟦U⟧ \\
  ⟦\lam{T}{t}⟧ &≔& \curry(⟦t⟧).
\end{Align*}
The interpretation of $\app{t}{u}$, assuming $⟦t⟧ ∶ ⟦Γ⟧ → ⟦T ↝ U⟧$ and $⟦u⟧ ∶ ⟦Γ⟧ →
⟦T⟧$, is
\begin{Align*}
  ⟦\app{t}{u}⟧ &∶& ⟦Γ⟧ → ⟦U⟧ \\
  ⟦\app{t}{u}⟧ &≔& \eval ∘ \anglebrackets{⟦t⟧ × ⟦u⟧}.
\end{Align*}
The operator
\begin{displaymath}
  ⟨∙×∙⟩ ∶ (A → A′) → (B → B′) → A × B → A′ × B′
\end{displaymath}
can be defined in any category with products.

\subsection{Size Quantification}
\label{sec:model:terms:quantification}

To interpret size quantification, we must consider size abstractions and size
applications. Their typing rules are reproduced in
\figref{typing:quantification} for reference.

\begin{figure}
  \begin{mathpar}
    \inferrule{\ctx{Δ}{n}; \sub{Γ}{\Wk} ⊢ t ∶ T \\ Δ ⊢ Γ}
      {Δ; Γ ⊢ \slam{n}{t} ∶ \All{n}{T}}

    \inferrule{Δ; Γ ⊢ t ∶ \All{n}{T} \\ Δ ⊢ m < n}
      {Δ; Γ ⊢ \sapp{t}{m} ∶ \sub{T}{\Sing(m)}}
  \end{mathpar}

  \caption{Typing rules for terms related to size quantification}
  \label{fig:typing:quantification}
\end{figure}

When interpreting size quantification, we may assume a morphism $⟦t⟧ ∶
⟦\sub{Γ}{\Wk}⟧ → ⟦T⟧$ with components
\begin{AlignAnnot*}
  ⟦t⟧_{(δ,n)} &∶& ⟦\sub{Γ}{\Wk}⟧(δ, n) → ⟦T⟧(δ, n) \\
    &=& \sub{⟦Γ⟧}{⟦\Wk⟧}(δ, n) → ⟦T⟧(δ, n) &\quad \text{(by Lemma \ref{lem:⟦subT⟧})} \\
    &=& ⟦Γ⟧(⟦\Wk⟧(δ, n)) → ⟦T⟧(δ, n) &\quad \text{(by definition)} \\
    &=& ⟦Γ⟧(δ) → ⟦T⟧(δ, n) &\quad \text{(by Lemma \ref{lem:sub-app}).}
\end{AlignAnnot*}
We then define
\begin{gather*}
  ⟦\slam{n}{t}⟧ ∶ ⟦Γ⟧ → ⟦\All{n}{T}⟧ \\
  ⟦\slam{n}{t}⟧_δ(γ) ≔ \fun{m < ⟦n⟧(δ)}{⟦t⟧_{(δ,m)}(γ)}.
\end{gather*}
This definition is valid due to the following observations:
\begin{itemize}
\item The right-hand side of the equation is a size-parametric function. Recall
  that for all $m$ and $m′$, $(δ, m) ≈_{⟦\ctx{Δ}{n}⟧} (δ, m′)$. We also have $γ
  ≈_{⟦Γ⟧} γ$ by reflexivity and this implies $⟦t⟧_{(δ, m)}(γ) ≈_{⟦T⟧} ⟦t⟧_{(δ,
    m′)}(γ)$ because $⟦t⟧$ is a morphism of PRGraph families.
\item $⟦\slam{n}{t}⟧$ is a morphism of PRGraph families. This follows from
  essentially the same argument, only replacing the fact $γ ≈_{⟦Γ⟧} γ$ with an
  assumption $γ ≈_{⟦Γ⟧} γ′$ for some arbitrary $γ′$.
\end{itemize}

Moving to size application, we may assume a morphism
\begin{displaymath}
  ⟦t⟧ ∶ ⟦Γ⟧ → ⟦\All{n}{T}⟧
\end{displaymath}
and we construct the morphism
\begin{AlignAnnot*}
  ⟦\sapp{t}{m}⟧_δ &∶& ⟦Γ⟧(δ) → ⟦\sub{T}{\Sing(m)}⟧ \\
    &=& ⟦Γ⟧(δ) → ⟦T⟧(δ, ⟦m⟧(δ)) &\quad \text{(by Lemmas \ref{lem:⟦subT⟧} and
      \ref{lem:sub-app})} \\
  ⟦\sapp{t}{m}⟧_δ(γ) &≔& ⟦t⟧_δ(γ, ⟦m⟧(δ)).
\end{AlignAnnot*}
The size $⟦m⟧(δ)$ is a valid argument to $⟦t⟧_δ(γ)$ because we have $Δ ⊢ m < n$
and thus (by Lemma \ref{lem:⟦<⟧}) $⟦m⟧(δ) < ⟦n⟧(δ)$ for all $δ$. $⟦\sapp{t}{m}⟧$
is a morphism of PRGraph families because $⟦t⟧$ is.

\subsection{Natural Numbers}
\label{sec:model:terms:nat}

The sized natural number type $\Nat{n}$ has two constructors, zero and
successor, and an eliminator, $\mathrm{caseNat}$. Their typing rules are
reproduced in \figref{typing:nat}. Recall that $\Nat{n}$ is modelled by the type
of natural numbers less than or equal to a size $n$.

\begin{figure}
  \begin{mathpar}
    \inferrule{Δ ⊢ n < \Star \\ Δ ⊢ Γ}{Δ; Γ ⊢ \zero{n} ∶ \Nat{n}}

    \inferrule{Δ ⊢ n < \Star \\ Δ ⊢ m < n \\ Δ; Γ ⊢ i ∶ \Nat{m}}
    {Δ; Γ ⊢ \suc{n}{m}{i} ∶ \Nat{n}}

    \inferrule{Δ ⊢ T \\ Δ ⊢ n < \Star \\ Δ; Γ ⊢ i ∶ \Nat{n} \\ Δ; Γ ⊢ z ∶ T \\
      Δ; Γ ⊢ s ∶ \All{n}{\Nat{v_0} → \sub{T}{\Wk}}}
    {Δ; Γ ⊢ \case{T}{n}{i}{z}{s} ∶ T}
  \end{mathpar}
  \caption{Typing rules for terms related to $\Nat{n}$}
  \label{fig:typing:nat}
\end{figure}

The term $\zero{n}$ is interpreted by
\begin{displaymath}
  ⟦\zero{n}⟧_δ(γ) ≔ 0.
\end{displaymath}
This is valid since $0 ≤ n$ for all $n$.

To interpret the successor, given a morphism $⟦i⟧ ∶ ⟦Γ⟧ → ⟦\Nat{n}⟧$, we define
\begin{displaymath}
  ⟦\suc{n}{m}{i}⟧_δ(γ) ≔ ⟦i⟧_δ(γ) + 1.
\end{displaymath}
This is valid because we have $⟦i⟧_δ(γ) ≤ ⟦m⟧(δ)$ (by definition of $⟦\Nat{m}⟧$)
and $⟦m⟧(δ) < ⟦n⟧(δ)$ (by Lemma \ref{lem:⟦<⟧}), which implies $⟦i⟧_δ(γ) + 1 ≤
⟦n⟧(δ)$.

To interpret the eliminator $\mathrm{caseNat}$, we assume morphisms $⟦i⟧ ∶ ⟦Γ⟧ →
⟦\Nat{n}⟧$, $⟦z⟧ ∶ ⟦Γ⟧ → ⟦T⟧$ and $⟦s⟧ ∶ ⟦Γ⟧ → ⟦\All{n}{\Nat{v_0} →
  \sub{T}{\Wk}}⟧$. The interpretation is then
\begin{displaymath}
  ⟦\case{T}{n}{i}{z}{s}⟧_δ(γ) ≔
    \begin{cases}
      ⟦z⟧_δ(γ) &\quad \text{if $⟦i⟧_δ(γ) = 0$} \\
      ⟦s⟧_δ(γ, ⟦n⟧(δ) - 1, ⟦i⟧_δ(γ) - 1) &\quad \text{otherwise.}
    \end{cases}
\end{displaymath}
Note that in the second branch, $⟦n⟧(δ)$ cannot be zero because $⟦i⟧_δ(γ) ≤
⟦n⟧(δ)$ and $⟦i⟧_δ(γ) ≠ 0$.

\subsection{Streams}
\label{sec:model:terms:stream}

Sized streams are constructed by the term $\mathrm{cons}$ and eliminated by
$\mathrm{head}$ and $\mathrm{tail}$. The typing rules of these terms are
reproduced in \figref{typing:stream}. Recall that the model of $\Stream{n}$ is
the type of functions $ℕ_{≤n} → ℕ$.

\begin{figure}
  \begin{mathpar}
    \inferrule{Δ ⊢ n < \Star \\ Δ; Γ ⊢ i ∶ \Nat{∞} \\
      Δ; Γ ⊢ \V{is} ∶ \All{n}{\Stream{v_0}}}
      {Δ; Γ ⊢ \cons{n}{i}{\V{is}} ∶ \Stream{n}}

    \inferrule{Δ ⊢ n < \Star \\ Δ; Γ ⊢ \V{is} ∶ \Stream{n}}
      {Δ; Γ ⊢ \head{n}{\V{is}} ∶ \Nat{∞}}

    \inferrule{Δ ⊢ n < \Star \\ Δ; Γ ⊢ \V{is} ∶ \Stream{n} \\ Δ ⊢ m < n}
      {Δ; Γ ⊢ \tail{n}{\V{is}}{m} ∶ \Stream{m}}
  \end{mathpar}
  \caption{Typing rules for terms related to $\Stream{n}$}
  \label{fig:typing:stream}
\end{figure}

To interpret $\mathrm{cons}$, we assume morphisms $⟦i⟧$ and $⟦\V{is}⟧$ with
components
\begin{Align*}
  ⟦i⟧_δ
  &∶& ⟦Γ⟧(δ) → ⟦\Nat{∞}⟧(δ) \\
  &=& ⟦Γ⟧(δ) → ℕ_{<ω} \\
  &=& ⟦Γ⟧(δ) → ℕ \\
  ⟦\V{is}⟧_δ
  &∶& ⟦Γ⟧(δ) → ⟦\All{n}{\Stream{v_0}}⟧(δ) \\
  &=& ⟦Γ⟧(δ) → \Param(⟦\Stream{v_0}⟧, δ) \\
  &≈& ⟦Γ⟧(δ) → (m ∶ \Size_{<⟦n⟧(δ)}) → ⟦\Stream{v_0}⟧(δ, m) \\
  &=& ⟦Γ⟧(δ) → (m ∶ \Size_{<⟦n⟧(δ)}) → ℕ_{≤m} → ℕ.
\end{Align*}
The $≈$ on the penultimate line indicates that we are ignoring the parametricity
requirement of $\Param$ to unfold it. We then define
\begin{displaymath}
  ⟦\cons{n}{i}{\V{is}}⟧_δ(γ, k) ≔
  \begin{cases}
    ⟦i⟧_δ(γ) &\quad \text{if $k = 0$} \\
    ⟦\V{is}⟧_δ(γ, k - 1, k - 1) &\quad \text{otherwise}.
  \end{cases}
\end{displaymath}
Note that $k ≤ ⟦n⟧(δ)$, so in the second equation we have $k - 1 < ⟦n⟧(δ)$.

The destructors of $\Stream{n}$ have less complex interpretations. For
$\mathrm{head}$, we assume a morphism $⟦\V{is}⟧ ∶ ⟦Γ⟧ → ⟦\Stream{n}⟧$ and define
\begin{gather*}
  ⟦\head{n}{\V{is}}⟧ ∶ ⟦Γ⟧ → ⟦\Nat{∞}⟧ \\
  ⟦\head{n}{\V{is}}⟧_δ(γ) ≔ ⟦\V{is}⟧_δ(γ, 0).
\end{gather*}
Similarly, for $\mathrm{tail}$, we assume $⟦\V{is}⟧ ∶ ⟦Γ⟧ → ⟦\Stream{n}⟧$ and $Δ
⊢ m < n$ and define
\begin{gather*}
  ⟦\tail{n}{\V{is}}{m}⟧ ∶ ⟦\Stream{m}⟧ \\
  ⟦\tail{n}{\V{is}}{m}⟧_δ(γ, k) ≔ ⟦\V{is}⟧_δ(γ, k + 1).
\end{gather*}
The application of $⟦\V{is}⟧$ to $k + 1$ is well-typed because $k ≤ ⟦m⟧(δ)$ and
$⟦m⟧(δ) < ⟦n⟧(δ)$ (by Lemma \ref{lem:⟦<⟧}).

\subsection{Fixpoint}
\label{sec:model:terms:fixpoint}

The sized fixpoint combinator is the sole means of recursion in λST. As such,
its interpretation is also recursive but otherwise mostly straightforward.

Recall the typing rule of $\mathrm{fix}$:
\begin{displaymath}
  \centering
  \inferrule{\ctx{Δ}{\Star} ⊢ T \\
    Δ; Γ ⊢ t ∶ \All{\Star}{(\All{v_0}{\sub{T}{\Skip}}) → T} \\ Δ ⊢ n < \Star}
  {Δ; Γ ⊢ \fix{T}{t}{n} ∶ \sub{T}{\Sing(n)}}
\end{displaymath}
According to this rule, we may assume a morphism $⟦t⟧$ with components
\begin{Align*}
  ⟦t⟧_δ
    &∶& ⟦Γ⟧(δ) → ⟦\All{\Star}{(\All{v_0}{\sub{T}{\Skip}}) → T}⟧(δ) \\
    &=& ⟦Γ⟧(δ) → (n ∶ \Size_{< ω + 1}) → ((m ∶ \Size_{<n}) → ⟦T⟧(⟦\Skip⟧(δ, n, m))) →
    ⟦T⟧(δ, n) \\
    &=& ⟦Γ⟧(δ) → (n ∶ \Size_{< ω + 1}) → ((m ∶ \Size_{<n}) → ⟦T⟧(δ, m)) → ⟦T⟧(δ, n).
\end{Align*}
The first step in this chain uses the fact that $⟦\sub{T}{\Skip}⟧ =
\sub{⟦T⟧}{⟦\Skip⟧}$ (by Lemma \ref{lem:⟦subT⟧}). In the second step, we simplify
$⟦\Skip⟧(δ, n, m)$ to $(δ, m)$ (by Lemma \ref{lem:sub-app}).

Given such a $⟦t⟧$, we first define the following auxiliary function:
\begin{gather*}
  f_δ ∶ ⟦Γ⟧(δ) → (n ∶ \Size_{< ω + 1}) → ⟦T⟧(δ, n) \\
  f_δ(γ, n) ≔ ⟦t⟧_δ(γ, n, \fun{m}{f_δ(γ, m)}).
\end{gather*}
This function is a standard fixpoint of $⟦t⟧_δ$. It terminates because the
recursive call is on a size $m < n$ and $<$ is well-founded: there is no
infinite descending chain $n₀ > n₁ > \dots$ and so a recursion which always
decreases the size argument must eventually stop. Interpreting $\mathrm{fix}$ is
then just a matter of applying $f$:
\begin{Align*}
  ⟦\fix{T}{t}{n}⟧_δ
    &∶& ⟦Γ⟧(δ) → ⟦\sub{T}{\Sing(n)}⟧(δ) \\
    &=& ⟦Γ⟧(δ) → ⟦T⟧(δ, ⟦n⟧(δ)) \\
  ⟦\fix{T}{t}{n}⟧_δ(γ) &≔& f_δ(γ, ⟦n⟧(δ)).
\end{Align*}

In the above argument, we have, as usual, glossed over various proof obligations
concerning size parametricity, preservation of relations and so on. However, one
of these obligations is actually nontrivial: in the definition of the auxiliary
function $f$, we use $f$ recursively as a size-parametric function. This means
that we must prove $f$ size-parametric \emph{mutually recursively} with its own
definition. The full, somewhat gory details of this construction appear in
\secref{formalisation:fixpoint}.

\section{Size Irrelevance}
\label{sec:model:conclusion}

With all elements of λST modelled, we should briefly ask what the model tells
us. It does not immediately allow us to conclude any syntactic size irrelevance
results, which would mean, for example, that for any term $t ∶ \All{n}{T}$ and
sizes $m$, $m′$ the applications $\sapp{t}{m}$ and $\sapp{t}{m′}$ normalise to
the same value up to sizes. (Indeed, I have not even given an operational
semantics for λST.) Ideally, we would like to prove the even stronger claim that
the entire reduction sequences of $\sapp{t}{m}$ and $\sapp{t}{m′}$ are equal up
to sizes. This would allow us to fully erase sizes at runtime. Deriving answers
to these questions from the model is significant additional work; I briefly
return to them in \secref{conclusion:future}.

What we do get from the model, however, is a denotational semantics of λST with
\enquote*{baked-in} size irrelevance. Our model construction can be read as an
interpreter from λST into Agda, and this interpreter must, due to the
parametricity requirement in our interpretation of size quantification, produce
size-irrelevant functions.


\documentclass[a4paper, 12pt]{report}

\usepackage{hyperref}
\usepackage{verbatim}
\usepackage{titlesec}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}

\begin{document}

\section*{Simple Polygonize}

Demonstration of algorithm for finding a simple polygon that passes through given points. Implemented for CSN-523 (Computational Geometry) course assignment.

\subsection*{Algorithm}

\begin{enumerate}
\item Choose a suitable reference point (in the code, used arithmetic mean of each axis)
\item Calculate angle of line segment joining each given point to the reference point, with respect to the X axis
\item Sort the points based upon the angle of incidence calculated above
\item Join adjacent points in the sorted order using line segments
\item Join first and last point with a line segment
\end{enumerate}

\subsection*{Code}

\verbatiminput{../simple-polygonize.py}

\subsection*{License}

All parts of the code are covered under the \href{https://jay.mit-license.org/2017}{MIT License}

\subsection*{How to Run}

Simply run the \verb|simply-polygonize.py| file using \verb|python simply-polygonize.py| or \verb|python simply-polygonize.py {N}|, where \verb|N| is the number of points required.

When the program runs, it will prompt with the help text:

\begin{verbatim}
        +/- Change N
         r  randomize points
         q  quit
\end{verbatim}

Press any of the above keys to do the corresponding action.

\subsection*{Demonstration}

A video of the code in action, is available at \\ \href{https://www.youtube.com/watch?v=WXUb6b_7CIk}{https://www.youtube.com/watch?v=WXUb6b\_7CIk}

Some screenshots are shown below:

\begin{figure*}[h]
    \centering
    \begin{subfigure}[t]{0.4\textwidth}
        \centering
        \includegraphics[width=\textwidth]{0-intro}
        \caption{Intro Screen}
    \end{subfigure}%
    ~
    \begin{subfigure}[t]{0.4\textwidth}
        \centering
        \includegraphics[width=\textwidth]{1-n3}
        \caption{N=3}
    \end{subfigure}%
    \\
    \begin{subfigure}[t]{0.4\textwidth}
    	\centering
    	\includegraphics[width=\textwidth]{2-n10}
    	\caption{N=10}
    \end{subfigure}%
    ~
    \begin{subfigure}[t]{0.4\textwidth}
    	\centering
    	\includegraphics[width=\textwidth]{3-n100}
    	\caption{N=100}
    \end{subfigure}
\end{figure*}

\end{document}


\section{Overview}\label{sec:refinedhaskell:overview}

We start with an informal overview of a sound refinement type
system for Haskell.
%
After recapitulating the basics of refinement types
we illustrate why the classical approach based on
verification conditions (VCs) is unsound due to
lazy evaluation.
%
Next, we step back to understand precisely how the
VCs arise from refinement subtyping and how subtyping
is different under eager and lazy evaluation.
In particular, we demonstrate that under lazy, but
\emph{not} eager, evaluation, the refinement type
system, and hence the VCs, must account for divergence.
%
Consequently, we develop a type system that accounts
for divergence in a modular and syntactic fashion
and illustrate its use via several small examples.
%
Finally, we show how a refinement-based termination
analysis is used to improve precision, yielding
a highly effective SMT-based verifier for Haskell.

\subsection{Standard Refinement Types: From Subtyping to VC}\label{subsec:vc}

\begin{figure}[!t]
\centering
\captionsetup{justification=centering}
$$
\begin{array}{rrcl}
\emphbf{Refinements} & \refi     & ::= & \dots \text{varies} \dots \\[0.05in]
\emphbf{Basic Types} & \base  & ::= & \tref{v}{\tint}{}{\refi} \spmid \dots \\[0.05in]
\emphbf{Types}       & \typ   & ::= & \base \spmid \tfunref{\x}{\typ}{\typ}{v}{\refi} \\[0.05in]
\emphbf{Environment} & \env   & ::= & \emptyset \spmid \bind{x}{\typ}, \env \\[0.1in]

\multicolumn{3}{l}{\emphbf{Subtyping}}   & \issubtype{\env}{\typ_1}{\typ_2} \\[0.1in]

\multicolumn{4}{l}{\mbox{\emphbf{Abbreviations}}} \\[0.05in]
  \multicolumn{2}{r}{\bind{x}{\ttref{\refi}}} & \doteq & \bind{x}{\tref{x}{\tint}{}{\refi}} \\[0.05in]
  \multicolumn{2}{r}{\ttreftsimple{\x}{\refi}}   & \doteq & {\tref{x}{\tint}{}{\refi}} \\[0.05in]
  \multicolumn{2}{r}{\ttref{\refi}}             & \doteq & {\tref{v}{\tint}{}{\refi}} \\[0.05in]
  \multicolumn{2}{r}{\reft{\x}{\reft{\y}{\tint}{\refi_\y}}{\refi_\x}} & \doteq &
  					{\reft{\x}{\tint}{\refi_\x \land \refi_\y\sub{\y}{\x}}} \\[0.05in]

\multicolumn{4}{l}{\mbox{\emphbf{Translation}}} \\[0.05in]
\multicolumn{2}{r}{\embed{\issubtype{\env}{\base_1}{\base_2}}} & \defeq& \isvalidvc{\embed{\env}}{\embed{\base_1}}{\embed{\base_2}}\\[0.05in]
  \multicolumn{2}{r}{\embed{\tttref{\x}{\tint}{}{\refi}}} & \defeq & \lref\\[0.05in]
  \multicolumn{2}{r}{\embed{\ttbind{\x}{\tttref{\vv}{\tint}{}{\refi}}}} &\defeq & \ \mbox{``$\mathtt{\x}$ is a value"}  \Rightarrow \SUBST{\lref}{\vv}{\x}\\[0.05in]
  \multicolumn{2}{r}{\embed{\bind{\x}{(\tfun{\y}{\typ_\y}{\typ})}}} &\defeq & \tttrue\\[0.05in]
  \multicolumn{2}{r}{\embed{\ttbind{\x_1}{\typ_1},\ldots,\ttbind{\x_\n}{\typ_\n}}} & \defeq & \embed{\ttbind{\x_1}{\typ_1}} \wedge \ldots \wedge \embed{\ttbind{\x_\n}{\typ_\n}} \\
\end{array}
$$
\caption[Summary of Informal Notation.]{Informal Notation: Types, Subtyping, and VCs.}
\label{fig:overview:syntax}
\end{figure}

First, let us see how standard refinement type systems
\cite{LiquidPLDI08, Knowles10} will
use
the aforementioned refinement type aliases @Pos@ and @Nat@
and the specification for @div@
%
to \emph{accept} @good@ and
\emph{reject} @bad@.
We use the syntax of Figure~\ref{fig:overview:syntax}, where $r$ is a
\emph{refinement expression}, or just \emph{refinement} for short.
We will vary the expressiveness of the language of refinements in
different parts of this document.
%
\begin{code}
    good     :: Nat -> Nat -> Int
    good x y = let z = y + 1 in x `div` z

    bad      :: Nat -> Nat -> Int
    bad x y  = x `div` y
\end{code}

\spara{Refinement Subtyping}
To analyze the body of @bad@, the refinement type system will
check that the second parameter @y@ has type @Pos@ at the call
to @div@; formally, that %. Formally, the system will check that the type of
the actual parameter @y@ is a \emph{subtype} of the type of
@div@'s second input, via a subtyping query:
%
$$
 \ttbind{x}{\tref{x}{Int}{}{x \geq 0}},\
 \ttbind{y}{\tref{y}{Int}{}{y \geq 0}}
 \ \vdash\
 \subt{\tttref{y}{Int}{}{y \geq 0}}{\tttref{v}{Int}{}{v > 0}}$$
%
We use the Abbreviations of Figure~\ref{fig:overview:syntax} to simplify the
syntax of the queries.
%
So the above query simplifies to:
$$\ttbind{x}{\ttref{x \geq 0}},\ \ttbind{y}{\ttref{y \geq 0}}\ \vdash\ \subtref{v \geq 0}{v > 0}$$

\spara{Verification Conditions}
To discharge the above subtyping query, a refinement type system
generates a \emph{verification condition} (VC), a logical formula
that stipulates that under the assumptions corresponding to the
environment bindings, the refinement in the sub-type \emph{implies}
the refinement in the super-type.
%
We use the translation \embed{\cdot} shown in Figure~\ref{fig:overview:syntax}
to reduce a subtyping query to a verification condition.
%
The translation of a basic type into logic is the refinement of the type.
The translation of an environment is the conjunction of its bindings.
Finally, the translation of a binding \ttbind{\x}{\typ} is the embedding of \typ
guarded by a predicate denoting that ``\x is a value''.
%
For now, let us ignore this guard and see how the subtyping query for
@bad@ reduces to the \emph{classical} VC:
%%
$$\mathvc{\mathvc{(\ttx \geq 0)}} \wedge \mathvc{(\tty \geq 0)}\ \Rightarrow\ \mathvc{(\ttv \geq 0)} \Rightarrow \mathvc{(\ttv > 0)}$$
%%
Refinement type systems are carefully engineered (\Sref{sec:typing})
so that (\emph{unlike} with full dependent types) the logic of
refinements \emph{precludes} arbitrary functions and only includes
formulas from efficiently decidable logics, \eg the quantifier-free
logic of linear arithmetic and uninterpreted functions (\logiclang).
Thus, VCs like the above can be efficiently validated by SMT
solvers \cite{z3}.
%
In this case, the solver will reject the above VC as \emph{invalid} meaning the
implication, and hence, the relevant subtyping requirement does not hold.
So the refinement type system will \emph{reject} @bad@.

On the other hand, a refinement system \emph{accepts} @good@.
Here, @+@'s type exactly captures its behaviour into the logic:
\begin{code}
  (+) :: x:Int -> y:Int -> {v:Int | v = x + y}
\end{code}
Thus, we can conclude that the divisor @z@ is a positive number.
The subtyping query for the argument to @div@ is
%
\begin{align*}
\ttbind{x}{\ttref{x \geq 0}},\
\ttbind{y}{\ttref{y \geq 0}},\
\ttbind{z}{\ttref{z = y + 1}}\
\vdash\ & \subtref{v = y + 1}{v > 0}
%\label{sub:good}
\intertext{which reduces to the \emph{valid} VC}
	\mathvc{(\ttx \geq 0)} \wedge \mathvc{(\tty \geq 0)}\wedge
	\mathvc{(\ttz = \tty+1)}
   \Rightarrow\ & \mathvc{(\ttv = \tty+1)}
   \Rightarrow \mathvc{(\ttv > 0)} \nonumber
\end{align*}

\subsection{Lazy Evaluation Makes VCs Unsound} \label{sec:overview:unsound}

To generate the classical VC, we ignored the ``\x is a value'' guard
that appears in the embedding of a binding \embed{\ttbind{\x}{\typ}} (Figure~\ref{fig:overview:syntax}).
%
Under lazy evaluation, ignoring this ``is a value'' guard can lead to unsoundness.
%
Consider
%
\begin{code}
   diverge   :: Int -> {v:Int | false}
   diverge n = diverge n
\end{code}
%
The output type captures the \emph{post-condition}
that the function returns an @Int@ satisfying @false@.
This counter-intuitive specification states, in essence,
that the function \emph{does not terminate}, \ie does not
return \emph{any} value.
%
Any standard refinement type checker (or Floyd-Hoare
verifier like Dafny~\cite{dafny})
will verify the given signature for @diverge@
via the classical method of inductively \emph{assuming}
the signature holds for @diverge@ and then
\emph{guaranteeing} the signature~\cite{Hoare71,Nipkow02}.
%
Next, consider the call to @div@ in @explode@:
%
\begin{code}
   explode   :: Int -> Int
   explode x = let {n = diverge 1; y = 0}
               in  x `div` y
\end{code}
%
To analyze @explode@, the refinement type system will check
that @y@ has type @Pos@ at the call to @div@, \ie will check
that
%
\begin{align}
   \ttbind{\ttn}{\ttref{\ttfalse}},\ \ttbind{\tty}{\ttref{\tty = 0}}\ \vdash\ & \subtref{\ttv = 0}{\ttv > 0}
   \label{sub:explode}
\intertext{In the environment, \texttt{n} is
  bound to the type corresponding to the \emph{output}
  type of \texttt{diverge} and \texttt{y} is bound to
  the type stating \texttt{y} equals \texttt{0}.
  In this environment, we must prove that actual parameter's
  type -- \ie that of \texttt{y} -- is a subtype of \texttt{Pos}.
  The subtyping, using the embedding of Figure~\ref{fig:overview:syntax}
  and ignoring the ``is a value'' guard,
  reduces to the VC:}
    \mathvc{\ttfalse} \wedge \mathvc{\tty = 0}\ \Rightarrow\ & \mathvc{(\ttv = 0)} \Rightarrow \mathvc{(\ttv > 0)}
    \label{vc:explode}
\end{align}
%
The SMT solver proves this VC valid using the
contradiction in the antecedent, thereby unsoundly
proving the call to @div@ safe!

\mypara{Eager vs. Lazy Verification Conditions}
%
We pause to emphasize that the problem lies
in the fact that the classical technique for encoding subtyping
(or generally, Hoare's ``rule of consequence" \cite{Hoare71})
with VCs is \emph{unsound under lazy evaluation}.
%
To see this, observe that the VC~(\ref{vc:explode}) is perfectly
\emph{sound} under eager (strict, call-by-value) evaluation.
%
In the eager setting, the program is safe in that
@div@ is never called with the divisor @0@, as it
is not called at all!
%
The inconsistent antecedent in the VC logically encodes the
fact that, under eager evaluation, the call to @div@ is
\emph{dead code}.
%
Of course, this conclusion is spurious under Haskell's lazy
semantics. As @n@ is not required, the program will dive
headlong into evaluating the @div@ and hence crash,
rendering the VC meaningless.

\mypara{The Problem is Laziness} Readers familar
with fully dependently typed languages, for instance
Cayenne~\cite{cayenne}, Agda~\cite{agda},
Coq~\cite{coq-book}, and Idris~\cite{Brady13}, may be
tempted to attribute the unsoundness to the presence
of arbitrary recursion and hence non-termination
(\eg @diverge@).
While it \emph{is} possible to define a sound semantics
for dependent types that mention potentially non-terminating
expressions~\citep{Knowles10}, it is not clear how to reconcile
such semantics with decidable type checking.

Refinement type systems avoid this situation by carefully restricting
types so that they do not contain arbitrary terms (even through
substitution), but rather only terms from restricted logics that
preclude arbitrary user-defined functions~\cite{pfenningxi98,Dunfield07,fstar}.
Very much like previous work, for now, we enforce the same restriction
with a \emph{well-formedness condition} on
refinements (\rwbased in Fig.~\ref{fig:declang:typing}).
%
In Chapter~\ref{refinementrflection} we present how
our logic is extended with provably terminating arbitrary terms,
while preserving both soundness and decidability.

However, we show that restricting the logic of refinements
\emph{is plainly not sufficient for soundness}
when laziness is combined with non-termination,
as binders can be bound to diverging expressions.
Unsurprisingly, in a strongly
normalizing language the question of lazy or strict semantics is irrelevant for soundness, and hence
an ``easy'' way to solve the problem would be to completely eliminate non-termination and rely on the soundness
of previous refinement or dependent type systems! Instead, we show here how to
recover soundness for a lazy language \emph{without} imposing such a drastic requirement.

\subsection{Semantics, Subtyping \& Verification Conditions} \label{sec:den-sem}

To understand the problem, let us take a step
back to get a clear view of the relationship
between the operational semantics, subtyping,
and verification conditions.
%
We use the formulation of evaluation-order
independent refinement subtyping developed
for \hlang~\cite{Knowles10} in which
refinements $r$ are \emph{arbitrary} expressions $e$ from the source language.
We define a denotation for types and use it
to define subtyping declaratively.

\mypara{Denotations of Types and Environments}
%
Recall the type @Pos@ defined as {@{v:Int | 0 < v}@}.
Intuitively, @Pos@ denotes the \emph{set of} @Int@
expressions which evaluate to values greater than @0@.
%
We formalize this intuition by defining the denotation
of a type as:
$$\interp{\tttref{\x}{\typ}{}{\refi}} \defeq \{e \mid \hastype{\emptyset}{e}{\typ}, \mbox{ if } \goesto{e}{\val} \mbox{ then } \goesto{\SUBST{\refi}{\x}{\val}}{\etrue} \}$$
%
That is, the type denotes the set of expressions \mie that have
the corresponding base type \typ which \emph{diverge or} reduce
to values that make the refinement reduce to $\etrue$.
%
The guard \goesto{\mie}{\val} is crucially required to prove soundness in the presence of recursion.
Thus, quoting~\cite{Knowles10}, ``refinement types specify partial and not total correctness''.

An \emph{environment} $\env$ is a sequence of type bindings
and a \emph{closing substitution} \sto\xspace is a sequence of expression bindings:
$$\env \defeq \ttbind{\x_1}{\typ_1},\ldots\ttbind{\x_\n}{\typ_\n} \qquad \qquad
  \sto \defeq \tgbind{\x_1}{\mie_1}, \ldots, \tgbind{\x_\n}{\mie_\n}$$ %%
%%
Thus, we define the denotation of $\env$ as the set of substitutions:
%%
$$\interp{\env} \defeq \{\sto \mid \forall \ttbind{\x}{\typ} \in \env. \sto(\x) \in \interp{\thetasub{\sto}{\typ}} \}$$

\mypara{Declarative Subtyping}
Equipped with interpretations for types and environments,
we define the \emph{declarative subtyping} \rtdsub
(over basic types $\base$, shown in Figure~\ref{fig:overview:syntax})
to be containment between the types' denotations:
$$
\inference
  {\forall \sto\in \interp{\env}.\
  		 \interp{\thetasub{\sto}{\tttref{\vv}{\Base}{}{\refi_1}}}
  		\subseteq   \interp{\thetasub{\sto}{\tttref{\vv}{\Base}{}{\refi_2}}}}
  {\issubtype{\env}{\tttref{\vv}{\Base}{}{\refi_1}}{\tttref{\vv}{\Base}{}{\refi_2}}}
  \rtdsub
$$
%
Let us revisit the @explode@ example from \Sref{sec:overview:unsound};
recall that the function is safe under eager evaluation but unsafe under
lazy evaluation. Let us see how the declarative subtyping allows us to
reject in the one case and accept in the other.

\mypara{Declarative Subtyping with Lazy Evaluation}
Let us revisit the query (\ref{sub:explode}) to see whether it
holds under the declarative subtyping rule \rtdsub. The denotation
containment
%
\begin{align}
\label{con:explode}
   \forall \sto \in &\interp{
   		\ttbind{n}{\ttref{\ttfalse}},\ \ttbind{y}{\ttref{y = 0}}
   		}.
     \interp{{{\sto}\ {\ttref{v = 0}}}} \subseteq \interp{{\sto}\ {\ttref{v > 0}}}
\end{align}
%
\emph{does not} hold. To see why, consider a $\sto$ that maps
$n$ to any diverging expression of type $\ttInt$ and $y$
to the value $0$.
%
Then, $0 \in \interp{\sto\ \ttref{v = 0}}$ but $0 \not \in \interp{\sto\ \ttref{v > 0}}$,
thereby showing that the denotation containment does not hold.

\mypara{Declarative Subtyping with Eager Evaluation}
Since denotational containment (\ref{con:explode}) does not hold,
\hlang cannot verify @explode@ under eager evaluation.
%
However, Belo \etal~\cite{Greenberg11} note that under eager (call-by-value)
evaluation, each binder in the environment is only added \emph{after}
the previous binders have been reduced to \emph{values}.
%
Hence, under eager evaluation we can \emph{restrict the range} of
the closing substitutions to values (as opposed to expressions).
%
Let us reconsider (\ref{con:explode}) in this new light:
%
there \emph{is no value} that we can map \ttn to, so the set of
denotations of the environment is empty. Hence, the
containment~(\ref{con:explode}) vacuously holds under
eager evaluation, which proves the program safe.
%
Belo's observation
is implicitly used by refinement types for eager languages
to prove that the standard (\ie call-by-value)
reduction from subtyping to VC is sound.

\mypara{Algorithmic Subtyping via Verification Conditions}
The above subtyping (\rtdsub)
rule allows us to prove preservation and progress~\cite{Knowles10}
but quantifies over evaluation of arbitrary expressions,
and so is undecidable.
%
To make checking \emph{algorithmic} we approximate the
denotational containment using \emph{verification conditions} (VCs),
formulas drawn from a decidable logic, that are valid
only if the undecidable containment holds.
%
As we have seen, the classical VC is sound only under
eager evaluation. Next, let us use the distinctions
between lazy and eager declarative subtyping,
to obtain both sound and decidable VCs for the lazy setting.

\mypara{Step 1: Restricting Refinements To Decidable Logics}
%
Given that \hlang refinements can be \emph{arbitrary} expressions,
the first step towards obtaining a VC, regardless of evaluation order,
is to restrict the refinements to a \emph{decidable} logic.
%
We choose the quantifier free logic of equality, uninterpreted functions
and linear arithmetic (\logiclang).
%
Our typing rules ensure that for any valid derivation, all
refinements belong in this restricted language.

\mypara{Step 2: Translating Containment into VCs}
Our goal is to encode the denotation containment antecedent of \rtdsub
%
\begin{align}\label{denotcont}
\forall \sto\in \interp{\env}.\
  		 \interp{\thetasub{\sto}{\tttref{\vv}{\Base}{}{\refi_1}}}
  		\subseteq   \interp{\thetasub{\sto}{\tttref{\vv}{\Base}{}{\refi_2}}}
\end{align}
as a logical formula, that is valid \emph{only when} the above holds.
Intuitively, we can think of the closing substitutions $\sto$ as
corresponding to \emph{assignments} or \emph{interpretations}
$\embed{\sto}$
of variables $X$ of the VC.
%
We use the variable \x to approximate denotational containment
by stating that
if \x belongs to the type $\tttref{\vv}{\Base}{}{\refi_1}$
then \x belongs to the type $\tttref{\vv}{\Base}{}{\refi_2}$:
$$
\forall X \in \mathit{dom}(\Gamma), \x.
    \embed{\Env}\Rightarrow
  		 {\embed{\ttbind{\x}{\tttref{\vv}{\Base}{}{\refi_1}}}}
  		\Rightarrow \embed{\ttbind{\x}{\tttref{\vv}{\Base}{}{\refi_2}}}
$$
where $\embed{\env}$ and $\embed{\ttbind{\x}{\typ}}$ are respectively the translation
of the environment and bindings into logical formulas
that are only satisfied by assignments $\embed{\sto}$
as shown in Figure~\ref{fig:overview:syntax}.
%
Using the translation of bindings,
and by renaming \x to \vv,
we rewrite the condition as
$$
\forall X \in \mathit{dom}(\Gamma), \vv.
    \embed{\env}
    \Rightarrow
     ({\text{``}\vv\ \text{is a value"}}  \Rightarrow \lref_1)
    \Rightarrow
     ({\text{``}\vv\ \text{is a value"}}  \Rightarrow \lref_2)
$$
Type refinements are carefully chosen to belong to the
decidable logical sublanguage \logiclang, so we directly translate
type refinements into the logic.
%
Thus, what is left is to translate into logic the environment and the ``is a value'' guards.
%
We postpone translation of the guards as we approximate the above formula by
a \emph{stronger}, \ie sound with respect to \ref{denotcont},
VC that just omits the guards:
$$
\forall X \in \mathit{dom}(\Gamma), \vv.
    \embed{\env}
    \Rightarrow
      \lref_1 \Rightarrow \lref_2
$$
%
To translate environments, we conjoin their bindings' translations:
\begin{align*}
%
\embed{\ttbind{\x_1}{\typ_1},\ldots,\ttbind{\x_\n}{\typ_\n}} \defeq &
\embed{\ttbind{\x_1}{\typ_1}} \wedge \ldots \wedge \embed{\ttbind{\x_\n}{\typ_\n}} \\
%
\intertext{However, since types denote \emph{partial correctness},
   the translations must also explicitly account for possible divergence:}
\embed{\ttbind{\x}{\tlref{\vv}{\tint}{}{\refi}}} \defeq & \ \mbox{``$\x$ is a value"}  \Rightarrow \SUBST{\lref}{\vv}{\x}
\end{align*}
%
That is, we \emph{cannot} assume that each \x satisfies its
refinement \refi; we must \emph{guard} that assumption with a
predicate stating that \x is bound to a value (not a diverging term).

The crucial question is: \emph{how} can one discharge these guards
to conclude that \x indeed satisfies \refi?
%
One natural route is to enrich the refinement logic with
a predicate that states that ``\x is a value", and then
use the SMT solver to \emph{explicitly} reason about
this predicate and hence, divergence.
%
Unfortunately, we show in \Sref{sec:refinedhaskell:conclusion}, that
such predicates lead to three-valued logics,
which fall outside the scope of the efficiently
decidable theories supported by current solvers.
%
Hence, this route is problematic if we want to use
existing SMT machinery to build automated verifiers
for Haskell.

\subsection{Our Answer: Implicit Reasoning About Divergence}

One way forward is to \emph{implicitly} reason about divergence
by \emph{eliminating} the ``\x is a value" guards (\ie \emph{value guards}) from the VCs.

\mypara{Implicit Reasoning: Eager Evaluation}
Under eager evaluation the domain of the closing substitutions
can be restricted to values~\cite{Greenberg11}.
%
Thus, we can trivially eliminate the value guards,
as they are guaranteed to hold by virtue of the
evaluation order.
%
Returning to @explode@, we see that after eliminating
the value guards, we get the VC (\ref{vc:explode})
which is, therefore, sound under eager evaluation.

\mypara{Implicit Reasoning: Lazy Evaluation}
However, with lazy evaluation, we cannot just
eliminate the value guards, as the closing
substitutions are not restricted to just values.
%
Our solution is to take this reasoning out of the
hands of the SMT logic and place it in the hands of
a \emph{stratified type system}.
%
We use a non-deterministic $\beta$-reduction
(formally defined in \Sref{sec:language})
to label each type as:
%
A \Div-type, written $\DivTy{\typ}$,
which are the default types given to binders
that \emph{may diverge}, or,
%
a \Wnf-type, written $\WnfTy{\typ}$,
which are given to binders that are guaranteed to
reduce, in a finite number of steps, to \emph{Haskell values}
in Weak Head Normal Form (WHNF).
%
Up to now we only discussed \tint basic types, but
our theory supports user-defined algebraic data types.
%
An expression like @0 : repeat 0@ is an infinite Haskell value.
%
As we shall discuss, such infinite values cannot be represented in the logic.
%
To distinguish infinite from finite values, we use a \Fin-type, written $\FinTy{\typ}$,
to label binders of expressions that are guaranteed to reduce to \emph{finite values} with no redexes.
%%%
This stratification lets us generate VCs that are sound
for lazy evaluation.
%
Let \Base be a basic labelled type.
%
The key piece is the translation of environment bindings:
$$
\embed{\ttbind{\x}{\tttref{\vv}{\Base}{}{\refi}}} \defeq
  \begin{cases}
    \tttrue,         & \mbox{if $\Base$ is a \Div type} \\
    \SUBST{\lref}{\vv}{\x}, & \mbox{otherwise}
  \end{cases}
$$
That is, if the binder may diverge, we simply \emph{omit}
any constraints for it in the VC, and otherwise the translation
directly states (\ie without the value guard) that the
refinement holds.
%
Returning to @explode@, the subtyping query (\ref{sub:explode})
yields the \emph{invalid} VC
$$
\tttrue \Rightarrow \ttv = 0 \Rightarrow \ttv > 0
$$
and so @explode@ is soundly rejected under lazy evaluation.

As binders appear in refinements and binders may refer
to potentially infinite computations (\eg @[0..]@), we must
ensure that refinements are well defined (\ie do not diverge).
%
We achieve this via stratification itself, \ie by ensuring that
all refinements have type $\FinTy{\tbool}$. By
Corollary~\ref{cor:stratification}, this suffices to ensure that
all the refinements are indeed well-defined and converge.

\subsection{Verification With Stratified Types}\label{sec:overview:examples}
While it is reassuring that the lazy VC soundly \emph{rejects}
unsafe programs like @explode@, we demonstrate by example
that it usefully \emph{accepts} safe programs.
%
First, we show how the basic system -- all terms
have \Div types -- allows us to prove ``partial correctness''
properties without requiring termination.
%
Second, we extend the basic system by
using Haskell's pattern matching semantics to assign
the pattern match scrutinees \Wnf types, thereby
increasing the expressiveness of the verifier.
%
Third, we further improve the precision
and usability of the system by using a termination
checker to assign various terms \Fin types.
%
Fourth, we close the loop, by illustrating how the
termination checker can itself be realized using
refinement types.
%
Finally, we use the termination checker to ensure that
all refinements are well-defined (\ie do converge).

\mypara{Example: VCs and Partial Correctness}
The first example illustrates how, unlike Curry-Howard based
systems, refinement types \emph{do not require} termination.
%
That is, we retain the Floyd-Hoare notion of ``partial correctness''
and can verify programs where \emph{all} terms have \Div-types.
%
Consider @ex1@ which uses the result of @collatz@ as a divisor.
%
\begin{code}
  ex1   :: Int -> Int
  ex1 n = let x = collatz n in 10 `div` x

  collatz :: Int -> {v:Int | v = 1}
  collatz n
    | n == 1    = 1
    | even n    = collatz (n / 2)
    | otherwise = collatz (3*n + 1)
\end{code}
%
The jury is still out on \emph{whether} the @collatz@
function terminates\footnote{
Collatz Conjecture: \url{http://en.wikipedia.org/wiki/Collatz\_conjecture}},
but it is easy
to verify that its output is a \Div @Int@ equal to @1@.
%
At the call to @div@ the parameter @x@ has the output type
of @collatz@, yielding the subtyping query:
%
\begin{align*}
   \tbind{\ttx}{\tref{\ttv}{\ttInt}{}{\ttv=1}} \vdash\ & \subtref{v = 1}{v > 0}
\end{align*}
%
where the sub-type is just the type of $\ttx$.
As $\ttInt$ is a \Div type, the above reduces to the VC
${(\etrue \Rightarrow\  \ttv = 1 \Rightarrow\ \ttv > 0)}$
which the SMT solver proves valid, verifying @ex1@.

\mypara{Example: Improving Precision By Forcing Evaluation}
\label{sec:overview:pattern-match}
If all binders in the environment have \Div-types then, effectively,
the verifier can make \emph{no} assumptions about the context in
which a term evaluates, which leads to a drastic loss of precision.
Consider:
\begin{code}
  ex2 = let {x = 1; y = inc x} in 10 `div` y

  inc :: z:Int -> {v:Int | v > z }
  inc = \z -> z + 1
\end{code}
%
The call to @div@ in @ex2@ is obviously safe, but the system
would reject it, as the call yields the subtyping query:
%
$$
   \tbind{\ttx}{\tref{\ttx}{\ttInt}{}{\ttx = 1}},\
   \tbind{\tty}{\tref{\tty}{\ttInt}{}{\tty > \ttx}}\
   \vdash\ \subtref{v > \ttx}{v > 0}
$$
Which, as $\ttx$ is a \Div type, reduces to the invalid VC:
$$
   \tttrue \Rightarrow\ \ttv > \ttx \Rightarrow \ttv > 0
$$
%
We could solve the problem by forcing evaluation of @x@.
%
In Haskell the @seq@ operator or a bang-pattern can be used to force evaluation.
%
In our system the same effect is achieved by the @case-of@ primitive:
inside each case the matched
binder is guaranteed to be a Haskell value in WHNF.
%
This intuition is formalized by the typing rule (\rtcased), which checks each
case after assuming the scrutinee and the match binder have \Wnf types.
%

If we force @x@'s evaluation, using the case primitive,
the call to @div@ yields the subtyping query:
\begin{align}
   \ttbind{\ttx}{\ttreft{\ttx}{\WnfTy{\ttInt}}{\ttx = 1}},\
   \ttbind{\tty}{\ttreft{\tty}{\ttInt}{\tty > \ttx}}
	& \vdash\ \subtref{v > \ttx}{v > 0}\label{sub:pm:ex3:good}
\intertext{As $\ttx$ is \Wnf, we accept \texttt{ex2} by proving the validity of the VC:}
   \ttx = 1 \Rightarrow\  \ttv > \ttx & \Rightarrow \ttv > 0
\label{vc:pm:ex3:good}
\end{align}

\mypara{Example: Improving Precision By Termination}
While forcing evaluation allows us to ensure that certain
environment binders have non-\Div types,
it requires program rewriting using case-splitting
or the @seq@ operator which leads to non-idiomatic code.

Instead, our next key optimization is based on
the observation that in practice, \emph{most terms don't diverge}.
%
Thus, we can use a termination analysis to
aggressively assign terminating expressions
\Fin types, which lets us strengthen the
environment assumptions needed to prove
the VCs.
%
For example, in the @ex2@ example the term @1@ obviously terminates.
Hence, we type @x@ as $\FinTy{\ttInt}$, yielding
the subtyping query for @div@ application:
%
\begin{align}
   \ttbind{\ttx}{\ttreft{\ttx}{\FinTy{\ttInt}}{\ttx = 1}},\
   \ttbind{\tty}{\ttreft{\tty}{\ttInt}{\tty > \ttx}}
	& \vdash\ \subtref{v > \ttx}{v > 0}\label{sub:ex3:good}
\intertext{As $\ttx$ is \Fin, we accept \texttt{ex2} by proving the validity of the VC:}
   \ttx = 1 \Rightarrow\ \ttv > \ttx & \Rightarrow \ttv > 0
\label{vc:ex3:good}
\end{align}

\mypara{Example: Verifying Termination With Refinements}
%
While it is straightforward to conclude that the term @1@
does not diverge, how do we do so in general?
%
For example:
%
\begin{code}
  ex4 = let {x = f 9; y = inc x} in 10 `div` y

  f   :: Nat -> {v:Int | v = 1}
  f n = if n == 0 then 1 else f (n-1)
\end{code}
%
We check the call to @div@ via subtyping query (\ref{sub:ex3:good}) and
VC (\ref{vc:ex3:good}), which requires us to prove that @f@ terminates on
\emph{all} $\FinTy{\mathtt{Nat}}$ inputs.

We solve this problem by showing how
refinement types may themselves be
used to prove termination, by following
the classical recipe of proving termination
via decreasing metrics~\cite{Turing36}
as embodied in sized types~\cite{HughesParetoSabry96,XiTerminationLICS01}.
%
The key idea is to show that each
recursive call is made with arguments
of a \emph{strictly smaller} size,
where the size is itself a well
founded metric, \eg a natural number.

We formalize this intuition by type checking
recursive procedures in a {termination-weakened environment}
where the procedure itself may only be called with arguments
that are strictly smaller than the current parameter
(using terminating fixpoints of \Sref{sec:typing:stratify}).
%
For example, to prove @f@ terminates, we check its body in an environment
%
$${\ttn} : {\FinTy{\ttNat}}, \qquad {\ttf} : {\ttreft{\ttnp}{\FinTy{\ttNat}}{\ttnp < \ttn} \rightarrow \ttref{v=1}}$$
%
where we have weakened the type of $\ttf$ to stipulate that it
\emph{only} be (recursively) called with $\ttNat$ values $\ttnp$ that are
\emph{strictly less than} the (current) parameter $\ttn$.
The argument of \ttf exactly captures these constraints,
as using the Abbreviations of Figure~\ref{fig:overview:syntax}
the argument of \ttf is expanded to
$\ttreft{\ttnp}{\FinTy{\tint}}{\ttnp < \ttn \land \ttnp >= 0}$.
The body
type-checks as the recursive call generates the valid VC:
%
$$0 \leq \ttn \wedge \lnot (0 = \ttn)  \Rightarrow \ttv = \ttn - 1 \Rightarrow (0 \leq \ttv < \ttn)$$

\mypara{Example: Diverging Refinements}
Finally, we discuss why refinements should always converge
and how we statically ensure convergence.
%
Consider the invalid specification
\begin{code}
  diverge 0 :: {v:Int | v = 12}
\end{code}
that states that the value of a diverging integer is @12@.
%
The above specification should be rejected,
as the refinement $\mathtt{v = 12}$ does not evaluate to \etrue
(\goesto{\mathtt{diverge\ 0 = 12} \not}{\etrue}),
instead it diverges.

We want to check the validity of the formula $\mathtt{v = 12}$
under a model that maps \ttv to the diverging integer $\mathtt{diverge \ 0}$.
%
Any system that decides this formula to be true
will be unsound, \ie the VCs will not soundly approximate subtyping.
%
For similar reasons, the system should not decide that this formula is false.
%
To reason about diverging refinements one needs three valued logic,
where logical formulas can be solved to true, false, or diverging.
%
Since we want to discharge VC using SMT solvers that currently do not support
three valued reasoning, we exclude diverging refinements from types.
%
To do so, we restrict $\mathtt{=}$ to finite integers
$$ (\mathtt{=}) :: {\tint^{\finite}}\rightarrow{\tint^\finite}\rightarrow{\tbool^\finite}$$
and we say that \ttreft{\vv}{\Base}{\refi}
is well-formed \emph{iff} \refi has a $\tbool^\finite$ type (Corollary~\ref{cor:stratification}).
%
Thus the initial invalid specification will be rejected as non well-formed.
%%\DV{This paragraph is confusing. I thought
%%$len :: [a]^\Downarrow -> Int^\Downarrow$ no? But then we are not able to apply len to anything else? Is len (repeat 35) ill typed? This does not look good.
%%Or is this typing only affecting refinements and not actual programs?}
%%\NV{
%%It can be either
%%$len :: [a]^\Downarrow -> Int^\Downarrow$
%%or
%%$len :: [a]^\Downarrow -> Int$.
%%Either ways len (repeat 35) should be ill typed, when len is required to terminate,
%%for example when the result of len is used inside the refinements.
%%Though, in actual programs we can have diverging expressions, so
%%length (repeat 35) can be well-typed, with
%%$length :: [a] -> Int$.
%%}

%
%%% In \Sref{sec:typing} we formalize our system for proving termination
%%% with refinements, and then show, in \S~\ref{sec:haskell}, how to generalize
%%% it to handle complex data types.
%%% The proof of the pudding is in \S~\ref{sec:evaluation} where we demonstrate
%%% empirically the effectiveness of \toolname's approach of proving termination
%%% \emph{for} and \emph{by} refinements, on a large corpus of 10KLOC of widely
%%% used, complex, real-world Haskell libraries.

%% JUNK
%%         take 0 _  = []
%%         take n xs = case xs of
%%                       (x:xs') -> x : take (n-1) xs'
%%                       []      -> liquidError
%%
%%
%%
%%         findPos (x:xs)
%%           | x > 0       = Just x
%%           | otherwise   = find p xs
%%         findPos []      = Nothing
%%
%%         ex0 ys = 24 `div` (findPos ys)
%%
%%         x:Nat -> {y | x < y} -> Int
%%         ex1 = 24 `div` y

%% \subsection{An Optimization: Termination}
%%   x:Nat -> {y | x < y} -> Int
%%   ex1 = 24 `div` y
%%
%% fail      :: n:Nat -> {m:Nat | n < m} -> Int
%% fail n m  = 10000 `div` m
%%
%% fail'     :: n:Nat -> {m:Nat | n < m} -> Int
%% fail' n m = case n of _ -> 10000 `div` m
%%
%% bar     :: Int -> Int -> Int
%% bar     = foo x y
%%   where
%%     x   = fac 10
%%     y   = x + 1

%%% THE FOLLOWING FAILS IN APROVE BUT COMPLETES AUTOMATICALLY IN LH
%%%
%%% foo   :: Int -> Int
%%% foo 0 = 0
%%% foo n = 0 + foo (n-1)
%%%
%%% top   :: Int -> Int
%%% top n = if n < 0 then 1 else foo (foo n)

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End: