\chapter{Inference of Guarded Recursion}
\label{cha:infer-guard-recurs}
In Section~\ref{sec:less-restr-prod}, we provided the motivation behind
extending Idris with a less restrictive productivity checker using guarded
recursion. As we saw in Section~\ref{sec:guarded-recursion}, defining guarded
recursive programs can be quite tedious. Also, it requires the user to
thoroughly understand guarded recursion in order to write provably productive
programs. In this chapter, we propose a system where the productivity of
programs can be verified using guarded recursion with only a minimal amount of
user involvement. In particular, we present an implementation of a term
inference system, which infers guarded recursive terms from elaborated TT
terms. Additionally, a checking system is presented which ensures that the
inferred guarded recursive terms result in productive definitions. Throughout
this chapter, the main focus will be on implementation, showing how we have put
theory into practice.

To ease the inference process, we divide user-written definitions into two
classes, causal and non-causal definitions (we will revisit this classification
in Section~\ref{sec:causal-non-causal}). However, we have yet to finish the
implementation of inference and productivity checking for non-causal
definitions. Consequently, any discussion of non-causal definitions in the following
should be considered mostly theoretical. Nevertheless, we are confident that
implementing support for non-causal definitions is possible.

\section{Practical Considerations}
Applying a theoretical model for productivity to actual Idris programs means
that we must address several practical issues concerning the Idris compiler.

\subsection{Target Language}
As discussed in Chapter~\ref{cha:idris}, an Idris program has multiple different
representations throughout the compilation process, namely concrete Idris,
\IdrisM{}, TT, and machine code. Therefore, the compilation
stage and program representation chosen for the productivity analysis has great
impact on how a solution unfolds.

Since guarded recursion is a typing discipline, the system needs the ability to
both infer and check types of arbitrary terms. This is not possible prior to
elaboration, as type checking (or inference) may require evaluation. Because program
structure is important for the analysis, the machine code would be impractical
as a target language. After elaboration, the resulting TT
terms have all type information available, while program structure is still
preserved. Hence, the productivity analysis is performed on elaborated TT terms.

Choosing TT for the analysis means that all coverage checking can be handled by existing coverage checker
in Idris. Since coverage checking happens prior to the invocation of our
productivity analysis, all definitions analysed by our system are assumed to be covering.

\subsection{Lifting Parameters} % -- Subsubsection til forrige section?
\label{sec:handling-parameters}
Recall the typing rule for the later application operator, $\tensor^\kappa$, in
Figure~\ref{fig:guarded_recursion_rules_clocks}:

\input{figures/guarded_tensor_intro_rule}

While this rule provides us with a mechanism for sequential application of
values available later, it only works for the simply typed case. Notably, it
does not take substitution in the resulting type into account, so the function
argument to $\tensor^\kappa$, $f$, can never be applied to an argument $e$ which
refines the type of $f$, e.g. a type argument. The following function,
\texttt{repeat}, requires an application of a type argument:

\begin{lstlisting}[mathescape,title=\ttBlock]
repeat : $\forall \kappa.$ ((a : Type) $\rightarrow$ a $\rightarrow$ Stream$^{\kappa}$ a)
repeat = $\Lambda\kappa.$ fix$^{\kappa}$($\lambda{}$rec$.\lambda{}$a$.\lambda{}$n$.$
             StreamCons a n ((rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ a)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)))
\end{lstlisting}

By the use of the guarded recursive fixed point, the recursive reference is not
available until later ($\laterkappa$). Therefore, it must be
applied to its type argument by later application. But, as shown in
Figure~\ref{fig:repeat_failed_typing}, such an application cannot be well-typed. In
particular, the type argument in the type of ${Next^{\kappa}\,repeat[\kappa]}$ is not bound as the type variable \texttt{a},
since this connection is not expressed in the typing rule for later application.

\begin{figure}[h]
\centering
\[
\frac { \begin{matrix} \inference { \frac { ? }{ \Gamma '\, \vdash \, (Next^{\kappa}\,repeat[\kappa])\, :\, \later
        ^{\kappa}(Type\, \rightarrow \, a\, \rightarrow \, Stream^{\kappa}\, a) } \,
      \frac {
        \frac {  }{ \Gamma '\, \vdash \, a\, :\, Type }
      }
      { \Gamma '\, \vdash \,
        Next^{\kappa}\, a\, :\, \later ^{\kappa}\, Type }
    }{ \, \Gamma '\, \vdash \, (Next^{\kappa}\,repeat[\kappa])\,
      \tensor ^{\kappa} \, (Next^{\kappa}\, a)\, :\, \later ^{\kappa}(a\, \rightarrow \, Stream^{\kappa}\,
      a)\ }  & \inference { \inference {  }{ \Gamma '\, \vdash \, n\, :\, a }  }{
      \Gamma '\, \vdash \, Next^{\kappa}\, n\, :\, \later ^{\kappa} \, a }  \end{matrix} }{
  \Gamma '\, \vdash \, ((Next^{\kappa}\,(repeat[\kappa]))\, \tensor ^{\kappa} \, (Next^{\kappa}\, a))\, \tensor ^{\kappa} \,
  (Next^{\kappa}\, n))\, :\, \later ^{\kappa} Stream^{\kappa}\, a }
\]
\[
\Gamma '\, =\, \Gamma ,\, repeat\, :\, \forall\kappa.((a\, :\, Type)\, \rightarrow \,
a\, \rightarrow \, Stream^{\kappa}\, a),\, a\, :\, Type,\, n\, :\, a
\]
  \caption{A failed attempt at typing the tail argument to the
    \texttt{StreamCons} constructor in the definition of \texttt{repeat}.}
  \label{fig:repeat_failed_typing}
\end{figure}

One way of solving this problem would be to change the typing rule for later applitcation, such that it takes substitution in types into account, as shown in
Figure~\ref{fig:tensor_with_subst}. However, this formulation of the rule has
yet to be proven sound.

\begin{figure}[h]
\[
\inference { \Gamma \, \vdash \, t\, :\, \later^{\kappa} ((a\, :\, A)\,
  \rightarrow \, B)\quad \Gamma \, \vdash \, u\, :\, \later^{\kappa} A }{
  \Gamma \, \vdash \, t\, \tensor ^{\kappa} \, u\, :\, \later^{\kappa} B[{ u
  }/{ a }] }
\]
  \caption{A potential rule for later application with substitution in
    types. However, the type $\later^{\kappa} B[{ u }/{ a }]$ in the conclusion
    is not well-formed according to the rules of guarded recursion presented in Figure~\ref{fig:guarded_recursion_rules_clocks}.}
  \label{fig:tensor_with_subst}
\end{figure}

Instead, we can change which arguments appear under the fixed point. Any
parameter which would have to be substituted in the type is therefore lifted out
of the fixed point operator, thus changing the type of the recursive
reference. This gives us the definition of \texttt{repeat} in
Figure~\ref{fig:repeat_guarded_example_new}, where the type of the recursive
reference is \texttt{$\later ^{\kappa}$(a~$\rightarrow$~Stream$^{\kappa}$
  a)}. Because the type parameter is now fixed outside of the fixed point
operator, we can type the part of \texttt{repeat} that failed previously, as
shown in Figure~\ref{fig:repeat_typing_new}.

\begin{figure}[h]
  \begin{lstlisting}[mathescape,title=\ttBlock]
repeat : (a : Type) $\to$ $\forall \kappa.$ (a $\to$ Stream$^{\kappa}$ a)
repeat a = $\Lambda\kappa.$ fix$^{\kappa}$($\lambda{}$rec$.\lambda{}$n$.$
                    StreamCons a n (rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)))
\end{lstlisting}
  \caption{A definition of \texttt{repeat} where the type parameter is has been lifted
    out of the fixed point operator.}
  \label{fig:repeat_guarded_example_new}
\end{figure}

\begin{figure}[h]
\[
\frac { \frac {  }{ \Gamma '\, \vdash \, rec\, :\, \later ^{\kappa}(a\, \rightarrow
    \, Stream^{\kappa}\, a) } \, \frac { \Gamma '\, \vdash \, n\, :\, a }{ \Gamma '\,
    \vdash \, Next^{\kappa}\, n\, :\, \later ^{\kappa}\, a }  }{ \, \Gamma '\, \vdash \, rec\,
  \tensor ^{\kappa} \, (Next^{\kappa}\, n)\, :\, \later ^{\kappa}Stream^{\kappa}\, a }
\]
\[
 \Gamma '\, =\, \Gamma ,\, rec\, :\, \later ^{\kappa}(a\, \rightarrow \, Stream^{\kappa}\,
 a),\, a\, :\, Type,\, n\, :\, a
\]

  \caption{Part of typing repeat with fixed type parameter.}
  \label{fig:repeat_typing_new}
\end{figure}

The problem described here applies to all names bound by dependent function
types that occur free in the body type. Therefore, any such parameter must be
lifted out of the fixed point in this manner. Note that names bound to a type
depending on a clock, e.g. $Stream^{\kappa}$, cannot be safely lifted out from the clock
quantification. Presently, support for clock-dependent types has been deemed out
of scope. For further elaboration, see Section~\ref{sec:guarded-types}.

\subsection{Eliminating the \texttt{fix$^\kappa$} Rule}
\label{sec:fixkappa-rule}
In the following, we describe how one can supposedly encode dependent functions
under clock quantification by eliminating the guarded recursive fixed
point. While eliminating the fixed point seems to work as intended up to polymorphic
types, the theory behind it does not cover dependent function types. This
limitation was discovered late in the process, and is therefore a part of the
current implementation. Since it does work for non-dependent functions, we
describe the technique here, and use it throughout the remainder of the
chapter. The implications of using this technique for dependent function types
is discussed in Section~\ref{sec:depend-funct-types}.

In the theoretical model of guarded recursion, all programs must be encoded
inside a special fixed point operator, as shown in
Section~\ref{sec:guarded-recursion}. Ideally, we could simply port this idea to
Idris, encoding TT programs inside a TT definition of the fixed point
operator. While this would work fine for single-clause definitions, it becomes
problematic when we consider definitions with multiple clauses, such as the
following:

\begin{lstlisting}[mathescape,title=\ttBlock]
cycle : Nat $\to$ Nat $\to$ Stream Nat
cycle Z     m = (::) Nat Z (cycle m m)
cycle (S n) m = (::) Nat (S n) (cycle n m)
\end{lstlisting}

When transforming \texttt{cycle} to guarded recursive form, both clauses must be
part of the same fixed point definition. A seemingly obvious solution is to
convert the left-hand side pattern matching structure in \texttt{cycle} into
right-hand side \texttt{case}-expressions. For two reasons, this is not
possible: (1) TT does not have \texttt{case}-expressions, so the definition of
\texttt{cycle} is elaborated into two TT clauses, and (2) Idris
\texttt{case}-expressions only support non-dependent pattern matching. Hence,
the problem persists after elaboration.

Instead, we could attempt to define \texttt{cycle} as two functions: A
single-clause definition with the fixed point operator, and an auxiliary
function where pattern matching is performed. With this solution, all the clauses of
\texttt{cycle} are part of the same fixed point, where the guarded recursive reference,
\texttt{rec}, is given to \texttt{cycle} as an argument:

\begin{lstlisting}[mathescape, title=\ttBlock]
cycle$'$ : $\laterkappa\,$(Nat $\to$ Nat $\to$ Stream$^{\kappa}\,$Nat) $\to$ Nat $\to$ Nat $\to$ Stream$^{\kappa}$ Nat
cycle$'$ rec  Z    m = StreamCons Z   ((rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ m)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ m))
cycle$'$ rec (S n) m = StreamCons (S n) ((rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ m))

cycle : $\forall \kappa.\,$(Nat $\to$ Nat $\to$ Stream$^{\kappa}\,$Nat)
cycle = $\Lambda \kappa.\,$fix$^{\kappa}$($\lambda$rec.$\lambda$n.$\lambda$m. cycle$'$ rec n m)
\end{lstlisting}

% \begin{figure}[h]
% \begin{lstlisting}[mathescape]
% cycle$'$ : $\laterkappa\,$(Nat $\to$ Nat $\to$ Stream$^{\kappa}\,$Nat) $\to$ Nat $\to$ Nat $\to$ Stream$^{\kappa}$ Nat
% cycle$'$ rec  Z    m = StreamCons Z  ((rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ m)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ m))
% cycle$'$ rec (S n) m = StreamCons (S n) ((rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ m))

% cycle : $\forall \kappa.\,$(Nat $\to$ Nat $\to$ Stream$^{\kappa}\,$Nat)
% cycle = $\Lambda \kappa.\,$fix$^{\kappa}$($\lambda$rec.$\lambda$n.$\lambda$m. cycle rec n m)
% \end{lstlisting}
%   \caption{A guarded recursive definition of \texttt{cycle}, where the pattern
%     matching is handled by an auxiliary function \texttt{cycle'}. The
%     \texttt{Stream$^\kappa$ type is defined in Figure~\ref{fig:guarded_recursion_stream}.} }
%   \label{fig:cycle_guarded}
% \end{figure}

This approach works as expected, until we consider dependent types. In
particular, the problem is that we cannot have dependent quantification under
clock quantification. For example, in the function \texttt{prepend} from
Figure~\ref{fig:guarded_prepend}, the \texttt{n} in the type of \texttt{rec} is
fixed. But \texttt{n} is refined to \texttt{Z} in first clause and \texttt{S n}
in the the second clause, respectively, so \texttt{rec} can never be applied to
\texttt{xs} in a well-typed manner, since the type of xs is \texttt{Vect n a}.

\begin{figure}[h]
\begin{lstlisting}[mathescape,title=\ttBlock]
prepend$'$ : (n : Nat) $\to$ (a : Type) $\to$
           $\laterkappa\,$(Vect n a $\to$ Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a) $\to$
           Vect n a $\to$ Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a
prepend$'$ n a rec []        s = s
prepend$'$ n a rec (x :: xs) s =
                    StreamCons a x ((rec $\tensor$ (Next xs)) $\tensor$ (Next s))

prepend : (n : Nat) $\to$ (a : Type) $\to$
          $\forall\kappa.$(Vect n a $\to$ Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
prepend n a = $\Lambda\kappa.\,$fix$^\kappa$($\lambda$rec.$\lambda$xs.$\lambda$s. prepend$'$ n a rec xs s)
\end{lstlisting}
  \caption{A function prepending a vector on a stream. This definition is not well-typed.}
  \label{fig:guarded_prepend}
\end{figure}

To circumvent this issue, the current implementation eliminates the fixed point operator altogether according
to the elimination rules in Figure~\ref{fig:fix_elim_rules}. By eliminating the
fixed point, the type of the recursive reference is no longer fixed. This
elimination should allow us to write prepend as shown in
Figure~\ref{fig:guarded_prepend_bad}. However, as described in
Section~\ref{sec:depend-funct-types}, we cannot safely eliminate the fixed point
in this manner.

% The
% elimination of the fixed point is well-typed, since \texttt{Next$^{\kappa}$ f}
% and the recursive reference, here denoted \texttt{rec}, always have the same
% type according to the guarded recursive typing rules in Figure~\ref{fig:guarded_recursion_rules_clocks}.

\begin{figure}[h]
\centering

\begin{prooftree}
\def\fCenter{\vdash}
\Axiom$\Delta,\kappa;\Gamma,f:A\fCenter \texttt{fix}^{\kappa}(\lambda rec.e) :
  A$
\UnaryInf$\Delta,\kappa;\Gamma,f:A\fCenter
  e[(\texttt{Next}^{\kappa}\,f)/rec]:A$
\end{prooftree}

\begin{prooftree}
\def\fCenter{\vdash}
\Axiom$\Delta,\kappa;\Gamma,f:\forall\kappa.A\fCenter
\Lambda\kappa.\,\texttt{fix}^{\kappa}(\lambda rec.e) : \forall\kappa.A$
\UnaryInf$\Delta,\kappa;\Gamma,f:\forall\kappa.A\fCenter \Lambda\kappa.\,e[(\texttt{Next}^{\kappa}\,f[\kappa])/rec]:\forall\kappa.A$
\end{prooftree}

% \def\fCenter{\vdash}
% \AXD{\Delta,\kappa;\Gamma,f:\forall\kappa.A\fCenter \texttt{fix}^{\kappa}(\lambda rec.e) :
%   A}
% \UID{\Delta,\kappa;\Gamma,f:\forall\kappa.A\fCenter
%   e[(Next^{\kappa}\,f)/rec]:A}
% \DisplayProof

% %\AXD{\Delta,\kappa;\Gamma,f:\forall\kappa.A\vdash \texttt{fix}^{\kappa}(\lambda \texttt{rec}.e :
% %  A}

%   \[
% \frac { \Delta ,\, \kappa ; \, \Gamma \, \vdash \, f\, =\, { fix }^{ \kappa  }(\lambda
%   rec.\, e)\, :\, A }{ \Delta ,\, \kappa \, ; \Gamma \vdash \, f\, =\, e[{ (Next^{ \kappa
%     }\,f) }/{ rec }]\, :\, A } fix_{E_1}
% \]

% \[
% \frac { \Delta \, ; \Gamma \vdash \, f\, =\, \Lambda \kappa .{ fix }^{ \kappa  }(\lambda
%   rec.\, e)\, :\, \forall \kappa .A }{ \Delta \, ; \Gamma \vdash \, f\, =\, \Lambda
%   \kappa .e[{ (Next^{ \kappa  }\, f[\kappa ]) }/{ rec }]\, :\, \forall \kappa .A
% } fix_{E_2}
% \]
  \caption{The rules for fixed point elimination.}
  \label{fig:fix_elim_rules}
\end{figure}
\todo{Is there a better way express the fix elimination rules?}

\begin{figure}[h]
\begin{lstlisting}[mathescape, title=\ttBlock]
prepend$'$ : (n : Nat) $\to$ (a : Type) $\to$
           Vect n a $\to$ Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a
prepend$'$ Z    $\ $ a []        $\,$s = s
prepend$'$ (S k) a (x :: xs) s =
   StreamCons a x (((Next$^{\kappa}$ ((prepend[$\kappa$]) n a)) $\tensor$ (Next xs)) $\tensor$ (Next s))

prepend : (n : Nat) $\to$ (a : Type) $\to$
          $\forall\kappa.$(Vect n a $\to$ Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
prepend n a = $\Lambda\kappa.\,$($\lambda$xs.$\lambda$s. prepend$'$ n a xs s)
\end{lstlisting}
  \caption{The implementation of \texttt{prepend} after fixed point elimination.}
  \label{fig:guarded_prepend_bad}
\end{figure}

% After elimination of the fixed point operator, the guarded recursive version of
% \texttt{prepend} can be defined as follows:

% \begin{lstlisting}[mathescape]
% prepend : $\forall\kappa.$(Vect n a $\to$ Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
% prepend []        s = $\Lambda\kappa.\,$s
% prepend (x :: xs) s = $\Lambda\kappa.\,$StreamCons x
%                           (((Next$^\kappa$ prepend) $\tensor$ (Next$^\kappa$ xs)) $\tensor$ (Next$^\kappa$ s))
% \end{lstlisting}

% An elaboration upon this solution will be provided in Section~\ref{sec:impl-guard-recurs}.

\section{Scope}
Aside from the practical considerations arising from both the guarded recursion
theory and the implementation of the Idris compiler, we have chosen to narrow the
scope of our productivity analysis in two central areas. Specifically, we limit
the number of clock variables supported, and we identify two classes of
functions for which inference of guarded recursive terms will be supported.

\subsection{A Singleton Clock}
\label{sec:singleton-clock}
% Argumenter:
%% Hvornår bruger man hvilket ur?
%% GR-regler for checkeren her
%%
% f = /\k. fix(\rec. e)
% f = /\k. e[(Next(f[k])/rec]

% e :
% e1 = rhs[Next(f[k])/rec]
% e2 =
The theoretical model for guarded recursion with clock variables, due to Atkey
and McBride\,\citep{Atkey:2013}, imposes no limitations on the number of
simultaneous clock variables. This means that their system is very
expressive, but can lead to quite complicated definitions. Furthermore, the user must
explicitly specify which clock variable is applicable in a given situation to ensure
productivity. Automating the process of choosing the right clock variable for
any given combination of clock applications is not feasible in general, since for $n$ clock applications with $c$
clocks in scope, the number of possible combinations is $c^n$. Any linear
inference process would thus be in $O(c^n)$, and doing better would require
heuristics for common clock combinations. Presently, we have no knowledge of the
existence of such heuristics.

To avoid the problem of finding the correct combination of clock variables, we
simplify our system such that at most one clock is in scope at any given
time. The implication is that our productivity analysis will never return a
positive answer for programs whose guarded recursive equivalent requires more
than one clock. However, as noted by Clouston et
al.\,\citep{BirkedalL:guarded-lambda-conf}, all examples in the current
literature on guarded recursion require only one clock. This claim will be
supported by our evaluation in Chapter~\ref{cha:evaluation}, where we show a
that significant number of realistic programs have guarded recursive versions
that require only one clock.

Incorporating this simplification means that we
must adjust the typing rules for guarded recursion accordingly. The adjusted
rules are discussed in Section~\ref{sec:guard-recurs-check}.

% While
% deriving this set of adjusted rules from the original rules has not followed a
% specific methodology, a general trend is:

% \begin{itemize}
% \item If the original rule required a specific clock in the environment, the
%   adjusted rule requires an open clock.
% \item Side conditions concerned with specific clocks not being free in the
%   environment are adjusted so that no free clocks are allowed in the
%   environment at all.
% \end{itemize}

% Note that the $\kappa$, indicating which clock that applies for a given term,
% has been removed from most of the types and terms. Seeing as the rules can only
% express properties about the singleton clock, it is unnecessary to specify the
% current clock explicitly. For example, all $\later$ types now always operate on the
% same clock. However, $\kappa$ remains in some cases, such as $\forall \kappa$ and
% $\Lambda \kappa$. These still only mention the singleton clock, but the
% $\kappa$ has been kept in order to disambiguate $\forall \kappa$ from standard universal quantification and
% $\Lambda \kappa$ from standard lambda abstractions.

\subsection{Causal and Non-causal Functions}
\label{sec:causal-non-causal}
% Problem: The inferred type might not be the intended type, since more than one
% may be correct.
When inferring a guarded recursive definition for an Idris function definition,
we must find a type for the inferred definition. For instance, we may infer
several different guarded recursive types for the following definition of \texttt{evens}:
\begin{lstlisting}[mathescape,title=\idrisBlock]
evens : Stream a $\to$ Stream a
&head evens s = head s
&tail evens s = evens (tail (tail s))
\end{lstlisting}
Considering only the placement of clock quantifications (and not later
($\laterkappa$) applications), four different types are possible:
\begin{lstlisting}[mathescape,title=\ttBlock]
-- Possible guarded recursive types for evens
evens : $\forall\kappa$.(Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
evens : Stream$^\kappa$ a $\to$ ($\forall\kappa$.Stream$^\kappa$ a)
evens : ($\forall\kappa$.Stream$^\kappa$ a) $\to$ Stream$^\kappa$ a
evens : ($\forall\kappa$.Stream$^\kappa$ a) $\to$ ($\forall\kappa$.Stream$^\kappa$ a)
\end{lstlisting}
Without any further information, all of these types are equally good
candidates. In general, we cannot infer the correct combination of clock
quantifications for an arbitrary type. Therefore, we simplify the problem by introducing
the idea of \emph{modality} (not to be confused with the modality considered by
Nakano, presented in Section~\ref{sec:guarded-recursion}). Modality is a property of a function definition,
specifying that it is in one of two disjoint classes: \emph{causal} or
\emph{non-causal}.

\begin{definition}[\textit{Causality}]
\label{def:causality}
  Given a function $f : (x : A) \to B$ and an element $x : A$, where $B$ is a
  coinductive type, $f$ is \emph{causal} if the computation of the first $n$
  unfoldings of $f x$ only depends on the result of the first $n$ unfoldings of $x$.
\end{definition}

Inspired by M\o gelberg\,\citep{Mogelberg:2014}, we have chosen to divide
function definitions into those that has the property of causality (see
Definition~\ref{def:causality}), and those that do not. Concretely, this narrows
our previous choice for \texttt{evens} down to two possible types:
\begin{lstlisting}[mathescape,title=\ttBlock]
-- Possible guarded recursive types for evens
(causal)     evens : $\forall\kappa$.(Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
(non-causal) evens : ($\forall\kappa$.Stream$^\kappa$ a) $\to$ ($\forall\kappa$.Stream$^\kappa$ a)
\end{lstlisting}
If \texttt{evens} has causal type, it means that the clock for the argument type
and the result type are the same, ensuring that the input argument can be
unfolded at most as many times as the output value, but not more. If
\texttt{evens} has non-causal type, the input argument and the output value can
be unfolded independently.

However, we have still not arrived at a type for the guarded recursive version
of \texttt{evens}. While inferring the modality of a function is possible,
simply by trying to infer a guarded recursive version for both choices, some
functions may have both a causal and a non-causal guarded recursive
version. Since recursive references cannot be given as input to non-causal
functions, the choice has great impact on the result of the productivity
analysis. Instead of attempting to infer the modality, we introduce the keyword
\texttt{causal} as a function option, such that it must be added to any causal
definition. Function definitions which are not marked as causal are assumed to
be non-causal. For example, the previously presented definition of
\texttt{cycle} is marked \texttt{causal}, since it produces one element for each
unfolding of its output:
\begin{lstlisting}[mathescape,title=\idrisBlock]
causal
cycle : Nat $\to$ Nat $\to$ Stream Nat
cycle Z     m = Z :: (cycle m m)
cycle (S n) m = (S n) :: (cycle n m)
\end{lstlisting}
Also, the above definition of \texttt{evens} is non-causal, since it consumes two
elements of its input for every unfolding of its output.

The two types of modality cover many different function definitions, but
certainly not all. Consider the following definition of \texttt{mergef}:
\begin{lstlisting}[mathescape,title=\idrisBlock]
mergef : (Nat $\to$ Nat $\to$ Stream Nat $\to$ Stream Nat) $\to$
          Stream Nat $\to$ Stream Nat $\to$ Stream Nat
mergef f s t = f (head s) (head t) (mergef f (tail s) (tail t))
\end{lstlisting}
This definition actually has the following guarded recursive type:
\begin{lstlisting}[mathescape,title=\ttBlock]
mergef : (Nat $\to$ Nat $\to$ $\laterkappa$Stream$^\kappa$ Nat $\to$ Stream$^\kappa$ Nat) $\to$
          Stream$^\kappa$ Nat $\to$ Stream$^\kappa$ Nat $\to$ Stream$^\kappa$ Nat
\end{lstlisting}
Since it is neither causal nor non-causal, inferring guarded recursive versions
for functions such as \texttt{mergef} is therefore deemed out of
scope. Also, as mentioned in the introduction to this chapter, the description of
inference for non-causal definitions in the following is still mostly theoretic.

% Here, the clock quantification has to be on the entire type, whereas for the
% definition of the function \texttt{evens}, the
% clock quantification must be on each individual parameter type.
% As the number of
% arguments to a function is increased, the number of different ways we could
% quantify over clocks in the type of the function increases as well.

% Since we cannot in general infer the correct combination of clock
% quantifications for an arbitrary type, we simplify the problem by introducing
% the idea of \emph{modality}. Modality is a property of a function definition,
% specifying that it is in one of two disjoint classes: \emph{causal} or
% \emph{non-causal}.

% If a function is causal, the clock quantification is over the
% outermost type, since this means that all function arguments operate on the same
% clock. Definition~\ref{def:causality}. Informally, the
% output of a causal function at time $n$ can only depend on the input at time
% $n$. If a function is non-causal, the quantification is on each individual
% guarded type, since the output of a non-causal function may depend arbitrarily
% on its input. Therefore, the definition of \texttt{evens} in
% Figure~\ref{fig:guarded_recursion_evens} is non-causal.

% \begin{lstlisting}[mathescape,title=\idrisBlock]
% mergef : (Nat $\to$ Nat $\to$ Stream Nat $\to$ Stream Nat) $\to$
%           Stream Nat $\to$ Stream Nat $\to$ Stream Nat
% mergef f s t = f (head s) (head t) (mergef f (tail s) (tail t))
% \end{lstlisting}

% While inferring the modality of a function is possible, simply by trying all
% possible combinations of clock quantification on its type, some functions may
% have both a causal and a non-causal guarded recursive version. Since recursive
% references cannot be given as input to non-causal functions, the semantics of
% the two versions differ significantly. Instead of attempting to infer the
% modality, we introduce the keyword \texttt{causal} as a function option, such
% that it must be added to any causal definition. Function definitions which are
% not marked as causal are assumed to be non-causal. This means that the
% \texttt{cycle} function from Section~\ref{sec:fixkappa-rule} must be given as
% follows:
% \begin{lstlisting}[mathescape,title=\idrisBlock]
% causal
% cycle : Nat $\rightarrow$ Nat $\rightarrow$ Stream Nat
% cycle Z     m = Z :: (cycle m m)
% cycle (S n) m = (S n) :: (cycle n m)
% \end{lstlisting}

% \section{Implementation}
% The inference of guarded recursive versions of productive programs happens in
% two steps: (1) the inference system infers a guarded recursive TT definition
% from an elaborated TT definition, and (2) the checking system verifies that the
% inferred guarded recursive definition is well-formed according to the typing
% rules in Section~\ref{sec:guard-recurs-check}.. The two systems are implemented
% independently, and the checking system does not rely on any
% implementation-specific details of the inference system. Nevertheless, they do
% agree on the initial inference environment in which a guarded recursive definition should
% hold. Inference environments will be introduced in Section~\ref{sec:inference-system}.

\section{Preparing Idris}
% Preprocessing, how are guarded data types created?
\begin{figure}[h]
\begin{lstlisting}[mathescape,title=\idrisBlock]
namespace GuardedRecursion
  ||| A computation that is available later (''tomorrow'').
  data Later$'$ : Type $\to$ Type where
    Next : {a : Type} $\to$ a $\to$ Later$'$ a

  ||| A universal quantification over clocks.
  |||
  ||| Since the implementation uses only one clock,
  ||| no clock needs to be specified.
  data Forall : Type $\to$ Type where
    LambdaKappa : {a : Type} $\to$ a $\to$ Forall a

  ||| Applies the singleton clock to a value of a
  ||| universally quantified type.
  apply : {a : Type} $\to$ Forall a $\to$ a
  apply (LambdaKappa a) = a

  ||| Specifies the time at which a computation is available.
  data Availability = Now | Tomorrow Availability

  ||| A computation that is available arbitrarily later.
  Later : Availability $\to$ Type $\to$ Type
  Later Now a = a
  Later (Tomorrow n) a = Later$'$ (Later n a)

  ||| Composition of two values that are available later.
  compose : {a : Type} $\to$ {b : Type} $\to$
            {n : Availability} $\to$
            Later (Tomorrow n) (a $\to$ b) $\to$
            Later (Tomorrow n) a $\to$
            Later (Tomorrow n) b
  compose {n = Now} t u = compose$'$ t u
    where
     compose$'$ : {a, b : Type} $\to$ Later$'$ (a $\to$ b) $\to$ Later$'$ a $\to$ Later$'$ b
     compose$'$ (Next t) (Next u) = Next (t u)
  compose {n = Tomorrow n$'$} (Next t) (Next u) =
                                           Next (compose {n = n$'$} t u)
\end{lstlisting}
  \caption{The guarded recursion primitives in Builtins.idr}
  \label{fig:guarded_recursion_primitives}
\end{figure}

Before being able to infer guarded recursive terms, we must first define what it
means for a term to be guarded recursive within Idris. To this end, we have
added the definitions in Figure~\ref{fig:guarded_recursion_primitives} as
built-in primitives in Idris. These include a fundamental type \texttt{Later'},
modeling the later ($\laterkappa$) operator, and a type \texttt{Forall},
modeling clock quantification ($\forall\kappa$). Accordingly, \texttt{apply}
models clock application. We introduce the idea of \texttt{Availability} to
model the ``lateness'' of a given type, essentially isomorphic with
the natural numbers. Concretely, \texttt{Availability} is used for later
application with \texttt{compose}, in order to support later application under
arbitrarily many applications of \texttt{Later'}. We have delibrately chosen to
add these as built-in primitives, and not as a part of the standard library,
since totality checking is a fundamental feature of the compiler which should
not require specific libraries to be in scope.

Thus, a guarded recursive term is defined as a term which consists of one or more of
these added primitives. However, a well-typed guarded recursive term is not
necessarily productive, since the primitives do not model any of the side
conditions from the rules in Figure~\ref{fig:gr_rules_sin_clock}. Therefore, the
purpose of the inference system is to infer guarded recursive terms, while the
purpose of the checking system is to make sure that the guarded recursive terms
are actually productive.

% \paragraph{Guarded Recursion Library}
% The first step to adding guarded recursion to Idris is to add the guarded
% recursive types and functions. We have added these to the Idris built-in
% library, and not as a part of the prelude. This is because the user should be
% able to check functions for productivity using our guarded recursion checker
% without having to rely on the standard library.  While most of the
% implementations are straight forward, and can be found in Appendix\todo{Add ref
%   to appendix. And add appendix!}, there are interesting parts to discuss. We
% have added the notion of \emph{how much later} something is, through the idea of
% \texttt{Availability}, seen in Figure~\ref{fig:availability}. This is, in
% conjunction with \texttt{Later} done so that we can many $\later$ applications
% as a single \texttt{Later} applications.

% \begin{figure}[h]
%   \begin{lstlisting}[mathescape]
% namespace GuardedRecursion
%   ||| A computation that is available later.
%   data Later$'$ : Type $\to$ Type where
%     Next : {a : Type} $\to$ a $\to$ Later$'$ a

%   ||| A universal quantification over clocks
%   |||
%   ||| Since the implementation uses only one clock,
%   ||| no clock needs to be specified
%   data Forall : Type $\to$ Type where
%     LambdaKappa : {a : Type} $\to$ a $\to$ Forall a

%   ||| Applies the singleton clock to a  universally
%   ||| quantified value.
%   apply : {a : Type} $\to$ Forall a $\to$ a
%   apply (LambdaKappa a) = a

%   ||| Specifies the time at which a computation is available
%   data Availability = Now | Tomorrow Availability

%   ||| A computation that is available arbitrarily later.
%   Later : Availability $\to$ Type $\to$ Type
%   Later Now a = a
%   Later (Tomorrow n) a = Later$'$ (Later n a)

%   laterDist : Later$'$ (a $\to$ b) $\to$ (Later$'$ a $\to$ Later$'$ b)
%   laterDist (Next f) = \a => case a of
%                                (Next a$'$) => Next (f a$'$)

%   ||| Composition of two values that are available later.
%   compose : {a, b : Type} $\to$
%             {n : Availability} $\to$
%             Later (Tomorrow n) (a $\to$ b) $\to$
%             Later (Tomorrow n) a $\to$
%             Later (Tomorrow n) b
%   compose {n = Now} t u = compose$'$ t u
%     where
%      compose$'$ : {a, b : Type} $\to$ Later$'$ (a $\to$ b) $\to$ Later$'$ a $\to$ Later$'$ b
%      compose$'$ (Next t) (Next u) = Next (t u)
%   compose {n = Tomorrow n$'$} (Next t) (Next u) = Next (compose {n = n$'$} t u)
% \end{lstlisting}
%   \caption{The guarded recursion primitives in Builtins.idr}
%   \label{fig:guarded_recursion_primitives_old}
% \end{figure}

% \subsection{Guarded Names}
% Seeing as we want to infer guarded recursive versions of input programs, while not
% overwriting the names of the original input programs, we have created a system for
% generating new names for guarded recursive definitions. Although it is fairly
% trivial, it is an important part of our system. During compilation, we build a
% map from the original name for a definition, $n$, to its generated guarded recursive name,
% $_gn$. If the original name is the name of a record projection function, an
% additional name $_{\forall}n$ is generated for its universally quantified
% projection.

% Henceforth, we will refer to the name of an original definition as
% an \emph{Idris name} and its guarded recursive name as its \emph{guarded name}. For
% record projections, the name for the universally quantified projection will be
% referred to as the \emph{quantified name}.

% As we want to infer new types and terms, and not override the existing ones, we
% need a system for creating a guarded name from an existing user written
% name. While this is fairly trivial, it is an important part of our system. We
% will hence forth refer to these as the \emph{guarded names} as oppose to their
% original \emph{Idris names}. We will mark these guarded names with a subscript
% $g$, such that a name $Name$ becomes $_gName$.

% During compilation we keep a map from Idris names to their guarded names. This
% means that we can for any Idris name find their guarded name, and vice
% versa. This comes in handy when we infer the guarded terms.

\subsection{Guarded Types}
\label{sec:guarded-types}
Guarded types are guarded recursive versions of coinductive data types. During
elaboration, a guarded type is constructed for each coinductive data definition,
and then elaborated separately. First, guarded names are invented for the type constructor and
each of the data constructors.

\paragraph{Guarded Names}
Seeing as we want to infer guarded recursive versions of input programs, while not
overwriting the names of the original input programs, we have created a system for
generating new names for guarded recursive definitions. During compilation, we build a
map from the original name for a definition, $n$, to its generated guarded recursive name,
$_gn$. If the original name is the name of a record projection function, an
additional name $_{\forall}n$ is generated for its universally quantified
projection. Henceforth, we will refer to the name of an original definition as
an \emph{Idris name} and its guarded recursive name as its \emph{guarded name}. For
record projections, the name for the universally quantified projection will be
referred to as the \emph{quantified name}.

After a guarded name for the type in question has been generated, the later type constructor ($\laterkappa$)
is applied to the type of each recursive reference in each data
constructor. The type of the type constructor remains unchanged. As hinted at in
Section~\ref{sec:handling-parameters}, guarded types cannot be constructed for
clock-dependent types. In fact, guarded types are only constructed if the type
constructor for the input type definition consists solely of the type of types
(i.e. \texttt{Type}) and function types (i.e. $\to$).

An example of a
coinductive type and its guarded equivalent is shown in
Figure~\ref{fig:guarded_stream_inf}. Note that the guarded type \texttt{$_g$Stream} is not coinductive, but
inductive, since \texttt{$_g$Stream} is an inductive encoding of the
possibly infinite type \texttt{Stream}.

\begin{figure}[h]
\begin{lstlisting}[mathescape,title=\idrisBlock]
codata Stream : Type $\to$ Type where
  (::) : a $\to$ Stream a $\to$ Stream a
\end{lstlisting}
\begin{lstlisting}[mathescape,title=\idrisBlock]
data $_g$Stream : Type $\to$ Type where
  ($_g$::) : a $\to$ $\laterkappa$$ _g$Stream a $\to$ $_g$Stream a
\end{lstlisting}
  \caption{Above: A coinductive type definition for \texttt{Stream}. Below: Its
    guarded recursive equivalent.}
  \label{fig:guarded_stream_inf}
\end{figure}

The inferred applications of the later type constructor ($\laterkappa$, represented
as \texttt{Later'} in Figure~\ref{fig:guarded_recursion_primitives}) on
recursive references matches the existing encoding for lazy evaluation, where
recursive references in coinductive data constructors are guarded by the
\texttt{Inf} type constructor (see
Section~\ref{sec:coind-data-types}). Nevertheless, we have chosen to create a
separate encoding of coinductive types for guarded recursion, because the
intuition behind \texttt{Inf} and later differ. The \texttt{Inf} constructor
indicates that the data must be evaluated lazily, while the later constructor
indicates availability. As such, $\laterkappa\laterkappa\,_{g}Stream$ indicates that any value of
this type is available two time steps from now (i.e. ``the day after tomorrow''),
whereas \texttt{Inf (Inf Stream)} says that any value of this
type may unfold infinitely unless it is delayed twice. Be that as it may, the
later constructor could be encoded with \texttt{Inf}, if all of its primitives
were ported to \texttt{Inf} as well.

\begin{figure}[h]
\begin{lstlisting}[mathescape,title=\idrisBlock]
corecord Tree a where
  left  : Tree a $\to$ Tree a
  value : Tree a $\to$ a
  right : Tree a $\to$ Tree a
\end{lstlisting}
\begin{lstlisting}[mathescape,title=\idrisBlock]
record $_g$Tree a where
  $_g$left  $\;$: $_g$Tree a $\to$ $\later_g$Tree a
  $_g$value : $_g$Tree a $\to$ a
  $_g$right : $_g$Tree a $\to$ $\later_g$Tree a
\end{lstlisting}
  \caption{Above: A coinductive record definition. Below: Its guarded equivalent.}
  \label{fig:guarded_tree_inf}
\end{figure}

Guarded types are created for all non-dependent coinductive data types,
including coinductive records. For the latter, quantified
projections which preserve clock quantification under
projections are also generated. Consider the example of the coinductive record type \texttt{Tree}
in Figure~\ref{fig:guarded_tree_inf}. For the guarded record type $_{g}Tree$, the
quantified projections defined in Figure~\ref{fig:tree_quantified_projections}
are virtually generated. In order for them to be well-typed, we use the type
isomorphism \texttt{force} in Figure~\ref{fig:quantified_later_iso} introduced by
Møgelberg\,\citep{Mogelberg:2014} for eliminating later constructors in a
quantified context. When we say that these quantified projections are
\emph{virtually} generated, it means that only their types are generated and
added to the typing context as Idris postulates. Hence, they do not reduce
during type checking. One advantage of using postulates instead of regular
function definitions for these projections is that postulates are not compiled
to machine code, so the system ``cleans up'' after itself in this respect.

\begin{figure}[h]
\begin{lstlisting}[mathescape,title=\idrisBlock]
$_{\forall}$left$\ \;$ : $\forall\kappa.\,$$_g$Stream a $\,\to\,$ $\forall\kappa.\,$$_g$Stream a
$_{\forall}$left   s = force ($\Lambda\kappa.$ $\,$($_{g}$left$\,$(s[$\kappa$])))
$_{\forall}$value : $\forall\kappa.\,$$_g$Stream a $\,\to\,$ a
$_{\forall}$value s = $_{g}$value$\,$(s[$\kappa$])
$_{\forall}$right : $\forall\kappa.\,$$_g$Stream a $\,\to\,$ $\forall\kappa.\,$$_g$Stream a
$_{\forall}$right s = force ($\Lambda\kappa.$$\,$($_{g}$right$\,$(s[$\kappa$]))
\end{lstlisting}
  \caption{The quantified projections generated for $_{g}Tree$.}
\label{fig:tree_quantified_projections}
\end{figure}

\begin{figure}[h]
\[
force = \forall \kappa .A\cong \forall\kappa.\laterkappa A
\]
\begin{lstlisting}[mathescape,title=\idrisBlock]
postulate force : $\forall\kappa.\,\laterkappa$a $\to$ $\forall\kappa.$a
\end{lstlisting}
  \caption{A type isomorphism \texttt{force} for removing later types in a quantified context, and
    its right-to-left Idris implementation.}
\label{fig:quantified_later_iso}
\end{figure}

% \paragraph{Clocked Types}
% These are made by inferring a new data declaration for any codata or corecord
% declaration. This new data declaration is simply constructed during the
% elaboration of the original and then elaborated by itself. This means that for
% any user written codata or corecord declaration a guarded version is an
% intrinsic part of the program.

% A such guarded version of a declaration is fairly straight forward. Guarded
% names are given to the type and to all constructors. Any recursive reference in
% the type of the constructor is placed under a $\later$-type, in a similar
% fashion to how Idris already handles lazy evaluation. The type constructor
% remains unchanged. An example of this inferences for a codata declaration can be
% seen in Figure~\ref{fig:guarded_stream_inf}. Note that the inferred declaration
% is a data declaration, not codata. This is because we do not need both Idris's
% built in laziness (\texttt{Inf}), and the guarded recursion laziness ($\later$)
% \todo{Explain why these are not the same}.

% \begin{figure}[h]
% \begin{lstlisting}[mathescape]
% codata Stream : Type -> Type where
%   MkStream : a -> Stream a -> Stream a

% data $_g$Stream : Type -> Type where
%   $_g$MkStream : a -> $\later_g$Stream a -> $_g$Stream a
% \end{lstlisting}
%   \caption{Inference of the guarded stream declaration.}
%   \label{fig:guarded_stream_inf}
% \end{figure}

% In the corecord case, we take a similar approach. However, instead of
% constructors we have to guard projections. Again, any recursive projection is
% guarded such that $A \rightarrow A$ becomes $A \rightarrow \later A$, and all
% projections are given a guarded name. Figure~\ref{fig:guarded_tree_inf} shows an
% example of such an inference.

% \begin{figure}[h]
% \begin{lstlisting}[mathescape]
% corecord Tree a where
%   left : Tree a -> Tree a
%   value : Tree a -> a
%   right : Tree a -> Tree a

% record $_g$Tree a where
%   $_g$left : $_g$Tree a -> $\later_g$Tree a
%   $_g$value : $_g$Tree a -> a
%   $_g$right : $_g$Tree a -> $\later_g$Tree a
% \end{lstlisting}
%   \caption{Inference of the guarded tree declaration.}
%   \label{fig:guarded_tree_inf}
% \end{figure}

% Furthermore, for each projection we also generate what we call a \emph{forall
%   projection}, henceforth denoted as $_\forall Name$. We use this for
% projections on quantified types. Consider a coinductive type $A$ with a
% projection $p$ of type $A \rightarrow A$, and a variable $x$ of type $\forall
% \kappa.A$. In order to perform $p$ on $x$ and maintain the quantification in the
% type, we must first apply the clock to $x$, apply $_gp$, and then abstract over the
% clock again using $\Lambda \kappa$. This gives us:

% \[
% \Lambda \kappa . _gp (apply\,x) : \forall \kappa . \later A
% \]

% The type of the above is isomorphic with $\forall \kappa . A$ according to the
% isomorphism described by Rasmus M\o gelberg\,\cite{Mogelberg:2014} seen in
% Figure~\ref{fig:quantified_later_iso}. As a short for all of this we simply use
% $_\forall p$ which has type $\forall A \rightarrow \forall A$, giving us the
% same result. As such these \emph{forall projections} do not add anything new,
% they are just a simpler way for us to perform projections on terms of quantified
% type. The intuition is that because of Figure~\ref{fig:quantified_later_iso} we
% can perform projections on quantified types without having to worrying about
% their lateness. Because they are quantified over clocks, they are always available.

% \begin{figure}[h]
% \[
% \forall \kappa .A\cong \forall \kappa .\rhd ^\kappa A
% \]
%   \caption{A type isomorphism describe by M\o gelberg\,\cite{Mogelberg:2014}.}
%   \label{fig:quantified_later_iso}
% \end{figure}

%\section{Inference of Guarded Recursive Definitions}

\section{Preprocessing Guarded Recursive Definitions}
\label{sec:impl-guard-recurs}
% Meta
%% Samspil mellem inferens og check
%% Hvordan behandles causal vs. non-causal
We have now defined that a guarded recursive term is a term that consists of one or
more of the built-in guarded recursive primitives. Also, we have established
that guarded recursive type definitions are created for any non-dependent
coinductive type definition, and guarded names are created for definitions with
a coinductive result type. Now, we reach the first step of the inference
process, namely preprocessing. Directed by the left-hand sides of a user-written
definition, the preprocessing step provides a setup for the inference of
right-hand side terms, which will be the subject of
Section~\ref{sec:inference-system}. As explained in Section~\ref{sec:causal-non-causal},
the system distinguishes between causal and non-causal definitions. The two classes
of function definitions are preprocessed differently, although the steps are
the same:

% Before
% making an attempt to infer a guarded recursive version of a definition, the
% definition is first preprocessed in order to ease the inference process.

\begin{enumerate}
\item Create auxiliary functions to circumvent the limitations of the
  \texttt{fix$^\kappa$} rule.
\item Lift parameters out of the fixed point.
\item Eliminate the fixed point by the fixed point elimination rules from
  Figure~\ref{fig:fix_elim_rules}.
\item Eliminate the recursive argument in the auxiliary function(s).
\end{enumerate}

% \newcommand{\prepend}[5]{\ensuremath{{\boxed{#1;\causal;\phi,(#2,#3);\open;\Gamma\,\vdash\,\text{#4}\,:\,\text{#5}\,\infer
%         \text{?}\,:\,_{g}\text{#5})}}}}
% \newcommand{\prependm}[5]{\ensuremath{{\boxed{
%             \begin{matrix*}[l] #1;\causal;\phi,(#2,#3);\open;\Gamma\,\vdash \\
%                            \quad\text{#4}\,:\,\text{#5}\,\infer\,\text{?}\,:\,_{g}\text{#5})
%             \end{matrix*}
%             }}}}
\newcommand{\prepend}[5]{\ensuremath{{\boxed{IE\,\vdash\,\text{#4}\,:\,\text{#5}\,\infer
        \text{?}\,:\,_{g}\text{#5})}}}}
\newcommand{\prependm}[5]{\ensuremath{{\boxed{
            \begin{matrix*}[l] IE\,\vdash \\
                           \quad\text{#4}\,:\,\text{#5}\,\infer\,\text{?}\,:\,_{g}\text{#5})
            \end{matrix*}
            }}}}
\newcommand{\changed}[1]{\ensuremath{\fcolorbox{gray}{light-gray}{a rec}}}

On the right-hand side of the preprocessed definitions, a box will be shown
which indicates the starting point for the inference system presented in
Section~\ref{sec:inference-system},
e.g. \prepend{\text{prepend}}{\text{prepend}}{\,_{g}\text{prepend}}{s}{Stream
  a}. In particular, this example means that in a given \emph{inference
  environment}, $IE$, where \texttt{s} has type \texttt{Stream a}, we must infer
an as yet unknown term of type \texttt{$_g$Stream a}. Inference environments will
be defined along with the remaining inference system in
Section~\ref{sec:inference-system}.

% For neither the causal or the non-causal case, all the steps presented in the following are
% actually performed. Instead, we provide the setup for the inference system by
% proceeding directly to the last step. We show all the steps here in order to
% demonstrate how we have arrived
In the following, we demonstrate the theoretical steps taken in order to provide
a setup for the inference system. In practice, we proceed directly to the last
step for both the causal and the non-causal case. The intermediate steps are
merely shown here to justify our approach.

\subsection{Preprocessing Causal Functions}
\label{sec:prepr-caus-funct}
 We imagine that a user has written the following causal function
 \texttt{prepend} as a (concrete) Idris program:
\begin{lstlisting}[mathescape, title=\idrisBlock]
  total causal
  prepend : (a : Type) $\to$ List a $\to$ Stream a $\to$ Stream a
  prepend a []        s = s
  prepend a (x :: xs) s = x :: (prepend a xs s)
\end{lstlisting}
 From this point on, no user intervention is necessary.  (1) To infer a guarded
 recursive version of \texttt{prepend}, we first split the definition in
 two, such that pattern matching happens in an auxiliary function,
 \texttt{$_g$prepend$'$}, which is then called inside the fixed point on the
 right-hand side of \texttt{$_g$prepend}:

% \newcommand{\prepend}[4]{\ensuremath{{\boxed{\text{#1};\causal;\phi,\text{#2};\open;\Gamma\,\vdash\,\text{#3}\,:\,\text{#4}\,\infer
%         \\\text{?}\,:\,_{g}\text{#4})}}}}}
\begin{lstlisting}[mathescape, title=\ttBlock]
  $_g$prepend$'$ : $\laterkappa$((a$\,$:$\,$Type) $\to$ List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a) $\to$
                (a$\,$:$\,$Type) $\to$ List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a
  $_g$prepend$'$ rec a []        $\;$s =
     $\prepend{\text{prepend}}{\text{prepend}}{\,_{g}\text{prepend}}{s}{Stream a}$
  $_g$prepend$'$ rec a (x :: xs) s =
     $\prepend{\text{prepend}}{\text{prepend}}{\,_{g}\text{prepend}}{x :: (prepend a xs s)}{Stream a}$

  $_g$prepend : $\forall\kappa.$ (a$\,$:$\,$Type) $\to$ List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a
  $_g$prepend = $\Lambda\kappa.\,$fix$^\kappa$($\lambda$rec.$\lambda$a.$\lambda$xs.$\lambda$s.$\,$$_g$prepend$'\;$rec a xs s)
\end{lstlisting}
As \texttt{$_g$prepend} is defined with a fixed point, the recursive reference
\texttt{rec} is inserted in place of the original recursive reference.

(2) The type parameter \texttt{a} is lifted out of the fixed point to make up
for the lack of type substitution in the later application rule, as explained in
Section~\ref{sec:handling-parameters}. Note that this also lifts \texttt{a} out
of the type of the recursive reference, \texttt{rec}. Furthermore, \texttt{a} is
no longer bound under the clock quantification in the type of
\texttt{$_g$prepend}. After the lifting of \texttt{a}, we arrive at the following
(changes are highlighted in grey boxes):
\begin{lstlisting}[mathescape, title=\ttBlock]
  $_g$prepend$'$ : $\fcolorbox{gray}{light-gray}{(a\,:\,Type)}$ $\to$ $\fcolorbox{gray}{light-gray}{\ensuremath{\laterkappa}(List a \ensuremath{\to} \ensuremath{_{g}}Stream a \ensuremath{\to} \ensuremath{_{g}}Stream a)}$ $\to$
               List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a
  $_g$prepend$'$ $\fcolorbox{gray}{light-gray}{a rec}$ []        s =
   $\prepend{\text{(prepend a)}}{\text{(prepend a)}}{\,(_{g}\text{prepend a})}{s}{Stream a}$
  $_g$prepend$'$ $\fcolorbox{gray}{light-gray}{a rec}$ (x :: xs) s =
   $\prepend{\text{(prepend a)}}{\text{(prepend a)}}{\,(_{g}\text{prepend a})}{x :: (prepend a xs s)}{Stream a}$

  $_g$prepend : $\fcolorbox{gray}{light-gray}{(a\,:\,Type)}$ $\to$ ($\forall\kappa.\,$ List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a)
  $_g$prepend $\fcolorbox{gray}{light-gray}{a}$ = $\Lambda\kappa.\,$fix$^\kappa$($\lambda$rec.$\lambda$xs.$\lambda$s.$\,$prepend$'$ $\fcolorbox{gray}{light-gray}{a rec}$ xs s)
\end{lstlisting}
(3) The fixed point is eliminated by replacing all references to
\texttt{rec} with \texttt{Next~(($_g$prepend~a)~[$\kappa$])} in \texttt{$_g$prepend}, since this term has
exactly the same type as \texttt{rec} in step 2.
\begin{lstlisting}[mathescape, title=\ttBlock]
  $_g$prepend$'$ : (a$\,$:$\,$Type) $\to$ $\laterkappa$(List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a) $\to$
               List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a
  $_g$prepend$'$ a rec []        s =
    $\prepend{\text{(prepend a)}}{\text{(prepend a)}}{\,(_{g}\text{prepend a})}{s}{Stream a}$
  $_g$prepend$'$ a rec (x :: xs) s =
    $\prepend{\text{(prepend a)}}{\text{(prepend a)}}{\,(_{g}\text{prepend a})}{x :: (prepend a xs s)}{Stream a}$

  $_g$prepend : (a$\,$:$\,$Type) $\to$ ($\forall\kappa.\,$ List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a)
  $_g$prepend a = $\Lambda\kappa.\,$$\lambda$xs.$\lambda$s.$\,$prepend$'$ a $\fcolorbox{gray}{light-gray}{(Next ((prepend a)[\ensuremath{\kappa}]))}$ xs s
\end{lstlisting}
(4) The \texttt{rec} argument to \texttt{$_g$prepend$'$} is eliminated, but will
be recovered by the inference system when the rule for causal recursive
references is used (see Figure~\ref{fig:epsilon_rec_causal}o):
\begin{lstlisting}[mathescape,title=\ttBlock]
  $_g$prepend$'$ : $\fcolorbox{gray}{light-gray}{(a : Type) \ensuremath{\to} List a \ensuremath{\to\,_{g}}Stream a \ensuremath{\to\,_{g}}Stream a}$
  $_g$prepend$'$ a []        s =
    $\prepend{\text{(prepend a)}}{\text{(prepend a)}}{\,(_{g}\text{prepend a})}{s}{Stream a}$
  $_g$prepend$'$ a (x :: xs) s =
    $\prepend{\text{(prepend a)}}{\text{(prepend a)}}{\,(_{g}\text{prepend a})}{x :: (prepend a xs s)}{Stream a}$

  $_g$prepend : (a$\,$:$\,$Type) $\to$ ($\forall\kappa.\,$ List a $\to$ $_{g}$Stream a $\to$ $_{g}$Stream a)
  $_g$prepend a = $\Lambda\kappa.\,$$\lambda$xs.$\lambda$s.$\,$prepend$'$ a xs s
\end{lstlisting}
After preprocessing, the inference system will attempt to build well-typed
guarded recursive right-hand sides as specified in the boxes.

% \newcommand{\evens}[5]{\ensuremath{\boxed{#1;\noncausal;\phi,(#2,#3);\open;\Gamma\,\vdash\,\text{#4}\,:\,\text{#5}\,\infer
%         \text{?}\,:\,\forall\kappa\,_{g}\text{#5})}}}
% \newcommand{\evensm}[5]{\ensuremath{\boxed{
%             \begin{matrix*}[l] #1;\causal;\phi,(#2,#3);\open;\Gamma\,\vdash \\
%                            \quad\text{#4}\,:\,\text{#5}\,\infer\,\text{?}\,:\,\forall\kappa.\,_{g}\text{#5})
%             \end{matrix*}
%             }}}
\newcommand{\evens}[5]{\ensuremath{\boxed{IE\,\vdash\,\text{#4}\,:\,\text{#5}\,\infer
        \text{?}\,:\,\forall\kappa.\,_{g}\text{#5})}}}
\newcommand{\evensm}[5]{\ensuremath{\boxed{
            \begin{matrix*}[l] IE\,\vdash \\
                           \quad\text{#4}\,:\,\text{#5}\,\infer\,\text{?}\,:\,\forall\kappa.\,_{g}\text{#5})
            \end{matrix*}
            }}}

\subsection{Preprocessing Non-causal Functions}
Recall the definition of the indexed fixed point for guarded recursion:
\begin{center}
  \input{figures/pfix}
\end{center}
Non-causal definitions are preprocessed slightly differently, mainly because the
recursive reference has a different form on account of the use of the indexed
fixed point. Consider the following non-causal Idris definition \texttt{evens},
provided by a user:
\begin{lstlisting}[mathescape, title=\idrisBlock]
evens : (a : Type) $\to$ Stream a $\to$ Stream a
evens a s = head s :: evens a (tail (tail s))
\end{lstlisting}
(1) Initially, two auxiliary functions are created, \texttt{$_{g}$evens$'$} and
\texttt{$_{g}$evens$''$}. The \texttt{$_{g}$evens$'$} function is necessary because its type
enables us to use the indexed fixed point, \texttt{pfix$^\kappa$}, to provide a recursive reference
without clock quantification in its result type.
\begin{lstlisting}[mathescape, title=\ttBlock]
$_g$evens$''$ : (($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\laterkappa$$_{g}$Stream a)) $\to$
           ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$''$ rec a s =
          $\evens{\text{evens}}{\text{evens}}{\,_{g}\text{evens}}{head s :: evens a (tail (tail s))}{Stream a}$

$_g$evens$'$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$'$ = pfix$^\kappa$($\lambda$rec.$\lambda$a.$\lambda$s. evens$''$ rec s)

$_g$evens : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\forall\kappa.\,$$_{g}$Stream a)
$_g$evens = $\Lambda\kappa.\,$evens$'$
\end{lstlisting}
(2) Exactly as for the causal case, the type parameter, \texttt{a}, is lifted out of the fixed point.
\begin{lstlisting}[mathescape, title=\ttBlock]
$_g$evens$''$ : $\fcolorbox{gray}{light-gray}{(\ensuremath{\forall\kappa.\,}(a :
Type))}$ $\to$ $\fcolorbox{gray}{light-gray}{((\ensuremath{\forall\kappa.\,_{g}}Stream a)
\ensuremath{\,\to} (\ensuremath{\laterkappa\, _{g}}Stream a))}$ $\to$
           $\forall\kappa.\,$$_{g}$Stream a $\to$ $_{g}$Stream a
$_g$evens$''$ $\fcolorbox{gray}{light-gray}{a rec}$ s =
          $\evens{\text{(evens a)}}{\text{(evens a)}}{\,(_{g}\text{evens a})}{head s :: evens a (tail (tail s))}{Stream a}$

$_g$evens$'$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$'$ $\fcolorbox{gray}{light-gray}{a}$ = pfix$^\kappa$($\lambda$rec.$\lambda$s. evens$''$ $\fcolorbox{gray}{light-gray}{a}$ rec s)

$_g$evens : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\forall\kappa.\,$$_{g}$Stream a)
$_g$evens $\fcolorbox{gray}{light-gray}{a}$ = $\Lambda\kappa.\,$evens$'$ $\fcolorbox{gray}{light-gray}{a}$
\end{lstlisting}
(3.1) The indexed fixed point is replaced by the equivalent ordinary guarded
recursive fixed point. This step requires that the recursive reference is
placed inside a function where the \texttt{Next} rule is used on its
argument, \texttt{x}. Also, using \texttt{fix$^\kappa$} instead of
\texttt{pfix$^\kappa$} means that the type of the recursive reference,
\texttt{rec}, has now changed.
\begin{lstlisting}[mathescape, title=\ttBlock]
$_g$evens$''$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ (($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\laterkappa$$_{g}$Stream a)) $\to$
          ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$''$ a rec s =
         $\evens{\text{(evens a)}}{\text{(evens a)}}{\,(_{g}\text{evens a})}{head s :: evens a (tail (tail s))}{Stream a}$

$_g$evens$'$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$'$ a = $\fcolorbox{gray}{light-gray}{fix\ensuremath{^\kappa}}$($\lambda$rec.$\lambda$s. evens$''$$\;$a $\fcolorbox{gray}{light-gray}{(\ensuremath{\lambda}x. rec \ensuremath{\tensor^\kappa} (Next x))}$ s)

$_g$evens : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\forall\kappa.\,$$_{g}$Stream a)
$_g$evens a = $\Lambda\kappa.\,$evens$'$ a
\end{lstlisting}
(3.2) The fixed point is eliminated according to the rules in Figure~\ref{fig:fix_elim_rules}.
\begin{lstlisting}[mathescape, title=\ttBlock]
$_g$evens$''$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ (($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\laterkappa$$_{g}$Stream a)) $\to$
           ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a

$_g$evens$''$ a rec s =
         $\evens{\text{(evens a)}}{\text{(evens a)}}{\,(_{g}\text{evens a})}{head s :: evens a (tail (tail s))}{Stream a}$

$_g$evens$'$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$'$ a = $\lambda$s. evens$''$ a ($\lambda$x.$\,$$\fcolorbox{gray}{light-gray}{Next (evens\ensuremath{'} a)}$ $\tensor^\kappa$ (Next x)) s

$_g$evens : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\forall\kappa.\,$$_{g}$Stream a)
$_g$evens a = $\Lambda\kappa.\,$evens$'$ a
\end{lstlisting}
(4) The \texttt{rec} argument to \texttt{$_{g}$evens$''$} is eliminated, but will
be recovered by the inference system when the rules for non-causal recursive
references is used (see Figure~\ref{fig:epsilon_rec_causal}).
\begin{lstlisting}[mathescape, title=\ttBlock]
$_g$evens$''$ : $\fcolorbox{gray}{light-gray}{(\ensuremath{\forall\kappa.\,}(a : Type)) \ensuremath{\to} (\ensuremath{\forall\kappa.\,_{g}}Stream a) \ensuremath{\to\,_{g}}Stream a}$
$_g$evens$''$ a s =
         $\evens{\text{(evens a)}}{\text{(evens a)}}{\,(_{g}\text{evens a})}{head s :: evens a (tail (tail s))}{Stream a}$

$_g$evens$'$ : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ $_{g}$Stream a
$_g$evens$'$ a = $\lambda$s. $_g$evens$''$ a s

$_g$evens : ($\forall\kappa.\,$(a$\,$:$\,$Type)) $\to$ ($\forall\kappa.\,$$_{g}$Stream a) $\to$ ($\forall\kappa.\,$$_{g}$Stream a)
$_g$evens a = $\Lambda\kappa.\,$$_g$evens$'$ a
\end{lstlisting}
The inference system can now attempt to infer a guarded recursive version as
specified in the box.

\section{The Inference System}
\label{sec:inference-system}
% RULES
% Regler - forklar (også notation)
% Rekursive referencer
% Eksempel - zeros?
% Preprocessing
% Renaming
% Forskel på causal og non causal

%(1) Gennemgang af interessante regler
%(2) Eksempel
%(3) Implementation details, e.g. when Next and tensor rules clash
%%(3.1) Preprocessing, herunder renaming
%%(3.2) Forskel på causal og non causal

Inference of guarded recursive TT terms from elaborated TT terms happens by a
bottom-up, type-directed derivation according to the rules given in
Figure~\ref{fig:epsilon_rules}. Let $\Gamma$ be a typing environment and $\iota$ be the recursive
reference for the function which is currently being analysed. Then the inference
environment ($IE$) in which guarded recursive TT terms are built is defined as follows:
\begin{align*}
   \clockEnv,\,\clockEnv^\prime &::=\,\open\,|\,\closed & \text{(singleton clock)} \\
   \Psi &::=\,\causal\,|\,\noncausal & \text{(modality)} \\
   \rho &::= n \mapsto \,_gn & \text{(renaming)} \\
   \phi &::=\,\cdot\,|\,\rho\,\phi & \text{(collection of renamings)} \\
   \pi &::= \,n \mapsto (_gn,\, _{\forall}n) & \text{(projection renaming)} \\
   \Pi &::= \cdot\,|\,\pi \,\Pi & \text{(collection of projection renamings)} \\
   IE &::= \iota;\Psi;\phi;\,c;\Pi;\,\Gamma & \text{(inference environment)}
\end{align*}
The singleton clock is either open (\open) or closed (\closed). Modality is
specified by $\Psi$, and is either causal (\causal) or non-causal
(\noncausal). The intuition is that a causal function may only refer to past
values (thus \causal{} is pointing backwards), while a non-causal function may
refer to values at any point in time (thus \noncausal{} points in both
directions). A renaming, given as $\rho$, matches an Idris name $n$ to a guarded
name $_gn$. Disjoint from $\rho$, $\pi$ defines a renaming for an Idris name of
a record projection, to either a guarded name or a quantified name
($_{\forall}n$). In particular, in a given inference environment there is never
both a $\rho$ and a $\pi$ for a given name $n$.

\subsection{Reading Guide}
Before presenting the inference system, we provide a reading guide for each type
of judgment.

\subsubsection{The Inference Judgment}
The first of these, and the arguably most interesting, is the inference judgment.

\begin{center}
  ${IE\vdash e : A \infer e' : B}$
\end{center}

The inference judgment reads as follows: ``If $e$ has type $A$ in a given
inference environment $IE$, and our goal is to infer a term of type $B$, then
$e'$ of type $B$ \emph{can be} the guarded recursive version $e$''. Since a
given term may have more than one valid guarded recursive version, we stress
that $e'$ \emph{can} be a solution.
% Inference (\infer) of a guarded recursive TT term $e'$ of type $B$ from an elaborated TT term $e$ of type $A$ is then defined as
% ${IE\vdash e : A \infer e' : B}$.

%Dur ikke for typer
\subsubsection{The Projection Renaming Judgment}
Using the projection renaming judgment, we can replace a user-supplied
projection name with a guarded name or a quantified name, respectively.
\begin{center}
  ${IE\vdash \Pi(e) \mapsto (_ge,\,_{\forall}e)}$
\end{center}
This judgment reads: ``If a term $e$ is a
reference to a name $n$, where $n$ is the name of a projection, then $\Pi$ in the inference environment $IE$ maps $n$
to both a guarded name $_gn$ and a quantified name $_{\forall}n$''. Note that since $e$ is a term referring
to the name of a projection, it is assumed that the type of $e$ is not the
type of types.

% Dur ikke for typer
\subsubsection{The Renaming Equality Judgment}
Renaming equality is a structural equality on TT terms.
\begin{center}
  ${IE\vdash e \phieq e'}$
\end{center}
This rules reads: ``If $e$ and $e'$ are normalized terms in an inference
environment $IE$, and neither $e$ nor $e'$ is a type,
then $e$ is structurally equal to $e'$ after each name $n$ in
$e$ has been substituted with their guarded name $_gn$, where ($n\mapsto\,_gn$) is in $\phi$''.

\subsubsection{The Typing Judgment}
The inference system operates with a standard typing judgment.
\begin{center}
  ${IE\vdash e : A}$
\end{center}
It reads: ``Given that $A$ is not the type of types, $e$ has type $A$ in the inference
environment $IE$''.

% Additionally, we have the following judgment for types.
% \begin{center}
%   ${IE\vdash A\, type}$
% \end{center}
% It reads: ``A is a type, i.e. its type is the type of types, in the inference
% environment $IE$''.

\subsubsection{Side Conditions}
Most of the rules have a side condition, comparing a term $e$ with the recursive
reference, $\iota$. Whenever there is a side condition $e = \iota$, then $e$
must be structurally equal to $\iota$ after normalization. The inverse holds when
$e \not = \iota$.

\subsection{Rule Disambiguation}
The inference system is type-directed, in the sense that given an input term $e$
of type $A$ and a goal type $B$, the system tries to infer a guarded recursive
term of type $B$. Concretely, we have the following situation, where \texttt{?}
represents the term that will be inferred:
\begin{center}
  (${IE\vdash e : A \infer\, ? : B}$)
\end{center}
Given a specific $B$, there may be situations where more than one rule can be
applied, since both rules match the given goal type $B$. In these situations,
the system simply tries all the applicable rules in succession until one of them succeeds.

% In Figure~\ref{fig:epsilon_rules}, the $\Longrightarrow_{Next^\kappa}$ rule follows directly from the $Next$ rule in Figure~\ref{fig:guarded_recursion_rules_clocks}. The
% $\Longrightarrow_{\Lambda\kappa}$ and $\Longrightarrow_{apply^\kappa}$ rules have a
% similar structure, but here the clock changes state from premise to conclusion
% (e.g. from open to closed). For handling guarded names, the
% $\Longrightarrow_{\phi}$ rule says that if some Idris name has type $A$, and its
% guarded version has type $A^\prime$, then we can insert the guarded name in its
% place. Note that the type $A^\prime$ of the guarded name is not arbitrary, but follows the
% rules for causal and non-causal function types (see Section~\todo{insert ref
%   here}). Renaming is important for the $\Longrightarrow_{App}$ rule, since it
% is often used for the transformations required in the premises. This reasoning
% also applies to the $\Longrightarrow_{\tensor^{\kappa}_{n}}$ rule. Here,
% the $n$ is a natural number denoting the required ``lateness'' of both input and
% output, where $n \ge 1$. Specifically, ${\laterkappa_{\!\!1} B \cong \laterkappa B}, {\laterkappa_{\!\!2}
% \cong \laterkappa\laterkappa B}$ and so on. For trivial cases, the
% $\Longrightarrow_{Refl}$ rule is used. \todo{Say something about abstraction and
% let-rules here, when they have been formulated.}

\begin{figure}[H]
\centering
\textbf{The Inference System}$\hfill \boxed{IE\vdash e : A \infer e' : B}$

\begin{figure}[H]

\begin{mdframed}
This is the only rule for which $A$ in $IE\vdash e : A \infer e' : B$ can be of
the type of types. In every subsequent rule, it is assumed that $A$ is not be
the type of types.
\\

\vspace{1em}
\centering
\ContinuedFloat
\subcaptionbox{
The reflexivity rule simply states that any term can be inferred to itself. This
rule is used for terms which occur in both the elaborated TT term and the guarded
recursive TT term, e.g. constants.
}{\input{figures/epsilon_refl_rule}}
\end{mdframed}
\end{figure}
\subcaptionbox{
The rule for inferring \texttt{Next} applications.
}{\input{figures/epsilon_next_rule}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
The $\infer_{\Lambda\kappa}$-rule opens the closed clock. Due to the use of
a singleton clock, it is impossible to open a new clock in a context where the
clock is already open.
}{\input{figures/epsilon_lambdakappa_rule}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
The $\infer_{[\kappa]}$-rule is dual to the  $\infer_{\Lambda\kappa}$-rule,
closing the open clock by clock application.
}{\input{figures/epsilon_apply_rule}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
This rule provides inference by renaming equality. In particular, if $e$
becomes structurally equal to $_ge$ after replacing all Idris names in $e$ with
their guarded name (given in $\phi$), then $_ge$ can be the guarded recursive version for $e$.
}{\input{figures/epsilon_renaming_rule}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
This rule renames a projection to its quantified version when both the result
type and the argument type of the inferred projection term is expected to be quantified over clocks.
}{\input{figures/epsilon_projection_rule_forall}}
\end{figure}
\begin{figure}[H]
\ContinuedFloat
\centering
\subcaptionbox{
Similar to the $\infer_{\Pi_{\forall}}$-rule, this rule renames a projection to
its guarded version when both the result type and the argument type of the
inferred projection term is \emph{not} expected to be quantified over clocks.
}{\input{figures/epsilon_projection_rule_guarded}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
This rule ensures that the system is invoked recursively on the subterms
of an application which is not expected to be in a later ($\laterkappa$) context.
}{\input{figures/epsilon_app_rule}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
The $\infer_{\tensor^\kappa_n}$ rule is used when the guarded recursive version
of an application is expected to be in a later ($\laterkappa$) context. Here, $n$ is a natural number denoting the
required availability of both inputs. Specifically, $\laterkappa_{\!\!n}$B
signifies and $n$-iterated application of the $\laterkappa$ type constructor,
such that ${\laterkappa_{\!\!1} B \cong \laterkappa B}, {\laterkappa_{\!\!2}B
\cong \laterkappa\laterkappa B}$ and so on. Therefore, $\tensor^{\kappa}_1$
denotes the standard later application, as presented in Section~\ref{sec:guarded-recursion}. Note that as discussed in
Section~\ref{sec:fixkappa-rule}, this rule does not apply to dependent function spaces.
}{\input{figures/epsilon_tensor_rule}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
  The $\infer_\lambda$-rule handles the recursive case by adding a new renaming
  entry to the renaming environment, $\phi$, such that all occurrences of the
  bound variable $a$ in $e$ can be renamed to $_{g}a$.
}{\input{figures/epsilon_lambda_rule}}

\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
As for the $\infer_\lambda$-rule, the $\infer_{let}$-rule uses the renaming
environment for the recursive case for $b$.
}{\input{figures/epsilon_let_rule}}
\end{figure}

\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
Due to the elimination of the indexed fixed point, this rule ensures that all
arguments to the non-causal recursive reference are not already in a later
($\laterkappa$) context. The $e\, \overset{\rightarrow}{a_n}$ notation denotes the recursive reference,
$e$, applied to arguments $a_0,\,a_1\,\cdots\,a_n$.
}{\input{figures/epsilon_rec_noncausal_n}}

\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
Handles the non-causal recursive reference applied to one argument. This rule
is necessary since the recursive case for $e$ is different from the $\infer_{Rec_{\noncausal{_n}}}$-rule.
}{\input{figures/epsilon_rec_noncausal_1}}

\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
This rule ensures that a \texttt{Next} is always applied to any non-causal recursive reference.
}{\input{figures/epsilon_rec_noncausal}}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
  The rule for recursive references for causal functions. This rule recovers
    the eliminated recursive reference for causal functions, since it is the
    only rule that applies for the recursive reference in the causal case.}
{\input{figures/epsilon_rec_causal}}

  \caption{Rules for inferring guarded recursive terms, excluding the rules for
    recursive references. All types used in typing judgments are assumed to be
    well-formed.}
  \label{fig:epsilon_rec_causal}
\label{fig:epsilon_rules}
\end{figure}

\subsection{An Example}
As an example, we show how to infer the guarded recursive version of the
function \texttt{repeat} in Figure~\ref{fig:repeat_proof_example_program}. The
proof is given in Figure~\ref{fig:repeat_inference_proof}. Here, all side
conditions have been elided, but can be easily proven by testing for equality
with the recursive reference, \texttt{repeat a}. The proof proceeds by
continually taking apart the input term, until the inference of the subterms can
be resolved by either renaming equality ($\infer_\phi$) or reflexivity
($\infer_{Refl}$). As soon as the type of one subterm has been inferred, its
type trickles down into the rest of the proof tree, leading more inferences to
resolution. None of the inferred terms are given prior to the inference, but the
type of the first step is known after preprocessing. Additional examples of the
inference of guarded terms can be found in Appendix~\ref{app:infer-guard-recurs}.

%All side conditions have been elided, but can be easily proven for each rule.
%Should be read top-down, but must be understood bottom-up.
%Only the right-hand side of _grepeat' is inferred
%A full example, along with a more advanced one, can be found in
%Appendix~\ref{app:infer-guard-recurs}.\todo{Make this appendix}
%The derivation proceeds by continually pushing type requirements down into the syntax tree

\begin{figure}[h]
\begin{lstlisting}[mathescape, title=\ttBlock]
repeat : (a : Type) -> a -> Stream a
repeat a n = (::) a n (repeat a n)
\end{lstlisting}
\begin{lstlisting}[mathescape, title=\ttBlock]
$_g$repeat$'$ : (a$\,$:$\,$Type) $\to$ a $\to$ $_{g}$Stream a
$_g$repeat$'$ a n = $(_g::)$ a n $(\onk{\text{Next}}\,((_g$repeat$\ $a$)[\kappa]) \tensor^\kappa_1 (\onk{\text{Next}}\,
$n$))$

causal
$_g$repeat : (a$\,$:$\,$Type) $\to$ ($\forall\kappa.\,$ a $\to$ $_{g}$Stream a)
$_g$repeat a = $\Lambda\kappa.\,$$\lambda$n.$\,$$_g\text{repeat}'$ a n
\end{lstlisting}
  \caption{Above: A simple causal function \texttt{repeat}. The data constructor for
    Stream, \texttt{(::)} is used in a prefix manner. Below: The guarded
    recursive version. Note that only the right-hand side of
    \texttt{$_g$repeat$'$} is inferred by the inference system, while the
    remaining changes happen by preprocessing.}
\label{fig:repeat_proof_example_program}
\end{figure}

% Figure~\ref{fig:epsilon_zeros} shows how a guarded recursive version of
% \texttt{zeros} can be inferred using the rules presented in Figure~\ref{fig:epsilon_rules}. The
% derivation proceeds by continually pushing type requirements down into the
% syntax tree, until these can be resolved either trivially (using the
% $\Longrightarrow_{Refl}$ rule), or by renaming (using the
% $\Longrightarrow_{\phi}$ rule).

% Note that all premises ensuring type consistency
% have been omitted for brevity.

\begin{figure}[H]
\centering

\subcaptionbox{
The derivation proceeds within this inference environment. From top to bottom:
The recursive reference is \texttt{repeat a}, and \texttt{repeat} is causal
(\causal). The renaming environment, $\phi$, is extended with entries for the
stream constructor \texttt{(::)} and \texttt{repeat a}, and the clock is
initially open (\open) due to preprocessing (see
Section~\ref{sec:prepr-caus-funct}). Finally, the typing environment, $\Gamma$,
is extended as shown.
}{
$\begin{matrix*}[l]IE = & repeat\ a;
  \\ & \causal ;\\ &
\phi, ((::),\ (_g::)), (repeat,\, _grepeat);\\ &
 \open;\\ &
\Gamma, a : Type,\ n : a,\,_grepeat : (a\ :\ Type) \to \forall \kappa.(a \to \onk{Stream}\ a),\
\\ & \ \ \ (_{g}::)\ : (a\ :\ Type)
\to a \to \later^\kappa_1 \onk{Stream}\ \text{a} \to \onk{Stream}\ a
\end{matrix*}$
}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
We begin with the conclusion, namely that the guarded recursive version of the
right-hand side of \texttt{repeat} is the term shown to the right of the double arrow (\infer) in
the conclusion. In this first step, we use the $\infer_{App}$-rule to take apart the two outermost applications.
}{
\AxiomC{(1)}
\AxiomC{}
\RightLabel{$\infer _{Refl}$}
\UnaryInfC{$IE \vdash n : a \infer n : a$}
\RightLabel{$\infer _{App}$}
\BinaryInfC{$\begin{matrix} IE \vdash (::)\,a\,n \ : Stream\,a \to Stream\,a \infer \\
  (_g::)\,a\,n \  : \later ^\kappa_1  \onk{Stream}\,a \to
  \onk{Stream}\,a\end{matrix}$}
\AxiomC{(2)}
\RightLabel{$\infer _{App}$}
\BinaryInfC{ $\begin{matrix}IE \vdash (::)\,a\,n\,(repeat\ a\ n) : Stream\,a\infer
\\ \,(_g::)\,a\,n\,((\onk{Next}\,((_grepeat\ a)[\kappa]) \tensor^\kappa_1 (\onk{Next}\,
n) : Stream^\kappa \,a\end{matrix}$}
\DisplayProof
}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
The third application is taken apart in the same manner.
}{
\AxiomC{(3)}
\AxiomC{}
\RightLabel{$\infer _{Refl}$}
\UnaryInfC{$IE \vdash a : Type \infer a : Type$}
\LeftLabel{(1)}
\RightLabel{$\infer _{App}$}
\BinaryInfC{$
\begin{matrix}IE \vdash (::)\,a : a \to Stream\,a \to Stream\,a \infer
  \\ (_g::)\,a \  : a \to \later ^\kappa_1  \onk{Stream}\,a \to
  \onk{Stream}\,a\end{matrix}$}
\DisplayProof
}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
Here, we need to show that the recursive reference can be applied to the $n$
argument by using the rule for later application (\tensor).
}{
\AxiomC{(4)}
\AxiomC{}
\RightLabel{$\infer _{Refl}$}
\UnaryInfC{$IE \vdash n : a \infer n : a$}
\RightLabel{$\infer _{\onk{Next}}$}
\UnaryInfC{$IE \vdash n : a \infer \onk{Next}\ n : \later^\kappa_1 a$}
\LeftLabel{(2)}
\RightLabel{$\infer _{\tensor^\kappa_n}$}
\BinaryInfC{$\begin{matrix}IE \vdash repeat\ a\ n : Stream\ a \infer \\ (\onk{Next}\,  (_grepeat\ a)[\kappa])
  \tensor^\kappa_1 (\onk{Next}\ n) : \later^\kappa_1 \onk{Stream} a\end{matrix}$}
\DisplayProof
}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
The $\infer_\phi$-rule is used to show that the data constructor
\texttt{($_g$::)} for $_g$Stream is the guarded recursive
version of the \texttt{(::)} constructor for \texttt{Stream}.
}{
  \AxiomC{}
  \UnaryInfC{$IE \vdash (::) \phieq (_g::)$}
\AxiomC{}
  \UnaryInfC{$\begin{matrix}IE \vdash (_g::) : (a : Type) \to a \to \\
    \later^\kappa_1\onk{Stream}\,a \to \onk{Stream}\,a\end{matrix}$}
\RightLabel{$\infer _{\phi}$}
\LeftLabel{(3)}
\BinaryInfC{$\begin{matrix}IE \vdash (::) : (a : Type) \to a \to Stream\,a \to
    Stream\,a \infer \\
    (_g::) : (a : Type) \to a \to \later^\kappa_1\onk{Stream}\,a \to \onk{Stream}\,a
\end{matrix}$}
\DisplayProof
}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat
\subcaptionbox{
The rule for the recursive reference in the causal case is used to eliminate the
recursive reference \texttt{repeat a}.
}{
  \AxiomC{(5)}
\AxiomC{}
\UnaryInfC{$\begin{matrix} IE \vdash _grepeat : (a\ :\ Type) \to  \forall
    \kappa.( a \to \onk{Stream}\ a) \end{matrix}$}
\AxiomC{}
\UnaryInfC{$IE \vdash a : Type$}
\RightLabel{App}
\BinaryInfC{$IE \vdash \, _grepeat\ a : \forall \kappa.( a \to \onk{Stream}\ a)$}
\RightLabel{$\infer _{Rec\causal}$}
\LeftLabel{(4)}
\BinaryInfC{$\begin{matrix}IE \vdash repeat\ a : a \to Stream\ a \infer \\ \onk{Next} (_grepeat\ a)[\kappa]
  : a \to \onk{Stream}\ a\end{matrix}$}
\DisplayProof
}
\end{figure}
\begin{figure}[H]
\centering
\ContinuedFloat

\subcaptionbox{
Follows directly from the inference environment.
}{
\AxiomC{}
\LeftLabel{(5)}
\UnaryInfC{$IE \vdash repeat\ a \phieq\ _grepeat\ a$}
\DisplayProof
}

\caption{An inference of the guarded recursive version of repeat.}
\label{fig:repeat_inference_proof}
\end{figure}

% \begin{figure}
% \begin{lstlisting}[mathescape]
% causal zeros : Stream Nat
% zeros = Z :: zeros

% $_g$zeros : $\forall\kappa.$ $_g$Stream Nat
% $_g$zeros = $\Lambda\kappa.$ Z $_g$:: (Next (apply $_g$zeros))
% \end{lstlisting}
%   % \[
%   % \frac{x}{\eps{IE}{Z :: zeros}{Stream Nat}{IE}{Z :: gzeros}{gStream Nat}}
%   % \]
% %\input{figures/epsilon_zeros}
%   \caption{Above: The user-provided program \texttt{zeros}, along with the
%     inferred program $_g$\texttt{zeros}. Below: Inferring $_g$\texttt{zeros} from \texttt{zeros} using the rules from
%   Figure~\ref{fig:epsilon_rules}.}
%   \label{fig:epsilon_zeros}
% \end{figure}

% \subsubsection{Implementing the Inference System}
% \label{sec:impl-infer-syst}

% \paragraph{Preprocessing} Two aspects of the inference system, renaming and
% delaying the recursive reference, are mandatory, and these
% are therefore handled in a separate preprocessing step. Both must take modality
% into account.

% Renaming, i.e. all applications of the $\Longrightarrow_{\phi}$ rule, is
% performed by substituting all Idris names in $\phi$ with their guarded
% versions. Special care must be taken when substituting names of projection
% functions, since the modality of the function in question, $f$, influences the choice
% of guarded name. If $f$ is causal,

% Delaying the recursive reference
%Preprocessing
%Modality and Recursive reference
%When rules clash

\input{sections/guarded_recursion_checking}

\section{Discussion}
\label{sec:discussion}
Although the system presented throughout this chapter can prove productive quite
a few realistic programs (see Chapter~\ref{cha:evaluation}), it currently has
several shortcomings and limitations.
%\subsection{Guarded Recursion and Dependent Types}

\subsection{Preservation of Semantics}
\label{sec:pres-semant}
In Section~\ref{sec:inference-system}, we presented the rules for inferring
guarded recursive TT terms from elaborated TT terms. Even though we are
confident in our approach, we have no proof that the semantics of the inferred
guarded recursive terms are the same as the semantics of the input terms. In
order to provide this proof, we could implement an erasure mechanism for guarded
recursive TT terms back to ordinary TT terms (without guarded recursion),
mapping guarded names and quantified names back to Idris names. After erasure,
we could then attempt to prove that the erased program had equivalent semantics to the
original input program by showing that in an abstract machine modeling the
dynamic semantics of Idris, they evaluate to the same term in the same (or
approximately the same) number of steps.

% Naturally, the guarded recursive version must have the same semantics in
% order for the productivity analysis to have any value. We imagine that such a
% proof could be provided by showing that the input term and the output term of each
% rule reduce to the same or equivalent TT semantics. The TT
% semantics are defined by Brady\,\citep{BradyIdrisImpl13}.

\subsection{Dependent Function Types and Fixed Point Elimination}
\label{sec:depend-funct-types}
As described in Section~\ref{sec:fixkappa-rule}, our current implementation uses
fixed point elimination in order to enable inference of guarded recursive
programs with dependent types. However, this leads the system to make an
unfortunate assumption. Recall the example of \texttt{prepend} from
Section~\ref{sec:fixkappa-rule}:
\begin{lstlisting}[mathescape, title=\ttBlock]
prepend$'$ : (n : Nat) $\to$ (a : Type) $\to$
           $\laterkappa\,$(Vect n a $\to$ Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a) $\to$
           Vect n a $\to$ Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a
prepend$'$ n a rec []        s = s
prepend$'$ n a rec (x $_g$:: xs) s =
                    ($_g$::) a x ((rec $\tensor$ (Next xs)) $\tensor$ (Next s))

prepend : (n : Nat) $\to$ (a : Type) $\to$
          $\forall\kappa.$(Vect n a $\to$ Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
prepend n a = $\Lambda\kappa.\,$fix$^\kappa$($\lambda$rec.$\lambda$xs.$\lambda$s. prepend$'$ n a rec xs s)
\end{lstlisting}
Here, the type of \texttt{rec} is {$\laterkappa\,$(Vect n a $\to$
  Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a)}. Through fixed point
elimination, we wish to substitute \texttt{rec} with \texttt{{(Next$^{\kappa}$
    ((prepend[$\kappa$]) n a)}}, such that we arrive at the following definition
of \texttt{prepend}:
\begin{lstlisting}[mathescape, title=\ttBlock]
prepend$'$ : (n : Nat) $\to$ (a : Type) $\to$
           Vect n a $\to$ Stream$^{\kappa}\,$a $\to$ Stream$^{\kappa}\,$a
prepend$'$ n a []        s = s
prepend$'$ n a (x $_g$:: xs) s =
   ($_g$::) a x (((Next$^{\kappa}$ ((prepend[$\kappa$]) n a)) $\tensor$ (Next xs)) $\tensor$ (Next s))

prepend : (n : Nat) $\to$ (a : Type) $\to$
          $\forall\kappa.$(Vect n a $\to$ Stream$^\kappa$ a $\to$ Stream$^\kappa$ a)
prepend n a = $\Lambda\kappa.\,$fix$^\kappa$($\lambda$xs.$\lambda$s. prepend$'$ n a xs s)
\end{lstlisting}
Because \texttt{n} and \texttt{a} are universally quantified in the type of
\texttt{prepend}, we are allowed to specialise the type of \texttt{prepend} on
the right-hand side of \texttt{prepend$'$}, making the implementation
well-typed. In the type of \texttt{rec}, however, \texttt{n} and \texttt{a} are
fixed. Hence, we have by fixed point elimination assumed that a recursive
reference with fixed parameters can be substituted with a term with universally
quantified parameters. In general, we do not know whether such a substitution is sound, since we
cannot recover the fixed point version of the program afterwards.

Consequently, the analysis should not rely on fixed point elimination. Instead,
the inference should simply proceed after step 2 of preprocessing for causal
functions, and after step 3.1 for non-causal functions (see
Section~\ref{sec:impl-guard-recurs}). For the inference system, fixed point
elimination means that recursive references must be handled differently for
causal and non-causal functions, namely by the $\infer_{Rec_\causal}$-rule in
the causal case and by the $\infer_{Rec_\noncausal_{n}}$,
$\infer_{Rec_\noncausal_{0}}$, and $\infer_{Rec_\noncausal}$ rules in the non-causal
case. Without fixed point elimination, the recursive reference can be handled by
the inference system with one uniform rule for both the causal and the noncausal case:

\begin{prooftree}
\AxiomC{$\IEc\vdash \iota \phieq e$}
\AxiomC{$\IEc\vdash e:A'$}
\RLabel{\infer_{Rec}}
\BinaryInfC{$\IEc\vdash \iota : A \infer e : A$'$$}
\end{prooftree}

This would simplify the inference system considerably. From the perspective of
the checking system, the absence of fixed point elimination would mean that all
the checking rules for recursive references (both causal and noncausal) could be
replaced by a single fixed point rule:

\begin{prooftree}
\def\fCenter{\vdash}
\Axiom$\IEopen,x:\laterkappa A\fCenter t : A$
\RLabel{fix_I}
\UnaryInf$\IEopen\fCenter fix^{\kappa} x. t : A$
\end{prooftree}

Since fixed point elimination in general is has not yet been proven sound,
although it seems to work in most cases up to polymorphic types, it should not be
part of a future implementation.

\subsection{Type Class Instances}
\label{sec:type-class-instances}
The inference system does not support function definitions given in type class
instances at present, as these require special treatment. Type classes in Idris
are implemented by dictionary passing, and type class constraints are modeled as
additional parameters. Consequently, Idris expects that for each type class
instance for a coinductive type $A$, its guarded type $_gA$ has an equivalent
instance. Type class instances for guarded types are not derived at the moment,
so no guarded recursive definition involving type classes can be
well-typed. Deriving type class instances should be possible during elaboration,
since it is a question of inferring guarded recursive versions of each
instance function, taking modality into account.

% An alternative to deriving guarded type class instances is to eliminate the idea of
% type classes entirely in the inference system, such that

\subsection{Mutual Recursion}
\label{sec:mutual-recursion}
Since our productivity analysis emerges from the use of the guarded recursive
fixed point defined in Section~\ref{sec:guarded-recursion}, mutually recursive
definitions are not (yet) supported. The reason is that our analysis prevents
infinite recursion by ensuring that all direct recursive references are not
immediately available, seeing as they must have a type under a specific type
constructor, later ($\laterkappa$). If other constructs can lead to infinite
recursion, these must be identified separately. This is deferred to future work
(see Chapter~\ref{cha:future-work}).

\subsection{Totality Dependencies}
\label{sec:total-depend}
Currently, the system does not keep track of totality dependencies between
functions. Consider the following program:
\begin{lstlisting}[mathescape, title=\idrisBlock]
nats : Stream Nat
nats = Z :: map S nats
\end{lstlisting}
Here, \texttt{nats} depends on the totality of \texttt{map}. If \texttt{map}
turns out to be partial, it is not currently detected that \texttt{nats} is also
partial as a consequence thereof. The reason is that the productivity analysis
is a type-level check, so the analysis of \texttt{nats} relies on the promise that
a total version of \texttt{map} has been found, and not on the actual
implementation of \texttt{map}. This can quite easily be fixed by checking that
any non-recursive reference has already been proven total before it is accepted
as the guarded recursive version of a term.

\subsection{User-written Guarded Recursion}
\label{sec:user-written-guarded}
% Problem: Non-causal functions require two functions
%% However, the checker checks non-causal definitions in an open clock
Our system does not currently allow the user to circumvent the inference
system. This means that users cannot have the checking system verify whether
their hand-written guarded recursive definitions are productive, since the
checking system assumes that all input definitions have been preprocessed
according to the procedure described in Section~\ref{sec:inference-system}.

However, allowing users to write guarded recursive programs is not merely a
question of adapting the checking system. Consider the following well-typed
Idris program, potentially written by a user:
\begin{lstlisting}[mathescape, title=\idrisBlock]
total
force : Later (Tomorrow Now) a $\to$ a
force (Next a) = a

total
f : Stream Nat
f = $\Lambda\kappa.\,$fix$^\kappa$($\lambda$rec.$\,$force$\,$rec)
\end{lstlisting}
Here, \texttt{fix$^\kappa$} is used correctly in \texttt{f}, but the use of
\texttt{force} means that \texttt{f} is not productive. Although the recursive
reference is well-typed, infinite recursion results from the application of
\texttt{force}. In practice, this leads to a situation where users can add
arbitrary axioms to the checking system, since the checking system cannot
readily dispute the correctness of the well-typed and total definition of
\texttt{force}.

In order to allow users to write guarded recursive programs manually,
restrictions must therefore be implemented in the Idris compiler. Concretely,
the example above is problematic because the user is allowed to define pattern
matching on a value of type \texttt{Later}. Restricting users from writing such
definitions would therefore be necessary. Further exploration into this area is
needed in order to determine whether additional restrictions are required.

\subsection{Multiple Clocks}
\label{sec:multiple-clocks}
In Section~\ref{sec:singleton-clock}, we explained that the inference system has
been restricted to only inferring guarded recursive terms that require at most
one clock variable. The $\infer_{\Lambda\kappa}$ and $\infer_{[\kappa]}$ rules
take advantage of this restriction, since they assume that the clock in question
is always the singleton clock. Extending these rules to multiple clocks would
most likely be hard, because the $\infer_{[\kappa]}$ rule would have to infer
which clock to apply in any given situation.

In contrast, the checking system could probably be successfully extended to
accommodate multiple clocks. It merely has to check whether a given situation is
allowed according to the rules in Figure~\ref{fig:gr_rules_sin_clock}, and does
not perform any inference whatsoever. Therefore, user-written guarded recursive
definitions with multiple clocks could most likely be supported by extending the
checking system.

\subsection{Error Reporting}
\label{sec:error-reporting}
Giving helpful error messages concerning guarded recursion can be difficult,
mainly because it may require that the user is familiar or at least partially
familiar with the underlying theory. Using the erasure mechanism discussed in
Section~\ref{sec:pres-semant}, however, it might be possible to use the existing
delaborator to translate an erased TT term back to \IdrisM{} in order to provide
useful error messages.

Aside from that, it should be possible to
generate quite detailed error messages, considering that each rule may fail
independently. We have not yet put any effort into providing helpful error
messages, but we imagine that such messages could have the form: ``The causal
definition $f$ is not productive because $x$ at line $n$, column $c$, has no
guarded recursive form of type $A'$ (inferred from type $A$)''. All information
used in this example is directly available in each of the inference rules.

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../copatterns-thesis"
%%% End:


\section{Bind Soul}
\textbf{Cost:} 200 CP\\
\textbf{Requirements:}~\nameref{rune:nil} I, Any Anima Rune I except Nil\\
\textbf{Spell, Active, Repeatable, Source(100 Gold), Memory}\\
You capture the soul of one recently deceased, non-humanoid creature of a combined level of 5 or lower by casting a spell that takes 12 AP and costs 10 Mana.
The spell only works up to 10 minutes after a creature's death, and a creature's soul can not be captured twice.
You gain 1 tiny soul shard from this creature.\\
\\
Level Progression:\\
\\
\rowcolors{2}{lightgray}{white}
\begin{tabular}{l | l | p{5.5cm} | p{2.5cm}}
    Level & Cost & additional Option & gain\\
    II & 500 CP & 15 Mana for creatures of combined level 6--10 & gaining 1 small soul shard\\
    III & 1,000 CP & 30 Mana for creatures of combined level 11--15 & gaining 1 normal soul shard\\
    IV & 2,500 CP & 60 Mana for creatures of combined level 16--20 & gaining 1 large soul shard\\
    V & 5,000 CP & 100 Mana for creatures of combined level 21--25 & gaining 1 massive soul shard\\
    VI & 10,000 CP & 200 Mana for creatures of combined level 26--30 & gaining 1 huge soul shard\\
    VII & 25,000 CP & 300 Mana for humanoid creatures and creatures of combined level 31 and above.\linebreak For every level above 31, the spell requires 10 Mana more. & gaining 1 radiant soul shard\\
\end{tabular}