\section{The \kw{Equations} Vernacular}
\label{manual}

\def\cst#1{\coqdoccst{#1}}

\subsection{Syntax of programs}
\def\kw#1{\coqdockw{#1}}
\def\vec#1{\overrightarrow{#1}}
\def\vecplus#1{{\overrightarrow{#1}}^{+}}
\def\textcoloneq{\texttt{:=}}
\def\userref#1#2{\coqdockw{with}~#1~\textcoloneq~#2}
\def\var#1{\coqdocvar{#1}}
\def\figdefs{\begin{array}{llcl}
  \texttt{term}, \texttt{type} & t, ~τ & \Coloneqq &
  \coqdocvar{x} `| \lambda \coqdocvar{x} : \tau, t, R `| ∀ \coqdocvar{x} :
                                                    \tau, \tau' `|
  \mathbf{\lambda}\texttt{\{}\,\vecplus{\vec{up} \coloneqq t}\texttt{\}}
   \cdots \\
  \texttt{binding} & d & \Coloneqq & \texttt{(}\coqdocvar{x}~\texttt{:}~\tau\texttt{)} `|
  \texttt{(}\coqdocvar{x}~\textcoloneq~t~\texttt{:}~\tau\texttt{)} \\
  \texttt{context} & Γ, Δ & \Coloneqq & \vec{d} \\
  \texttt{programs} & progs & \Coloneqq & prog~\overrightarrow{mutual} \texttt{.} \\
  \texttt{mutual programs} & mutual & \Coloneqq & \coqdockw{with}~p `| where \\
  \texttt{where clause} & where & \Coloneqq & \coqdockw{where}~p `| \coqdockw{where}~not\\
  \texttt{notation} & not & \Coloneqq & \texttt{''}string\texttt{''}~\textcoloneq~t~(\texttt{:}~scope)?\\
  \texttt{program} & p, prog & \Coloneqq & \coqdoccst{f}(\texttt{@\{} univ\_decl \texttt{\}})?~Γ~\texttt{:}~τ~(\coqdockw{by}~\textit{annot})?~\textcoloneq~clauses \\
  \texttt{annotation} & annot & \Coloneqq & \kw{struct}~\var{x}? `| \kw{wf}~t~R? \\
  \texttt{user clauses} & clauses & \Coloneqq & \vecplus{cl} `| \texttt{\{}\,\vec{cl}\,\texttt{\}} \\
  \texttt{user clause} & cl & \Coloneqq & \coqdoccst{f}~\vec{up}~n?~\texttt{;} `|
      \texttt{|} up~\vec{(\texttt{,} `| \texttt{|})~up}~n?~\texttt{;}? \\
  \texttt{user pattern} & up & \Coloneqq & x `| \_
  `| \coqdocconstr{C}~\vec{up}
  `| \texttt{?(}\,t\,\texttt{)} `| \texttt{!} \\
  \texttt{user node} & n & \Coloneqq &
   \textcoloneq~t~\overrightarrow{where} `|\, \userref{t~\vec{, t}}{clauses}
\end{array}}

In the grammar, $\vec{t}$ denotes a possibly empty list of $t$,
$\vecplus{t}$ a non-empty list. Concrete syntax is in
\texttt{typewriter} font.
\begin{figure}[h]
\centering$\figdefs$
\caption{Definitions and user clauses}
\label{fig:usergram}
\end{figure}
The syntax allows the definition of toplevel mutual (\kw{with}) and
nested (\kw{where}) structurally recursive definitions. 
Notations can be used globally to attach a syntax to a 
recursive definition, or locally inside a user node. A single program is given as a tuple of a (globally
fresh) identifier, an optional universe annotation, 
a signature and a list of user clauses (order matters), along with an optional recursion annotation (see next
section). The signature is simply a list of bindings and a result
type. The expected type of the function \cst{f} is then $∀~Γ, τ$.
An empty set of clauses denotes that one of the variables has an empty type.

Each user clause comprises a list of patterns that will match the
bindings $Γ$ and an optional right hand side. Patterns can be named or
anonymous variables, constructors applied to patterns, the inaccessible
pattern \texttt{?(}t\texttt{)} (a.k.a. "dot" pattern in \Agda) or the
empty pattern \texttt{!} indicating a variable has empty type (in this
case only, the right hand side must be absent). Patterns are parsed
using \Coq's regular term parser, so any term with implicit arguments
and notations which desugars to this syntax is also allowed.

A right hand side can either be a program node returning a term $t$
potentially relying on auxiliary definitions through local \kw{where}
clauses, or a \kw{with} node.  Local \kw{where} clauses can be used to
define nested programs, as in \Haskell or \Agda, or local
notations. They depend on the lexical scope of the enclosing program. As
programs, they can be recursive definitions themselves and depend on
previous \kw{where} clauses as well: they will be elaborated to
dependent let bindings. The syntax permits the use of curly braces
around a list of clauses to allow disambiguation of the scope of
\kw{where} and \kw{with} clauses. The $\lambda\{$ syntax (using a
unicode lambda attached to a curly brace) extends \Coq's term syntax
with pattern-matching lambdas, which are elaborated to local \kw{where}
clauses. A local \kw{with}~$t$ node essentialy desugars to a program
node with a local \kw{where} clause taking all the enclosing context as
arguments plus a new argument for the term $t$, and whose clauses are
the clauses of the \kw{with}. The \kw{with} construct can be nested also
by giving multiple terms, in which case the clauses should refine a new
problem with as many new patterns.

\subsection{Generated definitions}

Upon the completion of an \Equations definition, a few supporting lemmas
are generated.

\subsubsection{Equations}

Each compiled clause of the program or one
of its subprograms defined implicitely by \kw{with} or explicitly by
\kw{where} nodes gives rise to an equation. Note that the clauses
correspond to the program's splitting tree, i.e. to the expansion of
pattern-matchings, so a single source clause catching multiple cases
can correspond to multiple equations. All of these equations are
registered as hints in a rewrite hint database named $\cst{f}$, which can be
used by the \coqdoctac{simp} or \coqdoctac{autorewrite} tactic
afterwards. The $\coqdoctac{simp}~f$ tactic is just an alias to
$\coqdoctac{autorewrite with}~f$. The equation lemmas are named
after the position they appear in in the program, and are of the
form $\cst{f}\_clause\_n\_equation\_k$.

In case the program is well-founded, \Equations first generates an
unfolded definition named \cst{f\_unfold} corresponding to the
1-unfolding of the recursive definition and shows that it is
extensionally equal to \cst{f}. This unfolding equation is used
to generate the equations associated to \cst{f}, which might also
refer to the unfolded versions of subprograms. Well-founded
recursive definitions can hence generate a set of equations that
is not terminating as an unconditional rewrite system.

\subsubsection{Elimination principle}

\Equations also automatically generates a mutually-inductive relation
corresponding to the graph of the programs, whose first inductive is named
$\cst{f}\_ind$. It automatically shows that the functions respects their
graphs (lemma $\cst{f}\_ind\_fun$) and derives from this proof an
elimination principle named $\cst{f}\_elim$. This eliminator can be used
directly using the \tac{apply} tactic to prove goals involving a call to
the function(s). One has to provide predicates for each of the toplevel
programs and the \kw{where} subprograms (\kw{with} subprograms's
predicates follow from their enclosing programs).

In case the program has a single predicate, one can use the
$\tac{funelim}~call$ tactic to launch the elimination by specifying
which call of the goal should be used as the elimination target.
A most general predicate is inferred in this case.

\subsection{Logic parameterization}

\Equations comes with three possible instances of its library,
one where equality is \Coq's standard equality \ind{eq} in \Prop and
another where equality is proof-relevant and defined in \kw{Type}, finally 
a last instance is a variant of the second reusing the definitions of the 
\texttt{Coq-HoTT} library.
The first can be used simply by requiring \cst{Equations.Prop.Equations}
(or \texttt{From Equations Require Import Equations}),
while the other two can be used by importing \cst{Equations.Type.All}
or \cst{Equations.HoTT.All} instead. The libraries are qualified respectively 
by the \cst{Equations.Prop},\cst{Equations.Type} or \cst{Equations.HoTT} prefixes. 
When referring to classes in the following, one can find their definition in the respective prefix. 
In other words, \cst{Classes.EqDec} might refer to \cst{Equations.Prop.Classes.EqDec},
\coqdoccst{Equations.Type.Classes.EqDec} or \coqdoccst{Equations.HoTT.Classes.EqDec}
depending on the logic used.

\subsection{Local Options}
The \kw{Equations} command takes a few options using the syntax
\[\texttt{\#[}attributes\texttt{]}~\kw{Equations}\texttt{(}opts\texttt{)} ~progs~\ldots\]

One can use the \kw{Equations?} syntax to use the interactive proof mode
instead of obligations to resolve holes in the term or obligations
coming from well-founded recursive definitions.

In \Equations v1.3 and higher, the command supports the following attributes:
  
- \texttt{universes(polymorphic | monomorphic)} for universe polymorphic or
  monomorphic definitions (also depending on the global \texttt{Universe Polymorphism} flag).

- \texttt{tactic=tac} for setting the default tactic to try solve obligations/holes.
  If not set, the default tactic is the same as for \texttt{Program}, controlled by
  the \text{Obligation Tactic} command. The \texttt{tac} can be either an unquoted 
  unqualified identifier or a string delimited by quotes to provide a qualified name, as in 
  \[\texttt{\#[tactic="Program.Tactics.program\_simpl"] Equations foo ...}\]

- Flags \texttt{derive(equations=yes|no, eliminator=yes|no)}, both enabled by default,
  to control the derivation of the propositional equalities of the definition and its 
  graph and elimination principle, respectively. Note that \texttt{eliminator = yes} 
  forces \texttt{equations = yes}.

The \emph{deprecated} syntax $opts$ is a list of flags among:

\begin{itemize}
\item $\texttt{ind} `| \texttt{noind}$: Generate (default) or do not generate 
  the inductive graph of the function and the derived eliminator.
\item $\texttt{eqns} `| \texttt{noeqns}$: Generate (default) or do not generate 
  the equations corresponding to the (expanded) clauses of the program.
  \texttt{noeqns} implies \texttt{noind}.
\end{itemize}

\subsection{Global Options}

The \kw{Equations} command obeys a few global options:
\begin{itemize}
\item \texttt{Equations Transparent}: governs the opacity of definitions
  generated by \kw{Equations}. By default this is off and means that
  definitions are declared \emph{opaque} for reduction, avoiding
  spurious unfoldings of well-founded definitions when using the 
  \texttt{simpl} tactic for example.
  The \texttt{simp} $\cst{c}$ tactic is favored in this case to do
  simplifications using the equations generated for $\cst{c}$.
  One can always use \kw{Transparent} after a definition to get its
  definitional behavior.

\item \texttt{Equations With Funext} (since v1.2): governs the use of the functional
  extensionality axiom to prove the unfolding lemma of well-founded
  definitions, which can require extensionality of the functional. By
  default \emph{on}. When this flag is off, the unfolding lemmas of
  well-founded definitions might fail to be proven automatically and be
  left to the user as an obligation. To prove this obligation, the user
  is encouraged to use the \tac{Equations.Init.unfold\_recursor}
  tactic to help solve goals of the form \[\cst{FixWf}~x~f = \cst{f\_unfold}~x\].

\item \texttt{Equations With UIP} (since v1.2): governs the use of instances of
  \texttt{Classes.UIP} derived by the user, or automatically
  from instances of the decidable equality class
  \texttt{Classes.EqDec}. By default \emph{off}. When switched
  on, equations will look for an instance of $\ind{UIP}\~A$ when solving
  equalities of the form \[\forall (e : x = x :> A), P e\], i.e. to
  apply the deletion rule to such equations, or to unify indices of
  constructors for inductive families without a \ind{NoConfusionHom}
  instance. It will report an error if it cannot find any. Note that
  when this option is on, the computational behavior of \Equations
  definitions on open terms does not follow the clauses: it might block
  on the uip proof (for example if it is a decidable equality test).
  The rewriting equations and functional elimination principle can still
  be derived though and are the preferred way to reason on the
  definition.

\item \texttt{Equations WithK} DEPRECATED. Use \texttt{With UIP} and
  declare your own version of the \cst{UIP} axiom as a typeclass
  instance. Governs the use of the \texttt{K} axiom.
  By default \emph{off}. The computational behavior of definitions
  using axioms changes entirely: their reduction will get stuck even
  on closed terms. It is advised to keep such definitions opaque and use
  the derived rewriting equations and functional elimination principle
  to reason on them.

\item \texttt{Equations Derive Equations} (since v1.2) This sets the default for
  the generation of equations, governed by the local
  \texttt{derive(equations)} attribute.

\item \texttt{Equations Derive Eliminator} (since v1.2) This sets the default for the
  generation of the graph and functional elimination principle
  associated to a definition, governed locally by the
  \texttt{derive(eliminator)} attribute.
\end{itemize}

\section{Derive}

\Equations comes with a suite of deriving commands that take inductive
families and generate definitions based on them. The common syntax for
these is:

\[(\mathtt{Equations})?~\mathtt{Derive}~\ind{C}_1 \ldots \ind{C}_n~\mathtt{for}~\ind{ind}_1 \ldots \ind{ind}_n.\]

Which will try to generate an instance of type class \ind{C} on
inductive type \ind{Ind}. 

\paragraph{Note} The \texttt{Equations} prefix can be used to disambiguate
from other plugins defining \texttt{Derive} commands such as \texttt{QuickChick}.  

We assume $\ind{ind}_i : \Pi \Delta. s$. The derivations provided by \Equations are:

\begin{itemize}
\item \ind{DependentEliminationPackage}: generates the dependent
  elimination principle for the given inductive type, which can differ
  from the standard one generated by \Coq.
  It derives an instance of the class

  \texttt{DepElim.DependentEliminationPackage}.
\item \ind{Signature}: generate the signature of the inductive, as a
  sigma type packing the indices $\Delta$ (again as a sigma type) and
  an object of the inductive type. This is used to produce homogeneous
  constructions on inductive families, by working on their packed
  version (total space in HoTT lingo).
  It derives an instances of the class
  \texttt{Equations.Signature.Signature}.

\item \ind{NoConfusion}: generate the no-confusion principle for the
  given family, as an heterogeneous relation. It embodies the
  discrimination and injectivity principles for the
  total space of the given inductive family: i.e.
  $\Sigma \Delta, \ind{I}~\bar{\Gamma}~\Delta$ for a family
  $\ind{I} : \forall \Gamma, \Delta "->" \kw{Type}$ where $\Gamma$ are
  (uniform) parameters of the inductive and $\Delta$ its indices.

  It derives an instance of the class \texttt{Classew.NoConfusionPackage}.

\item \ind{NoConfusionHom}: generate the \emph{homogeneous} no-confusion
  principle for the given family, which embodies the discrimination and
  injectivity principles for (non-propositional) inductive types.
  This principle can be derived if and only if the no-confusion property
  on the inductive family instance reduces to equality of the non-forced
  arguments of the constructors. In case of success it generates an instance of the class
  \texttt{Classes.NoConfusionPackage} for the type $\ind{I}~
  \Delta~\Gamma$ applicable to equalities of two objects in the \emph{same}
  instance of the family $\ind{I}$.

\item \ind{EqDec}
  This derives a decidable equality on $C$, assuming decidable equality 
  instances for the parameters and supposing any primitive inductive
  type used in the definition also has decidable equality. If
  successful it generates an instance of the class (in \texttt{Classes.EqDec}):
\begin{verbatim}
Class EqDec (A : Type) :=
  eq_dec : forall x y : A, { x = y } + { x <> y }.
\end{verbatim}
  
\item \ind{Subterm}: this generates the direct subterm relation for the
  inductive (asuming it is in \kw{Set} or \kw{Type}) as an inductive family.
  It then derives the well-foundedness of this relation and wraps it
  as an homogeneous relation on the signature of the datatype (in case
  it is indexed). These relations can be used with the \texttt{by wf}
  clause of equations. It derives an instance of the class
  \texttt{Classes.WellFounded}.

\end{itemize}

\section{\texttt{dependent elimination}}

The \tac{dependent elimination} tactic can be used to do dependent
pattern-matching during a proof, using the same engine as Equations.

Its syntax is:
\begin{figure}[h]
  \tac{dependent elimination} \textit{ident} \texttt{as} [ up | .. | up ].
\end{figure}

It takes a list of patterns (see figure \ref{fig:usergram}) that should cover the type of \textit{ident}
and generates the corresponding subgoals.


\section{\texttt{simp}}

The $\tac{simp}~\cst{f}_1 \ldots \cst{f}_n$ tactic is an alias to
\[\begin{array}{l}
  \tac{autorewrite}~\tac{with}~\cst{f}_1 \ldots \cst{f}_n ; \\
  \tac{try typeclasses eauto with subterm\_relation simp rec\_decision} \cst{f}_1
  \ldots \cst{f}_n
\end{array}\]

It can be used to simplify goals involving equations definitions
$\cst{f}_1 \ldots \cst{f}_n$, by rewriting with the equations declared
for the constants in the associated rewrite hint database and trying to
solve the goal using the hints declared in the associated ``auto'' hint
database, both named $\cst{f}$.

\section{Functional elimination}

The $\tac{funelim}~t$ tactic can be used to launch a functional
elimination proof on a call $t$ of an Equations-defined function $t =
\cst{f}~args$ (the eliminator is named $\cst{f\_elim}$). By default, it will
generalize the goal by an equality betwee \texttt{f args} and a fresh
call to the function \texttt{f args'}, keeping information about initial
arguments of the function before doing elimination. This ensures that
subgoals do not become unprovable due to generalization. This might
produce complex induction hypotheses that are guarded by dependent
equalities between the initial arguments and the recursive call
arguments. These can be simplified by instantiating the induction
hypotheses sufficiently and providing reflexive equality proofs to
instantiate the equalities.

A variant $\tac{apply\_funelim}~t$ simply applies the
eliminator without generalization, avoiding the generation of
(dependent) equalities. Note that in this case (as when using \Coq's
built-in \tac{induction} tactic) one may have to explicitly
generalize the goal by equalities (e.g. using the \tac{remember}
tactic) if the function call being eliminated is not made of distinct
variables, otherwise it can produce unprovable subgoals.

Finally, for mutual or nested programs, no automation is provided yet.
The user has to invoke the functional elimination directly,
e.g. using \[\tac{eapply}~(\cst{f\_elim}~P_1 \ldots P_n)\] providing
predicates for each of the nested or mutual function definitions in
\cst{f} (use \kw{About} \cst{f\_elim} to figure out the predicates to be
provided).

\newpage
\section{Changes}

\def\issue#1{\href{https://github.com/mattam82/Coq-Equations/issues/#1}{\texttt{\##1}}}

\begin{itemize}
\item Version 1.3: 
  \begin{itemize}
  \item \textbf{Incompatible change} Support for the Coq-HoTT library, out of the box. This required a slight reorganization 
    of the directories. To use this, simply install the \texttt{opam} \texttt{coq-hott} package before 
    \texttt{rocq-equations} and \[\texttt{From Equations.HoTT Require Import All}\]
    Now \[\texttt{Require Import Equations.Equations}\] no longer works, 
    use \texttt{Require Import Equations.Prop.Equations} (absolute path, future-proof) or 
    \texttt{From Equations Require Import Equations} (relative path) to use the 
    (default) \texttt{Prop} instance.

  \item Complete support for building with \texttt{dune}.

  \item New attributes \texttt{tactic = tac} and \texttt{derive(eliminator, equations)}.
  \item Improved syntax for concise clauses: no ";" separator needed for clauses 
    already separated by \texttt{|}. Useful in with clauses but also at the toplevel, e.g.
    the following definition is now accepted:
\begin{verbatim} 
Equations foo (x : nat) : nat :=
  | 0 => 1
  | S n => S (foo n).
\end{verbatim}
  \item Fixed issues:
    \begin{itemize}
    \item \issue{329}: improved strengthening avoiding to abstract over recursive definitions
      which would not pass the guardness checker. This can simplify the produced terms, avoiding 
      unnecessary "commutative cuts".
    \item \issue{321}: warn rather than error when using \texttt{Equations?} and no subgoals are left.
      This will leave a proof state with no subgoals, that \emph{must} be closed using a \texttt{Qed} 
      or \texttt{Defined} (similarly to \Coq's \texttt{\#[refine] Instance} command).
    \item \issue{372}, \issue{194}: funelim applied to a partial application failing
    \item \issue{354}: support for building values in \texttt{SProp}
    \item \issue{353}: name capture problem in presence of modules
    \item \issue{335}: provide an alias \texttt{Equations Derive} to not conflict with QuickChick's \texttt{Derive}
    \item \issue{325}: properly inline all Equations helper constants during Extraction
\end{itemize}
\end{itemize}

\item Version 1.2.4:
  Fixed issues:
  \begin{itemize}
    \item \issue{338}: incompatibility with ssreflect's \texttt{rewrite -!}
    \item \issue{346}: Derive not working when the inductive type's sort is hidden under a constant.
    \item \issue{228}, \issue{306}, \issue{349}: functional elimination proofs were failing for no good reason.
      Improved automation when functional extensionality is disabled.
    \item \issue{328}: uncaught \texttt{Not\_found} exception raised while printing an error message.
  \end{itemize}
\end{itemize}


%%% Local Variables: 
%%% mode: latex
%%% TeX-master: "equations"
%%% TeX-PDF-mode: t
%%% End: 
