\chapter{Extensions of \Gallina{}}
\label{Gallina-extension}\index{Gallina}

{\gallina} is the kernel language of {\Coq}. We describe here extensions of
the Gallina's syntax.

\section{Record types
\comindex{Record}
\label{Record}}

The \verb+Record+ construction is a macro allowing the definition of
records as is done in many programming languages.  Its syntax is
described on figure \ref{record-syntax}.  In fact, the \verb+Record+
macro is more general than the usual record types, since it allows
also for ``manifest'' expressions. In this sense, the \verb+Record+
construction allows to define ``signatures''.

\begin{figure}[h]
\begin{centerframe}
\begin{tabular}{lcl}
{\sentence} & ++= & {\record}\\
  & & \\
{\record} & ::= &
   {\tt Record} {\ident} \sequence{\binderlet}{} {\tt :} {\sort} \verb.:=. \\
&& ~~~~\zeroone{\ident}
       \verb!{! \zeroone{\nelist{\field}{;}} \verb!}! \verb:.:\\
  & & \\
{\field} & ::= & {\name} : {\type} \\
 & $|$ & {\name} {\typecstr} := {\term}
\end{tabular}
\end{centerframe}
\caption{Syntax for the definition of {\tt Record}}
\label{record-syntax}
\end{figure}

\noindent In the expression

\smallskip
{\tt Record} {\ident} {\params} \texttt{:} 
   {\sort} := {\ident$_0$} \verb+{+
 {\ident$_1$} \texttt{:} {\term$_1$}; 
              \dots
  {\ident$_n$} \texttt{:} {\term$_n$} \verb+}+.
\smallskip
 
\noindent the identifier {\ident} is the name of the defined record
and {\sort} is its type. The identifier {\ident$_0$} is the name of
its constructor. If {\ident$_0$} is omitted, the default name {\tt
Build\_{\ident}} is used. The identifiers {\ident$_1$}, ..,
{\ident$_n$} are the names of fields and {\term$_1$}, .., {\term$_n$}
their respective types. Remark that the type of {\ident$_i$} may
depend on the previous {\ident$_j$} (for $j<i$). Thus the order of the
fields is important. Finally, {\params} are the parameters of the
record.

More generally, a record may have explicitly defined (a.k.a.
manifest) fields. For instance, {\tt Record} {\ident} {\tt [}
{\params} {\tt ]} \texttt{:} {\sort} := \verb+{+ {\ident$_1$}
\texttt{:} {\type$_1$} \verb+;+ {\ident$_2$} \texttt{:=} {\term$_2$}
\verb+;+ {\ident$_3$} \texttt{:} {\type$_3$} \verb+}+ in which case
the correctness of {\type$_3$} may rely on the instance {\term$_2$} of
{\ident$_2$} and {\term$_2$} in turn may depend on {\ident$_1$}.


\Example
The set of rational numbers may be defined as:
\begin{coq_eval}
Reset Initial.
\end{coq_eval}
\begin{coq_example}
Record Rat : Set := mkRat
  {sign : bool;
   top : nat;
   bottom : nat;
   Rat_bottom_cond : 0 <> bottom;
   Rat_irred_cond :
    forall x y z:nat, (x * y) = top /\ (x * z) = bottom -> x = 1}.
\end{coq_example}

Remark here that the field
\verb+Rat_cond+ depends on the field \verb+bottom+. 

%Let us now see the work done by the {\tt Record} macro.
%First the macro generates an inductive definition
%with just one constructor:
%
%\medskip
%\noindent
%{\tt Inductive {\ident} {\binderlet} : {\sort} := \\
%\mbox{}\hspace{0.4cm} {\ident$_0$} : forall ({\ident$_1$}:{\term$_1$}) .. 
%({\ident$_n$}:{\term$_n$}), {\ident} {\rm\sl params}.}
%\medskip

Let us now see the work done by the {\tt Record} macro.  First the
macro generates an inductive definition with just one constructor:
\begin{quote}
{\tt Inductive {\ident} {\params} :{\sort} :=} \\
\qquad {\tt
  {\ident$_0$} ({\ident$_1$}:{\term$_1$}) .. ({\ident$_n$}:{\term$_n$}).}
\end{quote}
To build an object of type {\ident}, one should provide the
constructor {\ident$_0$} with $n$ terms filling the fields of
the record.

As an example, let us define the rational $1/2$:
\begin{coq_example*}
Require Import Arith.
Theorem one_two_irred :
 forall x y z:nat, x * y = 1 /\ x * z = 2 -> x = 1.
\end{coq_example*}
\begin{coq_eval}
Lemma mult_m_n_eq_m_1 : forall m n:nat, m * n = 1 -> m = 1.
destruct m; trivial.
intros; apply f_equal with (f := S).
destruct m; trivial.
destruct n; simpl in H.
 rewrite <- mult_n_O in H.
   discriminate.
 rewrite <- plus_n_Sm in H.
   discriminate.
Qed.

intros x y z [H1 H2].
 apply mult_m_n_eq_m_1 with (n := y); trivial.
\end{coq_eval}
\ldots
\begin{coq_example*}
Qed.
\end{coq_example*}
\begin{coq_example}
Definition half := mkRat true 1 2 (O_S 1) one_two_irred.
\end{coq_example}
\begin{coq_example}
Check half.
\end{coq_example}

The macro generates also, when it is possible, the projection
functions for destructuring an object of type {\ident}.  These
projection functions have the same name that the corresponding
fields. If a field is named ``\verb=_='' then no projection is built
for it.  In our example:

\begin{coq_example}
Eval compute in half.(top).
Eval compute in half.(bottom).
Eval compute in half.(Rat_bottom_cond).
\end{coq_example}
\begin{coq_eval}
Reset Initial.
\end{coq_eval}

\begin{Warnings}
\item {\tt Warning: {\ident$_i$} cannot be defined.}

  It can happen that the definition of a projection is impossible.
  This message is followed by an explanation of this impossibility.
  There may be three reasons:
   \begin{enumerate}
   \item The name {\ident$_i$} already exists in the environment (see
     Section~\ref{Axiom}).
   \item The body of {\ident$_i$} uses an incorrect elimination for
     {\ident} (see Sections~\ref{Fixpoint} and~\ref{Caseexpr}).
   \item The type of the projections {\ident$_i$} depends on previous
   projections which themselves couldn't be defined.
   \end{enumerate}  
\end{Warnings}     

\begin{ErrMsgs}

\item \errindex{A record cannot be recursive}

  The record name {\ident} appears in the type of its fields.
  
\item During the definition of the one-constructor inductive
  definition, all the errors of inductive definitions, as described in
  Section~\ref{gal_Inductive_Definitions}, may also occur.

\end{ErrMsgs}

\SeeAlso Coercions and records in Section~\ref{Coercions-and-records}
of the chapter devoted to coercions.

\Rem {\tt Structure} is a synonym of the keyword {\tt Record}.

\Rem An experimental syntax for projections based on a dot notation is
available. The command to activate it is
\begin{quote}
{\tt Set Printing Projections.}
\end{quote}

\begin{figure}[t]
\begin{centerframe}
\begin{tabular}{lcl}
{\term} & ++= & {\term} {\tt .(} {\qualid} {\tt )}\\
 & $|$ & {\term} {\tt .(} {\qualid} \nelist{\termarg}{} {\tt )}\\
 & $|$ & {\term} {\tt .(} {@}{\qualid} \nelist{\term}{} {\tt )}
\end{tabular}
\end{centerframe}
\caption{Syntax of \texttt{Record} projections}
\label{fig:projsyntax}
\end{figure}

The corresponding grammar rules are given Figure~\ref{fig:projsyntax}.
When {\qualid} denotes a projection, the syntax {\tt
  {\term}.({\qualid})} is equivalent to {\qualid~\term}, the syntax
{\tt {\term}.({\qualid}~{\termarg}$_1$~ \ldots~ {\termarg}$_n$)} to
{\qualid~{\termarg}$_1$ \ldots {\termarg}$_n$~\term}, and the syntax
{\tt {\term}.(@{\qualid}~{\term}$_1$~\ldots~{\term}$_n$)} to
{@\qualid~{\term}$_1$ \ldots {\term}$_n$~\term}. In each case, {\term}
is the object projected and the other arguments are the parameters of
the inductive type.

To deactivate the printing of projections, use 
{\tt Unset Printing Projections}.


\section{Variants and extensions of {\tt match}
\label{Extensions-of-match}
\index{match@{\tt match\ldots with\ldots end}}}

\subsection{Multiple and nested pattern-matching
\index{ML-like patterns}
\label{Mult-match}}

The basic version of \verb+match+ allows pattern-matching on simple
patterns. As an extension, multiple nested patterns or disjunction of
patterns are allowed, as in ML-like languages.

The extension just acts as a macro that is expanded during parsing
into a sequence of {\tt match} on simple patterns. Especially, a
construction defined using the extended {\tt match} is generally
printed under its expanded form (see~\texttt{Set Printing Matching} in
section~\ref{SetPrintingMatching}).

\SeeAlso chapter \ref{Mult-match-full}.

\subsection{Pattern-matching on boolean values: the {\tt if} expression
\index{if@{\tt if ... then ... else}}}

For inductive types with exactly two constructors and for
pattern-matchings expressions which do not depend on the arguments of
the constructors, it is possible to use a {\tt if ... then ... else}
notation. For instance, the definition

\begin{coq_example}
Definition not (b:bool) :=
  match b with
  | true => false
  | false => true
  end.
\end{coq_example}

can be alternatively written

\begin{coq_eval}
Reset not.
\end{coq_eval}
\begin{coq_example}
Definition not (b:bool) := if b then false else true.
\end{coq_example}

More generally, for an inductive type with constructors {\tt C$_1$}
and {\tt C$_2$}, we have the following equivalence

\smallskip

{\tt if {\term} \zeroone{\ifitem} then {\term}$_1$ else {\term}$_2$} $\equiv$
\begin{tabular}[c]{l}
{\tt match {\term} \zeroone{\ifitem} with}\\
{\tt \verb!|! C$_1$ \_ {\ldots} \_ \verb!=>! {\term}$_1$} \\
{\tt \verb!|! C$_2$ \_ {\ldots} \_ \verb!=>! {\term}$_2$} \\
{\tt end}
\end{tabular}

Here is an example.

\begin{coq_example}
Check (fun x (H:{x=0}+{x<>0}) =>
  match H with
  | left _ => true
  | right _ => false
  end).
\end{coq_example}

Notice that the printing uses the {\tt if} syntax because {\tt sumbool} is
declared as such (see section \ref{printing-options}).

\subsection{Irrefutable patterns: the destructuring {\tt let}
\index{let in@{\tt let ... in}}
\label{Letin}}



Closed terms (that is not relying on any axiom or variable) in an
inductive type having only one constructor, say {\tt foo}, have
necessarily the form \texttt{(foo ...)}. In this case, the {\tt match}
construction can be written with a syntax close to the {\tt let ... in
...}  construction. Expression {\tt let
(}~{\ident$_1$},\ldots,{\ident$_n$}~{\tt ) :=}~{\term$_0$}~{\tt
in}~{\term$_1$} performs case analysis on {\term$_0$} which must be in
an inductive type with one constructor with $n$ arguments. Variables
{\ident$_1$}\ldots{\ident$_n$} are bound to the $n$ arguments of the
constructor in expression {\term$_1$}. For instance, the definition

\begin{coq_example}
Definition fst (A B:Set) (H:A * B) := match H with
                                      | pair x y => x
                                      end.
\end{coq_example}

can be alternatively written 

\begin{coq_eval}
Reset fst.
\end{coq_eval}
\begin{coq_example}
Definition fst (A B:Set) (p:A * B) := let (x, _) := p in x.
\end{coq_example}
Note however that reduction is slightly different from regular {\tt
let ... in ...} construction since it can occur only if {\term$_0$}
can be put in constructor form. Otherwise, reduction is blocked.

The pretty-printing of a definition by matching on a
irrefutable pattern can either be done using {\tt match} or the {\tt
let} construction (see Section~\ref{printing-options}).

The general equivalence for an inductive type with one constructors {\tt C} is

\smallskip
{\tt let ({\ident}$_1$,\ldots,{\ident}$_n$) \zeroone{\ifitem} := {\term} in {\term}'} \\
$\equiv$~
{\tt match {\term} \zeroone{\ifitem} with C {\ident}$_1$ {\ldots} {\ident}$_n$ \verb!=>! {\term}' end}

\subsection{Controlling pretty-printing of {\tt match} expressions
\label{printing-options}}

The following commands give some control over the pretty-printing of
{\tt match} expressions.

\subsubsection{Printing nested patterns
\label{SetPrintingMatching}
\comindex{Set Printing Matching}
\comindex{Unset Printing Matching}
\comindex{Test Printing Matching}}

The Calculus of Inductive Constructions knows pattern-matching only
over simple patterns. It is however convenient to re-factorize nested
pattern-matching into a single pattern-matching over a nested pattern.
{\Coq}'s printer try to do such limited re-factorization.

\begin{quote}
{\tt Set Printing Matching.}
\end{quote}
This tells {\Coq} to try to use nested patterns. This is the default
behavior.

\begin{quote}
{\tt Unset Printing Matching.}
\end{quote}
This tells {\Coq} to print only simple pattern-matching problems in
the same way as the {\Coq} kernel handles them.

\begin{quote}
{\tt Test Printing Matching.}
\end{quote}
This tells if the printing matching mode is on or off. The default is
on.

\subsubsection{Printing of wildcard pattern
\comindex{Set Printing Wildcard}
\comindex{Unset Printing Wildcard}
\comindex{Test Printing Wildcard}}

Some variables in a pattern may not occur in the right-hand side of
the pattern-matching clause.  There are options to control the
display of these variables.

\begin{quote}
{\tt Set Printing Wildcard.}
\end{quote}
The variables having no occurrences in the right-hand side of the
pattern-matching clause are just printed using the wildcard symbol
``{\tt \_}''.

\begin{quote}
{\tt Unset Printing Wildcard.}
\end{quote}
The variables, even useless, are printed using their usual name. But some
non dependent variables have no name. These ones are still printed
using a ``{\tt \_}''.

\begin{quote}
{\tt Test Printing Wildcard.}
\end{quote}
This tells if the wildcard printing mode is on or off. The default is
to print wildcard for useless variables.

\subsubsection{Printing of the elimination predicate
\comindex{Set Printing Synth}
\comindex{Unset Printing Synth}
\comindex{Test Printing Synth}}

In most of the cases, the type of the result of a matched term is
mechanically synthesisable. Especially, if the result type does not
depend of the matched term.

\begin{quote}
{\tt Set Printing Synth.}
\end{quote}
The result type is not printed when {\Coq} knows that it can
re-synthesise it.

\begin{quote}
{\tt Unset Printing Synth.}
\end{quote}
This forces the result type to be always printed.

\begin{quote}
{\tt Test Printing Synth.}
\end{quote}
This tells if the non-printing of synthesisable types is on or off.
The default is to not print synthesisable types.

\subsubsection{Printing matching on irrefutable pattern
\comindex{Add Printing Let {\ident}}
\comindex{Remove Printing Let {\ident}}
\comindex{Test Printing Let {\ident}}
\comindex{Print Table Printing Let}}

If an inductive type has just one constructor,
pattern-matching can be written using {\tt let} ... {\tt :=}
... {\tt in}~...

\begin{quote}
{\tt Add Printing Let {\ident}.}
\end{quote}
This adds {\ident} to the list of inductive types for which
pattern-matching is written using a {\tt let} expression.

\begin{quote}
{\tt Remove Printing Let {\ident}.}
\end{quote}
This removes {\ident} from this list.

\begin{quote}
{\tt Test Printing Let {\ident}.}
\end{quote}
This tells if {\ident} belongs to the list.

\begin{quote}
{\tt Print Table Printing Let.}
\end{quote}
This prints the list of inductive types for which pattern-matching is
written using a {\tt let} expression.

The list of inductive types for which pattern-matching is written
using a {\tt let} expression is managed synchronously. This means that
it is sensible to the command {\tt Reset}.

\subsubsection{Printing matching on booleans
\comindex{Add Printing If {\ident}}
\comindex{Remove Printing If {\ident}}
\comindex{Test Printing If {\ident}}
\comindex{Print Table Printing If}}

If an inductive type is isomorphic to the boolean type,
pattern-matching can be written using {\tt if} ... {\tt then} ... {\tt
  else} ...

\begin{quote}
{\tt Add Printing If {\ident}.}
\end{quote}
This adds {\ident} to the list of inductive types for which
pattern-matching is written using an {\tt if} expression.

\begin{quote}
{\tt Remove Printing If {\ident}.}
\end{quote}
This removes {\ident} from this list.

\begin{quote}
{\tt Test Printing If {\ident}.}
\end{quote}
This tells if {\ident} belongs to the list.

\begin{quote}
{\tt Print Table Printing If.}
\end{quote}
This prints the list of inductive types for which pattern-matching is
written using an {\tt if} expression.

The list of inductive types for which pattern-matching is written
using an {\tt if} expression is managed synchronously. This means that
it is sensible to the command {\tt Reset}.

\subsubsection{Example}

This example emphasizes what the printing options offer.

\begin{coq_example}
Test Printing Let prod.
Print fst.
Remove Printing Let prod.
Unset Printing Synth.
Unset Printing Wildcard.
Print fst.
\end{coq_example}

% \subsection{Still not dead old notations}

% The following variant of {\tt match} is inherited from older version
% of {\Coq}. 

% \medskip
% \begin{tabular}{lcl}
% {\term} & ::= & {\annotation} {\tt Match} {\term} {\tt with} {\terms} {\tt end}\\
% \end{tabular}
% \medskip

% This syntax is a macro generating a combination of {\tt match} with {\tt
% Fix} implementing a combinator for primitive recursion equivalent to
% the {\tt Match} construction of \Coq\ V5.8. It is provided only for
% sake of compatibility with \Coq\ V5.8. It is recommended to avoid it.
% (see section~\ref{Matchexpr}).

% There is also a notation \texttt{Case} that is the
% ancestor of \texttt{match}. Again, it is still in the code for
% compatibility with old versions but the user should not use it.

% Explained in RefMan-gal.tex
%% \section{Forced type}

%% In some cases, one may wish to assign a particular type to a term. The
%% syntax to force the type of a term is the following:

%% \medskip
%% \begin{tabular}{lcl}
%% {\term} & ++= & {\term} {\tt :} {\term}\\
%% \end{tabular}
%% \medskip

%% It forces the first term to be of type the second term. The
%% type must be compatible with
%% the term. More precisely it must be either a type convertible to
%% the automatically inferred type (see chapter \ref{Cic}) or a type
%% coercible to it, (see \ref{Coercions}). When the type of a
%% whole expression is forced, it is usually not necessary to give the types of
%% the variables involved in the term.

%% Example:

%% \begin{coq_example}
%% Definition ID := forall X:Set, X -> X.
%% Definition id := (fun X x => x):ID.
%% Check id.
%% \end{coq_example}

\section{Section mechanism
\index{Sections}
\label{Section}}

The sectioning mechanism allows to organise a proof in structured
sections. Then local declarations become available (see
Section~\ref{Simpl-definitions}). 

\subsection{\tt Section {\ident}\comindex{Section}}

This command is used to open a section named {\ident}.

%% Discontinued ?
%% \begin{Variants}
%% \comindex{Chapter}
%% \item{\tt Chapter {\ident}}\\
%%         Same as {\tt Section {\ident}}
%% \end{Variants}

\subsection{\tt End {\ident}
\comindex{End}}

This command closes the section named {\ident}. When a section is
closed, all local declarations (variables and local definitions) are
{\em discharged}. This means that all global objects defined in the
section are generalised with respect to all variables and local
definitions it depends on in the section.  None of the local
declarations (considered as autonomous declarations) survive the end
of the section.

Here is an example :
\begin{coq_example}
Section s1.
Variables x y : nat.
Let y' := y.
Definition x' := S x.
Definition x'' := x' + y'.
Print x'.
End s1.
Print x'.
Print x''.
\end{coq_example}
Notice the difference between the value of {\tt x'} and {\tt x''}
inside section {\tt s1} and outside.

\begin{ErrMsgs}
\item \errindex{This is not the last opened section}
\end{ErrMsgs}

\begin{Remarks}
\item Most commands, like {\tt Hint}, {\tt Notation}, option management, ...
which appear inside a section are cancelled when the
section is closed.
% cf section \ref{LongNames}
%\item Usually all identifiers must be distinct. 
%However, a name already used in a closed section (see \ref{Section})
%can be reused. In this case, the old name is no longer accessible.

% Obsolète
%\item A module implicitly open a section. Be careful not to name a
%module with an identifier already used in the module (see \ref{compiled}).
\end{Remarks}

\input{RefMan-mod.v}

\section{Libraries and qualified names}

\subsection{Names of libraries and files
\label{Libraries}
\index{Libraries}
\index{Logical paths}}

\paragraph{Libraries}

The theories developed in {\Coq} are stored in {\em libraries}.  A
library is characterised by a name called {\it root} of the
library. The standard library of {\Coq} has root name {\tt Coq} and is
known by default when a {\Coq} session starts.

Libraries have a tree structure. E.g., the {\tt Coq} library
contains the sub-libraries {\tt Init}, {\tt Logic}, {\tt Arith}, {\tt
Lists}, ... The ``dot notation'' is used to separate the different
component of a library name. For instance, the {\tt Arith} library of
{\Coq} standard library is written ``{\tt Coq.Arith}''.

\medskip
\Rem no blank is allowed between the dot and the identifier on its
right, otherwise the dot is interpreted as the full stop (period) of
the command!
\medskip

\paragraph{Physical paths vs logical paths}

Libraries and sub-libraries are denoted by {\em logical directory
paths} (written {\dirpath} and of which the syntax is the same as
{\qualid}, see \ref{qualid}). Logical directory
paths can be mapped to physical directories of the
operating system using the command (see \ref{AddLoadPath})
\begin{quote}
{\tt Add LoadPath {\it physical\_path} as {\dirpath}}.
\end{quote}
A library can inherit the tree structure of a physical directory by
using the {\tt -R} option to {\tt coqtop} or the
command (see \ref{AddRecLoadPath})
\begin{quote}
{\tt Add Rec LoadPath {\it physical\_path} as {\dirpath}}.
\end{quote}

\Rem When used interactively with {\tt coqtop} command, {\Coq} opens a
library called {\tt Top}.

\paragraph{The file level}

At some point, (sub-)libraries contain {\it modules} which coincide
with files at the physical level.  As for sublibraries, the dot
notation is used to denote a specific module of a library. Typically,
{\tt Coq.Init.Logic} is the logical path associated to the file {\tt
  Logic.v} of {\Coq} standard library.  Notice that compilation (see
\ref{Addoc-coqc}) is done at the level of files.

If the physical directory where a file {\tt File.v} lies is mapped to
the empty logical directory path (which is the default when using the
simple form of {\tt Add LoadPath} or {\tt -I} option to coqtop), then
the name of the module it defines is {\tt File}.

\subsection{Qualified names
\label{LongNames}
\index{Qualified identifiers}
\index{Absolute names}}

Modules contain constructions (sub-modules, axioms, parameters,
definitions, lemmas, theorems, remarks or facts). The (full) name of a
construction starts with the logical name of the module in which it is defined
followed by the (short) name of the construction.
Typically, the full name {\tt Coq.Init.Logic.eq} denotes Leibniz' equality
defined in the module {\tt Logic} in the sublibrary {\tt Init} of the
standard library of \Coq.

\paragraph{Absolute, partially qualified and short names}

The full name of a library, module, section, definition, theorem,
... is its {\it absolute name}.  The last identifier ({\tt eq} in the
previous example) is its {\it short name} (or sometimes {\it base
name}). Any suffix of the absolute name is a {\em partially qualified
name} (e.g. {\tt Logic.eq} is a partially qualified name for {\tt
Coq.Init.Logic.eq}). Partially qualified names (shortly {\em
qualified name}) are also built from identifiers separated by dots.
They are written {\qualid} in the documentation.

{\Coq} does not accept two constructions (definition, theorem, ...)
with the same absolute name but different constructions can have the
same short name (or even same partially qualified names as soon as the
full names are different).

\paragraph{Visibility}

{\Coq} maintains a {\it name table} mapping qualified names to absolute
names. This table is modified by the commands {\tt Require} (see
\ref{Require}), {\tt Import} and {\tt Export} (see \ref{Import}) and
also each time a new declaration is added to the context.

An absolute name is called {\it visible} from a given short or
partially qualified name when this name suffices to denote it. This
means that the short or partially qualified name is mapped to the absolute
name in {\Coq} name table.

It may happen that a visible name is hidden by the short name or a
qualified name of another construction. In this case, the name that
has been hidden must be referred to using one more level of
qualification. Still, to ensure that a construction always remains
accessible, absolute names can never be hidden.

Examples:
\begin{coq_eval}
Reset Initial.
\end{coq_eval}
\begin{coq_example}
Check 0.
Definition nat := bool.
Check 0.
Check Datatypes.nat.
Locate nat.
\end{coq_example}

\Rem There is also a name table for sublibraries, modules and sections.

\Rem In versions prior to {\Coq} 7.4, lemmas declared with {\tt
Remark} and {\tt Fact} kept in their full name the names of the
sections in which they were defined. Since {\Coq} 7.4, they strictly
behaves as {\tt Theorem} and {\tt Lemma} do.

\SeeAlso Command {\tt Locate} in Section~\ref{Locate}.

%% \paragraph{The special case of remarks and facts}
%% 
%% In contrast with definitions, lemmas, theorems, axioms and parameters,
%% the absolute name of remarks includes the segment of sections in which
%% it is defined. Concretely, if a remark {\tt R} is defined in
%% subsection {\tt S2} of section {\tt S1} in module {\tt M}, then its
%% absolute name is {\tt M.S1.S2.R}. The same for facts, except that the
%% name of the innermost section is dropped from the full name. Then, if
%% a fact {\tt F} is defined in subsection {\tt S2} of section {\tt S1}
%% in module {\tt M}, then its absolute name is {\tt M.S1.F}.


\paragraph{Requiring a file}

A module compiled in a ``.vo'' file comes with a logical names (e.g. 
physical file \verb!theories/Init/Datatypes.vo! in the {\Coq} installation directory is bound to the logical module {\tt Coq.Init.Datatypes}). 
When requiring the file, the mapping between physical directories and logical library should be consistent with the mapping used to compile the file (for modules of the standard library, this is automatic -- check it by typing {\tt Print LoadPath}).

The command {\tt Add Rec LoadPath} is also available from {\tt coqtop}
and {\tt coqc} by using option~\verb=-R=.

\section{Implicit arguments
\index{Implicit arguments}
\label{Implicit Arguments}}

An implicit argument of a function is an argument which can be
inferred from the knowledge of the type of other arguments of the
function, or of the type of the surrounding context of the application.
Especially, an implicit argument corresponds to a parameter
dependent in the type of the function. Typical implicit
arguments are the type arguments in polymorphic functions.
More precisely, there are several kinds of implicit arguments.

\paragraph{Strict Implicit Arguments.} 
An implicit argument can be either strict or non strict. An implicit
argument is said {\em strict} if, whatever the other arguments of the
function are, it is still inferable from the type of some other
argument. Technically, an implicit argument is strict if it
corresponds to a parameter which is not applied to a variable which
itself is another parameter of the function (since this parameter
may erase its arguments), not in the body of a {\tt match}, and not
itself applied or matched against patterns (since the original
form of the argument can be lost by reduction).

For instance, the first argument of
\begin{quote}
\verb|cons: forall A:Set, A -> list A -> list A|
\end{quote}
in module {\tt List.v} is strict because {\tt list} is an inductive
type and {\tt A} will always be inferable from the type {\tt
list A} of the third argument of {\tt cons}.
On the opposite, the second argument of a term of type 
\begin{quote}
\verb|forall P:nat->Prop, forall n:nat, P n -> ex nat P|
\end{quote}
is implicit but not strict, since it can only be inferred from the
type {\tt P n} of the the third argument and if {\tt P} is e.g. {\tt
fun \_ => True}, it reduces to an expression where {\tt n} does not
occur any longer. The first argument {\tt P} is implicit but not
strict either because it can only be inferred from {\tt P n} and {\tt
P} is not canonically inferable from an arbitrary {\tt n} and the
normal form of {\tt P n} (consider e.g. that {\tt n} is {\tt 0} and
the third argument has type {\tt True}, then any {\tt P} of the form
{\tt fun n => match n with 0 => True | \_ => \mbox{\em anything} end} would
be a solution of the inference problem.

\paragraph{Contextual Implicit Arguments.} 
An implicit argument can be {\em contextual} or non. An implicit
argument is said {\em contextual} if it can be inferred only from the
knowledge of the type of the context of the current expression. For
instance, the only argument of
\begin{quote}
\verb|nil : forall A:Set, list A|
\end{quote}
is contextual. Similarly, both arguments of a term of type
\begin{quote}
\verb|forall P:nat->Prop, forall n:nat, P n \/ n = 0|
\end{quote}
are contextual (moreover, {\tt n} is strict and {\tt P} is not).

\subsection{Casual use of implicit arguments}

In a given expression, if it is clear that some argument of a function
can be inferred from the type of the other arguments, the user can
force the given argument to be guessed by replacing it by ``{\tt \_}''. If
possible, the correct argument will be automatically generated.

\begin{ErrMsgs}

\item \errindex{Cannot infer a term for this placeholder}

  {\Coq} was not able to deduce an instantiation of a ``{\tt \_}''.

\end{ErrMsgs}

\subsection{Declaration of implicit arguments for a constant
\comindex{Implicit Arguments}}

In case one wants that some arguments of a given object (constant,
inductive types, constructors, assumptions, local or not) are always
inferred by Coq, one may declare once for all which are the expected
implicit arguments of this object. The syntax is
\begin{quote}
\tt Implicit Arguments {\qualid} [ \nelist{\ident}{} ]
\end{quote}
where the list of {\ident} is the list of parameters to be declared
implicit. After this, implicit arguments can just (and have to) be
skipped in any expression involving an application of {\qualid}.

\Example
\begin{coq_eval}
Reset Initial.
\end{coq_eval}
\begin{coq_example*}
Inductive list (A:Set) : Set :=
 | nil : list A 
 | cons : A -> list A -> list A.
\end{coq_example*}
\begin{coq_example}
Check (cons nat 3 (nil nat)).
Implicit Arguments cons [A].
Implicit Arguments nil [A].
Check (cons 3 nil).
\end{coq_example}

\Rem To know which are the implicit arguments of an object, use command
{\tt Print Implicit} (see \ref{PrintImplicit}).

\Rem If the list of arguments is empty, the command removes the
implicit arguments of {\qualid}.

\subsection{Automatic declaration of implicit arguments for a constant}

{\Coq} can also automatically detect what are the implicit arguments
of a defined object. The command is just
\begin{quote}
\tt Implicit Arguments {\qualid}.
\end{quote}
The auto-detection is governed by options telling if strict and
contextual implicit arguments must be considered or not (see
Sections~\ref{SetStrictImplicit} and~\ref{SetContextualImplicit}). 

\Example
\begin{coq_eval}
Reset Initial.
\end{coq_eval}
\begin{coq_example*}
Inductive list (A:Set) : Set := 
  | nil : list A 
  | cons : A -> list A -> list A.
\end{coq_example*}
\begin{coq_example}
Implicit Arguments cons.
Print Implicit cons.
Implicit Arguments nil.
Print Implicit nil.
Set Contextual Implicit.
Implicit Arguments nil.
Print Implicit nil.
\end{coq_example}

The computation of implicit arguments takes account of the
unfolding of constants.  For instance, the variable {\tt p} below has
type {\tt (Transitivity R)} which is reducible to {\tt forall x,y:U, R x
y -> forall z:U, R y z -> R x z}. As the variables {\tt x}, {\tt y} and
{\tt z} appear strictly in body of the type, they are implicit.

\begin{coq_example*}
Variable X : Type.
Definition Relation := X -> X -> Prop.
Definition Transitivity (R:Relation) :=
  forall x y:X, R x y -> forall z:X, R y z -> R x z.
Variables (R : Relation) (p : Transitivity R).
Implicit Arguments p.
\end{coq_example*}
\begin{coq_example}
Print p.
Print Implicit p.
\end{coq_example}
\begin{coq_example*}
Variables (a b c : X) (r1 : R a b) (r2 : R b c).
\end{coq_example*}
\begin{coq_example}
Check (p r1 r2).
\end{coq_example}

\subsection{Mode for automatic declaration of implicit arguments
\label{Auto-implicit}
\comindex{Set Implicit Arguments}
\comindex{Unset Implicit Arguments}}

In case one wants to systematically declare implicit the arguments
detectable as such, one may switch to the automatic declaration of
implicit arguments mode by using the command
\begin{quote}
\tt Set Implicit Arguments.
\end{quote}
Conversely, one may unset the mode by using {\tt Unset Implicit
Arguments}.  The mode is off by default. Auto-detection of implicit
arguments is governed by options controlling whether strict and
contextual implicit arguments have to be considered or not.

\subsection{Controlling strict implicit arguments
\comindex{Set Strict Implicit}
\comindex{Unset Strict Implicit}
\label{SetStrictImplicit}}

By default, {\Coq} automatically set implicit only the strict implicit
arguments. To relax this constraint, use command 
\begin{quote}
\tt Unset Strict Implicit.
\end{quote}
Conversely, use command {\tt Set Strict Implicit} to
restore the strict implicit mode.

\Rem In versions of {\Coq} prior to version 8.0, the default was to
declare the strict implicit arguments as implicit.

\subsection{Controlling contextual implicit arguments
\comindex{Set Contextual Implicit}
\comindex{Unset Contextual Implicit}
\label{SetContextualImplicit}}

By default, {\Coq} does not automatically set implicit the contextual
implicit arguments. To tell {\Coq} to infer also contextual implicit
argument, use command  
\begin{quote}
\tt Set Contextual Implicit. 
\end{quote}
Conversely, use command {\tt Unset Contextual Implicit} to
unset the contextual implicit mode.

\subsection{Explicit applications
\index{Explicitation of implicit arguments}
\label{Implicits-explicitation}
\index{qualid@{\qualid}}}

In presence of non strict or contextual argument, or in presence of
partial applications, the synthesis of implicit arguments may fail, so
one may have to give explicitly certain implicit arguments of an
application. The syntax for this is {\tt (\ident:=\term)} where {\ident}
is the name of the implicit argument and {\term} is its corresponding
explicit term. Alternatively, one can locally deactivate the hidding of
implicit arguments of a function by using the notation
{\tt @{\qualid}~{\term}$_1$..{\term}$_n$}. This syntax extension is
given Figure~\ref{fig:explicitations}.
\begin{figure}
\begin{centerframe}
\begin{tabular}{lcl}
{\term} & ++= & @ {\qualid} \nelist{\term}{}\\
& $|$ & @ {\qualid}\\
& $|$ & {\qualid} \nelist{\textrm{\textsl{argument}}}{}\\
\\
{\textrm{\textsl{argument}}} & ::= & {\term} \\
& $|$ & {\tt ({\ident}:={\term})}\\
\end{tabular}
\end{centerframe}
\caption{Syntax for explicitations of implicit arguments}
\label{fig:explicitations}
\end{figure}

\noindent {\bf Example (continued): }
\begin{coq_example}
Check (p r1 (z:=c)).
Check (p (x:=a) (y:=b) r1 (z:=c) r2).
\end{coq_example}

\subsection{Displaying what the implicit arguments are
\comindex{Print Implicit}
\label{PrintImplicit}}

To display the implicit arguments associated to an object use command
\begin{quote}
\tt Print Implicit {\qualid}.
\end{quote}

\subsection{Explicitation of implicit arguments for pretty-printing
\comindex{Set Printing Implicit}
\comindex{Unset Printing Implicit}}

By default the basic pretty-printing rules hide the inferable implicit
arguments of an application. To force printing all implicit arguments,
use command
\begin{quote}
{\tt Set Printing Implicit.}
\end{quote}
Conversely, to restore the hidding of implicit arguments, use command
\begin{quote}
{\tt Unset Printing Implicit.}
\end{quote}

\SeeAlso {\tt Set Printing All} in section \ref{SetPrintingAll}.

\subsection{Interaction with subtyping}

When an implicit argument can be inferred from the type of more than
one of the other arguments, then only the type of the first of these
arguments is taken into account, and not an upper type of all of
them.  As a consequence, the inference of the implicit argument of
``='' fails in

\begin{coq_example*}
Check nat = Prop.
\end{coq_example*}

but succeeds in 

\begin{coq_example*}
Check Prop = nat.
\end{coq_example*}

\subsection{Canonical structures
\comindex{Canonical Structure}}

A canonical structure is an instance of a record/structure type that
can be used to solve equations involving implicit arguments. Assume
that {\qualid} denotes an object $(Build\_struc~ c_1~ \ldots~ c_n)$ in the
structure {\em struct} of which the fields are $x_1$, ...,
$x_n$. Assume that {\qualid} is declared as a canonical structure
using the command
\begin{quote}
{\tt Canonical Structure {\qualid}.}
\end{quote}
Then, each time an equation of the form $(x_i~
\_)=_{\beta\delta\iota\zeta}c_i$ has to be solved during the
type-checking process, {\qualid} is used as a solution. Otherwise
said, {\qualid} is canonically used to extend the field $c_i$ into a
complete structure built on $c_i$.

Canonical structures are particularly useful when mixed with
coercions and strict implicit arguments. Here is an example.
\begin{coq_example*}
Require Import Relations.
Require Import EqNat.
Set Implicit Arguments.
Unset Strict Implicit.
Structure Setoid : Type := 
  {Carrier :> Set;
   Equal : relation Carrier;
   Prf_equiv : equivalence Carrier Equal}.
Definition is_law (A B:Setoid) (f:A -> B) :=
  forall x y:A, Equal x y -> Equal (f x) (f y).
Axiom eq_nat_equiv : equivalence nat eq_nat.
Definition nat_setoid : Setoid := Build_Setoid eq_nat_equiv.
Canonical Structure nat_setoid.
\end{coq_example*}

Thanks to \texttt{nat\_setoid} declared as canonical, the implicit
arguments {\tt A} and {\tt B} can be synthesised in the next statement.
\begin{coq_example}
Lemma is_law_S : is_law S.
\end{coq_example}

\Rem If a same field occurs in several canonical structure, then
only the structure declared first as canonical is considered.

\begin{Variants}
\item {\tt Canonical Structure {\ident} := {\term} : {\type}.}\\
 {\tt Canonical Structure {\ident} := {\term}.}\\
 {\tt Canonical Structure {\ident} : {\type} := {\term}.}

These are equivalent to a regular definition of {\ident} followed by
the declaration 

{\tt Canonical Structure {\ident}}.
\end{Variants}

\SeeAlso more examples in user contribution \texttt{category}
(\texttt{Rocq/ALGEBRA}).

\subsubsection{Print Canonical Projections.
\comindex{Print Canonical Projections}}

This displays the list of global names that are components of some
canonical structure. For each of them, the canonical structure of
which it is a projection is indicated. For instance, the above example 
gives the following output:

\begin{coq_example}
Print Canonical Projections.
\end{coq_example}

\subsection{Implicit types of variables}

It is possible to bind variable names to a given type (e.g. in a
development using arithmetic, it may be convenient to bind the names
{\tt n} or {\tt m} to the type {\tt nat} of natural numbers). The
command for that is
\begin{quote}
\tt Implicit Types \nelist{\ident}{} : {\type}
\end{quote}
The effect of the command is to automatically set the type of bound
variables starting with {\ident} (either {\ident} itself or
{\ident} followed by one or more single quotes, underscore or digits)
to be {\type} (unless the bound variable is already declared with an
explicit type in which case, this latter type is considered).

\Example
\begin{coq_example}
Require Import List.
Implicit Types m n : nat.
Lemma cons_inj_nat : forall m n l, n :: l = m :: l -> n = m.
intros m n.
Lemma cons_inj_bool : forall (m n:bool) l, n :: l = m :: l -> n = m.
\end{coq_example}

\begin{Variants}
\item {\tt Implicit Type {\ident} : {\type}}\\
This is useful for declaring the implicit type of a single variable.
\end{Variants}

\section{Coercions
\label{Coercions}
\index{Coercions}}

Coercions can be used to implicitly inject terms from one {\em class} in
which they reside into another one. A {\em class} is either a sort
(denoted by the keyword {\tt Sortclass}), a product type (denoted by the
keyword {\tt Funclass}), or a type constructor (denoted by its name),
e.g. an inductive type or any constant with a type of the form
\texttt{forall} $(x_1:A_1) .. (x_n:A_n),~s$ where $s$ is a sort.

Then the user is able to apply an
object that is not a function, but can be coerced to a function, and
more generally to consider that a term of type A is of type B provided
that there is a declared coercion between A and B. The main command is
\comindex{Coercion}
\begin{quote}
\tt Coercion {\qualid} : {\class$_1$} >-> {\class$_2$}.
\end{quote}
which declares the construction denoted by {\qualid} as a
coercion between {\class$_1$} and {\class$_2$}.

More details and examples, and a description of the commands related
to coercions are provided in chapter \ref{Coercions-full}.

\section{Printing constructions in full}
\label{SetPrintingAll}
\comindex{Set Printing All}
\comindex{Unset Printing All}

Coercions, implicit arguments, the type of pattern-matching, but also
notations (see chapter \ref{Addoc-syntax}) can obfuscate the behavior
of some tactics (typically the tactics applying to occurrences of
subterms are sensitive to the implicit arguments). The command
\begin{quote}
{\tt Set Printing All.}
\end{quote}
deactivates all high-level printing features such as coercions,
implicit arguments, returned type of pattern-matching, notations and
various syntactic sugar for pattern-matching or record projections.
Otherwise said, {\tt Set Printing All} includes the effects
of the commands {\tt Set Printing Implicit}, {\tt Set Printing
Coercions}, {\tt Set Printing Synth}, {\tt Unset Printing Projections}
and {\tt Unset Printing Notations}.  To reactivate the high-level
printing features, use the command
\begin{quote}
{\tt Unset Printing All.}
\end{quote}

\section{Printing universes}
\label{PrintingUniverses}
\comindex{Set Printing Universes}
\comindex{Unset Printing Universes}

The following command:
\begin{quote}
{\tt Set Printing Universes}
\end{quote}
activates the display of the actual level of each occurrence of
{\Type}. See section~\ref{Sorts} for details.  This wizard option, in
combination with \texttt{Set Printing All} (see
section~\ref{SetPrintingAll}) can help to diagnose failures to unify
terms apparently identical but internally different in the Calculus of
Inductive Constructions. To reactivate the display of the actual level
of the occurrences of {\Type}, use
\begin{quote}
{\tt Unset Printing Universes.}
\end{quote}

\comindex{Print Universes}

The constraints on the internal level of the occurrences of {\Type}
(see section~\ref{Sorts}) can be printed using the command
\begin{quote}
{\tt Print Universes.}
\end{quote}


%%% Local Variables: 
%%% mode: latex
%%% TeX-master: "Reference-Manual"
%%% TeX-master: "Reference-Manual"
%%% End: 
