diff options
Diffstat (limited to 'doc/sphinx')
34 files changed, 3946 insertions, 1206 deletions
diff --git a/doc/sphinx/_static/CoqNotations.ttf b/doc/sphinx/_static/CoqNotations.ttf Binary files differnew file mode 100644 index 0000000000..da8f2850df --- /dev/null +++ b/doc/sphinx/_static/CoqNotations.ttf diff --git a/doc/sphinx/_static/UbuntuMono-Square.ttf b/doc/sphinx/_static/UbuntuMono-Square.ttf Binary files differdeleted file mode 100644 index 12b7c6d51a..0000000000 --- a/doc/sphinx/_static/UbuntuMono-Square.ttf +++ /dev/null diff --git a/doc/sphinx/_static/notations.css b/doc/sphinx/_static/notations.css index 9b7b826d58..f899945a35 100644 --- a/doc/sphinx/_static/notations.css +++ b/doc/sphinx/_static/notations.css @@ -22,10 +22,10 @@ } @font-face { /* This font has been edited to center all characters */ - font-family: 'UbuntuMono-Square'; + font-family: 'CoqNotations'; font-style: normal; font-weight: 800; - src: local('UbuntuMono-Square'), url(./UbuntuMono-Square.ttf) format('truetype'); + src: local('CoqNotations'), url(./CoqNotations.ttf) format('truetype'); } .notation .notation-sup, .notation .notation-sub { @@ -34,15 +34,15 @@ color: black; /* cursor: help; */ display: inline-block; - font-size: 0.5em; + font-size: 0.45em; font-weight: bolder; - font-family: UbuntuMono-Square, monospace; - height: 2em; + font-family: CoqNotations, monospace; + height: 2.2em; line-height: 1.6em; position: absolute; right: -1em; /* half of the width */ text-align: center; - width: 2em; + width: 2.2em; } .notation .repeat { diff --git a/doc/sphinx/addendum/extended-pattern-matching.rst b/doc/sphinx/addendum/extended-pattern-matching.rst index 64d4eddf04..1d3b661732 100644 --- a/doc/sphinx/addendum/extended-pattern-matching.rst +++ b/doc/sphinx/addendum/extended-pattern-matching.rst @@ -305,6 +305,8 @@ explicitations (as for terms 2.7.11). end). +.. _matching-dependent: + Matching objects of dependent types ----------------------------------- @@ -414,6 +416,7 @@ length, by writing I have a copy of :g:`b` in type :g:`listn 0` resp :g:`listn (S n')`. +.. _match-in-patterns: Patterns in ``in`` ~~~~~~~~~~~~~~~~~~ diff --git a/doc/sphinx/addendum/extraction.rst b/doc/sphinx/addendum/extraction.rst index d7f97edab1..38365e4035 100644 --- a/doc/sphinx/addendum/extraction.rst +++ b/doc/sphinx/addendum/extraction.rst @@ -1,16 +1,16 @@ -.. _extraction: - .. include:: ../replaces.rst -Extraction of programs in OCaml and Haskell -============================================ +.. _extraction: + +Extraction of programs in |OCaml| and Haskell +============================================= :Authors: Jean-Christophe Filliâtre and Pierre Letouzey We present here the |Coq| extraction commands, used to build certified and relatively efficient functional programs, extracting them from either |Coq| functions or |Coq| proofs of specifications. The -functional languages available as output are currently OCaml, Haskell +functional languages available as output are currently |OCaml|, Haskell and Scheme. In the following, "ML" will be used (abusively) to refer to any of the three. @@ -89,11 +89,11 @@ in the |Coq| sources. .. cmd:: Extraction TestCompile @qualid ... @qualid. All the mentioned objects and all their dependencies are extracted - to a temporary OCaml file, just as in ``Extraction "file"``. Then + to a temporary |OCaml| file, just as in ``Extraction "file"``. Then this temporary file and its signature are compiled with the same - OCaml compiler used to built |Coq|. This command succeeds only - if the extraction and the OCaml compilation succeed. It fails - if the current target language of the extraction is not OCaml. + |OCaml| compiler used to built |Coq|. This command succeeds only + if the extraction and the |OCaml| compilation succeed. It fails + if the current target language of the extraction is not |OCaml|. Extraction Options ------------------- @@ -102,26 +102,26 @@ Setting the target language ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ability to fix target language is the first and more important -of the extraction options. Default is ``Ocaml``. +of the extraction options. Default is ``OCaml``. -.. cmd:: Extraction Language Ocaml. +.. cmd:: Extraction Language OCaml. .. cmd:: Extraction Language Haskell. .. cmd:: Extraction Language Scheme. Inlining and optimizations ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Since OCaml is a strict language, the extracted code has to +Since |OCaml| is a strict language, the extracted code has to be optimized in order to be efficient (for instance, when using induction principles we do not want to compute all the recursive calls but only the needed ones). So the extraction mechanism provides an automatic optimization routine that will be called each time the user -want to generate OCaml programs. The optimizations can be split in two +want to generate |OCaml| programs. The optimizations can be split in two groups: the type-preserving ones (essentially constant inlining and reductions) and the non type-preserving ones (some function abstractions of dummy types are removed when it is deemed safe in order to have more elegant types). Therefore some constants may not appear in the -resulting monolithic OCaml program. In the case of modular extraction, +resulting monolithic |OCaml| program. In the case of modular extraction, even if some inlining is done, the inlined constant are nevertheless printed, to ensure session-independent programs. @@ -264,10 +264,9 @@ what ML term corresponds to a given axiom. be inlined everywhere instead of being declared via a ``let``. .. note:: - - This command is sugar for an ``Extract Constant`` followed - by a ``Extraction Inline``. Hence a ``Reset Extraction Inline`` - will have an effect on the realized and inlined axiom. + This command is sugar for an ``Extract Constant`` followed + by a ``Extraction Inline``. Hence a ``Reset Extraction Inline`` + will have an effect on the realized and inlined axiom. .. caution:: It is the responsibility of the user to ensure that the ML terms given to realize the axioms do have the expected types. In @@ -336,7 +335,7 @@ native boolean type instead of |Coq| one. The syntax is the following: argument is considered to have one unit argument, in order to block early evaluation of the branch: ``| O => bar`` leads to the functional form ``(fun () -> bar)``. For instance, when extracting ``nat`` - into OCaml ``int``, the code to provide has type: + into |OCaml| ``int``, the code to provide has type: ``(unit->'a)->(int->'a)->int->'a``. .. caution:: As for ``Extract Constant``, this command should be used with care: @@ -347,15 +346,15 @@ native boolean type instead of |Coq| one. The syntax is the following: * Extracting an inductive type to a pre-existing ML inductive type is quite sound. But extracting to a general type (by providing an ad-hoc pattern-matching) will often **not** be fully rigorously - correct. For instance, when extracting ``nat`` to OCaml ``int``, + correct. For instance, when extracting ``nat`` to |OCaml| ``int``, it is theoretically possible to build ``nat`` values that are - larger than OCaml ``max_int``. It is the user's responsibility to + larger than |OCaml| ``max_int``. It is the user's responsibility to be sure that no overflow or other bad events occur in practice. * Translating an inductive type to an arbitrary ML type does **not** magically improve the asymptotic complexity of functions, even if the ML type is an efficient representation. For instance, when extracting - ``nat`` to OCaml ``int``, the function ``Nat.mul`` stays quadratic. + ``nat`` to |OCaml| ``int``, the function ``Nat.mul`` stays quadratic. It might be interesting to associate this translation with some specific ``Extract Constant`` when primitive counterparts exist. @@ -369,9 +368,9 @@ Typical examples are the following: .. note:: - When extracting to Ocaml, if an inductive constructor or type has arity 2 and + When extracting to |OCaml|, if an inductive constructor or type has arity 2 and the corresponding string is enclosed by parentheses, and the string meets - Ocaml's lexical criteria for an infix symbol, then the rest of the string is + |OCaml|'s lexical criteria for an infix symbol, then the rest of the string is used as infix constructor or type. .. coqtop:: in @@ -380,7 +379,7 @@ Typical examples are the following: Extract Inductive prod => "(*)" [ "(,)" ]. As an example of translation to a non-inductive datatype, let's turn -``nat`` into OCaml ``int`` (see caveat above): +``nat`` into |OCaml| ``int`` (see caveat above): .. coqtop:: in @@ -394,7 +393,7 @@ directly depends from the names of the |Coq| files. It may happen that these filenames are in conflict with already existing files, either in the standard library of the target language or in other code that is meant to be linked with the extracted code. -For instance the module ``List`` exists both in |Coq| and in OCaml. +For instance the module ``List`` exists both in |Coq| and in |OCaml|. It is possible to instruct the extraction not to use particular filenames. .. cmd:: Extraction Blacklist @ident ... @ident. @@ -410,7 +409,7 @@ It is possible to instruct the extraction not to use particular filenames. Allow the extraction to use any filename. -For OCaml, a typical use of these commands is +For |OCaml|, a typical use of these commands is ``Extraction Blacklist String List``. Differences between |Coq| and ML type systems @@ -418,7 +417,7 @@ Differences between |Coq| and ML type systems Due to differences between |Coq| and ML type systems, some extracted programs are not directly typable in ML. -We now solve this problem (at least in OCaml) by adding +We now solve this problem (at least in |OCaml|) by adding when needed some unsafe casting ``Obj.magic``, which give a generic type ``'a`` to any term. @@ -432,7 +431,7 @@ function: Definition dp {A B:Type}(x:A)(y:B)(f:forall C:Type, C->C) := (f A x, f B y). -In Ocaml, for instance, the direct extracted term would be:: +In |OCaml|, for instance, the direct extracted term would be:: let dp x y f = Pair((f () x),(f () y)) @@ -455,12 +454,12 @@ of a constructor; for example: Inductive anything : Type := dummy : forall A:Set, A -> anything. which corresponds to the definition of an ML dynamic type. -In OCaml, we must cast any argument of the constructor dummy +In |OCaml|, we must cast any argument of the constructor dummy (no GADT are produced yet by the extraction). Even with those unsafe castings, you should never get error like ``segmentation fault``. In fact even if your program may seem -ill-typed to the Ocaml type-checker, it can't go wrong : it comes +ill-typed to the |OCaml| type-checker, it can't go wrong : it comes from a Coq well-typed terms, so for example inductive types will always have the correct number of arguments, etc. Of course, when launching manually some extracted function, you should apply it to arguments @@ -470,14 +469,14 @@ More details about the correctness of the extracted programs can be found in :cite:`Let02`. We have to say, though, that in most "realistic" programs, these problems do not -occur. For example all the programs of Coq library are accepted by the OCaml +occur. For example all the programs of Coq library are accepted by the |OCaml| type-checker without any ``Obj.magic`` (see examples below). Some examples ------------- We present here two examples of extractions, taken from the -|Coq| Standard Library. We choose OCaml as target language, +|Coq| Standard Library. We choose |OCaml| as target language, but all can be done in the other dialects with slight modifications. We then indicate where to find other examples and tests of extraction. @@ -493,7 +492,7 @@ This module contains a theorem ``eucl_dev``, whose type is:: where ``diveucl`` is a type for the pair of the quotient and the modulo, plus some logical assertions that disappear during extraction. -We can now extract this program to OCaml: +We can now extract this program to |OCaml|: .. coqtop:: none @@ -513,7 +512,7 @@ You can then copy-paste the output to a file ``euclid.ml`` or let Extraction "euclid" eucl_dev. -Let us play the resulting program (in an OCaml toplevel):: +Let us play the resulting program (in an |OCaml| toplevel):: #use "euclid.ml";; type nat = O | S of nat @@ -527,7 +526,7 @@ Let us play the resulting program (in an OCaml toplevel):: # eucl_dev (S (S O)) (S (S (S (S (S O)))));; - : diveucl = Divex (S (S O), S O) -It is easier to test on OCaml integers:: +It is easier to test on |OCaml| integers:: # let rec nat_of_int = function 0 -> O | n -> S (nat_of_int (n-1));; val nat_of_int : int -> nat = <fun> diff --git a/doc/sphinx/addendum/generalized-rewriting.rst b/doc/sphinx/addendum/generalized-rewriting.rst index da9e97e6fa..e4dea34874 100644 --- a/doc/sphinx/addendum/generalized-rewriting.rst +++ b/doc/sphinx/addendum/generalized-rewriting.rst @@ -1,14 +1,12 @@ -.. _generalizedrewriting: - ------------------------ - Generalized rewriting ------------------------ +.. include:: ../preamble.rst +.. include:: ../replaces.rst -:Author: Matthieu Sozeau +.. _generalizedrewriting: Generalized rewriting ===================== +:Author: Matthieu Sozeau This chapter presents the extension of several equality related tactics to work over user-defined structures (called setoids) that are @@ -479,7 +477,7 @@ The declaration itself amounts to the definition of an object of the record type ``Coq.Classes.RelationClasses.Equivalence`` and a hint added to the ``typeclass_instances`` hint database. Morphism declarations are also instances of a type class defined in ``Classes.Morphisms``. See the -documentation on type classes :ref:`TODO-chapter-20-type-classes` +documentation on type classes :ref:`typeclasses` and the theories files in Classes for further explanations. One can inform the rewrite tactic about morphisms and relations just @@ -539,14 +537,19 @@ Notice, however, that using the prefixed tactics it is possible to pass additional arguments such as ``using relation``. .. tacv:: setoid_reflexivity + :name: setoid_reflexivity .. tacv:: setoid_symmetry [in @ident] + :name: setoid_symmetry .. tacv:: setoid_transitivity + :name: setoid_transitivity .. tacv:: setoid_rewrite [@orientation] @term [at @occs] [in @ident] + :name: setoid_rewrite .. tacv:: setoid_replace @term with @term [in @ident] [using relation @term] [by @tactic] + :name: setoid_replace The ``using relation`` arguments cannot be passed to the unprefixed form. @@ -585,7 +588,7 @@ Deprecated syntax and backward incompatibilities Due to backward compatibility reasons, the following syntax for the declaration of setoids and morphisms is also accepted. -.. tacv:: Add Setoid @A @Aeq @ST as @ident +.. cmd:: Add Setoid @A @Aeq @ST as @ident where ``Aeq`` is a congruence relation without parameters, ``A`` is its carrier and ``ST`` is an object of type (``Setoid_Theory A Aeq``) (i.e. a record @@ -707,22 +710,20 @@ defined constants as transparent by default. This may slow down the resolution due to a lot of unifications (all the declared ``Proper`` instances are tried at each node of the search tree). To speed it up, declare your constant as rigid for proof search using the command -``Typeclasses Opaque`` (see :ref:`TODO-20.6.7-typeclasses-transparency`). - +``Typeclasses Opaque`` (see :ref:`TypeclassesTransparent`). Strategies for rewriting ------------------------ - Definitions ~~~~~~~~~~~ -The generalized rewriting tactic is based on a set of strategies that -can be combined to obtain custom rewriting procedures. Its set of -strategies is based on Elan’s rewriting strategies :ref:`TODO-102-biblio`. Rewriting +The generalized rewriting tactic is based on a set of strategies that can be +combined to obtain custom rewriting procedures. Its set of strategies is based +on Elan’s rewriting strategies :cite:`Luttik97specificationof`. Rewriting strategies are applied using the tactic ``rewrite_strat s`` where ``s`` is a -strategy expression. Strategies are defined inductively as described -by the following grammar: +strategy expression. Strategies are defined inductively as described by the +following grammar: .. productionlist:: rewriting s, t, u : `strategy` @@ -812,7 +813,7 @@ Hint databases created for ``autorewrite`` can also be used by ``rewrite_strat`` using the ``hints`` strategy that applies any of the lemmas at the current subterm. The ``terms`` strategy takes the lemma names directly as arguments. The ``eval`` strategy expects a reduction -expression (see :ref:`TODO-8.7-performing-computations`) and succeeds +expression (see :ref:`performingcomputations`) and succeeds if it reduces the subterm under consideration. The ``fold`` strategy takes a term ``c`` and tries to *unify* it to the current subterm, converting it to ``c`` on success, it is stronger than the tactic ``fold``. @@ -822,7 +823,8 @@ Usage ~~~~~ -.. tacv:: rewrite_strat @s [in @ident] +.. tacn:: rewrite_strat @s [in @ident] + :name: rewrite_strat Rewrite using the strategy s in hypothesis ident or the conclusion. diff --git a/doc/sphinx/addendum/implicit-coercions.rst b/doc/sphinx/addendum/implicit-coercions.rst index f5ca5be44a..c48c2d7ce1 100644 --- a/doc/sphinx/addendum/implicit-coercions.rst +++ b/doc/sphinx/addendum/implicit-coercions.rst @@ -1,7 +1,7 @@ -.. _implicitcoercions: - .. include:: ../replaces.rst +.. _implicitcoercions: + Implicit Coercions ==================== @@ -138,7 +138,7 @@ Declaration of Coercions .. exn:: @qualid does not respect the uniform inheritance condition .. exn:: Found target class ... instead of ... - .. warn:: Ambigous path: + .. warn:: Ambiguous path When the coercion `qualid` is added to the inheritance graph, non valid coercion paths are ignored; they are signaled by a warning @@ -166,7 +166,7 @@ Declaration of Coercions Assumptions can be declared as coercions at declaration time. This extends the grammar of assumptions from -Figure :ref:`TODO-1.3-sentences-syntax` as follows: +Figure :ref:`vernacular` as follows: .. FIXME: @@ -186,7 +186,7 @@ assumptions are declared as coercions. Similarly, constructors of inductive types can be declared as coercions at definition time of the inductive type. This extends and modifies the -grammar of inductive types from Figure :ref:`TODO-1.3-sentences-syntax` as follows: +grammar of inductive types from Figure :ref:`vernacular` as follows: .. FIXME: @@ -218,6 +218,7 @@ declaration, this constructor is declared as a coercion. Idem but locally to the current section. .. cmdv:: SubClass @ident := @type. + :name: SubClass If `type` is a class `ident'` applied to some arguments then `ident` is defined and an identity coercion of name @@ -255,48 +256,45 @@ Displaying Available Coercions Activating the Printing of Coercions ------------------------------------- -.. cmd:: Set Printing Coercions. +.. opt:: Printing Coercions - This command forces all the coercions to be printed. - Conversely, to skip the printing of coercions, use - ``Unset Printing Coercions``. By default, coercions are not printed. + When on, this option forces all the coercions to be printed. + By default, coercions are not printed. -.. cmd:: Add Printing Coercion @qualid. +.. cmd:: Add Printing Coercion @qualid - This command forces coercion denoted by `qualid` to be printed. - To skip the printing of coercion `qualid`, use - ``Remove Printing Coercion`` `qualid`. By default, a coercion is never printed. + This command forces coercion denoted by :n:`@qualid` to be printed. To skip + the printing of coercion :n:`@qualid`, use :cmd:`Remove Printing Coercion`. By + default, a coercion is never printed. +.. _coercions-classes-as-records: Classes as Records ------------------ -We allow the definition of *Structures with Inheritance* (or -classes as records) by extending the existing ``Record`` macro -(see Section :ref:`TODO-2.1-Record`). Its new syntax is: +We allow the definition of *Structures with Inheritance* (or classes as records) +by extending the existing :cmd:`Record` macro. Its new syntax is: -.. cmd:: Record {? >} @ident {? @binders} : @sort := {? @ident} { {+; @ident :{? >} @term } }. +.. cmdv:: Record {? >} @ident {? @binders} : @sort := {? @ident} { {+; @ident :{? >} @term } }. - The first identifier `ident` is the name of the defined record and - `sort` is its type. The optional identifier after ``:=`` is the name - of the constuctor (it will be ``Build_``\ `ident` if not given). - The other identifiers are the names of the fields, and the `term` - are their respective types. If ``:>`` is used instead of ``:`` in - the declaration of a field, then the name of this field is automatically - declared as a coercion from the record name to the class of this - field type. Remark that the fields always verify the uniform - inheritance condition. If the optional ``>`` is given before the - record name, then the constructor name is automatically declared as - a coercion from the class of the last field type to the record name - (this may fail if the uniform inheritance condition is not - satisfied). + The first identifier `ident` is the name of the defined record and + `sort` is its type. The optional identifier after ``:=`` is the name + of the constuctor (it will be ``Build_``\ `ident` if not given). + The other identifiers are the names of the fields, and the `term` + are their respective types. If ``:>`` is used instead of ``:`` in + the declaration of a field, then the name of this field is automatically + declared as a coercion from the record name to the class of this + field type. Remark that the fields always verify the uniform + inheritance condition. If the optional ``>`` is given before the + record name, then the constructor name is automatically declared as + a coercion from the class of the last field type to the record name + (this may fail if the uniform inheritance condition is not + satisfied). -.. note:: +.. cmdv:: Structure {? >} @ident {? @binders} : @sort := {? @ident} { {+; @ident :{? >} @term } }. + :name: Structure - The keyword ``Structure`` is a synonym of ``Record``. - -.. - FIXME: \comindex{Structure} + This is a synonym of :cmd:`Record`. Coercions and Sections @@ -312,20 +310,17 @@ coercions which do not verify the uniform inheritance condition any longer are also forgotten. Coercions and Modules ---------------------= - -From |Coq| version 8.3, the coercions present in a module are activated -only when the module is explicitly imported. Formerly, the coercions -were activated as soon as the module was required, whatever it was -imported or not. - -To recover the behavior of the versions of |Coq| prior to 8.3, use the -following command: +--------------------- -.. cmd:: Set Automatic Coercions Import. +.. opt:: Automatic Coercions Import -To cancel the effect of the option, use instead ``Unset Automatic Coercions Import``. + Since |Coq| version 8.3, the coercions present in a module are activated + only when the module is explicitly imported. Formerly, the coercions + were activated as soon as the module was required, whatever it was + imported or not. + This option makes it possible to recover the behavior of the versions of + |Coq| prior to 8.3. Examples -------- diff --git a/doc/sphinx/addendum/micromega.rst b/doc/sphinx/addendum/micromega.rst index e850587c8a..4f8cc34d4a 100644 --- a/doc/sphinx/addendum/micromega.rst +++ b/doc/sphinx/addendum/micromega.rst @@ -13,20 +13,19 @@ tactics for solving arithmetic goals over :math:`\mathbb{Z}`, :math:`\mathbb{Q}` It also possible to get the tactics for integers by a ``Require Import Lia``, rationals ``Require Import Lqa`` and reals ``Require Import Lra``. -+ ``lia`` is a decision procedure for linear integer arithmetic (see Section :ref:`lia <lia>`); -+ ``nia`` is an incomplete proof procedure for integer non-linear - arithmetic (see Section :ref:`nia <nia>`); -+ ``lra`` is a decision procedure for linear (real or rational) arithmetic - (see Section :ref:`lra <lra>`); -+ ``nra`` is an incomplete proof procedure for non-linear (real or - rational) arithmetic (see Section :ref:`nra <nra>`); -+ ``psatz D n`` where ``D`` is :math:`\mathbb{Z}` or :math:`\mathbb{Q}` or :math:`\mathbb{R}`, and ++ :tacn:`lia` is a decision procedure for linear integer arithmetic; ++ :tacn:`nia` is an incomplete proof procedure for integer non-linear + arithmetic; ++ :tacn:`lra` is a decision procedure for linear (real or rational) arithmetic; ++ :tacn:`nra` is an incomplete proof procedure for non-linear (real or + rational) arithmetic; ++ :tacn:`psatz` ``D n`` where ``D`` is :math:`\mathbb{Z}` or :math:`\mathbb{Q}` or :math:`\mathbb{R}`, and ``n`` is an optional integer limiting the proof search depth is an incomplete proof procedure for non-linear arithmetic. It is based on John Harrison’s HOL Light driver to the external prover `csdp` [#]_. Note that the `csdp` driver is generating a *proof cache* which makes it possible to rerun scripts - even without `csdp` (see Section :ref:`psatz <psatz>`). + even without `csdp`. The tactics solve propositional formulas parameterized by atomic arithmetic expressions interpreted over a domain :math:`D` ∈ {ℤ, ℚ, ℝ}. @@ -91,12 +90,13 @@ For each conjunct :math:`C_i`, the tactic calls a oracle which searches for expression* that is normalized by the ring tactic (see :ref:`theringandfieldtacticfamilies`) and checked to be :math:`-1`. -.. _lra: - `lra`: a decision procedure for linear real and rational arithmetic ------------------------------------------------------------------- -The `lra` tactic is searching for *linear* refutations using Fourier +.. tacn:: lra + :name: lra + +This tactic is searching for *linear* refutations using Fourier elimination [#]_. As a result, this tactic explores a subset of the *Cone* defined as @@ -107,16 +107,17 @@ The deductive power of `lra` is the combined deductive power of tactic *e.g.*, :math:`x = 10 * x / 10` is solved by `lra`. -.. _lia: - `lia`: a tactic for linear integer arithmetic --------------------------------------------- -The tactic lia offers an alternative to the omega and romega tactic -(see :ref:`omega`). Roughly speaking, the deductive power of lia is -the combined deductive power of `ring_simplify` and `omega`. However, it -solves linear goals that `omega` and `romega` do not solve, such as the -following so-called *omega nightmare* :cite:`TheOmegaPaper`. +.. tacn:: lia + :name: lia + +This tactic offers an alternative to the :tacn:`omega` and :tac:`romega` +tactics. Roughly speaking, the deductive power of lia is the combined deductive +power of :tacn:`ring_simplify` and :tacn:`omega`. However, it solves linear +goals that :tacn:`omega` and :tacn:`romega` do not solve, such as the following +so-called *omega nightmare* :cite:`TheOmegaPaper`. .. coqtop:: in @@ -124,8 +125,8 @@ following so-called *omega nightmare* :cite:`TheOmegaPaper`. 27 <= 11 * x + 13 * y <= 45 -> -10 <= 7 * x - 9 * y <= 4 -> False. -The estimation of the relative efficiency of `lia` *vs* `omega` and `romega` -is under evaluation. +The estimation of the relative efficiency of :tacn:`lia` *vs* :tacn:`omega` and +:tacn:`romega` is under evaluation. High level view of `lia` ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -182,12 +183,13 @@ Our current oracle tries to find an expression :math:`e` with a small range with an equation :math:`e = i` for :math:`i \in [c_1,c_2]` and recursively search for a proof. -.. _nra: - `nra`: a proof procedure for non-linear arithmetic -------------------------------------------------- -The `nra` tactic is an *experimental* proof procedure for non-linear +.. tacn:: nra + :name: nra + +This tactic is an *experimental* proof procedure for non-linear arithmetic. The tactic performs a limited amount of non-linear reasoning before running the linear prover of `lra`. This pre-processing does the following: @@ -202,21 +204,23 @@ does the following: After this pre-processing, the linear prover of `lra` searches for a proof by abstracting monomials by variables. -.. _nia: - `nia`: a proof procedure for non-linear integer arithmetic ---------------------------------------------------------- -The `nia` tactic is a proof procedure for non-linear integer arithmetic. +.. tacn:: nia + :name: nia + +This tactic is a proof procedure for non-linear integer arithmetic. It performs a pre-processing similar to `nra`. The obtained goal is solved using the linear integer prover `lia`. -.. _psatz: - `psatz`: a proof procedure for non-linear arithmetic ---------------------------------------------------- -The `psatz` tactic explores the :math:`\mathit{Cone}` by increasing degrees – hence the +.. tacn:: psatz + :name: psatz + +This tactic explores the :math:`\mathit{Cone}` by increasing degrees – hence the depth parameter :math:`n`. In theory, such a proof search is complete – if the goal is provable the search eventually stops. Unfortunately, the external oracle is using numeric (approximate) optimization techniques diff --git a/doc/sphinx/addendum/miscellaneous-extensions.rst b/doc/sphinx/addendum/miscellaneous-extensions.rst index 3ed4ce7625..80ea8a1166 100644 --- a/doc/sphinx/addendum/miscellaneous-extensions.rst +++ b/doc/sphinx/addendum/miscellaneous-extensions.rst @@ -3,15 +3,10 @@ .. _miscellaneousextensions: Miscellaneous extensions -======================= - -.. contents:: - :local: - :depth: 1 ----- +======================== Program derivation ------------------ +------------------ |Coq| comes with an extension called ``Derive``, which supports program derivation. Typically in the style of Bird and Meertens or derivations @@ -25,7 +20,7 @@ The first `ident` can appear in `term`. This command opens a new proof presenting the user with a goal for term in which the name `ident` is bound to an existential variable `?x` (formally, there are other goals standing for the existential variables but they are shelved, as -described in Section :ref:`TODO-8.17.4`). +described in :tacn:`shelve`). When the proof ends two constants are defined: diff --git a/doc/sphinx/addendum/nsatz.rst b/doc/sphinx/addendum/nsatz.rst index ef9b3505d4..387d614956 100644 --- a/doc/sphinx/addendum/nsatz.rst +++ b/doc/sphinx/addendum/nsatz.rst @@ -19,7 +19,7 @@ where :math:`P, Q, P₁,Q₁,\ldots,Pₛ, Qₛ` are polynomials and :math:`A` is domain, i.e. a commutative ring with no zero divisor. For example, :math:`A` can be :math:`\mathbb{R}`, :math:`\mathbb{Z}`, or :math:`\mathbb{Q}`. Note that the equality :math:`=` used in these goals can be -any setoid equality (see :ref:`TODO-27.2.2`) , not only Leibnitz equality. +any setoid equality (see :ref:`tactics-enabled-on-user-provided-relations`) , not only Leibnitz equality. It also proves formulas diff --git a/doc/sphinx/addendum/parallel-proof-processing.rst b/doc/sphinx/addendum/parallel-proof-processing.rst index 8c1b9d152b..edb8676a5b 100644 --- a/doc/sphinx/addendum/parallel-proof-processing.rst +++ b/doc/sphinx/addendum/parallel-proof-processing.rst @@ -39,14 +39,14 @@ Proof annotations To process a proof asynchronously |Coq| needs to know the precise statement of the theorem without looking at the proof. This requires some annotations if the theorem is proved inside a Section (see -Section :ref:`TODO-2.4`). +Section :ref:`section-mechanism`). When a section ends, |Coq| looks at the proof object to decide which section variables are actually used and hence have to be quantified in the statement of the theorem. To avoid making the construction of proofs mandatory when ending a section, one can start each proof with -the ``Proof using`` command (Section :ref:`TODO-7.1.5`) that declares which section -variables the theorem uses. +the ``Proof using`` command (Section :ref:`proof-editing-mode`) that +declares which section variables the theorem uses. The presence of ``Proof`` using is needed to process proofs asynchronously in interactive mode. diff --git a/doc/sphinx/addendum/program.rst b/doc/sphinx/addendum/program.rst index eb50e52dc7..be30d1bc4a 100644 --- a/doc/sphinx/addendum/program.rst +++ b/doc/sphinx/addendum/program.rst @@ -135,7 +135,7 @@ support types, avoiding uses of proof-irrelevance that would come up when reasoning with equality on the subset types themselves. The next two commands are similar to their standard counterparts -Definition (see Section `TODO-1.3.2-Definition`_) and Fixpoint (see Section `TODO-1.3.4-Fixpoint`_) +:cmd:`Definition` and :cmd:`Fixpoint` in that they define constants. However, they may require the user to prove some goals to construct the final definitions. @@ -151,7 +151,7 @@ Program Definition obligations. Once solved using the commands shown below, it binds the final |Coq| term to the name ``ident`` in the environment. - .. exn:: ident already exists + .. exn:: @ident already exists (Program Definition) .. cmdv:: Program Definition @ident : @type := @term @@ -174,7 +174,7 @@ Program Definition .. TODO refer to production in alias -See also: Sections `TODO-6.10.1-Opaque`_, `TODO-6.10.2-Transparent`_, `TODO-8.7.5-unfold`_ +See also: Sections :ref:`vernac-controlling-the-reduction-strategies`, :tacn:`unfold` .. _program_fixpoint: @@ -196,7 +196,7 @@ The optional order annotation follows the grammar: + :g:`wf R x` which is equivalent to :g:`measure x (R)`. The structural fixpoint operator behaves just like the one of |Coq| (see -Section `TODO-1.3.4-Fixpoint`_), except it may also generate obligations. It works +:cmd:`Fixpoint`), except it may also generate obligations. It works with mutually recursive definitions too. .. coqtop:: reset none @@ -276,6 +276,7 @@ obligations (e.g. when defining mutually recursive blocks). The optional tactic is replaced by the default one if not specified. .. cmd:: {? Local|Global} Obligation Tactic := @tactic + :name: Obligation Tactic Sets the default obligation solving tactic applied to all obligations automatically, whether to solve them or when starting to prove one, diff --git a/doc/sphinx/addendum/ring.rst b/doc/sphinx/addendum/ring.rst index b861892cbb..ae666a0d45 100644 --- a/doc/sphinx/addendum/ring.rst +++ b/doc/sphinx/addendum/ring.rst @@ -701,7 +701,7 @@ for |Coq|’s type-checker. Let us see why: At each step of rewriting, the whole context is duplicated in the proof term. Then, a tactic that does hundreds of rewriting generates huge proof terms. Since ``ACDSimpl`` was too slow, Samuel Boutin rewrote -it using reflection (see his article in TACS’97 [Bou97]_). Later, it +it using reflection (see :cite:`Bou97`). Later, it was rewritten by Patrick Loiseleur: the new tactic does not any more require ``ACDSimpl`` to compile and it makes use of |bdi|-reduction not only to replace the rewriting steps, but also to achieve the diff --git a/doc/sphinx/addendum/type-classes.rst b/doc/sphinx/addendum/type-classes.rst index 5518da9acc..3e95bd8c45 100644 --- a/doc/sphinx/addendum/type-classes.rst +++ b/doc/sphinx/addendum/type-classes.rst @@ -148,11 +148,10 @@ database. Sections and contexts --------------------- -To ease the parametrization of developments by type classes, we -provide a new way to introduce variables into section contexts, -compatible with the implicit argument mechanism. The new command works -similarly to the ``Variables`` vernacular (:ref:`TODO-1.3.2-Definitions`), except it -accepts any binding context as argument. For example: +To ease the parametrization of developments by type classes, we provide a new +way to introduce variables into section contexts, compatible with the implicit +argument mechanism. The new command works similarly to the :cmd:`Variables` +vernacular, except it accepts any binding context as argument. For example: .. coqtop:: all @@ -315,28 +314,25 @@ optional priority can be declared, 0 being the highest priority as for auto hints. If the priority is not specified, it defaults to the number of non-dependent binders of the instance. -Variants: - - -.. cmd:: Instance ident {? @binders} : forall {? @binders}, Class t1 … tn [| priority] := @term +..cmdv:: Instance @ident {? @binders} : forall {? @binders}, Class t1 … tn [| priority] := @term This syntax is used for declaration of singleton class instances or for directly giving an explicit term of type ``forall binders, Class t1 … tn``. One need not even mention the unique field name for singleton classes. -.. cmd:: Global Instance +..cmdv:: Global Instance One can use the ``Global`` modifier on instances declared in a section so that their generalization is automatically redeclared after the section is closed. -.. cmd:: Program Instance +..cmdv:: Program Instance - Switches the type-checking to Program (chapter :ref:`program`) and + Switches the type-checking to Program (chapter :ref:`programs`) and uses the obligation mechanism to manage missing fields. -.. cmd:: Declare Instance +..cmdv:: Declare Instance In a Module Type, this command states that a corresponding concrete instance should exist in any implementation of thisModule Type. This @@ -371,14 +367,10 @@ Context Declares variables according to the given binding context, which might use :ref:`implicit-generalization`. +.. tacn:: typeclasses eauto -.. _typeclasses-eauto: - -``typeclasses eauto`` -~~~~~~~~~~~~~~~~~~~~~ - -The ``typeclasses eauto`` tactic uses a different resolution engine than -eauto and auto. The main differences are the following: +This tactic uses a different resolution engine than :tacn:`eauto` and +:tacn:`auto`. The main differences are the following: + Contrary to ``eauto`` and ``auto``, the resolution is done entirely in the new proof engine (as of Coq v8.6), meaning that backtracking is @@ -429,118 +421,114 @@ Variants: typeclass subgoals the same as other subgoals (no shelving of non-typeclass goals in particular). -.. _autoapply: - -``autoapply term with ident`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. tacn:: autoapply @term with @ident + :name: autoapply -The tactic autoapply applies a term using the transparency information -of the hint database ident, and does *no* typeclass resolution. This can -be used in ``Hint Extern``’s for typeclass instances (in the hint -database ``typeclass_instances``) to allow backtracking on the typeclass -subgoals created by the lemma application, rather than doing type class -resolution locally at the hint application time. + The tactic autoapply applies a term using the transparency information + of the hint database ident, and does *no* typeclass resolution. This can + be used in :cmd:`Hint Extern`’s for typeclass instances (in the hint + database ``typeclass_instances``) to allow backtracking on the typeclass + subgoals created by the lemma application, rather than doing type class + resolution locally at the hint application time. .. _TypeclassesTransparent: Typeclasses Transparent, Typclasses Opaque ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. cmd:: Typeclasses { Transparent | Opaque } {+ @ident} +.. cmd:: Typeclasses Transparent {+ @ident} - This commands defines the transparency of the given identifiers - during type class resolution. It is useful when some constants - prevent some unifications and make resolution fail. It is also useful - to declare constants which should never be unfolded during - proof-search, like fixpoints or anything which does not look like an - abbreviation. This can additionally speed up proof search as the - typeclass map can be indexed by such rigid constants (see - :ref:`thehintsdatabasesforautoandeauto`). By default, all constants - and local variables are considered transparent. One should take care - not to make opaque any constant that is used to abbreviate a type, - like: + This command defines makes the identifiers transparent during type class + resolution. -:: + .. cmdv:: Typeclasses Opaque {+ @ident} + :name: Typeclasses Opaque + + Make the identifiers opaque for typeclass search. It is useful when some + constants prevent some unifications and make resolution fail. It is also + useful to declare constants which should never be unfolded during + proof-search, like fixpoints or anything which does not look like an + abbreviation. This can additionally speed up proof search as the typeclass + map can be indexed by such rigid constants (see + :ref:`thehintsdatabasesforautoandeauto`). + + By default, all constants and local variables are considered transparent. One + should take care not to make opaque any constant that is used to abbreviate a + type, like: - relation A := A -> A -> Prop. + :: -This is equivalent to ``Hint Transparent, Opaque ident : typeclass_instances``. + relation A := A -> A -> Prop. + This is equivalent to ``Hint Transparent, Opaque ident : typeclass_instances``. -Set Typeclasses Dependency Order -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This option (on by default since 8.6) respects the dependency order -between subgoals, meaning that subgoals which are depended on by other -subgoals come first, while the non-dependent subgoals were put before -the dependent ones previously (Coq v8.5 and below). This can result in -quite different performance behaviors of proof search. +.. opt:: Typeclasses Dependency Order + This option (on by default since 8.6) respects the dependency order + between subgoals, meaning that subgoals which are depended on by other + subgoals come first, while the non-dependent subgoals were put before + the dependent ones previously (Coq v8.5 and below). This can result in + quite different performance behaviors of proof search. -Set Typeclasses Filtered Unification -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This option, available since Coq 8.6 and off by default, switches the -hint application procedure to a filter-then-unify strategy. To apply a -hint, we first check that the goal *matches* syntactically the -inferred or specified pattern of the hint, and only then try to -*unify* the goal with the conclusion of the hint. This can drastically -improve performance by calling unification less often, matching -syntactic patterns being very quick. This also provides more control -on the triggering of instances. For example, forcing a constant to -explicitely appear in the pattern will make it never apply on a goal -where there is a hole in that place. +.. opt:: Typeclasses Filtered Unification + This option, available since Coq 8.6 and off by default, switches the + hint application procedure to a filter-then-unify strategy. To apply a + hint, we first check that the goal *matches* syntactically the + inferred or specified pattern of the hint, and only then try to + *unify* the goal with the conclusion of the hint. This can drastically + improve performance by calling unification less often, matching + syntactic patterns being very quick. This also provides more control + on the triggering of instances. For example, forcing a constant to + explicitely appear in the pattern will make it never apply on a goal + where there is a hole in that place. -Set Typeclasses Limit Intros -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Typeclasses Limit Intros -This option (on by default) controls the ability to apply hints while -avoiding (functional) eta-expansions in the generated proof term. It -does so by allowing hints that conclude in a product to apply to a -goal with a matching product directly, avoiding an introduction. -*Warning:* this can be expensive as it requires rebuilding hint -clauses dynamically, and does not benefit from the invertibility -status of the product introduction rule, resulting in potentially more -expensive proof-search (i.e. more useless backtracking). + This option (on by default) controls the ability to apply hints while + avoiding (functional) eta-expansions in the generated proof term. It + does so by allowing hints that conclude in a product to apply to a + goal with a matching product directly, avoiding an introduction. + *Warning:* this can be expensive as it requires rebuilding hint + clauses dynamically, and does not benefit from the invertibility + status of the product introduction rule, resulting in potentially more + expensive proof-search (i.e. more useless backtracking). -Set Typeclass Resolution For Conversion -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Typeclass Resolution For Conversion -This option (on by default) controls the use of typeclass resolution -when a unification problem cannot be solved during elaboration/type- -inference. With this option on, when a unification fails, typeclass -resolution is tried before launching unification once again. + This option (on by default) controls the use of typeclass resolution + when a unification problem cannot be solved during elaboration/type- + inference. With this option on, when a unification fails, typeclass + resolution is tried before launching unification once again. -Set Typeclasses Strict Resolution -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Typeclasses Strict Resolution -Typeclass declarations introduced when this option is set have a -stricter resolution behavior (the option is off by default). When -looking for unifications of a goal with an instance of this class, we -“freeze” all the existentials appearing in the goals, meaning that -they are considered rigid during unification and cannot be -instantiated. + Typeclass declarations introduced when this option is set have a + stricter resolution behavior (the option is off by default). When + looking for unifications of a goal with an instance of this class, we + “freeze” all the existentials appearing in the goals, meaning that + they are considered rigid during unification and cannot be + instantiated. -Set Typeclasses Unique Solutions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Typeclasses Unique Solutions -When a typeclass resolution is launched we ensure that it has a single -solution or fail. This ensures that the resolution is canonical, but -can make proof search much more expensive. + When a typeclass resolution is launched we ensure that it has a single + solution or fail. This ensures that the resolution is canonical, but + can make proof search much more expensive. -Set Typeclasses Unique Instances -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Typeclasses Unique Instances -Typeclass declarations introduced when this option is set have a more -efficient resolution behavior (the option is off by default). When a -solution to the typeclass goal of this class is found, we never -backtrack on it, assuming that it is canonical. + Typeclass declarations introduced when this option is set have a more + efficient resolution behavior (the option is off by default). When a + solution to the typeclass goal of this class is found, we never + backtrack on it, assuming that it is canonical. Typeclasses eauto `:=` @@ -563,7 +551,7 @@ Typeclasses eauto `:=` Set Typeclasses Debug ~~~~~~~~~~~~~~~~~~~~~ -.. cmd:: Set Typeclasses Debug {? Verbosity @num} +.. opt:: Typeclasses Debug {? Verbosity @num} These options allow to see the resolution steps of typeclasses that are performed during search. The ``Debug`` option is synonymous to ``Debug @@ -571,11 +559,10 @@ Verbosity 1``, and ``Debug Verbosity 2`` provides more information (tried tactics, shelving of goals, etc…). -Set Refine Instance Mode -~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Refine Instance Mode -The option Refine Instance Mode allows to switch the behavior of -instance declarations made through the Instance command. +This options allows to switch the behavior of instance declarations made through +the Instance command. + When it is on (the default), instances that have unsolved holes in their proof-term silently open the proof mode with the remaining diff --git a/doc/sphinx/biblio.bib b/doc/sphinx/biblio.bib index 247f32103c..97231c9ecf 100644 --- a/doc/sphinx/biblio.bib +++ b/doc/sphinx/biblio.bib @@ -675,7 +675,6 @@ s}, author = {G. Huet}, booktitle = {A perspective in Theoretical Computer Science. Commemorative Volume for Gift Siromoney}, editor = {R. Narasimhan}, - note = {Also in~\cite{CoC89}}, publisher = {World Scientific Publishing}, title = {{The Constructive Engine}}, year = {1989} @@ -791,8 +790,7 @@ Matching and Term Rewriting}, @TechReport{Leroy90, author = {X. Leroy}, - title = {The {ZINC} experiment: an economical implementation -of the {ML} language}, + title = {The {ZINC} experiment: an economical implementation of the {ML} language}, institution = {INRIA}, number = {117}, year = {1990} @@ -815,11 +813,12 @@ of the {ML} language}, } @inproceedings{Luttik97specificationof, - Author = {Sebastiaan P. Luttik and Eelco Visser}, - Booktitle = {2nd International Workshop on the Theory and Practice of Algebraic Specifications (ASF+SDF'97), Electronic Workshops in Computing}, - Publisher = {Springer-Verlag}, - Title = {Specification of Rewriting Strategies}, - Year = {1997}} + author = {Sebastiaan P. Luttik and Eelco Visser}, + booktitle = {2nd International Workshop on the Theory and Practice of Algebraic Specifications (ASF+SDF'97), Electronic Workshops in Computing}, + publisher = {Springer-Verlag}, + title = {Specification of Rewriting Strategies}, + year = {1997} +} @Book{MaL84, author = {{P. Martin-L\"of}}, diff --git a/doc/sphinx/credits.rst b/doc/sphinx/credits.rst index f3d9f57b42..a756597986 100644 --- a/doc/sphinx/credits.rst +++ b/doc/sphinx/credits.rst @@ -1373,17 +1373,16 @@ The OPAM repository for |Coq| packages has been maintained by Guillaume Melquiond, Matthieu Sozeau, Enrico Tassi with contributions from many users. A list of packages is available at https://coq.inria.fr/opam/www. -The 40 contributors for this version are Yves Bertot, Joachim -Breitner, Tej Chajed, Arthur Charguéraud, Jacques-Pascal Deplaix, Maxime -Dénès, Jim Fehrle, Yannick Forster, Gaëtan Gilbert, Jason Gross, Samuel -Gruetter, Thomas Hebb, Hugo Herbelin, Jasper Hugunin, Emilio Jesus -Gallego Arias, Ralf Jung, Johannes Kloos, Matej Košík, Robbert Krebbers, -Tony Beta Lambda, Vincent Laporte, Pierre Letouzey, Farzon Lotfi, -Cyprien Mangin, Guillaume Melquiond, Raphaël Monat, Carl Patenaude -Poulin, Pierre-Marie Pédrot, Matthew Ryan, Matt Quinn, Sigurd Schneider, -Bernhard Schommer, Matthieu Sozeau, Arnaud Spiwack, Paul Steckler, -Enrico Tassi, Anton Trunov, Martin Vassor, Vadim Zaliva and Théo -Zimmermann. +The 44 contributors for this version are Yves Bertot, Joachim Breitner, Tej +Chajed, Arthur Charguéraud, Jacques-Pascal Deplaix, Maxime Dénès, Jim Fehrle, +Julien Forest, Yannick Forster, Gaëtan Gilbert, Jason Gross, Samuel Gruetter, +Thomas Hebb, Hugo Herbelin, Jasper Hugunin, Emilio Jesus Gallego Arias, Ralf +Jung, Johannes Kloos, Matej Košík, Robbert Krebbers, Tony Beta Lambda, Vincent +Laporte, Peter LeFanu Lumsdaine, Pierre Letouzey, Farzon Lotfi, Cyprien Mangin, +Guillaume Melquiond, Raphaël Monat, Carl Patenaude Poulin, Pierre-Marie Pédrot, +Clément Pit-Claudel, Matthew Ryan, Matt Quinn, Sigurd Schneider, Bernhard +Schommer, Michael Soegtrop, Matthieu Sozeau, Arnaud Spiwack, Paul Steckler, +Enrico Tassi, Anton Trunov, Martin Vassor, Vadim Zaliva and Théo Zimmermann. Version 8.8 is the third release of |Coq| developed on a time-based development cycle. Its development spanned 6 months from the release of diff --git a/doc/sphinx/index.rst b/doc/sphinx/index.rst index 8b1d0e7230..2963306075 100644 --- a/doc/sphinx/index.rst +++ b/doc/sphinx/index.rst @@ -16,6 +16,7 @@ Table of contents .. toctree:: :caption: The language + language/gallina-specification-language language/gallina-extensions language/coq-library language/cic @@ -27,6 +28,7 @@ Table of contents proof-engine/vernacular-commands proof-engine/proof-handling proof-engine/tactics + proof-engine/ltac proof-engine/detailed-tactic-examples proof-engine/ssreflect-proof-language diff --git a/doc/sphinx/introduction.rst b/doc/sphinx/introduction.rst index 67de2ae68e..4a313df0ce 100644 --- a/doc/sphinx/introduction.rst +++ b/doc/sphinx/introduction.rst @@ -60,7 +60,7 @@ continuous reading. However, it has some structure that is explained below. - The first part describes the specification language, |Gallina|. - Chapters :ref:`thegallinaspecificationlanguage` and :ref:`extensionsofgallina` describe the concrete + Chapters :ref:`gallinaspecificationlanguage` and :ref:`extensionsofgallina` describe the concrete syntax as well as the meaning of programs, theorems and proofs in the Calculus of Inductive Constructions. Chapter :ref:`thecoqlibrary` describes the standard library of |Coq|. Chapter :ref:`calculusofinductiveconstructions` is a mathematical description @@ -76,7 +76,7 @@ below. Chapter :ref:`proofhandling`. In Chapter :ref:`tactics`, all commands that realize one or more steps of the proof are presented: we call them *tactics*. The language to combine these tactics into complex proof - strategies is given in Chapter :ref:`thetacticlanguage`. Examples of tactics + strategies is given in Chapter :ref:`ltac`. Examples of tactics are described in Chapter :ref:`detailedexamplesoftactics`. - The third part describes how to extend the syntax of |Coq|. It diff --git a/doc/sphinx/language/cic.rst b/doc/sphinx/language/cic.rst index 13d20d7cf1..5a2aa0a1f8 100644 --- a/doc/sphinx/language/cic.rst +++ b/doc/sphinx/language/cic.rst @@ -97,7 +97,7 @@ ensure the existence of a mapping of the universes to the positive integers, the graph of constraints must remain acyclic. Typing expressions that violate the acyclicity of the graph of constraints results in a Universe inconsistency error (see also Section -:ref:`TODO-2.10`). +:ref:`printing-universes`). .. _Terms: @@ -401,9 +401,11 @@ can decide if two programs are *intentionally* equal (one says *convertible*). Convertibility is described in this section. -.. _β-reduction: +.. _beta-reduction: + +β-reduction +~~~~~~~~~~~ -**β-reduction.** We want to be able to identify some terms as we can identify the application of a function to a given argument with its result. For instance the identity function over a given type T can be written @@ -427,9 +429,11 @@ theoretically of great importance but we will not detail them here and refer the interested reader to :cite:`Coq85`. -.. _ι-reduction: +.. _iota-reduction: + +ι-reduction +~~~~~~~~~~~ -**ι-reduction.** A specific conversion rule is associated to the inductive objects in the global environment. We shall give later on (see Section :ref:`Well-formed-inductive-definitions`) the precise rules but it @@ -438,9 +442,11 @@ constructor behaves as expected. This reduction is called ι-reduction and is more precisely studied in :cite:`Moh93,Wer94`. -.. _δ-reduction: +.. _delta-reduction: + +δ-reduction +~~~~~~~~~~~ -**δ-reduction.** We may have variables defined in local contexts or constants defined in the global environment. It is legal to identify such a reference with its value, that is to expand (or unfold) it into its value. This @@ -461,9 +467,11 @@ reduction is called δ-reduction and shows as follows. E[Γ] ⊢ c~\triangleright_δ~t -.. _ζ-reduction: +.. _zeta-reduction: + +ζ-reduction +~~~~~~~~~~~ -**ζ-reduction.** |Coq| allows also to remove local definitions occurring in terms by replacing the defined variable by its value. The declaration being destroyed, this reduction differs from δ-reduction. It is called @@ -478,9 +486,11 @@ destroyed, this reduction differs from δ-reduction. It is called E[Γ] ⊢ \letin{x}{u}{t}~\triangleright_ζ~\subst{t}{x}{u} -.. _η-expansion: +.. _eta-expansion: + +η-expansion +~~~~~~~~~~~ -**η-expansion.** Another important concept is η-expansion. It is legal to identify any term :math:`t` of functional type :math:`∀ x:T, U` with its so-called η-expansion @@ -517,9 +527,11 @@ for :math:`x` an arbitrary variable name fresh in :math:`t`. convertible to the type of the original term :math:`∀ x:\Type(1),\Type(1).` -.. _Convertibility: +.. _convertibility: + +Convertibility +~~~~~~~~~~~~~~ -**Convertibility.** Let us write :math:`E[Γ] ⊢ t \triangleright u` for the contextual closure of the relation :math:`t` reduces to :math:`u` in the global environment :math:`E` and local context :math:`Γ` with one of the previous @@ -709,8 +721,6 @@ called the *context of parameters*. Furthermore, we must have that each :math:`T` in :math:`(t:T)∈Γ_I` can be written as: :math:`∀Γ_P,∀Γ_{\mathit{Arr}(t)}, S` where :math:`Γ_{\mathit{Arr}(t)}` is called the *Arity* of the inductive type t and :math:`S` is called the sort of the inductive type t (not to be confused with :math:`\Sort` which is the set of sorts). - - ** Examples** The declaration for parameterized lists is: .. math:: @@ -825,8 +835,9 @@ to inconsistent systems. We restrict ourselves to definitions which satisfy a syntactic criterion of positivity. Before giving the formal rules, we need a few definitions: +Arity of a given sort ++++++++++++++++++++++ -**Type is an Arity of Sort S.** A type :math:`T` is an *arity of sort s* if it converts to the sort s or to a product :math:`∀ x:T,U` with :math:`U` an arity of sort s. @@ -836,7 +847,8 @@ product :math:`∀ x:T,U` with :math:`U` an arity of sort s. :math:`\Prop`. -**Type is an Arity.** +Arity ++++++ A type :math:`T` is an *arity* if there is a :math:`s∈ \Sort` such that :math:`T` is an arity of sort s. @@ -846,32 +858,34 @@ sort s. :math:`A→ Set` and :math:`∀ A:\Prop,A→ \Prop` are arities. -**Type of Constructor of I.** +Type constructor +++++++++++++++++ We say that T is a *type of constructor of I* in one of the following two cases: - + :math:`T` is :math:`(I~t_1 … t_n )` + :math:`T` is :math:`∀ x:U,T'` where :math:`T'` is also a type of constructor of :math:`I` - - .. example:: :math:`\nat` and :math:`\nat→\nat` are types of constructor of :math:`\nat`. :math:`∀ A:Type,\List~A` and :math:`∀ A:Type,A→\List~A→\List~A` are types of constructor of :math:`\List`. -**Positivity Condition.** +.. _positivity: + +Positivity Condition +++++++++++++++++++++ + The type of constructor :math:`T` will be said to *satisfy the positivity condition* for a constant :math:`X` in the following cases: - + :math:`T=(X~t_1 … t_n )` and :math:`X` does not occur free in any :math:`t_i` + :math:`T=∀ x:U,V` and :math:`X` occurs only strictly positively in :math:`U` and the type :math:`V` satisfies the positivity condition for :math:`X`. - -**Occurs Strictly Positively.** +Strict positivity ++++++++++++++++++ + The constant :math:`X` *occurs strictly positively* in :math:`T` in the following cases: @@ -891,11 +905,12 @@ cases: any of the :math:`t_i`, and the (instantiated) types of constructor :math:`\subst{C_i}{p_j}{a_j}_{j=1… m}` of :math:`I` satisfy the nested positivity condition for :math:`X` -**Nested Positivity Condition.** +Nested Positivity ++++++++++++++++++ + The type of constructor :math:`T` of :math:`I` *satisfies the nested positivity condition* for a constant :math:`X` in the following cases: - + :math:`T=(I~b_1 … b_m~u_1 … u_p)`, :math:`I` is an inductive definition with :math:`m` parameters and :math:`X` does not occur in any :math:`u_i` + :math:`T=∀ x:U,V` and :math:`X` occurs only strictly positively in :math:`U` and the type :math:`V` @@ -942,12 +957,11 @@ For instance, if one considers the type │ ╰─ list satisfies the positivity condition for list A ... (bullet 1) - - - .. _Correctness-rules: -**Correctness rules.** +Correctness rules ++++++++++++++++++ + We shall now describe the rules allowing the introduction of a new inductive definition. @@ -1014,7 +1028,9 @@ has type :math:`\Type(k)` with :math:`k<j` and :math:`k≤ i`. .. _Template-polymorphism: -**Template polymorphism.** +Template polymorphism ++++++++++++++++++++++ + Inductive types declared in Type are polymorphic over their arguments in Type. If :math:`A` is an arity of some sort and s is a sort, we write :math:`A_{/s}` for the arity obtained from :math:`A` by replacing its sort with s. @@ -1058,7 +1074,7 @@ provided that the following side conditions hold: we have :math:`(E[Γ_{I′} ;Γ_{P′}] ⊢ C_i : s_{q_i})_{i=1… n}` ; + the sorts :math:`s_i` are such that all eliminations, to :math:`\Prop`, :math:`\Set` and :math:`\Type(j)`, are allowed - (see Section Destructors_). + (see Section :ref:`Destructors`). @@ -1088,14 +1104,14 @@ The sorts :math:`s_j` are chosen canonically so that each :math:`s_j` is minimal respect to the hierarchy :math:`\Prop ⊂ \Set_p ⊂ \Type` where :math:`\Set_p` is predicative :math:`\Set`. More precisely, an empty or small singleton inductive definition (i.e. an inductive definition of which all inductive types are -singleton – see paragraph Destructors_) is set in :math:`\Prop`, a small non-singleton +singleton – see Section :ref:`Destructors`) is set in :math:`\Prop`, a small non-singleton inductive type is set in :math:`\Set` (even in case :math:`\Set` is impredicative – see Section The-Calculus-of-Inductive-Construction-with-impredicative-Set_), and otherwise in the Type hierarchy. Note that the side-condition about allowed elimination sorts in the rule **Ind-Family** is just to avoid to recompute the allowed elimination -sorts at each instance of a pattern-matching (see section Destructors_). As +sorts at each instance of a pattern-matching (see Section :ref:`Destructors`). As an example, let us consider the following definition: .. example:: @@ -1111,7 +1127,7 @@ in the Type hierarchy. Here, the parameter :math:`A` has this property, hence, if :g:`option` is applied to a type in :math:`\Set`, the result is in :math:`\Set`. Note that if :g:`option` is applied to a type in :math:`\Prop`, then, the result is not set in :math:`\Prop` but in :math:`\Set` still. This is because :g:`option` is not a singleton type -(see section Destructors_) and it would lose the elimination to :math:`\Set` and :math:`\Type` +(see Section :ref:`Destructors`) and it would lose the elimination to :math:`\Set` and :math:`\Type` if set in :math:`\Prop`. .. example:: @@ -1219,9 +1235,11 @@ Coquand in :cite:`Coq92`. One is the definition by pattern-matching. The second one is a definition by guarded fixpoints. -.. _The-match…with-end-construction: +.. _match-construction: + +The match ... with ... end construction ++++++++++++++++++++++++++++++++++++++++ -**The match…with …end construction** The basic idea of this operator is that we have an object :math:`m` in an inductive type :math:`I` and we want to prove a property which possibly depends on :math:`m`. For this, it is enough to prove the property for @@ -1278,7 +1296,7 @@ and :math:`I:A` and :math:`λ a x . P : B` then by :math:`[I:A|B]` we mean that :math:`λ a x . P` with :math:`m` in the above match-construct. -.. _Notations: +.. _cic_notations: **Notations.** The :math:`[I:A|B]` is defined as the smallest relation satisfying the following rules: We write :math:`[I|B]` for :math:`[I:A|B]` where :math:`A` is the type of :math:`I`. @@ -1625,9 +1643,8 @@ Given a variable :math:`y` of type an inductive definition in a declaration ones in which one of the :math:`I_l` occurs) are structurally smaller than y. -The following definitions are correct, we enter them using the ``Fixpoint`` -command as described in Section :ref:`TODO-1.3.4` and show the internal -representation. +The following definitions are correct, we enter them using the :cmd:`Fixpoint` +command and show the internal representation. .. example:: .. coqtop:: all @@ -1684,7 +1701,7 @@ possible: **Mutual induction** The principles of mutual induction can be automatically generated -using the Scheme command described in Section :ref:`TODO-13.1`. +using the Scheme command described in Section :ref:`proofschemes-induction-principles`. .. _Admissible-rules-for-global-environments: diff --git a/doc/sphinx/language/coq-library.rst b/doc/sphinx/language/coq-library.rst index 82ced65b4a..6af6e78972 100644 --- a/doc/sphinx/language/coq-library.rst +++ b/doc/sphinx/language/coq-library.rst @@ -19,7 +19,7 @@ The |Coq| library is structured into two parts: developments of |Coq| axiomatizations about sets, lists, sorting, arithmetic, etc. This library comes with the system and its modules are directly accessible through the ``Require`` command (see - Section :ref:`TODO-6.5.1-Require`); + Section :ref:`compiled-files`); In addition, user-provided libraries or developments are provided by |Coq| users' community. These libraries and developments are available @@ -48,6 +48,7 @@ at the |Coq| root directory; this includes the modules ``Tactics``. Module ``Logic_Type`` also makes it in the initial state. +.. _init-notations: Notations ~~~~~~~~~ @@ -90,6 +91,8 @@ Notation Precedence Associativity ``_ ^ _`` 30 right ================ ============ =============== +.. _coq-library-logic: + Logic ~~~~~ @@ -521,7 +524,7 @@ provides a scope ``nat_scope`` gathering standard notations for common operations (``+``, ``*``) and a decimal notation for numbers, allowing for instance to write ``3`` for :g:`S (S (S O)))`. This also works on the left hand side of a ``match`` expression (see for example -section :ref:`TODO-refine-example`). This scope is opened by default. +section :tacn:`refine`). This scope is opened by default. .. example:: @@ -753,7 +756,7 @@ subdirectories: These directories belong to the initial load path of the system, and the modules they provide are compiled at installation time. So they are directly accessible with the command ``Require`` (see -Section :ref:`TODO-6.5.1-Require`). +Section :ref:`compiled-files`). The different modules of the |Coq| standard library are documented online at http://coq.inria.fr/stdlib. @@ -927,9 +930,8 @@ tactics (see Chapter :ref:`tactics`), there are also: Goal forall x y z:R, x * y * z <> 0. intros; split_Rmult. -These tactics has been written with the tactic language Ltac -described in Chapter :ref:`thetacticlanguage`. - +These tactics has been written with the tactic language |Ltac| +described in Chapter :ref:`ltac`. List library ~~~~~~~~~~~~ diff --git a/doc/sphinx/language/gallina-extensions.rst b/doc/sphinx/language/gallina-extensions.rst index 6877759806..1a7628d893 100644 --- a/doc/sphinx/language/gallina-extensions.rst +++ b/doc/sphinx/language/gallina-extensions.rst @@ -148,7 +148,7 @@ available: It can be activated for printing with -.. cmd:: Set Printing Projections. +.. opt:: Printing Projections .. example:: @@ -183,7 +183,7 @@ other arguments are the parameters of the inductive type. .. note:: Induction schemes are automatically generated for inductive records. Automatic generation of induction schemes for non-recursive records defined with the ``Record`` keyword can be activated with the - ``Nonrecursive Elimination Schemes`` option (see :ref:`TODO-13.1.1-nonrecursive-elimination-schemes`). + ``Nonrecursive Elimination Schemes`` option (see :ref:`proofschemes-induction-principles`). .. note:: ``Structure`` is a synonym of the keyword ``Record``. @@ -193,9 +193,9 @@ other arguments are the parameters of the inductive type. This message is followed by an explanation of this impossibility. There may be three reasons: - #. The name `ident` already exists in the environment (see Section :ref:`TODO-1.3.1-axioms`). + #. The name `ident` already exists in the environment (see :cmd:`Axiom`). #. The body of `ident` uses an incorrect elimination for - `ident` (see Sections :ref:`TODO-1.3.4-fixpoint` and :ref:`TODO-4.5.3-case-expr`). + `ident` (see :cmd:`Fixpoint` and :ref:`Destructors`). #. The type of the projections `ident` depends on previous projections which themselves could not be defined. @@ -212,9 +212,9 @@ other arguments are the parameters of the inductive type. During the definition of the one-constructor inductive definition, all the errors of inductive definitions, as described in Section -:ref:`TODO-1.3.3-inductive-definitions`, may also occur. +:ref:`gallina-inductive-definitions`, may also occur. -**See also** Coercions and records in Section :ref:`TODO-18.9-coercions-and-records` of the chapter devoted to coercions. +**See also** Coercions and records in Section :ref:`coercions-classes-as-records` of the chapter devoted to coercions. .. _primitive_projections: @@ -249,7 +249,7 @@ printing of pattern-matching over primitive records. Primitive Record Types ++++++++++++++++++++++ -When the ``Set Primitive Projections`` option is on, definitions of +When the :opt:`Primitive Projections` option is on, definitions of record types change meaning. When a type is declared with primitive projections, its :g:`match` construct is disabled (see :ref:`primitive_projections` though). To eliminate the (co-)inductive type, one must use its defined primitive projections. @@ -316,7 +316,7 @@ printed back as :g:`match` constructs. Variants and extensions of :g:`match` ------------------------------------- -.. _extended pattern-matching: +.. _mult-match: Multiple and nested pattern-matching ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -328,10 +328,11 @@ patterns are allowed, as in ML-like languages. The extension just acts as a macro that is expanded during parsing into a sequence of match on simple patterns. Especially, a construction defined using the extended match is generally printed -under its expanded form (see ``Set Printing Matching`` in :ref:`controlling-match-pp`). +under its expanded form (see :opt:`Printing Matching`). -See also: :ref:`extended pattern-matching`. +See also: :ref:`extendedpatternmatching`. +.. _if-then-else: Pattern-matching on boolean values: the if expression ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -626,7 +627,7 @@ The following experimental command is available when the ``FunInd`` library has This command can be seen as a generalization of ``Fixpoint``. It is actually a wrapper for several ways of defining a function *and other useful related objects*, namely: an induction principle that reflects the recursive -structure of the function (see Section :ref:`TODO-8.5.5-functional-induction`) and its fixpoint equality. +structure of the function (see :tacn:`function induction`) and its fixpoint equality. The meaning of this declaration is to define a function ident, similarly to ``Fixpoint`. Like in ``Fixpoint``, the decreasing argument must be given (unless the function is not recursive), but it might not @@ -639,8 +640,8 @@ The ``Function`` construction also enjoys the ``with`` extension to define mutually recursive definitions. However, this feature does not work for non structurally recursive functions. -See the documentation of functional induction (:ref:`TODO-8.5.5-functional-induction`) -and ``Functional Scheme`` (:ref:`TODO-13.2-functional-scheme`) for how to use +See the documentation of functional induction (:tacn:`function induction`) +and ``Functional Scheme`` (:ref:`functional-scheme`) for how to use the induction principle to easily reason about the function. Remark: To obtain the right principle, it is better to put rigid @@ -711,7 +712,7 @@ terminating functions. `functional inversion` will not be available for the function. -See also: :ref:`TODO-13.2-generating-ind-principles` and ref:`TODO-8.5.5-functional-induction` +See also: :ref:`functional-scheme` and :tacn:`function induction` Depending on the ``{…}`` annotation, different definition mechanisms are used by ``Function``. A more precise description is given below. @@ -722,7 +723,7 @@ used by ``Function``. A more precise description is given below. the following are defined: + `ident_rect`, `ident_rec` and `ident_ind`, which reflect the pattern - matching structure of `term` (see the documentation of :ref:`TODO-1.3.3-Inductive`); + matching structure of `term` (see :cmd:`Inductive`); + The inductive `R_ident` corresponding to the graph of `ident` (silently); + `ident_complete` and `ident_correct` which are inversion information linking the function and its graph. @@ -771,13 +772,14 @@ used by ``Function``. A more precise description is given below. hand. Remark: Proof obligations are presented as several subgoals belonging to a Lemma `ident`\ :math:`_{\sf tcc}`. +.. _section-mechanism: Section mechanism ----------------- The sectioning mechanism can be used to to organize a proof in structured sections. Then local declarations become available (see -Section :ref:`TODO-1.3.2-Definitions`). +Section :ref:`gallina-definitions`). .. cmd:: Section @ident. @@ -847,7 +849,7 @@ together, as well as a means of massive abstraction. In the syntax of module application, the ! prefix indicates that any `Inline` directive in the type of the functor arguments will be ignored -(see :ref:`named_module_type` below). +(see the ``Module Type`` command below). .. cmd:: Module @ident. @@ -933,8 +935,6 @@ Reserved commands inside an interactive module is equivalent to an interactive module where each `module_expression` is included. -.. _named_module_type: - .. cmd:: Module Type @ident. This command is used to start an interactive module type `ident`. @@ -955,7 +955,8 @@ Reserved commands inside an interactive module type: is a shortcut for the command ``Include`` `module` for each `module`. -.. cmd:: @assumption_keyword Inline @assums. +.. cmd:: @assumption_keyword Inline @assums + :name: Inline The instance of this assumption will be automatically expanded at functor application, except when this functor application is prefixed by a ``!`` annotation. @@ -1195,7 +1196,7 @@ component is equal ``nat`` and hence ``M1.T`` as specified. Check T. Some features defined in modules are activated only when a module is -imported. This is for instance the case of notations (see :ref:`TODO-12.1-Notations`). +imported. This is for instance the case of notations (see :ref:`Notations`). Declarations made with the Local flag are never imported by theImport command. Such declarations are only accessible through their fully @@ -1241,13 +1242,11 @@ qualified name. This option (off by default) disables the printing of the types of fields, leaving only their names, for the commands ``Print Module`` and ``Print Module Type``. -.. cmd:: Locate Module @qualid. - - Prints the full name of the module `qualid`. - Libraries and qualified names --------------------------------- +.. _names-of-libraries: + Names of libraries ~~~~~~~~~~~~~~~~~~ @@ -1255,15 +1254,16 @@ The theories developed in |Coq| are stored in *library files* which are hierarchically classified into *libraries* and *sublibraries*. To express this hierarchy, library names are represented by qualified identifiers qualid, i.e. as list of identifiers separated by dots (see -:ref:`TODO-1.2.3-identifiers`). For instance, the library file ``Mult`` of the standard +:ref:`gallina-identifiers`). For instance, the library file ``Mult`` of the standard |Coq| library ``Arith`` is named ``Coq.Arith.Mult``. The identifier that starts the name of a library is called a *library root*. All library files of the standard library of |Coq| have the reserved root |Coq| but library file names based on other roots can be obtained by using |Coq| commands -(coqc, coqtop, coqdep, …) options ``-Q`` or ``-R`` (see :ref:`TODO-14.3.3-command-line-options`). +(coqc, coqtop, coqdep, …) options ``-Q`` or ``-R`` (see :ref:`command-line-options`). Also, when an interactive |Coq| session starts, a library of root ``Top`` is -started, unless option ``-top`` or ``-notop`` is set (see :ref:`TODO-14.3.3-command-line-options`). +started, unless option ``-top`` or ``-notop`` is set (see :ref:`command-line-options`). +.. _qualified-names: Qualified names ~~~~~~~~~~~~~~~ @@ -1298,13 +1298,13 @@ names also applies to library file names. |Coq| maintains a table called the name table which maps partially qualified names of constructions to absolute names. This table is updated by the -commands ``Require`` (see :ref:`TODO-6.5.1-Require`), Import and Export (see :ref:`import_qualid`) and +commands :cmd:`Require`, :cmd:`Import` and :cmd:`Export` and also each time a new declaration is added to the context. An absolute name is called visible from a given short or partially qualified name when this latter name is enough to denote it. This means that the short or partially qualified name is mapped to the absolute name in |Coq| name table. Definitions flagged as Local are only accessible with -their fully qualified name (see :ref:`TODO-1.3.2-definitions`). +their fully qualified name (see :ref:`gallina-definitions`). 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 @@ -1326,16 +1326,15 @@ accessible, absolute names can never be hidden. Locate nat. -See also: Command Locate in :ref:`TODO-6.3.10-locate-qualid` and Locate Library in -:ref:`TODO-6.6.11-locate-library`. +See also: Commands :cmd:`Locate` and :cmd:`Locate Library`. +.. _libraries-and-filesystem: Libraries and filesystem ~~~~~~~~~~~~~~~~~~~~~~~~ -Please note that the questions described here have been subject to -redesign in |Coq| v8.5. Former versions of |Coq| use the same terminology -to describe slightly different things. +.. note:: The questions described here have been subject to redesign in |Coq| 8.5. + Former versions of |Coq| use the same terminology to describe slightly different things. Compiled files (``.vo`` and ``.vio``) store sub-libraries. In order to refer to them inside |Coq|, a translation from file-system names to |Coq| names @@ -1371,7 +1370,7 @@ translation and with an empty logical prefix. The command line option ``-R`` is a variant of ``-Q`` which has the strictly same behavior regarding loadpaths, but which also makes the corresponding ``.vo`` files available through their short names in a way -not unlike the ``Import`` command (see :ref:`import_qualid`). For instance, ``-R`` `path` ``Lib`` +not unlike the ``Import`` command (see :ref:`here <import_qualid>`). For instance, ``-R`` `path` ``Lib`` associates to the ``filepath/fOO/Bar/File.vo`` the logical name ``Lib.fOO.Bar.File``, but allows this file to be accessed through the short names ``fOO.Bar.File,Bar.File`` and ``File``. If several files with @@ -1379,7 +1378,7 @@ identical base name are present in different subdirectories of a recursive loadpath, which of these files is found first may be system- dependent and explicit qualification is recommended. The ``From`` argument of the ``Require`` command can be used to bypass the implicit shortening -by providing an absolute root to the required file (see :ref:`TODO-6.5.1-require-qualid`). +by providing an absolute root to the required file (see :ref:`compiled-files`). There also exists another independent loadpath mechanism attached to OCaml object files (``.cmo`` or ``.cmxs``) rather than |Coq| object @@ -1387,11 +1386,12 @@ files as described above. The OCaml loadpath is managed using the option ``-I`` `path` (in the OCaml world, there is neither a notion of logical name prefix nor a way to access files in subdirectories of path). See the command ``Declare`` ``ML`` ``Module`` in -:ref:`TODO-6.5-compiled-files` to understand the need of the OCaml loadpath. +:ref:`compiled-files` to understand the need of the OCaml loadpath. -See :ref:`TODO-14.3.3-command-line-options` for a more general view over the |Coq| command +See :ref:`command-line-options` for a more general view over the |Coq| command line options. +.. _ImplicitArguments: Implicit arguments ------------------ @@ -1507,10 +1507,10 @@ inserted. In the second case, the function is considered to be implicitly applied to the implicit arguments it is waiting for: one says that the implicit argument is maximally inserted. -Each implicit argument can be declared to have to be inserted -maximally or non maximally. This can be governed argument per argument -by the command ``Implicit Arguments`` (see Section :ref:`declare-implicit-args`) or globally by the -command ``Set Maximal Implicit Insertion`` (see Section :ref:`controlling-insertion-implicit-args`). +Each implicit argument can be declared to have to be inserted maximally or non +maximally. This can be governed argument per argument by the command ``Implicit +Arguments`` (see Section :ref:`declare-implicit-args`) or globally by the +:opt:`Maximal Implicit Insertion` option. See also :ref:`displaying-implicit-args`. @@ -1586,6 +1586,7 @@ Declaring Implicit Arguments To set implicit arguments *a posteriori*, one can use the command: .. cmd:: Arguments @qualid {* @possibly_bracketed_ident }. + :name: Arguments (implicits) where the list of `possibly_bracketed_ident` is a prefix of the list of arguments of `qualid` where the ones to be declared implicit are @@ -1799,6 +1800,8 @@ declares implicit arguments to be automatically inserted when a function is partially applied and the next argument of the function is an implicit one. +.. _explicit-applications: + Explicit applications ~~~~~~~~~~~~~~~~~~~~~ @@ -1880,7 +1883,7 @@ arguments that are not detected as strict implicit arguments. This “defensive” mode can quickly make the display cumbersome so this can be deactivated by turning this option off. -See also: ``Set Printing All`` in :ref:`printing_constructions_full`. +See also: :opt:`Printing All`. Interaction with subtyping ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -2098,6 +2101,7 @@ implicitly, as maximally-inserted arguments. In these binders, the binding name for the bound object is optional, whereas the type is mandatory, dually to regular binders. +.. _Coercions: Coercions --------- @@ -2131,26 +2135,29 @@ sensitive to the implicit arguments). Turning this option on 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, ``Set Printing All`` includes the effects of the commands -``Set Printing Implicit``, ``Set Printing Coercions``, ``Set Printing Synth``, -``Unset Printing Projections``, and ``Unset Printing Notations``. To reactivate +Otherwise said, :opt:`Printing All` includes the effects of the options +:opt:`Printing Implicit`, :opt:`Printing Coercions`, :opt:`Printing Synth`, +:opt:`Printing Projections`, and :opt:`Printing Notations`. To reactivate the high-level printing features, use the command ``Unset Printing All``. +.. _printing-universes: + Printing universes ------------------ .. opt:: Printing Universes. -Turn this option on to activate the display of the actual level of each occurrence of ``Type``. -See :ref:`TODO-4.1.1-sorts` for details. This wizard option, in combination -with ``Set Printing All`` (see :ref:`printing_constructions_full`) can help to diagnose failures -to unify terms apparently identical but internally different in the -Calculus of Inductive Constructions. +Turn this option on to activate the display of the actual level of each +occurrence of :g:`Type`. See :ref:`Sorts` for details. This wizard option, in +combination with :opt:`Printing All` can help to diagnose failures to unify +terms apparently identical but internally different in the Calculus of Inductive +Constructions. The constraints on the internal level of the occurrences of Type -(see :ref:`TODO-4.1.1-sorts`) can be printed using the command +(see :ref:`Sorts`) can be printed using the command .. cmd:: Print {? Sorted} Universes. + :name: Print Universes If the optional ``Sorted`` option is given, each universe will be made equivalent to a numbered label reflecting its level (with a linear @@ -2158,12 +2165,13 @@ ordering) in the universe hierarchy. This command also accepts an optional output filename: -.. cmd:: Print {? Sorted} Universes @string. +.. cmdv:: Print {? Sorted} Universes @string. If `string` ends in ``.dot`` or ``.gv``, the constraints are printed in the DOT language, and can be processed by Graphviz tools. The format is unspecified if `string` doesn’t end in ``.dot`` or ``.gv``. +.. _existential-variables: Existential variables --------------------- @@ -2173,9 +2181,9 @@ subterms to eventually be replaced by actual subterms. Existential variables are generated in place of unsolvable implicit arguments or “_” placeholders when using commands such as ``Check`` (see -Section :ref:`TODO-6.3.1-check`) or when using tactics such as ``refine`` (see Section -:ref:`TODO-8.2.3-refine`), as well as in place of unsolvable instances when using -tactics such that ``eapply`` (see Section :ref:`TODO-8.2.4-apply`). An existential +Section :ref:`requests-to-the-environment`) or when using tactics such as +:tacn:`refine`, as well as in place of unsolvable instances when using +tactics such that :tacn:`eapply`. An existential variable is defined in a context, which is the context of variables of the placeholder which generated the existential variable, and a type, which is the expected type of the placeholder. @@ -2220,7 +2228,7 @@ existential variable used in the same context as its context of definition is wr Existential variables can be named by the user upon creation using the syntax ``?``\ `ident`. This is useful when the existential variable needs to be explicitly handled later in the script (e.g. -with a named-goal selector, see :ref:`TODO-9.2-goal-selectors`). +with a named-goal selector, see :ref:`goal-selectors`). .. _explicit-display-existentials: @@ -2245,7 +2253,7 @@ is not specified and is implementation-dependent. The inner tactic may use any variable defined in its scope, including repeated alternations between variables introduced by term binding as well as those introduced by tactic binding. The expression `tacexpr` can be any tactic -expression as described in :ref:`thetacticlanguage`. +expression as described in :ref:`ltac`. .. coqtop:: all @@ -2256,5 +2264,5 @@ using highly automated tactics without resorting to writing the proof-term by means of the interactive proof engine. This mechanism is comparable to the ``Declare Implicit Tactic`` command -defined at :ref:`TODO-8.9.7-implicit-automation`, except that the used +defined at :ref:`tactics-implicit-automation`, except that the used tactic is local to each hole instead of being declared globally. diff --git a/doc/sphinx/language/gallina-specification-language.rst b/doc/sphinx/language/gallina-specification-language.rst new file mode 100644 index 0000000000..a9c4dd7588 --- /dev/null +++ b/doc/sphinx/language/gallina-specification-language.rst @@ -0,0 +1,1376 @@ +.. _gallinaspecificationlanguage: + +------------------------------------ + The Gallina specification language +------------------------------------ + +This chapter describes Gallina, the specification language of Coq. It allows +developing mathematical theories and to prove specifications of programs. The +theories are built from axioms, hypotheses, parameters, lemmas, theorems and +definitions of constants, functions, predicates and sets. The syntax of logical +objects involved in theories is described in Section :ref:`term`. The +language of commands, called *The Vernacular* is described in Section +:ref:`vernacular`. + +In Coq, logical objects are typed to ensure their logical correctness. The +rules implemented by the typing algorithm are described in Chapter :ref:`calculusofinductiveconstructions`. + + +About the grammars in the manual +================================ + +Grammars are presented in Backus-Naur form (BNF). Terminal symbols are +set in black ``typewriter font``. In addition, there are special notations for +regular expressions. + +An expression enclosed in square brackets ``[…]`` means at most one +occurrence of this expression (this corresponds to an optional +component). + +The notation “``entry sep … sep entry``” stands for a non empty sequence +of expressions parsed by entry and separated by the literal “``sep``” [1]_. + +Similarly, the notation “``entry … entry``” stands for a non empty +sequence of expressions parsed by the “``entry``” entry, without any +separator between. + +At the end, the notation “``[entry sep … sep entry]``” stands for a +possibly empty sequence of expressions parsed by the “``entry``” entry, +separated by the literal “``sep``”. + + +Lexical conventions +=================== + +Blanks + Space, newline and horizontal tabulation are considered as blanks. + Blanks are ignored but they separate tokens. + +Comments + Comments in Coq are enclosed between ``(*`` and ``*)``, and can be nested. + They can contain any character. However, string literals must be + correctly closed. Comments are treated as blanks. + +Identifiers and access identifiers + Identifiers, written ident, are sequences of letters, digits, ``_`` and + ``'``, that do not start with a digit or ``'``. That is, they are + recognized by the following lexical class: + + .. productionlist:: coq + first_letter : a..z ∣ A..Z ∣ _ ∣ unicode-letter + subsequent_letter : a..z ∣ A..Z ∣ 0..9 ∣ _ ∣ ' ∣ unicode-letter ∣ unicode-id-part + ident : `first_letter` [`subsequent_letter` … `subsequent_letter`] + access_ident : . `ident` + + All characters are meaningful. In particular, identifiers are case- + sensitive. The entry ``unicode-letter`` non-exhaustively includes Latin, + Greek, Gothic, Cyrillic, Arabic, Hebrew, Georgian, Hangul, Hiragana + and Katakana characters, CJK ideographs, mathematical letter-like + symbols, hyphens, non-breaking space, … The entry ``unicode-id-part`` non- + exhaustively includes symbols for prime letters and subscripts. + + Access identifiers, written :token:`access_ident`, are identifiers prefixed by + `.` (dot) without blank. They are used in the syntax of qualified + identifiers. + +Natural numbers and integers + Numerals are sequences of digits. Integers are numerals optionally + preceded by a minus sign. + + .. productionlist:: coq + digit : 0..9 + num : `digit` … `digit` + integer : [-] `num` + +Strings + Strings are delimited by ``"`` (double quote), and enclose a sequence of + any characters different from ``"`` or the sequence ``""`` to denote the + double quote character. In grammars, the entry for quoted strings is + :production:`string`. + +Keywords + The following identifiers are reserved keywords, and cannot be + employed otherwise:: + + _ as at cofix else end exists exists2 fix for + forall fun if IF in let match mod Prop return + Set then Type using where with + +Special tokens + The following sequences of characters are special tokens:: + + ! % & && ( () ) * + ++ , - -> . .( .. + / /\ : :: :< := :> ; < <- <-> <: <= <> = + => =_D > >-> >= ? ?= @ [ \/ ] ^ { | |- + || } ~ + + Lexical ambiguities are resolved according to the “longest match” + rule: when a sequence of non alphanumerical characters can be + decomposed into several different ways, then the first token is the + longest possible one (among all tokens defined at this moment), and so + on. + +.. _term: + +Terms +===== + +Syntax of terms +--------------- + +The following grammars describe the basic syntax of the terms of the +*Calculus of Inductive Constructions* (also called Cic). The formal +presentation of Cic is given in Chapter :ref:`calculusofinductiveconstructions`. Extensions of this syntax +are given in Chapter :ref:`extensionsofgallina`. How to customize the syntax +is described in Chapter :ref:`syntaxextensionsandinterpretationscopes`. + +.. productionlist:: coq + term : forall `binders` , `term` + : | fun `binders` => `term` + : | fix `fix_bodies` + : | cofix `cofix_bodies` + : | let `ident` [`binders`] [: `term`] := `term` in `term` + : | let fix `fix_body` in `term` + : | let cofix `cofix_body` in `term` + : | let ( [`name` , … , `name`] ) [`dep_ret_type`] := `term` in `term` + : | let ' `pattern` [in `term`] := `term` [`return_type`] in `term` + : | if `term` [`dep_ret_type`] then `term` else `term` + : | `term` : `term` + : | `term` <: `term` + : | `term` :> + : | `term` -> `term` + : | `term` arg … arg + : | @ `qualid` [`term` … `term`] + : | `term` % `ident` + : | match `match_item` , … , `match_item` [`return_type`] with + : [[|] `equation` | … | `equation`] end + : | `qualid` + : | `sort` + : | num + : | _ + : | ( `term` ) + arg : `term` + : | ( `ident` := `term` ) + binders : `binder` … `binder` + binder : `name` + : | ( `name` … `name` : `term` ) + : | ( `name` [: `term`] := `term` ) + name : `ident` | _ + qualid : `ident` | `qualid` `access_ident` + sort : Prop | Set | Type + fix_bodies : `fix_body` + : | `fix_body` with `fix_body` with … with `fix_body` for `ident` + cofix_bodies : `cofix_body` + : | `cofix_body` with `cofix_body` with … with `cofix_body` for `ident` + fix_body : `ident` `binders` [annotation] [: `term`] := `term` + cofix_body : `ident` [`binders`] [: `term`] := `term` + annotation : { struct `ident` } + match_item : `term` [as `name`] [in `qualid` [`pattern` … `pattern`]] + dep_ret_type : [as `name`] `return_type` + return_type : return `term` + equation : `mult_pattern` | … | `mult_pattern` => `term` + mult_pattern : `pattern` , … , `pattern` + pattern : `qualid` `pattern` … `pattern` + : | @ `qualid` `pattern` … `pattern` + : | `pattern` as `ident` + : | `pattern` % `ident` + : | `qualid` + : | _ + : | num + : | ( `or_pattern` , … , `or_pattern` ) + or_pattern : `pattern` | … | `pattern` + + +Types +----- + +Coq terms are typed. Coq types are recognized by the same syntactic +class as :token`term`. We denote by :token:`type` the semantic subclass +of types inside the syntactic class :token:`term`. + +.. _gallina-identifiers: + +Qualified identifiers and simple identifiers +-------------------------------------------- + +*Qualified identifiers* (:token:`qualid`) denote *global constants* +(definitions, lemmas, theorems, remarks or facts), *global variables* +(parameters or axioms), *inductive types* or *constructors of inductive +types*. *Simple identifiers* (or shortly :token:`ident`) are a syntactic subset +of qualified identifiers. Identifiers may also denote local *variables*, +what qualified identifiers do not. + +Numerals +-------- + +Numerals have no definite semantics in the calculus. They are mere +notations that can be bound to objects through the notation mechanism +(see Chapter :ref:`syntaxextensionsandinterpretationscopes` for details). +Initially, numerals are bound to Peano’s representation of natural +numbers (see :ref:`datatypes`). + +.. note:: + + negative integers are not at the same level as :token:`num`, for this + would make precedence unnatural. + +Sorts +----- + +There are three sorts :g:`Set`, :g:`Prop` and :g:`Type`. + +- :g:`Prop` is the universe of *logical propositions*. The logical propositions + themselves are typing the proofs. We denote propositions by *form*. + This constitutes a semantic subclass of the syntactic class :token:`term`. + +- :g:`Set` is is the universe of *program types* or *specifications*. The + specifications themselves are typing the programs. We denote + specifications by *specif*. This constitutes a semantic subclass of + the syntactic class :token:`term`. + +- :g:`Type` is the type of :g:`Prop` and :g:`Set` + +More on sorts can be found in Section :ref:`sorts`. + +.. _binders: + +Binders +------- + +Various constructions such as :g:`fun`, :g:`forall`, :g:`fix` and :g:`cofix` +*bind* variables. A binding is represented by an identifier. If the binding +variable is not used in the expression, the identifier can be replaced by the +symbol :g:`_`. When the type of a bound variable cannot be synthesized by the +system, it can be specified with the notation ``(ident : type)``. There is also +a notation for a sequence of binding variables sharing the same type: +``(``:token:`ident`:math:`_1`…:token:`ident`:math:`_n` : :token:`type```)``. A +binder can also be any pattern prefixed by a quote, e.g. :g:`'(x,y)`. + +Some constructions allow the binding of a variable to value. This is +called a “let-binder”. The entry :token:`binder` of the grammar accepts +either an assumption binder as defined above or a let-binder. The notation in +the latter case is ``(ident := term)``. In a let-binder, only one +variable can be introduced at the same time. It is also possible to give +the type of the variable as follows: +``(ident : term := term)``. + +Lists of :token:`binder` are allowed. In the case of :g:`fun` and :g:`forall`, +it is intended that at least one binder of the list is an assumption otherwise +fun and forall gets identical. Moreover, parentheses can be omitted in +the case of a single sequence of bindings sharing the same type (e.g.: +:g:`fun (x y z : A) => t` can be shortened in :g:`fun x y z : A => t`). + +Abstractions +------------ + +The expression ``fun ident : type => term`` defines the +*abstraction* of the variable :token:`ident`, of type :token:`type`, over the term +:token:`term`. It denotes a function of the variable :token:`ident` that evaluates to +the expression :token:`term` (e.g. :g:`fun x : A => x` denotes the identity +function on type :g:`A`). The keyword :g:`fun` can be followed by several +binders as given in Section :ref:`binders`. Functions over +several variables are equivalent to an iteration of one-variable +functions. For instance the expression +“fun :token:`ident`\ :math:`_{1}` … :token:`ident`\ :math:`_{n}` +: :token:`type` => :token:`term`” +denotes the same function as “ fun :token:`ident`\ +:math:`_{1}` : :token:`type` => … +fun :token:`ident`\ :math:`_{n}` : :token:`type` => :token:`term`”. If +a let-binder occurs in +the list of binders, it is expanded to a let-in definition (see +Section :ref:`let-in`). + +Products +-------- + +The expression :g:`forall ident : type, term` denotes the +*product* of the variable :token:`ident` of type :token:`type`, over the term :token:`term`. +As for abstractions, :g:`forall` is followed by a binder list, and products +over several variables are equivalent to an iteration of one-variable +products. Note that :token:`term` is intended to be a type. + +If the variable :token:`ident` occurs in :token:`term`, the product is called +*dependent product*. The intention behind a dependent product +:g:`forall x : A, B` is twofold. It denotes either +the universal quantification of the variable :g:`x` of type :g:`A` +in the proposition :g:`B` or the functional dependent product from +:g:`A` to :g:`B` (a construction usually written +:math:`\Pi_{x:A}.B` in set theory). + +Non dependent product types have a special notation: :g:`A -> B` stands for +:g:`forall _ : A, B`. The *non dependent product* is used both to denote +the propositional implication and function types. + +Applications +------------ + +The expression :token:`term`\ :math:`_0` :token:`term`\ :math:`_1` denotes the +application of :token:`term`\ :math:`_0` to :token:`term`\ :math:`_1`. + +The expression :token:`term`\ :math:`_0` :token:`term`\ :math:`_1` ... +:token:`term`\ :math:`_n` denotes the application of the term +:token:`term`\ :math:`_0` to the arguments :token:`term`\ :math:`_1` ... then +:token:`term`\ :math:`_n`. It is equivalent to ( … ( :token:`term`\ :math:`_0` +:token:`term`\ :math:`_1` ) … ) :token:`term`\ :math:`_n` : associativity is to the +left. + +The notation ``(ident := term)`` for arguments is used for making +explicit the value of implicit arguments (see +Section :ref:`explicit-applications`). + +Type cast +--------- + +The expression ``term : type`` is a type cast expression. It enforces +the type of :token:`term` to be :token:`type`. + +``term <: type`` locally sets up the virtual machine for checking that +:token:`term` has type :token:`type`. + +Inferable subterms +------------------ + +Expressions often contain redundant pieces of information. Subterms that can be +automatically inferred by Coq can be replaced by the symbol ``_`` and Coq will +guess the missing piece of information. + +.. _let-in: + +Let-in definitions +------------------ + +``let`` :token:`ident` := :token:`term`:math:`_1` in :token:`term`:math:`_2` +denotes the local binding of :token:`term`:math:`_1` to the variable +:token:`ident` in :token:`term`:math:`_2`. There is a syntactic sugar for let-in +definition of functions: ``let`` :token:`ident` :token:`binder`:math:`_1` … +:token:`binder`:math:`_n` := :token:`term`:math:`_1` in :token:`term`:math:`_2` +stands for ``let`` :token:`ident` := ``fun`` :token:`binder`:math:`_1` … +:token:`binder`:math:`_n` => :token:`term`:math:`_1` in :token:`term`:math:`_2`. + +Definition by case analysis +--------------------------- + +Objects of inductive types can be destructurated by a case-analysis +construction called *pattern-matching* expression. A pattern-matching +expression is used to analyze the structure of an inductive objects and +to apply specific treatments accordingly. + +This paragraph describes the basic form of pattern-matching. See +Section :ref:`Mult-match` and Chapter :ref:`extendedpatternmatching` for the description +of the general form. The basic form of pattern-matching is characterized +by a single :token:`match_item` expression, a :token:`mult_pattern` restricted to a +single :token:`pattern` and :token:`pattern` restricted to the form +:token:`qualid` :token:`ident`. + +The expression match :token:`term`:math:`_0` :token:`return_type` with +:token:`pattern`:math:`_1` => :token:`term`:math:`_1` :math:`|` … :math:`|` +:token:`pattern`:math:`_n` => :token:`term`:math:`_n` end, denotes a +:token:`pattern-matching` over the term :token:`term`:math:`_0` (expected to be +of an inductive type :math:`I`). The terms :token:`term`:math:`_1`\ …\ +:token:`term`:math:`_n` are the :token:`branches` of the pattern-matching +expression. Each of :token:`pattern`:math:`_i` has a form :token:`qualid` +:token:`ident` where :token:`qualid` must denote a constructor. There should be +exactly one branch for every constructor of :math:`I`. + +The :token:`return_type` expresses the type returned by the whole match +expression. There are several cases. In the *non dependent* case, all +branches have the same type, and the :token:`return_type` is the common type of +branches. In this case, :token:`return_type` can usually be omitted as it can be +inferred from the type of the branches [2]_. + +In the *dependent* case, there are three subcases. In the first subcase, +the type in each branch may depend on the exact value being matched in +the branch. In this case, the whole pattern-matching itself depends on +the term being matched. This dependency of the term being matched in the +return type is expressed with an “as :token:`ident`” clause where :token:`ident` +is dependent in the return type. For instance, in the following example: + +.. coqtop:: in + + Inductive bool : Type := true : bool | false : bool. + Inductive eq (A:Type) (x:A) : A -> Prop := eq_refl : eq A x x. + Inductive or (A:Prop) (B:Prop) : Prop := + | or_introl : A -> or A B + | or_intror : B -> or A B. + + Definition bool_case (b:bool) : or (eq bool b true) (eq bool b false) := + match b as x return or (eq bool x true) (eq bool x false) with + | true => or_introl (eq bool true true) (eq bool true false) + (eq_refl bool true) + | false => or_intror (eq bool false true) (eq bool false false) + (eq_refl bool false) + end. + +the branches have respective types or :g:`eq bool true true :g:`eq bool true +false` and or :g:`eq bool false true` :g:`eq bool false false` while the whole +pattern-matching expression has type or :g:`eq bool b true` :g:`eq bool b +false`, the identifier :g:`x` being used to represent the dependency. Remark +that when the term being matched is a variable, the as clause can be +omitted and the term being matched can serve itself as binding name in +the return type. For instance, the following alternative definition is +accepted and has the same meaning as the previous one. + +.. coqtop:: in + + Definition bool_case (b:bool) : or (eq bool b true) (eq bool b false) := + match b return or (eq bool b true) (eq bool b false) with + | true => or_introl (eq bool true true) (eq bool true false) + (eq_refl bool true) + | false => or_intror (eq bool false true) (eq bool false false) + (eq_refl bool false) + end. + +The second subcase is only relevant for annotated inductive types such +as the equality predicate (see Section :ref:`Equality`), +the order predicate on natural numbers or the type of lists of a given +length (see Section :ref:`matching-dependent`). In this configuration, the +type of each branch can depend on the type dependencies specific to the +branch and the whole pattern-matching expression has a type determined +by the specific dependencies in the type of the term being matched. This +dependency of the return type in the annotations of the inductive type +is expressed using a “in I _ ... _ :token:`pattern`:math:`_1` ... +:token:`pattern`:math:`_n`” clause, where + +- :math:`I` is the inductive type of the term being matched; + +- the :g:`_` are matching the parameters of the inductive type: the + return type is not dependent on them. + +- the :token:`pattern`:math:`_i` are matching the annotations of the + inductive type: the return type is dependent on them + +- in the basic case which we describe below, each :token:`pattern`:math:`_i` + is a name :token:`ident`:math:`_i`; see :ref:`match-in-patterns` for the + general case + +For instance, in the following example: + +.. coqtop:: in + + Definition eq_sym (A:Type) (x y:A) (H:eq A x y) : eq A y x := + match H in eq _ _ z return eq A z x with + | eq_refl _ => eq_refl A x + end. + +the type of the branch has type :g:`eq A x x` because the third argument of +g:`eq` is g:`x` in the type of the pattern :g:`refl_equal`. On the contrary, the +type of the whole pattern-matching expression has type :g:`eq A y x` because the +third argument of eq is y in the type of H. This dependency of the case analysis +in the third argument of :g:`eq` is expressed by the identifier g:`z` in the +return type. + +Finally, the third subcase is a combination of the first and second +subcase. In particular, it only applies to pattern-matching on terms in +a type with annotations. For this third subcase, both the clauses as and +in are available. + +There are specific notations for case analysis on types with one or two +constructors: “if … then … else …” and “let (…, ” (see +Sections :ref:`if-then-else` and :ref:`let-in`). + +Recursive functions +------------------- + +The expression “fix :token:`ident`:math:`_1` :token:`binder`:math:`_1` : +:token:`type`:math:`_1` ``:=`` :token:`term`:math:`_1` with … with +:token:`ident`:math:`_n` :token:`binder`:math:`_n` : :token:`type`:math:`_n` +``:=`` :token:`term`:math:`_n` for :token:`ident`:math:`_i`” denotes the +:math:`i`\ component of a block of functions defined by mutual well-founded +recursion. It is the local counterpart of the :cmd:`Fixpoint` command. When +:math:`n=1`, the “for :token:`ident`:math:`_i`” clause is omitted. + +The expression “cofix :token:`ident`:math:`_1` :token:`binder`:math:`_1` : +:token:`type`:math:`_1` with … with :token:`ident`:math:`_n` :token:`binder`:math:`_n` +: :token:`type`:math:`_n` for :token:`ident`:math:`_i`” denotes the +:math:`i`\ component of a block of terms defined by a mutual guarded +co-recursion. It is the local counterpart of the ``CoFixpoint`` command. See +Section :ref:`CoFixpoint` for more details. When +:math:`n=1`, the “ for :token:`ident`:math:`_i`” clause is omitted. + +The association of a single fixpoint and a local definition have a special +syntax: “let fix f … := … in …” stands for “let f := fix f … := … in …”. The +same applies for co-fixpoints. + +.. _vernacular: + +The Vernacular +============== + +.. productionlist:: coq + sentence : `assumption` + : | `definition` + : | `inductive` + : | `fixpoint` + : | `assertion` `proof` + assumption : `assumption_keyword` `assums`. + assumption_keyword : Axiom | Conjecture + : | Parameter | Parameters + : | Variable | Variables + : | Hypothesis | Hypotheses + assums : `ident` … `ident` : `term` + : | ( `ident` … `ident` : `term` ) … ( `ident` … `ident` : `term` ) + definition : [Local] Definition `ident` [`binders`] [: `term`] := `term` . + : | Let `ident` [`binders`] [: `term`] := `term` . + inductive : Inductive `ind_body` with … with `ind_body` . + : | CoInductive `ind_body` with … with `ind_body` . + ind_body : `ident` [`binders`] : `term` := + : [[|] `ident` [`binders`] [:`term`] | … | `ident` [`binders`] [:`term`]] + fixpoint : Fixpoint `fix_body` with … with `fix_body` . + : | CoFixpoint `cofix_body` with … with `cofix_body` . + assertion : `assertion_keyword` `ident` [`binders`] : `term` . + assertion_keyword : Theorem | Lemma + : | Remark | Fact + : | Corollary | Proposition + : | Definition | Example + proof : Proof . … Qed . + : | Proof . … Defined . + : | Proof . … Admitted . + +.. todo:: This use of … in this grammar is inconsistent + +This grammar describes *The Vernacular* which is the language of +commands of Gallina. A sentence of the vernacular language, like in +many natural languages, begins with a capital letter and ends with a +dot. + +The different kinds of command are described hereafter. They all suppose +that the terms occurring in the sentences are well-typed. + +.. _gallina-assumptions: + +Assumptions +----------- + +Assumptions extend the environment with axioms, parameters, hypotheses +or variables. An assumption binds an :token:`ident` to a :token:`type`. It is accepted +by Coq if and only if this :token:`type` is a correct type in the environment +preexisting the declaration and if :token:`ident` was not previously defined in +the same module. This :token:`type` is considered to be the type (or +specification, or statement) assumed by :token:`ident` and we say that :token:`ident` +has type :token:`type`. + +.. _Axiom: + +.. cmd:: Axiom @ident : @term. + + This command links *term* to the name *ident* as its specification in + the global context. The fact asserted by *term* is thus assumed as a + postulate. + +.. exn:: @ident already exists (Axiom) + +.. cmdv:: Parameter @ident : @term. + :name: Parameter + + Is equivalent to ``Axiom`` :token:`ident` : :token:`term` + +.. cmdv:: Parameter {+ @ident } : @term. + + Adds parameters with specification :token:`term` + +.. cmdv:: Parameter {+ ( {+ @ident } : @term ) }. + + Adds blocks of parameters with different specifications. + +.. cmdv:: Parameters {+ ( {+ @ident } : @term ) }. + + Synonym of ``Parameter``. + +.. cmdv:: Local Axiom @ident : @term. + + Such axioms are never made accessible through their unqualified name by + :cmd:`Import` and its variants. You have to explicitly give their fully + qualified name to refer to them. + +.. cmdv:: Conjecture @ident : @term + :name: Conjecture + + Is equivalent to ``Axiom`` :token:`ident` : :token:`term`. + +.. cmd:: Variable @ident : @term. + +This command links :token:`term` to the name :token:`ident` in the context of +the current section (see Section :ref:`section-mechanism` for a description of +the section mechanism). When the current section is closed, name :token:`ident` +will be unknown and every object using this variable will be explicitly +parametrized (the variable is *discharged*). Using the ``Variable`` command out +of any section is equivalent to using ``Local Parameter``. + +.. exn:: @ident already exists (Variable) + +.. cmdv:: Variable {+ @ident } : @term. + + Links :token:`term` to each :token:`ident`. + +.. cmdv:: Variable {+ ( {+ @ident } : @term) }. + + Adds blocks of variables with different specifications. + +.. cmdv:: Variables {+ ( {+ @ident } : @term) }. + +.. cmdv:: Hypothesis {+ ( {+ @ident } : @term) }. + :name: Hypothesis + +.. cmdv:: Hypotheses {+ ( {+ @ident } : @term) }. + +Synonyms of ``Variable``. + +It is advised to use the keywords ``Axiom`` and ``Hypothesis`` for +logical postulates (i.e. when the assertion *term* is of sort ``Prop``), +and to use the keywords ``Parameter`` and ``Variable`` in other cases +(corresponding to the declaration of an abstract mathematical entity). + +.. _gallina-definitions: + +Definitions +----------- + +Definitions extend the environment with associations of names to terms. +A definition can be seen as a way to give a meaning to a name or as a +way to abbreviate a term. In any case, the name can later be replaced at +any time by its definition. + +The operation of unfolding a name into its definition is called +:math:`\delta`-conversion (see Section :ref:`delta-reduction`). A +definition is accepted by the system if and only if the defined term is +well-typed in the current context of the definition and if the name is +not already used. The name defined by the definition is called a +*constant* and the term it refers to is its *body*. A definition has a +type which is the type of its body. + +A formal presentation of constants and environments is given in +Section :ref:`typing-rules`. + +.. cmd:: Definition @ident := @term. + + This command binds :token:`term` to the name :token:`ident` in the environment, + provided that :token:`term` is well-typed. + +.. exn:: @ident already exists (Definition) + +.. cmdv:: Definition @ident : @term := @term. + + It checks that the type of :token:`term`:math:`_2` is definitionally equal to + :token:`term`:math:`_1`, and registers :token:`ident` as being of type + :token:`term`:math:`_1`, and bound to value :token:`term`:math:`_2`. + + +.. cmdv:: Definition @ident {* @binder } : @term := @term. + + This is equivalent to ``Definition`` :token:`ident` : :g:`forall` + :token:`binder`:math:`_1` … :token:`binder`:math:`_n`, :token:`term`:math:`_1` := + fun :token:`binder`:math:`_1` … + :token:`binder`:math:`_n` => :token:`term`:math:`_2`. + +.. cmdv:: Local Definition @ident := @term. + + Such definitions are never made accessible through their + unqualified name by :cmd:`Import` and its variants. + You have to explicitly give their fully qualified name to refer to them. + +.. cmdv:: Example @ident := @term. + +.. cmdv:: Example @ident : @term := @term. + +.. cmdv:: Example @ident {* @binder } : @term := @term. + +These are synonyms of the Definition forms. + +.. exn:: The term @term has type @type while it is expected to have type @type + +See also :cmd:`Opaque`, :cmd:`Transparent`, :tac:`unfold`. + +.. cmd:: Let @ident := @term. + +This command binds the value :token:`term` to the name :token:`ident` in the +environment of the current section. The name :token:`ident` disappears when the +current section is eventually closed, and, all persistent objects (such +as theorems) defined within the section and depending on :token:`ident` are +prefixed by the let-in definition ``let`` :token:`ident` ``:=`` :token:`term` +``in``. Using the ``Let`` command out of any section is equivalent to using +``Local Definition``. + +.. exn:: @ident already exists (Let) + +.. cmdv:: Let @ident : @term := @term. + +.. cmdv:: Let Fixpoint @ident @fix_body {* with @fix_body}. + +.. cmdv:: Let CoFixpoint @ident @cofix_body {* with @cofix_body}. + +See also Sections :ref:`section-mechanism`, commands :cmd:`Opaque`, +:cmd:`Transparent`, and tactic :tacn:`unfold`. + +.. _gallina-inductive-definitions: + +Inductive definitions +--------------------- + +We gradually explain simple inductive types, simple annotated inductive +types, simple parametric inductive types, mutually inductive types. We +explain also co-inductive types. + +Simple inductive types +~~~~~~~~~~~~~~~~~~~~~~ + +The definition of a simple inductive type has the following form: + +.. cmd:: Inductive @ident : @sort := {? | } @ident : @type {* | @ident : @type } + +The name :token:`ident` is the name of the inductively defined type and +:token:`sort` is the universes where it lives. The :token:`ident` are the names +of its constructors and :token:`type` their respective types. The types of the +constructors have to satisfy a *positivity condition* (see Section +:ref:`positivity`) for :token:`ident`. This condition ensures the soundness of +the inductive definition. If this is the case, the :token:`ident` are added to +the environment with their respective types. Accordingly to the universe where +the inductive type lives (e.g. its type :token:`sort`), Coq provides a number of +destructors for :token:`ident`. Destructors are named ``ident_ind``, +``ident_rec`` or ``ident_rect`` which respectively correspond to +elimination principles on :g:`Prop`, :g:`Set` and :g:`Type`. The type of the +destructors expresses structural induction/recursion principles over objects of +:token:`ident`. We give below two examples of the use of the Inductive +definitions. + +The set of natural numbers is defined as: + +.. coqtop:: all + + Inductive nat : Set := + | O : nat + | S : nat -> nat. + +The type nat is defined as the least :g:`Set` containing :g:`O` and closed by +the :g:`S` constructor. The names :g:`nat`, :g:`O` and :g:`S` are added to the +environment. + +Now let us have a look at the elimination principles. They are three of them: +:g:`nat_ind`, :g:`nat_rec` and :g:`nat_rect`. The type of :g:`nat_ind` is: + +.. coqtop:: all + + Check nat_ind. + +This is the well known structural induction principle over natural +numbers, i.e. the second-order form of Peano’s induction principle. It +allows proving some universal property of natural numbers (:g:`forall +n:nat, P n`) by induction on :g:`n`. + +The types of :g:`nat_rec` and :g:`nat_rect` are similar, except that they pertain +to :g:`(P:nat->Set)` and :g:`(P:nat->Type)` respectively. They correspond to +primitive induction principles (allowing dependent types) respectively +over sorts ``Set`` and ``Type``. The constant ``ident_ind`` is always +provided, whereas ``ident_rec`` and ``ident_rect`` can be impossible +to derive (for example, when :token:`ident` is a proposition). + +.. coqtop:: in + + Inductive nat : Set := O | S (_:nat). + +In the case where inductive types have no annotations (next section +gives an example of such annotations), a constructor can be defined +by only giving the type of its arguments. + +Simple annotated inductive types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In an annotated inductive types, the universe where the inductive type +is defined is no longer a simple sort, but what is called an arity, +which is a type whose conclusion is a sort. + +As an example of annotated inductive types, let us define the +:g:`even` predicate: + +.. coqtop:: all + + Inductive even : nat -> Prop := + | even_0 : even O + | even_SS : forall n:nat, even n -> even (S (S n)). + +The type :g:`nat->Prop` means that even is a unary predicate (inductively +defined) over natural numbers. The type of its two constructors are the +defining clauses of the predicate even. The type of :g:`even_ind` is: + +.. coqtop:: all + + Check even_ind. + +From a mathematical point of view it asserts that the natural numbers satisfying +the predicate even are exactly in the smallest set of naturals satisfying the +clauses :g:`even_0` or :g:`even_SS`. This is why, when we want to prove any +predicate :g:`P` over elements of :g:`even`, it is enough to prove it for :g:`O` +and to prove that if any natural number :g:`n` satisfies :g:`P` its double +successor :g:`(S (S n))` satisfies also :g:`P`. This is indeed analogous to the +structural induction principle we got for :g:`nat`. + +.. exn:: Non strictly positive occurrence of @ident in @type + +.. exn:: The conclusion of @type is not valid; it must be built from @ident + +Parametrized inductive types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the previous example, each constructor introduces a different +instance of the predicate even. In some cases, all the constructors +introduces the same generic instance of the inductive definition, in +which case, instead of an annotation, we use a context of parameters +which are binders shared by all the constructors of the definition. + +The general scheme is: + +.. cmdv:: Inductive @ident {+ @binder} : @term := {? | } @ident : @type {* | @ident : @type} + +Parameters differ from inductive type annotations in the fact that the +conclusion of each type of constructor :g:`term` invoke the inductive type with +the same values of parameters as its specification. + +A typical example is the definition of polymorphic lists: + +.. coqtop:: in + + Inductive list (A:Set) : Set := + | nil : list A + | cons : A -> list A -> list A. + +.. note:: + + In the type of :g:`nil` and :g:`cons`, we write :g:`(list A)` and not + just :g:`list`. The constructors :g:`nil` and :g:`cons` will have respectively + types: + + .. coqtop:: all + + Check nil. + Check cons. + + Types of destructors are also quantified with :g:`(A:Set)`. + +Variants +++++++++ + +.. coqtop:: in + + Inductive list (A:Set) : Set := nil | cons (_:A) (_:list A). + +This is an alternative definition of lists where we specify the +arguments of the constructors rather than their full type. + +.. coqtop:: in + + Variant sum (A B:Set) : Set := left : A -> sum A B | right : B -> sum A B. + +The ``Variant`` keyword is identical to the ``Inductive`` keyword, except +that it disallows recursive definition of types (in particular lists cannot +be defined with the Variant keyword). No induction scheme is generated for +this variant, unless :opt:`Nonrecursive Elimination Schemes` is set. + +.. exn:: The @num th argument of @ident must be @ident in @type + +New from Coq V8.1 ++++++++++++++++++ + +The condition on parameters for inductive definitions has been relaxed +since Coq V8.1. It is now possible in the type of a constructor, to +invoke recursively the inductive definition on an argument which is not +the parameter itself. + +One can define : + +.. coqtop:: all + + Inductive list2 (A:Set) : Set := + | nil2 : list2 A + | cons2 : A -> list2 (A*A) -> list2 A. + +that can also be written by specifying only the type of the arguments: + +.. coqtop:: all reset + + Inductive list2 (A:Set) : Set := nil2 | cons2 (_:A) (_:list2 (A*A)). + +But the following definition will give an error: + +.. coqtop:: all + + Fail Inductive listw (A:Set) : Set := + | nilw : listw (A*A) + | consw : A -> listw (A*A) -> listw (A*A). + +Because the conclusion of the type of constructors should be :g:`listw A` in +both cases. + +A parametrized inductive definition can be defined using annotations +instead of parameters but it will sometimes give a different (bigger) +sort for the inductive definition and will produce a less convenient +rule for case elimination. + +See also Section :ref:`inductive-definitions` and the :tacn:`induction` +tactic. + +Mutually defined inductive types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The definition of a block of mutually inductive types has the form: + +.. cmdv:: Inductive @ident : @term := {? | } @ident : @type {* | @ident : @type } {* with @ident : @term := {? | } @ident : @type {* | @ident : @type }}. + +It has the same semantics as the above ``Inductive`` definition for each +:token:`ident` All :token:`ident` are simultaneously added to the environment. +Then well-typing of constructors can be checked. Each one of the :token:`ident` +can be used on its own. + +It is also possible to parametrize these inductive definitions. However, +parameters correspond to a local context in which the whole set of +inductive declarations is done. For this reason, the parameters must be +strictly the same for each inductive types The extended syntax is: + +.. cmdv:: Inductive @ident {+ @binder} : @term := {? | } @ident : @type {* | @ident : @type } {* with @ident {+ @binder} : @term := {? | } @ident : @type {* | @ident : @type }}. + +The typical example of a mutual inductive data type is the one for trees and +forests. We assume given two types :g:`A` and :g:`B` as variables. It can +be declared the following way. + +.. coqtop:: in + + Variables A B : Set. + + Inductive tree : Set := + node : A -> forest -> tree + + with forest : Set := + | leaf : B -> forest + | cons : tree -> forest -> forest. + +This declaration generates automatically six induction principles. They are +respectively called :g:`tree_rec`, :g:`tree_ind`, :g:`tree_rect`, +:g:`forest_rec`, :g:`forest_ind`, :g:`forest_rect`. These ones are not the most +general ones but are just the induction principles corresponding to each +inductive part seen as a single inductive definition. + +To illustrate this point on our example, we give the types of :g:`tree_rec` +and :g:`forest_rec`. + +.. coqtop:: all + + Check tree_rec. + + Check forest_rec. + +Assume we want to parametrize our mutual inductive definitions with the +two type variables :g:`A` and :g:`B`, the declaration should be +done the following way: + +.. coqtop:: in + + Inductive tree (A B:Set) : Set := + node : A -> forest A B -> tree A B + + with forest (A B:Set) : Set := + | leaf : B -> forest A B + | cons : tree A B -> forest A B -> forest A B. + +Assume we define an inductive definition inside a section. When the +section is closed, the variables declared in the section and occurring +free in the declaration are added as parameters to the inductive +definition. + +See also Section :ref:`section-mechanism`. + +.. _coinductive-types: + +Co-inductive types +~~~~~~~~~~~~~~~~~~ + +The objects of an inductive type are well-founded with respect to the +constructors of the type. In other words, such objects contain only a +*finite* number of constructors. Co-inductive types arise from relaxing +this condition, and admitting types whose objects contain an infinity of +constructors. Infinite objects are introduced by a non-ending (but +effective) process of construction, defined in terms of the constructors +of the type. + +An example of a co-inductive type is the type of infinite sequences of +natural numbers, usually called streams. It can be introduced in +Coq using the ``CoInductive`` command: + +.. coqtop:: all + + CoInductive Stream : Set := + Seq : nat -> Stream -> Stream. + +The syntax of this command is the same as the command :cmd:`Inductive`. Notice +that no principle of induction is derived from the definition of a co-inductive +type, since such principles only make sense for inductive ones. For co-inductive +ones, the only elimination principle is case analysis. For example, the usual +destructors on streams :g:`hd:Stream->nat` and :g:`tl:Str->Str` can be defined +as follows: + +.. coqtop:: all + + Definition hd (x:Stream) := let (a,s) := x in a. + Definition tl (x:Stream) := let (a,s) := x in s. + +Definition of co-inductive predicates and blocks of mutually +co-inductive definitions are also allowed. An example of a co-inductive +predicate is the extensional equality on streams: + +.. coqtop:: all + + CoInductive EqSt : Stream -> Stream -> Prop := + eqst : forall s1 s2:Stream, + hd s1 = hd s2 -> EqSt (tl s1) (tl s2) -> EqSt s1 s2. + +In order to prove the extensionally equality of two streams :g:`s1` and :g:`s2` +we have to construct an infinite proof of equality, that is, an infinite object +of type :g:`(EqSt s1 s2)`. We will see how to introduce infinite objects in +Section :ref:`cofixpoint`. + +Definition of recursive functions +--------------------------------- + +Definition of functions by recursion over inductive objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This section describes the primitive form of definition by recursion over +inductive objects. See the :cmd:`Function` command for more advanced +constructions. + +.. _Fixpoint: + +.. cmd:: Fixpoint @ident @params {struct @ident} : @type := @term. + +This command allows defining functions by pattern-matching over inductive objects +using a fixed point construction. The meaning of this declaration is to +define :token:`ident` a recursive function with arguments specified by the +binders in :token:`params` such that :token:`ident` applied to arguments corresponding +to these binders has type :token:`type`:math:`_0`, and is equivalent to the +expression :token:`term`:math:`_0`. The type of the :token:`ident` is consequently +:g:`forall` :token:`params`, :token:`type`:math:`_0` and the value is equivalent to +:g:`fun` :token:`params` :g:`=>` :token:`term`:math:`_0`. + +To be accepted, a ``Fixpoint`` definition has to satisfy some syntactical +constraints on a special argument called the decreasing argument. They +are needed to ensure that the Fixpoint definition always terminates. The +point of the {struct :token:`ident`} annotation is to let the user tell the +system which argument decreases along the recursive calls. For instance, +one can define the addition function as : + +.. coqtop:: all + + Fixpoint add (n m:nat) {struct n} : nat := + match n with + | O => m + | S p => S (add p m) + end. + +The ``{struct`` :token:`ident```}`` annotation may be left implicit, in this case the +system try successively arguments from left to right until it finds one that +satisfies the decreasing condition. + +.. note:: + + Some fixpoints may have several arguments that fit as decreasing + arguments, and this choice influences the reduction of the fixpoint. Hence an + explicit annotation must be used if the leftmost decreasing argument is not the + desired one. Writing explicit annotations can also speed up type-checking of + large mutual fixpoints. + +The match operator matches a value (here :g:`n`) with the various +constructors of its (inductive) type. The remaining arguments give the +respective values to be returned, as functions of the parameters of the +corresponding constructor. Thus here when :g:`n` equals :g:`O` we return +:g:`m`, and when :g:`n` equals :g:`(S p)` we return :g:`(S (add p m))`. + +The match operator is formally described in detail in Section +:ref:`match-construction`. +The system recognizes that in the inductive call :g:`(add p m)` the first +argument actually decreases because it is a *pattern variable* coming from +:g:`match n with`. + +.. example:: + + The following definition is not correct and generates an error message: + + .. coqtop:: all + + Fail Fixpoint wrongplus (n m:nat) {struct n} : nat := + match m with + | O => n + | S p => S (wrongplus n p) + end. + + because the declared decreasing argument n actually does not decrease in + the recursive call. The function computing the addition over the second + argument should rather be written: + + .. coqtop:: all + + Fixpoint plus (n m:nat) {struct m} : nat := + match m with + | O => n + | S p => S (plus n p) + end. + +.. example:: + + The ordinary match operation on natural numbers can be mimicked in the + following way. + + .. coqtop:: all + + Fixpoint nat_match + (C:Set) (f0:C) (fS:nat -> C -> C) (n:nat) {struct n} : C := + match n with + | O => f0 + | S p => fS p (nat_match C f0 fS p) + end. + +.. example:: + + The recursive call may not only be on direct subterms of the recursive + variable n but also on a deeper subterm and we can directly write the + function mod2 which gives the remainder modulo 2 of a natural number. + + .. coqtop:: all + + Fixpoint mod2 (n:nat) : nat := + match n with + | O => O + | S p => match p with + | O => S O + | S q => mod2 q + end + end. + +In order to keep the strong normalization property, the fixed point +reduction will only be performed when the argument in position of the +decreasing argument (which type should be in an inductive definition) +starts with a constructor. + +The ``Fixpoint`` construction enjoys also the with extension to define functions +over mutually defined inductive types or more generally any mutually recursive +definitions. + +.. cmdv:: Fixpoint @ident @params {struct @ident} : @type := @term {* with @ident {+ @params} : @type := @term}. + +allows to define simultaneously fixpoints. + +The size of trees and forests can be defined the following way: + +.. coqtop:: all + + Fixpoint tree_size (t:tree) : nat := + match t with + | node a f => S (forest_size f) + end + with forest_size (f:forest) : nat := + match f with + | leaf b => 1 + | cons t f' => (tree_size t + forest_size f') + end. + +A generic command Scheme is useful to build automatically various mutual +induction principles. It is described in Section +:ref:`proofschemes-induction-principles`. + +.. _cofixpoint: + +Definitions of recursive objects in co-inductive types +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. cmd:: CoFixpoint @ident : @type := @term. + +introduces a method for constructing an infinite object of a coinductive +type. For example, the stream containing all natural numbers can be +introduced applying the following method to the number :g:`O` (see +Section :ref:`coinductive-types` for the definition of :g:`Stream`, :g:`hd` and +:g:`tl`): + +.. coqtop:: all + + CoFixpoint from (n:nat) : Stream := Seq n (from (S n)). + +Oppositely to recursive ones, there is no decreasing argument in a +co-recursive definition. To be admissible, a method of construction must +provide at least one extra constructor of the infinite object for each +iteration. A syntactical guard condition is imposed on co-recursive +definitions in order to ensure this: each recursive call in the +definition must be protected by at least one constructor, and only by +constructors. That is the case in the former definition, where the +single recursive call of :g:`from` is guarded by an application of +:g:`Seq`. On the contrary, the following recursive function does not +satisfy the guard condition: + +.. coqtop:: all + + Fail CoFixpoint filter (p:nat -> bool) (s:Stream) : Stream := + if p (hd s) then Seq (hd s) (filter p (tl s)) else filter p (tl s). + +The elimination of co-recursive definition is done lazily, i.e. the +definition is expanded only when it occurs at the head of an application +which is the argument of a case analysis expression. In any other +context, it is considered as a canonical expression which is completely +evaluated. We can test this using the command ``Eval``, which computes +the normal forms of a term: + +.. coqtop:: all + + Eval compute in (from 0). + Eval compute in (hd (from 0)). + Eval compute in (tl (from 0)). + +.. cmdv:: CoFixpoint @ident @params : @type := @term + + As for most constructions, arguments of co-fixpoints expressions + can be introduced before the :g:`:=` sign. + +.. cmdv:: CoFixpoint @ident : @type := @term {+ with @ident : @type := @term } + + As in the :cmd:`Fixpoint` command, it is possible to introduce a block of + mutually dependent methods. + +.. _Assertions: + +Assertions and proofs +--------------------- + +An assertion states a proposition (or a type) of which the proof (or an +inhabitant of the type) is interactively built using tactics. The interactive +proof mode is described in Chapter :ref:`proofhandling` and the tactics in +Chapter :ref:`Tactics`. The basic assertion command is: + +.. cmd:: Theorem @ident : @type. + +After the statement is asserted, Coq needs a proof. Once a proof of +:token:`type` under the assumptions represented by :token:`binders` is given and +validated, the proof is generalized into a proof of forall , :token:`type` and +the theorem is bound to the name :token:`ident` in the environment. + +.. exn:: The term @term has type @type which should be Set, Prop or Type + +.. exn:: @ident already exists (Theorem) + + The name you provided is already defined. You have then to choose + another name. + +.. cmdv:: Lemma @ident : @type. + :name: Lemma + +.. cmdv:: Remark @ident : @type. + :name: Remark + +.. cmdv:: Fact @ident : @type. + :name: Fact + +.. cmdv:: Corollary @ident : @type. + :name: Corollary + +.. cmdv:: Proposition @ident : @type. + :name: Proposition + + These commands are synonyms of ``Theorem`` :token:`ident` : :token:`type`. + +.. cmdv:: Theorem @ident : @type {* with @ident : @type}. + + This command is useful for theorems that are proved by simultaneous induction + over a mutually inductive assumption, or that assert mutually dependent + statements in some mutual co-inductive type. It is equivalent to + :cmd:`Fixpoint` or :cmd:`CoFixpoint` but using tactics to build the proof of + the statements (or the body of the specification, depending on the point of + view). The inductive or co-inductive types on which the induction or + coinduction has to be done is assumed to be non ambiguous and is guessed by + the system. + + Like in a :cmd:`Fixpoint` or :cmd:`CoFixpoint` definition, the induction hypotheses + have to be used on *structurally smaller* arguments (for a :cmd:`Fixpoint`) or + be *guarded by a constructor* (for a :cmd:`CoFixpoint`). The verification that + recursive proof arguments are correct is done only at the time of registering + the lemma in the environment. To know if the use of induction hypotheses is + correct at some time of the interactive development of a proof, use the + command :cmd:`Guarded`. + + The command can be used also with :cmd:`Lemma`, :cmd:`Remark`, etc. instead of + :cmd:`Theorem`. + +.. cmdv:: Definition @ident : @type. + + This allows defining a term of type :token:`type` using the proof editing + mode. It behaves as Theorem but is intended to be used in conjunction with + :cmd:`Defined` in order to define a constant of which the computational + behavior is relevant. + + The command can be used also with :cmd:`Example` instead of :cmd:`Definition`. + + See also :cmd:`Opaque`, :cmd:`Transparent`, :tacn:`unfold`. + +.. cmdv:: Let @ident : @type. + + Like Definition :token:`ident` : :token:`type`. except that the definition is + turned into a let-in definition generalized over the declarations depending + on it after closing the current section. + +.. cmdv:: Fixpoint @ident @binders with . + + This generalizes the syntax of Fixpoint so that one or more bodies + can be defined interactively using the proof editing mode (when a + body is omitted, its type is mandatory in the syntax). When the block + of proofs is completed, it is intended to be ended by Defined. + +.. cmdv:: CoFixpoint @ident with. + + This generalizes the syntax of CoFixpoint so that one or more bodies + can be defined interactively using the proof editing mode. + +.. cmd:: Proof + + A proof starts by the keyword Proof. Then Coq enters the proof editing mode + until the proof is completed. The proof editing mode essentially contains + tactics that are described in chapter :ref:`Tactics`. Besides tactics, there + are commands to manage the proof editing mode. They are described in Chapter + :ref:`proofhandling`. + +.. cmd:: Qed + + When the proof is completed it should be validated and put in the environment + using the keyword Qed. + +.. exn:: @ident already exists (Qed) + +.. note:: + + #. Several statements can be simultaneously asserted. + + #. Not only other assertions but any vernacular command can be given + while in the process of proving a given assertion. In this case, the + command is understood as if it would have been given before the + statements still to be proved. + + #. Proof is recommended but can currently be omitted. On the opposite + side, Qed (or Defined, see below) is mandatory to validate a proof. + + #. Proofs ended by Qed are declared opaque. Their content cannot be + unfolded (see :ref:`performingcomputations`), thus + realizing some form of *proof-irrelevance*. To be able to unfold a + proof, the proof should be ended by Defined (see below). + +.. cmdv:: Defined + :name: Defined + + Same as :cmd:`Qed` but the proof is then declared transparent, which means + that its content can be explicitly used for type-checking and that it can be + unfolded in conversion tactics (see :ref:`performingcomputations`, + :cmd:`Opaque`, :cmd:`Transparent`). + +.. cmdv:: Admitted. + :name: Admitted + + Turns the current asserted statement into an axiom and exits the proof mode. + +.. [1] + This is similar to the expression “*entry* :math:`\{` sep *entry* + :math:`\}`” in standard BNF, or “*entry* :math:`(` sep *entry* + :math:`)`\ \*” in the syntax of regular expressions. + +.. [2] + Except if the inductive type is empty in which case there is no + equation that can be used to infer the return type. diff --git a/doc/sphinx/practical-tools/coq-commands.rst b/doc/sphinx/practical-tools/coq-commands.rst index 1ff808894a..93dcfca4bf 100644 --- a/doc/sphinx/practical-tools/coq-commands.rst +++ b/doc/sphinx/practical-tools/coq-commands.rst @@ -16,6 +16,8 @@ The options are (basically) the same for the first two commands, and roughly described below. You can also look at the ``man`` pages of ``coqtop`` and ``coqc`` for more details. +.. _interactive-use: + Interactive use (coqtop) ------------------------ @@ -39,10 +41,12 @@ Batch compilation (coqc) The ``coqc`` command takes a name *file* as argument. Then it looks for a vernacular file named *file*.v, and tries to compile it into a -*file*.vo file (See :ref:`TODO-6.5`). Warning: The name *file* should be a -regular |Coq| identifier, as defined in Section :ref:'TODO-1.1'. It should contain -only letters, digits or underscores (_). For instance, ``/bar/foo/toto.v`` is valid, but -``/bar/foo/to-to.v`` is invalid. +*file*.vo file (See :ref:`compiled-files`). + +.. caution:: The name *file* should be a + regular |Coq| identifier, as defined in Section :ref:'TODO-1.1'. It should contain + only letters, digits or underscores (_). For instance, ``/bar/foo/toto.v`` is valid, but + ``/bar/foo/to-to.v`` is invalid. Customization at launch time @@ -63,6 +67,7 @@ This file may contain, for instance, ``Add LoadPath`` commands to add directories to the load path of |Coq|. It is possible to skip the loading of the resource file with the option ``-q``. +.. _customization-by-environment-variables: By environment variables ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -70,7 +75,7 @@ By environment variables Load path can be specified to the |Coq| system by setting up ``$COQPATH`` environment variable. It is a list of directories separated by ``:`` (``;`` on Windows). |Coq| will also honor ``$XDG_DATA_HOME`` and -``$XDG_DATA_DIRS`` (see Section :ref:`TODO-2.6.3`). +``$XDG_DATA_DIRS`` (see Section :ref:`libraries-and-filesystem`). Some |Coq| commands call other |Coq| commands. In this case, they look for the commands in directory specified by ``$COQBIN``. If this variable is @@ -84,6 +89,8 @@ list of assignments of the form ``name=``:n:``{*; attr}`` where ANSI escape code. The list of highlight tags can be retrieved with the ``-list-tags`` command-line option of ``coqtop``. +.. _command-line-options: + By command line options ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -91,25 +98,25 @@ The following command-line options are recognized by the commands ``coqc`` and ``coqtop``, unless stated otherwise: :-I *directory*, -include *directory*: Add physical path *directory* - to the OCaml loadpath. See also: :ref:`TODO-2.6.1` and the - command Declare ML Module Section :ref:`TODO-6.5`. + to the OCaml loadpath. See also: :ref:`names-of-libraries` and the + command Declare ML Module Section :ref:`compiled-files`. :-Q *directory* dirpath: Add physical path *directory* to the list of directories where |Coq| looks for a file and bind it to the the logical directory *dirpath*. The subdirectory structure of *directory* is recursively available from |Coq| using absolute names (extending the - dirpath prefix) (see Section :ref:`TODO-2.6.2`).Note that only those + dirpath prefix) (see Section :ref:`qualified-names`).Note that only those subdirectories and files which obey the lexical conventions of what is - an ident (see Section :ref:`TODO-1.1`) are taken into account. Conversely, the + an :n:`@ident` are taken into account. Conversely, the underlying file systems or operating systems may be more restrictive than |Coq|. While Linux’s ext4 file system supports any |Coq| recursive layout (within the limit of 255 bytes per file name), the default on NTFS (Windows) or HFS+ (MacOS X) file systems is on the contrary to disallow two files differing only in the case in the same directory. - See also: Section :ref:`TODO-2.6.1`. + See also: Section :ref:`names-of-libraries`. :-R *directory* dirpath: Do as -Q *directory* dirpath but make the subdirectory structure of *directory* recursively visible so that the recursive contents of physical *directory* is available from |Coq| using - short or partially qualified names. See also: Section :ref:`TODO-2.6.1`. + short or partially qualified names. See also: Section :ref:`names-of-libraries`. :-top dirpath: Set the toplevel module name to dirpath instead of Top. Not valid for `coqc` as the toplevel module name is inferred from the name of the output file. @@ -145,7 +152,7 @@ and ``coqtop``, unless stated otherwise: -compile-verbose. :-w (all|none|w₁,…,wₙ): Configure the display of warnings. This option expects all, none or a comma-separated list of warning names or - categories (see Section :ref:`TODO-6.9.3`). + categories (see Section :ref:`controlling-display`). :-color (on|off|auto): Enable or not the coloring of output of `coqtop`. Default is auto, meaning that `coqtop` dynamically decides, depending on whether the output channel supports ANSI escape sequences. @@ -170,7 +177,7 @@ and ``coqtop``, unless stated otherwise: :-compat *version*: Attempt to maintain some backward-compatibility with a previous version. :-dump-glob *file*: Dump references for global names in file *file* - (to be used by coqdoc, see :ref:`TODO-15.4`). By default, if *file.v* is being + (to be used by coqdoc, see :ref:`coqdoc`). By default, if *file.v* is being compiled, *file.glob* is used. :-no-glob: Disable the dumping of references for global names. :-image *file*: Set the binary image to be used by `coqc` to be *file* diff --git a/doc/sphinx/practical-tools/coqide.rst b/doc/sphinx/practical-tools/coqide.rst index a3b9426287..f9903e6104 100644 --- a/doc/sphinx/practical-tools/coqide.rst +++ b/doc/sphinx/practical-tools/coqide.rst @@ -75,7 +75,7 @@ There are two additional buttons for navigation within the running buffer. The "down" button with a line goes directly to the end; the "up" button with a line goes back to the beginning. The handling of errors when using the go-to-the-end button depends on whether |Coq| is running in asynchronous mode or not (see -Chapter :ref:`Asyncprocessing`). If it is not running in that mode, execution +Chapter :ref:`asynchronousandparallelproofprocessing`). If it is not running in that mode, execution stops as soon as an error is found. Otherwise, execution continues, and the error is marked with an underline in the error foreground color, with a background in the error background color (pink by default). The same @@ -90,10 +90,10 @@ There are other buttons on the |CoqIDE| toolbar: a button to save the running buffer; a button to close the current buffer (an "X"); buttons to switch among buffers (left and right arrows); an "information" button; and a "gears" button. -The "information" button is described in Section :ref:`sec:trytactics`. +The "information" button is described in Section :ref:`try-tactics-automatically`. The "gears" button submits proof terms to the |Coq| kernel for type-checking. -When |Coq| uses asynchronous processing (see Chapter :ref:`Asyncprocessing`), +When |Coq| uses asynchronous processing (see Chapter :ref:`asynchronousandparallelproofprocessing`), proofs may have been completed without kernel-checking of generated proof terms. The presence of unchecked proof terms is indicated by ``Qed`` statements that have a subdued *being-processed* color (light blue by default), rather than the @@ -150,8 +150,6 @@ arguments. Queries ------------ -.. _coqide_queryselected: - .. image:: ../_static/coqide-queries.png :alt: |CoqIDE| queries @@ -161,7 +159,7 @@ writing them in scripts, |CoqIDE| offers a *query pane*. The query pane can be displayed on demand by using the ``View`` menu, or using the shortcut ``F1``. Queries can also be performed by selecting a particular phrase, then choosing an item from the ``Queries`` menu. The response then appears in the message window. -Figure :ref:`fig:queryselected` shows the result after selecting of the phrase +The image above shows the result after selecting of the phrase ``Nat.mul`` in the script window, and choosing ``Print`` from the ``Queries`` menu. diff --git a/doc/sphinx/practical-tools/utilities.rst b/doc/sphinx/practical-tools/utilities.rst index 620c002ff3..59867988a4 100644 --- a/doc/sphinx/practical-tools/utilities.rst +++ b/doc/sphinx/practical-tools/utilities.rst @@ -33,6 +33,7 @@ For example, to statically link |L_tac|, you can just do: % ocamlfind ocamlopt -thread -rectypes -linkall -linkpkg \ -package coq.toplevel -package coq.ltac \ toplevel/coqtop\_bin.ml -o my\_toplevel.native + and similarly for other plugins. @@ -43,7 +44,7 @@ The majority of |Coq| projects are very similar: a collection of ``.v`` files and eventually some ``.ml`` ones (a |Coq| plugin). The main piece of metadata needed in order to build the project are the command line options to ``coqc`` (e.g. ``-R``, ``-I``, see also: Section -:ref:`bycommandline`). Collecting the list of files and options is the job +:ref:`command-line-options`). Collecting the list of files and options is the job of the ``_CoqProject`` file. A simple example of a ``_CoqProject`` file follows: @@ -59,7 +60,7 @@ A simple example of a ``_CoqProject`` file follows: src/qux_plugin.mlpack -Currently, both |CoqIDE| and |ProofGeneral| (version ≥ ``4.3pre``) +Currently, both |CoqIDE| and Proof-General (version ≥ ``4.3pre``) understand ``_CoqProject`` files and invoke |Coq| with the desired options. The ``coq_makefile`` utility can be used to set up a build infrastructure @@ -77,7 +78,7 @@ CoqMakefile is a generic makefile for ``GNU Make`` that provides targets to build the project (both ``.v`` and ``.ml*`` files), to install it system-wide in the ``coq-contrib`` directory (i.e. where |Coq| is installed) - as well as to invoke |coqdoc| to generate |HTML| documentation. + as well as to invoke coqdoc to generate HTML documentation. CoqMakefile.conf contains make variables assignments that reflect @@ -89,7 +90,7 @@ An optional file ``CoqMakefile.local`` can be provided by the user in order to extend ``CoqMakefile``. In particular one can declare custom actions to be performed before or after the build process. Similarly one can customize the install target or even provide new targets. Extension points are documented in -paragraph :ref:`coqmakefile:local`. +paragraph :ref:`coqmakefilelocal`. The extensions of the files listed in ``_CoqProject`` is used in order to decide how to build them. In particular: @@ -113,32 +114,38 @@ distinct plugins because of a clash in their auxiliary module names. .. _coqmakefilelocal: CoqMakefile.local -+++++++++++++++++ - - +~~~~~~~~~~~~~~~~~ The optional file ``CoqMakefile.local`` is included by the generated file ``CoqMakefile``. It can contain two kinds of directives. -Variable assignment - The variable must belong to the variables listed in the ``Parameters`` section of the generated makefile. - Here we describe only few of them. - :CAMLPKGS: - can be used to specify third party findlib packages, and is - passed to the OCaml compiler on building or linking of modules. Eg: - ``-package yojson``. - :CAMLFLAGS: - can be used to specify additional flags to the |OCaml| - compiler, like ``-bin-annot`` or ``-w``.... - :COQC, COQDEP, COQDOC: - can be set in order to use alternative binaries - (e.g. wrappers) - :COQ_SRC_SUBDIRS: can be extended by including other paths in which ``*.cm*`` files are searched. For example ``COQ\_SRC\_SUBDIRS+=user-contrib/Unicoq`` lets you build a plugin containing OCaml code that depends on the OCaml code of ``Unicoq``. - -Rule extension - The following makefile rules can be extended. - - .. example :: +**Variable assignment** + +The variable must belong to the variables listed in the ``Parameters`` +section of the generated makefile. +Here we describe only few of them. + +:CAMLPKGS: + can be used to specify third party findlib packages, and is + passed to the OCaml compiler on building or linking of modules. Eg: + ``-package yojson``. +:CAMLFLAGS: + can be used to specify additional flags to the |OCaml| + compiler, like ``-bin-annot`` or ``-w``.... +:COQC, COQDEP, COQDOC: + can be set in order to use alternative binaries + (e.g. wrappers) +:COQ_SRC_SUBDIRS: + can be extended by including other paths in which ``*.cm*`` files + are searched. For example ``COQ\_SRC\_SUBDIRS+=user-contrib/Unicoq`` + lets you build a plugin containing OCaml code that depends on the + OCaml code of ``Unicoq``. + +**Rule extension** + +The following makefile rules can be extended. + +.. example:: :: @@ -147,42 +154,41 @@ Rule extension install-extra:: cp ThisExtraFile /there/it/goes - ``pre-all::`` - run before the all target. One can use this to configure - the project, or initialize sub modules or check dependencies are met. +``pre-all::`` + run before the ``all`` target. One can use this to configure + the project, or initialize sub modules or check dependencies are met. - ``post-all::`` - run after the all target. One can use this to run a test - suite, or compile extracted code. +``post-all::`` + run after the ``all`` target. One can use this to run a test + suite, or compile extracted code. +``install-extra::`` + run after ``install``. One can use this to install extra files. - ``install-extra::`` - run after install. One can use this to install extra files. +``install-doc::`` + One can use this to install extra doc. - ``install-doc::`` - One can use this to install extra doc. +``uninstall::`` + \ - ``uninstall::`` - \ +``uninstall-doc::`` + \ - ``uninstall-doc::`` - \ +``clean::`` + \ - ``clean::`` - \ +``cleanall::`` + \ - ``cleanall::`` - \ +``archclean::`` + \ - ``archclean::`` - \ - - ``merlin-hook::`` - One can append lines to the generated .merlin file extending this - target. +``merlin-hook::`` + One can append lines to the generated ``.merlin`` file extending this + target. Timing targets and performance testing -++++++++++++++++++++++++++++++++++++++ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The generated ``Makefile`` supports the generation of two kinds of timing data: per-file build-times, and per-line times for an individual file. @@ -311,8 +317,8 @@ line timing data: + ``print-pretty-single-time-diff`` :: - print-pretty-single-time-diff BEFORE=path/to/file.v.before-timing AFTER=path/to/file.v.after-timing + this target will make a sorted table of the per-line timing differences between the timing logs in the ``BEFORE`` and ``AFTER`` files, display it, and save it to the file specified by the ``TIME_OF_PRETTY_BUILD_FILE`` variable, @@ -357,7 +363,7 @@ line timing data: Reusing/extending the generated Makefile -++++++++++++++++++++++++++++++++++++++++ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Including the generated makefile with an include directive is discouraged. The contents of this file, including variable names and @@ -400,8 +406,8 @@ have a generic target for invoking unknown targets. -Building a subset of the targets with -j -++++++++++++++++++++++++++++++++++++++++ +Building a subset of the targets with ``-j`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To build, say, two targets foo.vo and bar.vo in parallel one can use ``make only TGTS="foo.vo bar.vo" -j``. @@ -451,14 +457,16 @@ automatically compute the dependencies among the files part of the project. +.. _coqdoc: + Documenting |Coq| files with coqdoc ----------------------------------- -|coqdoc| is a documentation tool for the proof assistant |Coq|, similar to -``javadoc`` or ``ocamldoc``. The task of |coqdoc| is +coqdoc is a documentation tool for the proof assistant |Coq|, similar to +``javadoc`` or ``ocamldoc``. The task of coqdoc is -#. to produce a nice |Latex| and/or |HTML| document from the |Coq| +#. to produce a nice |Latex| and/or HTML document from the |Coq| sources, readable for a human and not only for the proof assistant; #. to help the user navigating in his own (or third-party) sources. @@ -468,18 +476,18 @@ Principles ~~~~~~~~~~ Documentation is inserted into |Coq| files as *special comments*. Thus -your files will compile as usual, whether you use |coqdoc| or not. |coqdoc| +your files will compile as usual, whether you use coqdoc or not. coqdoc presupposes that the given |Coq| files are well-formed (at least lexically). Documentation starts with ``(**``, followed by a space, and ends with the pending ``*)``. The documentation format is inspired by Todd A. Coram’s *Almost Free Text (AFT)* tool: it is mainly ``ASCII`` text with -some syntax-light controls, described below. |coqdoc| is robust: it +some syntax-light controls, described below. coqdoc is robust: it shouldn’t fail, whatever the input is. But remember: “garbage in, garbage out”. |Coq| material inside documentation. -++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++ |Coq| material is quoted between the delimiters ``[`` and ``]``. Square brackets may be nested, the inner ones being understood as being part of the @@ -494,7 +502,7 @@ followed by a newline and the latter must follow a newline. Pretty-printing. ++++++++++++++++ -|coqdoc| uses different faces for identifiers and keywords. The pretty- +coqdoc uses different faces for identifiers and keywords. The pretty- printing of |Coq| tokens (identifiers or symbols) can be controlled using one of the following commands: @@ -512,8 +520,8 @@ or (** printing *token* $...LATEX math...$ #...html...# *) -It gives the |Latex| and |HTML| texts to be produced for the given |Coq| -token. One of the |Latex| or |HTML| text may be omitted, causing the +It gives the |Latex| and HTML texts to be produced for the given |Coq| +token. One of the |Latex| or HTML text may be omitted, causing the default pretty-printing to be used for this token. The printing for one token can be removed with @@ -530,27 +538,28 @@ Initially, the pretty-printing table contains the following mapping: `->` → `<-` ← `*` × `<=` ≤ `>=` ≥ `=>` ⇒ `<>` ≠ `<->` ↔ `|-` ⊢ -`\/` ∨ `/\` ∧ `~` ¬ +`\/` ∨ `/\\` ∧ `~` ¬ ==== === ==== ===== === ==== ==== === Any of these can be overwritten or suppressed using the printing commands. -.. note :: - The recognition of tokens is done by a (``ocaml``) lex - automaton and thus applies the longest-match rule. For instance, `->~` - is recognized as a single token, where |Coq| sees two tokens. It is the - responsibility of the user to insert space between tokens *or* to give - pretty-printing rules for the possible combinations, e.g. +.. note:: + + The recognition of tokens is done by a (``ocaml``) lex + automaton and thus applies the longest-match rule. For instance, `->~` + is recognized as a single token, where |Coq| sees two tokens. It is the + responsibility of the user to insert space between tokens *or* to give + pretty-printing rules for the possible combinations, e.g. - :: + :: (** printing ->~ %\ensuremath{\rightarrow\lnot}% *) -Sections. -+++++++++ +Sections +++++++++ Sections are introduced by 1 to 4 leading stars (i.e. at the beginning of the line) followed by a space. One star is a section, two stars a @@ -559,7 +568,7 @@ line. .. example:: - :: + :: (** * Well-founded relations @@ -614,18 +623,18 @@ emphasis. Usually, these are spaces or punctuation. -Escaping to |Latex| and |HTML|. +Escaping to |Latex| and HTML. +++++++++++++++++++++++++++++++ -Pure |Latex| or |HTML| material can be inserted using the following +Pure |Latex| or HTML material can be inserted using the following escape sequences: + ``$...LATEX stuff...$`` inserts some |Latex| material in math mode. - Simply discarded in |HTML| output. + Simply discarded in HTML output. + ``%...LATEX stuff...%`` inserts some |Latex| material. Simply - discarded in |HTML| output. -+ ``#...HTML stuff...#`` inserts some |HTML| material. Simply discarded in + discarded in HTML output. ++ ``#...HTML stuff...#`` inserts some HTML material. Simply discarded in |Latex| output. .. note:: @@ -654,7 +663,7 @@ at the beginning of a line. Hyperlinks ++++++++++ -Hyperlinks can be inserted into the |HTML| output, so that any +Hyperlinks can be inserted into the HTML output, so that any identifier is linked to the place of its definition. ``coqc file.v`` automatically dumps localization information in @@ -662,7 +671,7 @@ identifier is linked to the place of its definition. file``. Take care of erasing this global file, if any, when starting the whole compilation process. -Then invoke |coqdoc| or ``coqdoc --glob-from file`` to tell |coqdoc| to look +Then invoke coqdoc or ``coqdoc --glob-from file`` to tell coqdoc to look for name resolutions into the file ``file`` (it will look in ``file.glob`` by default). @@ -703,17 +712,17 @@ be used around a whole proof. Usage ~~~~~ -|coqdoc| is invoked on a shell command line as follows: +coqdoc is invoked on a shell command line as follows: ``coqdoc <options and files>``. Any command line argument which is not an option is considered to be a file (even if it starts with a ``-``). |Coq| files are identified by the suffixes ``.v`` and ``.g`` and |Latex| files by the suffix ``.tex``. -:|HTML| output: This is the default output. One |HTML| file is created for +:HTML output: This is the default output. One HTML file is created for each |Coq| file given on the command line, together with a file - ``index.html`` (unless ``option-no-index is passed``). The |HTML| pages use a - style sheet named ``style.css``. Such a file is distributed with |coqdoc|. + ``index.html`` (unless ``option-no-index is passed``). The HTML pages use a + style sheet named ``style.css``. Such a file is distributed with coqdoc. :|Latex| output: A single |Latex| file is created, on standard output. It can be redirected to a file with option ``-o``. The order of files on the command line is kept in the final document. |Latex| @@ -732,7 +741,7 @@ Command line options **Overall options** - :--|HTML|: Select a |HTML| output. + :--HTML: Select a HTML output. :--|Latex|: Select a |Latex| output. :--dvi: Select a DVI output. :--ps: Select a PostScript output. @@ -760,7 +769,7 @@ Command line options **Index options** - Default behavior is to build an index, for the |HTML| output only, + Default behavior is to build an index, for the HTML output only, into ``index.html``. :--no-index: Do not output the index. @@ -775,7 +784,7 @@ Command line options :-toc, --table-of-contents: Insert a table of contents. For a |Latex| output, it inserts a ``\tableofcontents`` at the beginning of the - document. For a |HTML| output, it builds a table of contents into + document. For a HTML output, it builds a table of contents into ``toc.html``. :--toc-depth int: Only include headers up to depth ``int`` in the table of contents. @@ -795,28 +804,28 @@ Command line options directory ``coqdir`` (similarly to |Coq| option ``-R``). .. note:: - option ``-R`` only has - effect on the files *following* it on the command line, so you will - probably need to put this option first. + + option ``-R`` only has + effect on the files *following* it on the command line, so you will + probably need to put this option first. **Title options** :-s , --short: Do not insert titles for the files. The default - behavior is to insert a title like “Library Foo” for each file. + behavior is to insert a title like “Library Foo” for each file. :--lib-name string: Print “string Foo” instead of “Library Foo” in - titles. For example “Chapter” and “Module” are reasonable choices. + titles. For example “Chapter” and “Module” are reasonable choices. :--no-lib-name: Print just “Foo” instead of “Library Foo” in titles. :--lib-subtitles: Look for library subtitles. When enabled, the - beginning of each file is checked for a comment of the form: - - :: + beginning of each file is checked for a comment of the form: + :: - (** * ModuleName : text *) + (** * ModuleName : text *) - where ``ModuleName`` must be the name of the file. If it is present, the - text is used as a subtitle for the module in appropriate places. + where ``ModuleName`` must be the name of the file. If it is present, the + text is used as a subtitle for the module in appropriate places. :-t string, --title string: Set the document title. @@ -854,11 +863,11 @@ Command line options :-latin1, --latin1: Select ISO-8859-1 input files. It is equivalent to --inputenc latin1 --charset iso-8859-1. :-utf8, --utf8: Set --inputenc utf8x for |Latex| output and--charset - utf-8 for |HTML| output. Also use Unicode replacements for a couple of + utf-8 for HTML output. Also use Unicode replacements for a couple of standard plain ASCII notations such as → for ``->`` and ∀ for ``forall``. |Latex| UTF-8 support can be found at `<http://www.ctan.org/pkg/unicode>`_. For the interpretation of Unicode - characters by |Latex|, extra packages which |coqdoc| does not provide + characters by |Latex|, extra packages which coqdoc does not provide by default might be required, such as textgreek for some Greek letters or ``stmaryrd`` for some mathematical symbols. If a Unicode character is missing an interpretation in the utf8x input encoding, add @@ -866,13 +875,13 @@ Command line options and declarations can be added with option ``-p``. :--inputenc string: Give a |Latex| input encoding, as an option to |Latex| package ``inputenc``. - :--charset string: Specify the |HTML| character set, to be inserted in - the |HTML| header. + :--charset string: Specify the HTML character set, to be inserted in + the HTML header. The coqdoc |Latex| style file -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In case you choose to produce a document without the default |Latex| preamble (by using option ``--no-preamble``), then you must insert into @@ -929,16 +938,16 @@ There are options to produce the |Coq| parts in smaller font, italic, between horizontal rules, etc. See the man page of ``coq-tex`` for more details. -|Coq| and |GNU| |Emacs| +|Coq| and GNU Emacs ----------------------- -The |Coq| |Emacs| mode +The |Coq| Emacs mode ~~~~~~~~~~~~~~~~~~~~~~~~~ -|Coq| comes with a Major mode for |GNU| |Emacs|, ``gallina.el``. This mode +|Coq| comes with a Major mode for GNU Emacs, ``gallina.el``. This mode provides syntax highlighting and also a rudimentary indentation -facility in the style of the ``Caml`` |GNU| |Emacs| mode. +facility in the style of the ``Caml`` GNU Emacs mode. Add the following lines to your ``.emacs`` file: @@ -956,26 +965,26 @@ facility: + pressing ``Tab`` at the beginning of a line indents the line like the line above; -+ extra ``Tab``s increase the indentation level (by 2 spaces by default); ++ extra tabulations increase the indentation level (by 2 spaces by default); + ``M-Tab`` decreases the indentation level. -An inferior mode to run |Coq| under |Emacs|, by Marco Maggesi, is also +An inferior mode to run |Coq| under Emacs, by Marco Maggesi, is also included in the distribution, in file ``inferior-coq.el``. Instructions to use it are contained in this file. -Proof General +Proof-General ~~~~~~~~~~~~~ -|ProofGeneral| is a generic interface for proof assistants based on -|Emacs|. The main idea is that the |Coq| commands you are editing are sent -to a |Coq| toplevel running behind |Emacs| and the answers of the system -automatically inserted into other |Emacs| buffers. Thus you don’t need +Proof-General is a generic interface for proof assistants based on +Emacs. The main idea is that the |Coq| commands you are editing are sent +to a |Coq| toplevel running behind Emacs and the answers of the system +automatically inserted into other Emacs buffers. Thus you don’t need to copy-paste the |Coq| material from your files to the |Coq| toplevel or conversely from the |Coq| toplevel to some files. -|ProofGeneral| is developed and distributed independently of the system +Proof-General is developed and distributed independently of the system |Coq|. It is freely available at `<https://proofgeneral.github.io/>`_. diff --git a/doc/sphinx/proof-engine/detailed-tactic-examples.rst b/doc/sphinx/proof-engine/detailed-tactic-examples.rst index 932f967881..84810ddba5 100644 --- a/doc/sphinx/proof-engine/detailed-tactic-examples.rst +++ b/doc/sphinx/proof-engine/detailed-tactic-examples.rst @@ -6,6 +6,8 @@ Detailed examples of tactics This chapter presents detailed examples of certain tactics, to illustrate their behavior. +.. _dependent-induction: + dependent induction ------------------- @@ -316,7 +318,7 @@ explicit proof terms: This concludes our example. -See also: The ``induction`` :ref:`TODO-9-induction`, ``case`` :ref:`TODO-9-induction` and ``inversion`` :ref:`TODO-8.14-inversion` tactics. +See also: The :tacn:`induction`, :tacn:`case`, and :tacn:`inversion` tactics. autorewrite @@ -403,6 +405,8 @@ Example 2: Mac Carthy function autorewrite with base1 using reflexivity || simpl. +.. _quote: + quote ----- @@ -544,8 +548,7 @@ Combining variables and constants ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One can have both variables and constants in abstracts terms; for -example, this is the case for the ``ring`` tactic -:ref:`TODO-25-ringandfieldtacticfamilies`. Then one must provide to +example, this is the case for the :tacn:`ring` tactic. Then one must provide to ``quote`` a list of *constructors of constants*. For example, if the list is ``[O S]`` then closed natural numbers will be considered as constants and other terms as variables. @@ -606,7 +609,7 @@ don’t expect miracles from it! See also: comments of source file ``plugins/quote/quote.ml`` -See also: the ``ring`` tactic :ref:`TODO-25-ringandfieldtacticfamilies` +See also: the :tacn:`ring` tactic. Using the tactical language @@ -733,7 +736,7 @@ and this length is decremented for each rotation down to, but not including, 1 because for a list of length ``n``, we can make exactly ``n−1`` rotations to generate at most ``n`` distinct lists. Here, it must be noticed that we use the natural numbers of Coq for the -rotation counter. On Figure :ref:`TODO-9.1-tactic-language`, we can +rotation counter. In :ref:`ltac-syntax`, we can see that it is possible to use usual natural numbers but they are only used as arguments for primitive tactics and they cannot be handled, in particular, we cannot make computations with them. So, a natural @@ -830,7 +833,7 @@ The pattern matching on goals allows a complete and so a powerful backtracking when returning tactic values. An interesting application is the problem of deciding intuitionistic propositional logic. Considering the contraction-free sequent calculi LJT* of Roy Dyckhoff -:ref:`TODO-56-biblio`, it is quite natural to code such a tactic +:cite:`Dyc92`, it is quite natural to code such a tactic using the tactic language as shown on figures: :ref:`Deciding intuitionistic propositions (1) <decidingintuitionistic1>` and :ref:`Deciding intuitionistic propositions (2) @@ -868,7 +871,7 @@ Deciding type isomorphisms A more tricky problem is to decide equalities between types and modulo isomorphisms. Here, we choose to use the isomorphisms of the simply typed λ-calculus with Cartesian product and unit type (see, for -example, [:ref:`TODO-45`]). The axioms of this λ-calculus are given below. +example, :cite:`RC95`). The axioms of this λ-calculus are given below. .. coqtop:: in reset diff --git a/doc/sphinx/proof-engine/ltac.rst b/doc/sphinx/proof-engine/ltac.rst new file mode 100644 index 0000000000..009758319b --- /dev/null +++ b/doc/sphinx/proof-engine/ltac.rst @@ -0,0 +1,1300 @@ +.. include:: ../preamble.rst +.. include:: ../replaces.rst + +.. _ltac: + +The tactic language +=================== + +This chapter gives a compact documentation of |Ltac|, the tactic language +available in |Coq|. We start by giving the syntax, and next, we present the +informal semantics. If you want to know more regarding this language and +especially about its foundations, you can refer to :cite:`Del00`. Chapter +:ref:`detailedexamplesoftactics` is devoted to giving examples of use of this +language on small but also with non-trivial problems. + +.. _ltac-syntax: + +Syntax +------ + +The syntax of the tactic language is given below. See Chapter +:ref:`gallinaspecificationlanguage` for a description of the BNF metasyntax used +in these grammar rules. Various already defined entries will be used in this +chapter: entries :token:`natural`, :token:`integer`, :token:`ident`, +:token:`qualid`, :token:`term`, :token:`cpattern` and :token:`atomic_tactic` +represent respectively the natural and integer numbers, the authorized +identificators and qualified names, Coq terms and patterns and all the atomic +tactics described in Chapter :ref:`tactics`. The syntax of :token:`cpattern` is +the same as that of terms, but it is extended with pattern matching +metavariables. In :token:`cpattern`, a pattern-matching metavariable is +represented with the syntax :g:`?id` where :g:`id` is an :token:`ident`. The +notation :g:`_` can also be used to denote metavariable whose instance is +irrelevant. In the notation :g:`?id`, the identifier allows us to keep +instantiations and to make constraints whereas :g:`_` shows that we are not +interested in what will be matched. On the right hand side of pattern-matching +clauses, the named metavariable are used without the question mark prefix. There +is also a special notation for second-order pattern-matching problems: in an +applicative pattern of the form :g:`@?id id1 … idn`, the variable id matches any +complex expression with (possible) dependencies in the variables :g:`id1 … idn` +and returns a functional term of the form :g:`fun id1 … idn => term`. + +The main entry of the grammar is :n:`@expr`. This language is used in proof +mode but it can also be used in toplevel definitions as shown below. + +.. note:: + + - The infix tacticals “… \|\| …”, “… + …”, and “… ; …” are associative. + + - In :token:`tacarg`, there is an overlap between qualid as a direct tactic + argument and :token:`qualid` as a particular case of term. The resolution is + done by first looking for a reference of the tactic language and if + it fails, for a reference to a term. To force the resolution as a + reference of the tactic language, use the form :g:`ltac:(@qualid)`. To + force the resolution as a reference to a term, use the syntax + :g:`(@qualid)`. + + - As shown by the figure, tactical ``\|\|`` binds more than the prefix + tacticals try, repeat, do and abstract which themselves bind more + than the postfix tactical “… ;[ … ]” which binds more than “… ; …”. + + For instance + + .. coqtop:: in + + try repeat tac1 || tac2; tac3; [tac31 | ... | tac3n]; tac4. + + is understood as + + .. coqtop:: in + + try (repeat (tac1 || tac2)); + ((tac3; [tac31 | ... | tac3n]); tac4). + +.. productionlist:: coq + expr : `expr` ; `expr` + : | [> `expr` | ... | `expr` ] + : | `expr` ; [ `expr` | ... | `expr` ] + : | `tacexpr3` + tacexpr3 : do (`natural` | `ident`) tacexpr3 + : | progress `tacexpr3` + : | repeat `tacexpr3` + : | try `tacexpr3` + : | once `tacexpr3` + : | exactly_once `tacexpr3` + : | timeout (`natural` | `ident`) `tacexpr3` + : | time [`string`] `tacexpr3` + : | only `selector`: `tacexpr3` + : | `tacexpr2` + tacexpr2 : `tacexpr1` || `tacexpr3` + : | `tacexpr1` + `tacexpr3` + : | tryif `tacexpr1` then `tacexpr1` else `tacexpr1` + : | `tacexpr1` + tacexpr1 : fun `name` ... `name` => `atom` + : | let [rec] `let_clause` with ... with `let_clause` in `atom` + : | match goal with `context_rule` | ... | `context_rule` end + : | match reverse goal with `context_rule` | ... | `context_rule` end + : | match `expr` with `match_rule` | ... | `match_rule` end + : | lazymatch goal with `context_rule` | ... | `context_rule` end + : | lazymatch reverse goal with `context_rule` | ... | `context_rule` end + : | lazymatch `expr` with `match_rule` | ... | `match_rule` end + : | multimatch goal with `context_rule` | ... | `context_rule` end + : | multimatch reverse goal with `context_rule` | ... | `context_rule` end + : | multimatch `expr` with `match_rule` | ... | `match_rule` end + : | abstract `atom` + : | abstract `atom` using `ident` + : | first [ `expr` | ... | `expr` ] + : | solve [ `expr` | ... | `expr` ] + : | idtac [ `message_token` ... `message_token`] + : | fail [`natural`] [`message_token` ... `message_token`] + : | fresh | fresh `string` | fresh `qualid` + : | context `ident` [`term`] + : | eval `redexpr` in `term` + : | type of `term` + : | constr : `term` + : | uconstr : `term` + : | type_term `term` + : | numgoals + : | guard `test` + : | assert_fails `tacexpr3` + : | assert_suceeds `tacexpr3` + : | `atomic_tactic` + : | `qualid` `tacarg` ... `tacarg` + : | `atom` + atom : `qualid` + : | () + : | `integer` + : | ( `expr` ) + message_token : `string` | `ident` | `integer` + tacarg : `qualid` + : | () + : | ltac : `atom` + : | `term` + let_clause : `ident` [`name` ... `name`] := `expr` + context_rule : `context_hyp`, ..., `context_hyp` |- `cpattern` => `expr` + : | `cpattern` => `expr` + : | |- `cpattern` => `expr` + : | _ => `expr` + context_hyp : `name` : `cpattern` + : | `name` := `cpattern` [: `cpattern`] + match_rule : `cpattern` => `expr` + : | context [ident] [ `cpattern` ] => `expr` + : | _ => `expr` + test : `integer` = `integer` + : | `integer` (< | <= | > | >=) `integer` + selector : [`ident`] + : | `integer` + : (`integer` | `integer` - `integer`), ..., (`integer` | `integer` - `integer`) + toplevel_selector : `selector` + : | `all` + : | `par` + +.. productionlist:: coq + top : [Local] Ltac `ltac_def` with ... with `ltac_def` + ltac_def : `ident` [`ident` ... `ident`] := `expr` + : | `qualid` [`ident` ... `ident`] ::= `expr` + +.. _ltac-semantics: + +Semantics +--------- + +Tactic expressions can only be applied in the context of a proof. The +evaluation yields either a term, an integer or a tactic. Intermediary +results can be terms or integers but the final result must be a tactic +which is then applied to the focused goals. + +There is a special case for ``match goal`` expressions of which the clauses +evaluate to tactics. Such expressions can only be used as end result of +a tactic expression (never as argument of a non recursive local +definition or of an application). + +The rest of this section explains the semantics of every construction of +|Ltac|. + +Sequence +~~~~~~~~ + +A sequence is an expression of the following form: + +.. tacn:: @expr ; @expr + :name: ; + + The expression :n:`@expr__1` is evaluated to :n:`v__1`, which must be + a tactic value. The tactic :n:`v__1` is applied to the current goal, + possibly producing more goals. Then :n:`@expr__2` is evaluated to + produce :n:`v__2`, which must be a tactic value. The tactic + :n:`v__2` is applied to all the goals produced by the prior + application. Sequence is associative. + +Local application of tactics +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Different tactics can be applied to the different goals using the +following form: + +.. tacn:: [> {*| @expr }] + :name: [> ... | ... | ... ] (dispatch) + + The expressions :n:`@expr__i` are evaluated to :n:`v__i`, for + i=0,...,n and all have to be tactics. The :n:`v__i` is applied to the + i-th goal, for =1,...,n. It fails if the number of focused goals is not + exactly n. + + .. note:: + + If no tactic is given for the i-th goal, it behaves as if the tactic idtac + were given. For instance, ``[> | auto]`` is a shortcut for ``[> idtac | auto + ]``. + + .. tacv:: [> {*| @expr} | @expr .. | {*| @expr}] + + In this variant, token:`expr` is used for each goal coming after those + covered by the first list of :n:`@expr` but before those coevered by the + last list of :n:`@expr`. + + .. tacv:: [> {*| @expr} | .. | {*| @expr}] + + In this variant, idtac is used for the goals not covered by the two lists of + :n:`@expr`. + + .. tacv:: [> @expr .. ] + + In this variant, the tactic :n:`@expr` is applied independently to each of + the goals, rather than globally. In particular, if there are no goal, the + tactic is not run at all. A tactic which expects multiple goals, such as + ``swap``, would act as if a single goal is focused. + + .. tacv:: expr ; [{*| @expr}] + + This variant of local tactic application is paired with a sequence. In this + variant, there must be as many :n:`@expr` in the list as goals generated + by the application of the first :n:`@expr` to each of the individual goals + independently. All the above variants work in this form too. + Formally, :n:`@expr ; [ ... ]` is equivalent to :n:`[> @expr ; [> ... ] .. ]`. + +.. _goal-selectors: + +Goal selectors +~~~~~~~~~~~~~~ + +We can restrict the application of a tactic to a subset of the currently +focused goals with: + +.. tacn:: @toplevel_selector : @expr + :name: ... : ... (goal selector) + + We can also use selectors as a tactical, which allows to use them nested + in a tactic expression, by using the keyword ``only``: + + .. tacv:: only selector : expr + + When selecting several goals, the tactic expr is applied globally to all + selected goals. + + .. tacv:: [@ident] : @expr + + In this variant, :n:`@expr` is applied locally to a goal previously named + by the user (see :ref:`existential-variables`). + + .. tacv:: @num : @expr + + In this variant, :n:`@expr` is applied locally to the :token:`num`-th goal. + + .. tacv:: {+, @num-@num} : @expr + + In this variant, :n:`@expr` is applied globally to the subset of goals + described by the given ranges. You can write a single ``n`` as a shortcut + for ``n-n`` when specifying multiple ranges. + + .. tacv:: all: @expr + + In this variant, :n:`@expr` is applied to all focused goals. ``all:`` can only + be used at the toplevel of a tactic expression. + + .. tacv:: par: @expr + + In this variant, :n:`@expr` is applied to all focused goals in parallel. + The number of workers can be controlled via the command line option + ``-async-proofs-tac-j`` taking as argument the desired number of workers. + Limitations: ``par:`` only works on goals containing no existential + variables and :n:`@expr` must either solve the goal completely or do + nothing (i.e. it cannot make some progress). ``par:`` can only be used at + the toplevel of a tactic expression. + + .. exn:: No such goal + :name: No such goal (goal selector) + + .. TODO change error message index entry + +For loop +~~~~~~~~ + +There is a for loop that repeats a tactic :token:`num` times: + +.. tacn:: do @num @expr + :name: do + + :n:`@expr` is evaluated to ``v`` which must be a tactic value. This tactic + value ``v`` is applied :token:`num` times. Supposing :token:`num` > 1, after the + first application of ``v``, ``v`` is applied, at least once, to the generated + subgoals and so on. It fails if the application of ``v`` fails before the num + applications have been completed. + +Repeat loop +~~~~~~~~~~~ + +We have a repeat loop with: + +.. tacn:: repeat @expr + :name: repeat + + :n:`@expr` is evaluated to ``v``. If ``v`` denotes a tactic, this tactic is + applied to each focused goal independently. If the application succeeds, the + tactic is applied recursively to all the generated subgoals until it eventually + fails. The recursion stops in a subgoal when the tactic has failed *to make + progress*. The tactic :n:`repeat @expr` itself never fails. + +Error catching +~~~~~~~~~~~~~~ + +We can catch the tactic errors with: + +.. tacn:: try @expr + :name: try + + :n:`@expr` is evaluated to ``v`` which must be a tactic value. The tactic + value ``v`` is applied to each focused goal independently. If the application of + ``v`` fails in a goal, it catches the error and leaves the goal unchanged. If the + level of the exception is positive, then the exception is re-raised with its + level decremented. + +Detecting progress +~~~~~~~~~~~~~~~~~~ + +We can check if a tactic made progress with: + +.. tacn:: progress expr + :name: progress + + :n:`@expr` is evaluated to v which must be a tactic value. The tactic value ``v`` + is applied to each focued subgoal independently. If the application of ``v`` + to one of the focused subgoal produced subgoals equal to the initial + goals (up to syntactical equality), then an error of level 0 is raised. + + .. exn:: Failed to progress + +Backtracking branching +~~~~~~~~~~~~~~~~~~~~~~ + +We can branch with the following structure: + +.. tacn:: @expr__1 + @expr__2 + :name: + (backtracking branching) + + :n:`@expr__1` and :n:`@expr__2` are evaluated respectively to :n:`v__1` and + :n:`v__2` which must be tactic values. The tactic value :n:`v__1` is applied to + each focused goal independently and if it fails or a later tactic fails, then + the proof backtracks to the current goal and :n:`v__2` is applied. + + Tactics can be seen as having several successes. When a tactic fails it + asks for more successes of the prior tactics. + :n:`@expr__1 + @expr__2` has all the successes of :n:`v__1` followed by all the + successes of :n:`v__2`. Algebraically, + :n:`(@expr__1 + @expr__2); @expr__3 = (@expr__1; @expr__3) + (@expr__2; @expr__3)`. + + Branching is left-associative. + +First tactic to work +~~~~~~~~~~~~~~~~~~~~ + +Backtracking branching may be too expensive. In this case we may +restrict to a local, left biased, branching and consider the first +tactic to work (i.e. which does not fail) among a panel of tactics: + +.. tacn:: first [{*| @expr}] + :name: first + + The :n:`@expr__i` are evaluated to :n:`v__i` and :n:`v__i` must be + tactic values, for i=1,...,n. Supposing n>1, it applies, in each focused + goal independently, :n:`v__1`, if it works, it stops otherwise it + tries to apply :n:`v__2` and so on. It fails when there is no + applicable tactic. In other words, + :n:`first [:@expr__1 | ... | @expr__n]` behaves, in each goal, as the the first + :n:`v__i` to have *at least* one success. + + .. exn:: Error message: No applicable tactic + + .. tacv:: first @expr + + This is an |Ltac| alias that gives a primitive access to the first + tactical as a |Ltac| definition without going through a parsing rule. It + expects to be given a list of tactics through a ``Tactic Notation``, + allowing to write notations of the following form: + + .. example:: + + .. coqtop:: in + + Tactic Notation "foo" tactic_list(tacs) := first tacs. + +Left-biased branching +~~~~~~~~~~~~~~~~~~~~~ + +Yet another way of branching without backtracking is the following +structure: + +.. tacn:: @expr__1 || @expr__2 + :name: || (left-biased branching) + + :n:`@expr__1` and :n:`@expr__2` are evaluated respectively to :n:`v__1` and + :n:`v__2` which must be tactic values. The tactic value :n:`v__1` is + applied in each subgoal independently and if it fails *to progress* then + :n:`v__2` is applied. :n:`@expr__1 || @expr__2` is + equivalent to :n:`first [ progress @expr__1 | @expr__2 ]` (except that + if it fails, it fails like :n:`v__2`). Branching is left-associative. + +Generalized biased branching +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The tactic + +.. tacn:: tryif @expr__1 then @expr__2 else @expr__3 + :name: tryif + + is a generalization of the biased-branching tactics above. The + expression :n:`@expr__1` is evaluated to :n:`v__1`, which is then + applied to each subgoal independently. For each goal where :n:`v__1` + succeeds at least once, :n:`@expr__2` is evaluated to :n:`v__2` which + is then applied collectively to the generated subgoals. The :n:`v__2` + tactic can trigger backtracking points in :n:`v__1`: where :n:`v__1` + succeeds at least once, + :n:`tryif @expr__1 then @expr__2 else @expr__3` is equivalent to + :n:`v__1; v__2`. In each of the goals where :n:`v__1` does not succeed at least + once, :n:`@expr__3` is evaluated in :n:`v__3` which is is then applied to the + goal. + +Soft cut +~~~~~~~~ + +Another way of restricting backtracking is to restrict a tactic to a +single success *a posteriori*: + +.. tacn:: once @expr + :name: once + + :n:`@expr` is evaluated to ``v`` which must be a tactic value. The tactic value + ``v`` is applied but only its first success is used. If ``v`` fails, + :n:`once @expr` fails like ``v``. If ``v`` has a least one success, + :n:`once @expr` succeeds once, but cannot produce more successes. + +Checking the successes +~~~~~~~~~~~~~~~~~~~~~~ + +Coq provides an experimental way to check that a tactic has *exactly +one* success: + +.. tacn:: exactly_once @expr + :name: exactly_once + + :n:`@expr` is evaluated to ``v`` which must be a tactic value. The tactic value + ``v`` is applied if it has at most one success. If ``v`` fails, + :n:`exactly_once @expr` fails like ``v``. If ``v`` has a exactly one success, + :n:`exactly_once @expr` succeeds like ``v``. If ``v`` has two or more + successes, exactly_once expr fails. + + .. warning:: + + The experimental status of this tactic pertains to the fact if ``v`` + performs side effects, they may occur in a unpredictable way. Indeed, + normally ``v`` would only be executed up to the first success until + backtracking is needed, however exactly_once needs to look ahead to see + whether a second success exists, and may run further effects + immediately. + + .. exn:: This tactic has more than one success + +Checking the failure +~~~~~~~~~~~~~~~~~~~~ + +Coq provides a derived tactic to check that a tactic *fails*: + +.. tacn:: assert_fails @expr + :name: assert_fails + + This behaves like :n:`tryif @expr then fail 0 tac "succeeds" else idtac`. + +Checking the success +~~~~~~~~~~~~~~~~~~~~ + +Coq provides a derived tactic to check that a tactic has *at least one* +success: + +.. tacn:: assert_succeeds @expr + :name: assert_suceeds + + This behaves like + :n:`tryif (assert_fails tac) then fail 0 tac "fails" else idtac`. + +Solving +~~~~~~~ + +We may consider the first to solve (i.e. which generates no subgoal) +among a panel of tactics: + +.. tacn:: solve [{*| @expr}] + :name: solve + + The :n:`@expr__i` are evaluated to :n:`v__i` and :n:`v__i` must be + tactic values, for i=1,...,n. Supposing n>1, it applies :n:`v__1` to + each goal independently, if it doesn’t solve the goal then it tries to + apply :n:`v__2` and so on. It fails if there is no solving tactic. + + .. exn:: Cannot solve the goal + + .. tacv:: solve @expr + + This is an |Ltac| alias that gives a primitive access to the :n:`solve:` + tactical. See the :n:`first` tactical for more information. + +Identity +~~~~~~~~ + +The constant :n:`idtac` is the identity tactic: it leaves any goal unchanged but +it appears in the proof script. + +.. tacn:: idtac {* message_token} + :name: idtac + + This prints the given tokens. Strings and integers are printed + literally. If a (term) variable is given, its contents are printed. + +Failing +~~~~~~~ + +.. tacn:: fail + :name: fail + + This is the always-failing tactic: it does not solve any + goal. It is useful for defining other tacticals since it can be caught by + :tacn:`try`, :tacn:`repeat`, :tacn:`match goal`, or the branching tacticals. The + :tacn:`fail` tactic will, however, succeed if all the goals have already been + solved. + + .. tacv:: fail @natural + + The number is the failure level. If no level is specified, it defaults to 0. + The level is used by :tacn:`try`, :tacn:`repeat`, :tacn:`match goal` and the branching + tacticals. If 0, it makes :tacn:`match goal` considering the next clause + (backtracking). If non zero, the current :tacn:`match goal` block, :tacn:`try`, + :tacn:`repeat`, or branching command is aborted and the level is decremented. In + the case of :n:`+`, a non-zero level skips the first backtrack point, even if + the call to :n:`fail @natural` is not enclosed in a :n:`+` command, + respecting the algebraic identity. + + .. tacv:: fail {* message_token} + + The given tokens are used for printing the failure message. + + .. tacv:: fail @natural {* message_token} + + This is a combination of the previous variants. + + .. tacv:: gfail + :name: gfail + + This variant fails even if there are no goals left. + + .. tacv:: gfail {* message_token} + + .. tacv:: gfail @natural {* message_token} + + These variants fail with an error message or an error level even if + there are no goals left. Be careful however if Coq terms have to be + printed as part of the failure: term construction always forces the + tactic into the goals, meaning that if there are no goals when it is + evaluated, a tactic call like :n:`let x:=H in fail 0 x` will succeed. + + .. exn:: Tactic Failure message (level @natural). + +Timeout +~~~~~~~ + +We can force a tactic to stop if it has not finished after a certain +amount of time: + +.. tacn:: timeout @num @expr + :name: timeout + + :n:`@expr` is evaluated to ``v`` which must be a tactic value. The tactic value + ``v`` is applied normally, except that it is interrupted after :n:`@num` seconds + if it is still running. In this case the outcome is a failure. + + .. warning:: + + For the moment, timeout is based on elapsed time in seconds, + which is very machine-dependent: a script that works on a quick machine + may fail on a slow one. The converse is even possible if you combine a + timeout with some other tacticals. This tactical is hence proposed only + for convenience during debug or other development phases, we strongly + advise you to not leave any timeout in final scripts. Note also that + this tactical isn’t available on the native Windows port of Coq. + +Timing a tactic +~~~~~~~~~~~~~~~ + +A tactic execution can be timed: + +.. tacn:: time @string @expr + :name: time + + evaluates :n:`@expr` and displays the time the tactic expression ran, whether it + fails or successes. In case of several successes, the time for each successive + runs is displayed. Time is in seconds and is machine-dependent. The :n:`@string` + argument is optional. When provided, it is used to identify this particular + occurrence of time. + +Timing a tactic that evaluates to a term +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tactic expressions that produce terms can be timed with the experimental +tactic + +.. tacn:: time_constr expr + :name: time_constr + + which evaluates :n:`@expr ()` and displays the time the tactic expression + evaluated, assuming successful evaluation. Time is in seconds and is + machine-dependent. + + This tactic currently does not support nesting, and will report times + based on the innermost execution. This is due to the fact that it is + implemented using the tactics + + .. tacn:: restart_timer @string + :name: restart_timer + + and + + .. tacn:: finish_timing {? @string} @string + :name: finish_timing + + which (re)set and display an optionally named timer, respectively. The + parenthesized string argument to :n:`finish_timing` is also optional, and + determines the label associated with the timer for printing. + + By copying the definition of :n:`time_constr` from the standard library, + users can achive support for a fixed pattern of nesting by passing + different :n:`@string` parameters to :n:`restart_timer` and :n:`finish_timing` + at each level of nesting. + + .. example:: + + .. coqtop:: all + + Ltac time_constr1 tac := + let eval_early := match goal with _ => restart_timer "(depth 1)" end in + let ret := tac () in + let eval_early := match goal with _ => finish_timing ( "Tactic evaluation" ) "(depth 1)" end in + ret. + + Goal True. + let v := time_constr + ltac:(fun _ => + let x := time_constr1 ltac:(fun _ => constr:(10 * 10)) in + let y := time_constr1 ltac:(fun _ => eval compute in x) in + y) in + pose v. + Abort. + +Local definitions +~~~~~~~~~~~~~~~~~ + +Local definitions can be done as follows: + +.. tacn:: let @ident__1 := @expr__1 {* with @ident__i := @expr__i} in @expr + + each :n:`@expr__i` is evaluated to :n:`v__i`, then, :n:`@expr` is evaluated + by substituting :n:`v__i` to each occurrence of :n:`@ident__i`, for + i=1,...,n. There is no dependencies between the :n:`@expr__i` and the + :n:`@ident__i`. + + Local definitions can be recursive by using :n:`let rec` instead of :n:`let`. + In this latter case, the definitions are evaluated lazily so that the rec + keyword can be used also in non recursive cases so as to avoid the eager + evaluation of local definitions. + + .. but rec changes the binding!! + +Application +~~~~~~~~~~~ + +An application is an expression of the following form: + +.. tacn:: @qualid {+ @tacarg} + + The reference :n:`@qualid` must be bound to some defined tactic definition + expecting at least as many arguments as the provided :n:`tacarg`. The + expressions :n:`@expr__i` are evaluated to :n:`v__i`, for i=1,...,n. + + .. what expressions ?? + +Function construction +~~~~~~~~~~~~~~~~~~~~~ + +A parameterized tactic can be built anonymously (without resorting to +local definitions) with: + +.. tacn:: fun {+ @ident} => @expr + + Indeed, local definitions of functions are a syntactic sugar for binding + a :n:`fun` tactic to an identifier. + +Pattern matching on terms +~~~~~~~~~~~~~~~~~~~~~~~~~ + +We can carry out pattern matching on terms with: + +.. tacn:: match @expr with {+| @cpattern__i => @expr__i} end + + The expression :n:`@expr` is evaluated and should yield a term which is + matched against :n:`cpattern__1`. The matching is non-linear: if a + metavariable occurs more than once, it should match the same expression + every time. It is first-order except on the variables of the form :n:`@?id` + that occur in head position of an application. For these variables, the + matching is second-order and returns a functional term. + + Alternatively, when a metavariable of the form :n:`?id` occurs under binders, + say :n:`x__1, …, x__n` and the expression matches, the + metavariable is instantiated by a term which can then be used in any + context which also binds the variables :n:`x__1, …, x__n` with + same types. This provides with a primitive form of matching under + context which does not require manipulating a functional term. + + If the matching with :n:`@cpattern__1` succeeds, then :n:`@expr__1` is + evaluated into some value by substituting the pattern matching + instantiations to the metavariables. If :n:`@expr__1` evaluates to a + tactic and the match expression is in position to be applied to a goal + (e.g. it is not bound to a variable by a :n:`let in`), then this tactic is + applied. If the tactic succeeds, the list of resulting subgoals is the + result of the match expression. If :n:`@expr__1` does not evaluate to a + tactic or if the match expression is not in position to be applied to a + goal, then the result of the evaluation of :n:`@expr__1` is the result + of the match expression. + + If the matching with :n:`@cpattern__1` fails, or if it succeeds but the + evaluation of :n:`@expr__1` fails, or if the evaluation of + :n:`@expr__1` succeeds but returns a tactic in execution position whose + execution fails, then :n:`cpattern__2` is used and so on. The pattern + :n:`_` matches any term and shunts all remaining patterns if any. If all + clauses fail (in particular, there is no pattern :n:`_`) then a + no-matching-clause error is raised. + + Failures in subsequent tactics do not cause backtracking to select new + branches or inside the right-hand side of the selected branch even if it + has backtracking points. + + .. exn:: No matching clauses for match + + No pattern can be used and, in particular, there is no :n:`_` pattern. + + .. exn:: Argument of match does not evaluate to a term + + This happens when :n:`@expr` does not denote a term. + + .. tacv:: multimatch @expr with {+| @cpattern__i => @expr__i} end + + Using multimatch instead of match will allow subsequent tactics to + backtrack into a right-hand side tactic which has backtracking points + left and trigger the selection of a new matching branch when all the + backtracking points of the right-hand side have been consumed. + + The syntax :n:`match …` is, in fact, a shorthand for :n:`once multimatch …`. + + .. tacv:: lazymatch @expr with {+| @cpattern__i => @expr__i} end + + Using lazymatch instead of match will perform the same pattern + matching procedure but will commit to the first matching branch + rather than trying a new matching if the right-hand side fails. If + the right-hand side of the selected branch is a tactic with + backtracking points, then subsequent failures cause this tactic to + backtrack. + + .. tacv:: context @ident [@cpattern] + + This special form of patterns matches any term with a subterm matching + cpattern. If there is a match, the optional :n:`@ident` is assigned the "matched + context", i.e. the initial term where the matched subterm is replaced by a + hole. The example below will show how to use such term contexts. + + If the evaluation of the right-hand-side of a valid match fails, the next + matching subterm is tried. If no further subterm matches, the next clause + is tried. Matching subterms are considered top-bottom and from left to + right (with respect to the raw printing obtained by setting option + :opt:`Printing All`). + + .. example:: + + .. coqtop:: all + + Ltac f x := + match x with + context f [S ?X] => + idtac X; (* To display the evaluation order *) + assert (p := eq_refl 1 : X=1); (* To filter the case X=1 *) + let x:= context f[O] in assert (x=O) (* To observe the context *) + end. + Goal True. + f (3+4). + +.. _ltac-match-goal: + +Pattern matching on goals +~~~~~~~~~~~~~~~~~~~~~~~~~ + +We can make pattern matching on goals using the following expression: + +.. we should provide the full grammar here + +.. tacn:: match goal with {+| {+ hyp} |- @cpattern => @expr } | _ => @expr end + + If each hypothesis pattern :n:`hyp`\ :sub:`1,i`, with i=1,...,m\ :sub:`1` is + matched (non-linear first-order unification) by an hypothesis of the + goal and if :n:`cpattern_1` is matched by the conclusion of the goal, + then :n:`@expr__1` is evaluated to :n:`v__1` by substituting the + pattern matching to the metavariables and the real hypothesis names + bound to the possible hypothesis names occurring in the hypothesis + patterns. If :n:`v__1` is a tactic value, then it is applied to the + goal. If this application fails, then another combination of hypotheses + is tried with the same proof context pattern. If there is no other + combination of hypotheses then the second proof context pattern is tried + and so on. If the next to last proof context pattern fails then + the last :n:`@expr` is evaluated to :n:`v` and :n:`v` is + applied. Note also that matching against subterms (using the :n:`context + @ident [ @cpattern ]`) is available and is also subject to yielding several + matchings. + + Failures in subsequent tactics do not cause backtracking to select new + branches or combinations of hypotheses, or inside the right-hand side of + the selected branch even if it has backtracking points. + + .. exn:: No matching clauses for match goal + + No clause succeeds, i.e. all matching patterns, if any, fail at the + application of the right-hand-side. + + .. note:: + + It is important to know that each hypothesis of the goal can be matched + by at most one hypothesis pattern. The order of matching is the + following: hypothesis patterns are examined from the right to the left + (i.e. hyp\ :sub:`i,m`\ :sub:`i`` before hyp\ :sub:`i,1`). For each + hypothesis pattern, the goal hypothesis are matched in order (fresher + hypothesis first), but it possible to reverse this order (older first) + with the :n:`match reverse goal with` variant. + + .. tacv:: multimatch goal with {+| {+ hyp} |- @cpattern => @expr } | _ => @expr end + + Using :n:`multimatch` instead of :n:`match` will allow subsequent tactics + to backtrack into a right-hand side tactic which has backtracking points + left and trigger the selection of a new matching branch or combination of + hypotheses when all the backtracking points of the right-hand side have + been consumed. + + The syntax :n:`match [reverse] goal …` is, in fact, a shorthand for + :n:`once multimatch [reverse] goal …`. + + .. tacv:: lazymatch goal with {+| {+ hyp} |- @cpattern => @expr } | _ => @expr end + + Using lazymatch instead of match will perform the same pattern matching + procedure but will commit to the first matching branch with the first + matching combination of hypotheses rather than trying a new matching if + the right-hand side fails. If the right-hand side of the selected branch + is a tactic with backtracking points, then subsequent failures cause + this tactic to backtrack. + +Filling a term context +~~~~~~~~~~~~~~~~~~~~~~ + +The following expression is not a tactic in the sense that it does not +produce subgoals but generates a term to be used in tactic expressions: + +.. tacn:: context @ident [@expr] + + :n:`@ident` must denote a context variable bound by a context pattern of a + match expression. This expression evaluates replaces the hole of the + value of :n:`@ident` by the value of :n:`@expr`. + + .. exn:: not a context variable + +Generating fresh hypothesis names +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tactics sometimes have to generate new names for hypothesis. Letting the +system decide a name with the intro tactic is not so good since it is +very awkward to retrieve the name the system gave. The following +expression returns an identifier: + +.. tacn:: fresh {* component} + + It evaluates to an identifier unbound in the goal. This fresh identifier + is obtained by concatenating the value of the :n:`@component`s (each of them + is, either a :n:`@qualid` which has to refer to a (unqualified) name, or + directly a name denoted by a :n:`@string`). + + .. I don't understand this component thing. Couldn't we give the grammar? + + If the resulting name is already used, it is padded with a number so that it + becomes fresh. If no component is given, the name is a fresh derivative of + the name ``H``. + +Computing in a constr +~~~~~~~~~~~~~~~~~~~~~ + +Evaluation of a term can be performed with: + +.. tacn:: eval @redexpr in @term + + where :n:`@redexpr` is a reduction tactic among :tacn:`red`, :tacn:`hnf`, + :tacn:`compute`, :tacn:`simpl`, :tacn:`cbv`, :tacn:`lazy`, :tacn:`unfold`, + :tacn:`fold`, :tacn:`pattern`. + +Recovering the type of a term +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following returns the type of term: + +.. tacn:: type of @term + +Manipulating untyped terms +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tacn:: uconstr : @term + + The terms built in |Ltac| are well-typed by default. It may not be + appropriate for building large terms using a recursive |Ltac| function: the + term has to be entirely type checked at each step, resulting in potentially + very slow behavior. It is possible to build untyped terms using |Ltac| with + the :n:`uconstr : @term` syntax. + +.. tacn:: type_term @term + + An untyped term, in |Ltac|, can contain references to hypotheses or to + |Ltac| variables containing typed or untyped terms. An untyped term can be + type-checked using the function type_term whose argument is parsed as an + untyped term and returns a well-typed term which can be used in tactics. + +Untyped terms built using :n:`uconstr :` can also be used as arguments to the +:tacn:`refine` tactic. In that case the untyped term is type +checked against the conclusion of the goal, and the holes which are not solved +by the typing procedure are turned into new subgoals. + +Counting the goals +~~~~~~~~~~~~~~~~~~ + +.. tacn:: numgoals + + The number of goals under focus can be recovered using the :n:`numgoals` + function. Combined with the guard command below, it can be used to + branch over the number of goals produced by previous tactics. + + .. example:: + + .. coqtop:: in + + Ltac pr_numgoals := let n := numgoals in idtac "There are" n "goals". + + Goal True /\ True /\ True. + split;[|split]. + + .. coqtop:: all + + all:pr_numgoals. + +Testing boolean expressions +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tacn:: guard @test + :name: guard + + The :tacn:`guard` tactic tests a boolean expression, and fails if the expression + evaluates to false. If the expression evaluates to true, it succeeds + without affecting the proof. + + The accepted tests are simple integer comparisons. + + .. example:: + + .. coqtop:: in + + Goal True /\ True /\ True. + split;[|split]. + + .. coqtop:: all + + all:let n:= numgoals in guard n<4. + Fail all:let n:= numgoals in guard n=2. + + .. exn:: Condition not satisfied + +Proving a subgoal as a separate lemma +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tacn:: abstract @expr + :name: abstract + + From the outside, :n:`abstract @expr` is the same as :n:`solve @expr`. + Internally it saves an auxiliary lemma called ``ident_subproofn`` where + ``ident`` is the name of the current goal and ``n`` is chosen so that this is + a fresh name. Such an auxiliary lemma is inlined in the final proof term. + + This tactical is useful with tactics such as :tacn:`omega` or + :tacn:`discriminate` that generate huge proof terms. With that tool the user + can avoid the explosion at time of the Save command without having to cut + manually the proof in smaller lemmas. + + It may be useful to generate lemmas minimal w.r.t. the assumptions they + depend on. This can be obtained thanks to the option below. + + .. tacv:: abstract @expr using @ident + + Give explicitly the name of the auxiliary lemma. + + .. warning:: + + Use this feature at your own risk; explicitly named and reused subterms + don’t play well with asynchronous proofs. + + .. tacv:: transparent_abstract @expr + :name: transparent_abstract + + Save the subproof in a transparent lemma rather than an opaque one. + + .. warning:: + + Use this feature at your own risk; building computationally relevant + terms with tactics is fragile. + + .. tacv:: transparent_abstract @expr using @ident + + Give explicitly the name of the auxiliary transparent lemma. + + .. warning:: + + Use this feature at your own risk; building computationally relevant terms + with tactics is fragile, and explicitly named and reused subterms + don’t play well with asynchronous proofs. + + .. exn:: Proof is not complete + :name: Proof is not complete (abstract) + +Tactic toplevel definitions +--------------------------- + +Defining |Ltac| functions +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Basically, |Ltac| toplevel definitions are made as follows: + +.. cmd:: Ltac @ident {* @ident} := @expr + + This defines a new |Ltac| function that can be used in any tactic + script or new |Ltac| toplevel definition. + + .. note:: + + The preceding definition can equivalently be written: + + :n:`Ltac @ident := fun {+ @ident} => @expr` + + Recursive and mutual recursive function definitions are also possible + with the syntax: + + .. cmdv:: Ltac @ident {* @ident} {* with @ident {* @ident}} := @expr + + It is also possible to *redefine* an existing user-defined tactic using the syntax: + + .. cmdv:: Ltac @qualid {* @ident} ::= @expr + + A previous definition of qualid must exist in the environment. The new + definition will always be used instead of the old one and it goes across + module boundaries. + + If preceded by the keyword Local the tactic definition will not be + exported outside the current module. + +Printing |Ltac| tactics +~~~~~~~~~~~~~~~~~~~~~~~ + +.. cmd:: Print Ltac @qualid. + + Defined |Ltac| functions can be displayed using this command. + +.. cmd:: Print Ltac Signatures + + This command displays a list of all user-defined tactics, with their arguments. + +Debugging |Ltac| tactics +------------------------ + +Info trace +~~~~~~~~~~ + +.. cmd:: Info @num @expr + + This command can be used to print the trace of the path eventually taken by an + |Ltac| script. That is, the list of executed tactics, discarding + all the branches which have failed. To that end the Info command can be + used with the following syntax. + + + The number :n:`@num` is the unfolding level of tactics in the trace. At level + 0, the trace contains a sequence of tactics in the actual script, at level 1, + the trace will be the concatenation of the traces of these tactics, etc… + + .. example:: + + .. coqtop:: in reset + + Ltac t x := exists x; reflexivity. + Goal exists n, n=0. + + .. coqtop:: all + + Info 0 t 1||t 0. + + .. coqtop:: in + + Undo. + + .. coqtop:: all + + Info 1 t 1||t 0. + + The trace produced by ``Info`` tries its best to be a reparsable + |Ltac| script, but this goal is not achievable in all generality. + So some of the output traces will contain oddities. + + As an additional help for debugging, the trace produced by ``Info`` contains + (in comments) the messages produced by the idtac + tacticals \ `4.2 <#ltac%3Aidtac>`__ at the right possition in the + script. In particular, the calls to idtac in branches which failed are + not printed. + + .. opt:: Info Level @num. + + This option is an alternative to the ``Info`` command. + + This will automatically print the same trace as :n:`Info @num` at each + tactic call. The unfolding level can be overridden by a call to the + ``Info`` command. + +Interactive debugger +~~~~~~~~~~~~~~~~~~~~ + +.. opt:: Ltac Debug + + This option governs the step-by-step debugger that comes with the |Ltac| interpreter + +When the debugger is activated, it stops at every step of the evaluation of +the current |Ltac| expression and it prints information on what it is doing. +The debugger stops, prompting for a command which can be one of the +following: + ++-----------------+-----------------------------------------------+ +| simple newline: | go to the next step | ++-----------------+-----------------------------------------------+ +| h: | get help | ++-----------------+-----------------------------------------------+ +| x: | exit current evaluation | ++-----------------+-----------------------------------------------+ +| s: | continue current evaluation without stopping | ++-----------------+-----------------------------------------------+ +| r n: | advance n steps further | ++-----------------+-----------------------------------------------+ +| r string: | advance up to the next call to “idtac string” | ++-----------------+-----------------------------------------------+ + +A non-interactive mode for the debugger is available via the option: + +.. opt:: Ltac Batch Debug + + This option has the effect of presenting a newline at every prompt, when + the debugger is on. The debug log thus created, which does not require + user input to generate when this option is set, can then be run through + external tools such as diff. + +Profiling |Ltac| tactics +~~~~~~~~~~~~~~~~~~~~~~~~ + +It is possible to measure the time spent in invocations of primitive +tactics as well as tactics defined in |Ltac| and their inner +invocations. The primary use is the development of complex tactics, +which can sometimes be so slow as to impede interactive usage. The +reasons for the performence degradation can be intricate, like a slowly +performing |Ltac| match or a sub-tactic whose performance only +degrades in certain situations. The profiler generates a call tree and +indicates the time spent in a tactic depending its calling context. Thus +it allows to locate the part of a tactic definition that contains the +performance bug. + +.. opt:: Ltac Profiling + + This option enables and disables the profiler. + +.. cmd:: Show Ltac Profile + + Prints the profile + + .. cmdv:: Show Ltac Profile @string + + Prints a profile for all tactics that start with :n:`@string`. Append a period + (.) to the string if you only want exactly that name. + +.. cmd:: Reset Ltac Profile + + Resets the profile, that is, deletes all accumulated information. + + .. warning:: + + Backtracking across a Reset Ltac Profile will not restore the information. + +.. coqtop:: reset in + + Require Import Coq.omega.Omega. + + Ltac mytauto := tauto. + Ltac tac := intros; repeat split; omega || mytauto. + + Notation max x y := (x + (y - x)) (only parsing). + + Goal forall x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z, + max x (max y z) = max (max x y) z /\ max x (max y z) = max (max x y) z + /\ (A /\ B /\ C /\ D /\ E /\ F /\ G /\ H /\ I /\ J /\ K /\ L /\ M /\ N /\ O /\ P /\ Q /\ R /\ S /\ T /\ U /\ V /\ W /\ X /\ Y /\ Z + -> Z /\ Y /\ X /\ W /\ V /\ U /\ T /\ S /\ R /\ Q /\ P /\ O /\ N /\ M /\ L /\ K /\ J /\ I /\ H /\ G /\ F /\ E /\ D /\ C /\ B /\ A). + Proof. + +.. coqtop:: all + + Set Ltac Profiling. + tac. + Show Ltac Profile. + Show Ltac Profile "omega". + +.. coqtop:: in + + Abort. + Unset Ltac Profiling. + +.. tacn:: start ltac profiling + :name: start ltac profiling + + This tactic behaves like :tacn:`idtac` but enables the profiler. + +.. tacn:: stop ltac profiling + :name: stop ltac profiling + + Similarly to :tacn:`start ltac profiling`, this tactic behaves like + :tacn:`idtac`. Together, they allow you to exclude parts of a proof script + from profiling. + +.. tacn:: reset ltac profile + :name: reset ltac profile + + This tactic behaves like the corresponding vernacular command + and allow displaying and resetting the profile from tactic scripts for + benchmarking purposes. + +.. tacn:: show ltac profile + :name: show ltac profile + + This tactic behaves like the corresponding vernacular command + and allow displaying and resetting the profile from tactic scripts for + benchmarking purposes. + +.. tacn:: show ltac profile @string + :name: show ltac profile + + This tactic behaves like the corresponding vernacular command + and allow displaying and resetting the profile from tactic scripts for + benchmarking purposes. + +You can also pass the ``-profile-ltac`` command line option to ``coqc``, which +performs a ``Set Ltac Profiling`` at the beginning of each document, and a +``Show Ltac Profile`` at the end. + +.. warning:: + + Note that the profiler currently does not handle backtracking into + multi-success tactics, and issues a warning to this effect in many cases + when such backtracking occurs. + +Run-time optimization tactic +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tacn:: optimize_heap + :name: optimize_heap + +This tactic behaves like :n:`idtac`, except that running it compacts the +heap in the OCaml run-time system. It is analogous to the Vernacular +command :cmd:`Optimize Heap`. diff --git a/doc/sphinx/proof-engine/proof-handling.rst b/doc/sphinx/proof-engine/proof-handling.rst index adf3da3ebb..86c94bab36 100644 --- a/doc/sphinx/proof-engine/proof-handling.rst +++ b/doc/sphinx/proof-engine/proof-handling.rst @@ -20,20 +20,18 @@ prove. Initially, the list consists only in the theorem itself. After having applied some tactics, the list of goals contains the subgoals generated by the tactics. -To each subgoal is associated a number of hypotheses called the *local -context* of the goal. Initially, the local context contains the local -variables and hypotheses of the current section (see Section :ref:`TODO_gallina_assumptions`) -and the local variables and hypotheses of the theorem statement. It is -enriched by the use of certain tactics (see e.g. ``intro`` in Section -:ref:`managingthelocalcontext`). +To each subgoal is associated a number of hypotheses called the *local context* +of the goal. Initially, the local context contains the local variables and +hypotheses of the current section (see Section :ref:`gallina-assumptions`) and +the local variables and hypotheses of the theorem statement. It is enriched by +the use of certain tactics (see e.g. :tacn:`intro`). When a proof is completed, the message ``Proof completed`` is displayed. One can then register this proof as a defined constant in the environment. Because there exists a correspondence between proofs and -terms of λ-calculus, known as the *Curry-Howard isomorphism* [[How80]_, -[Bar81]_, [Gir89]_, [Hue88]_ ], |Coq| -stores proofs as terms of |Cic|. Those terms -are called *proof terms*. +terms of λ-calculus, known as the *Curry-Howard isomorphism* +:cite:`How80,Bar81,Gir89,Hue88`, |Coq| stores proofs as terms of |Cic|. Those +terms are called *proof terms*. .. exn:: No focused proof @@ -41,16 +39,15 @@ are called *proof terms*. Coq raises this error message when one attempts to use a proof editing command out of the proof editing mode. +.. _proof-editing-mode: + Switching on/off the proof editing mode ------------------------------------------- -The proof editing mode is entered by asserting a statement, which -typically is the assertion of a theorem: - -.. cmd:: Theorem @ident [@binders] : @form. - -The list of assertion commands is given in Section :ref:TODO-assertions_and_proof`. The -command ``Goal`` can also be used. +The proof editing mode is entered by asserting a statement, which typically is +the assertion of a theorem using an assertion command like :cmd:`Theorem`. The +list of assertion commands is given in Section :ref:`Assertions`. The command +:cmd:`Goal` can also be used. .. cmd:: Goal @form. @@ -61,13 +58,14 @@ statement is eventually completed and validated, the statement is then bound to the name ``Unnamed_thm`` (or a variant of this name not already used for another statement). -.. cmd:: Qed. +.. cmd:: Qed + :name: Qed (interactive proof) This command is available in interactive editing proof mode when the proof is completed. Then ``Qed`` extracts a proof term from the proof script, switches back to Coq top-level and attaches the extracted proof term to the declared name of the original goal. This name is -added to the environment as an ``Opaque`` constant. +added to the environment as an opaque constant. .. exn:: Attempt to save an incomplete proof @@ -84,6 +82,7 @@ a while when the proof is large. In some exceptional cases one may even incur a memory overflow. .. cmdv:: Defined. + :name: Defined (interactive proof) Defines the proved term as a transparent constant. @@ -93,14 +92,14 @@ Forces the name of the original goal to be :n:`@ident`. This command (and the following ones) can only be used if the original goal has been opened using the ``Goal`` command. - .. cmd:: Admitted. + :name: Admitted (interactive proof) This command is available in interactive editing proof mode to give up the current proof and declare the initial goal as an axiom. - .. cmd:: Proof @term. + :name: Proof `term` This command applies in proof editing mode. It is equivalent to @@ -109,8 +108,8 @@ This command applies in proof editing mode. It is equivalent to That is, you have to give the full proof in one gulp, as a proof term (see Section :ref:`applyingtheorems`). - .. cmdv:: Proof. + :name: Proof (interactive proof) Is a noop which is useful to delimit the sequence of tactic commands which start a proof, after a ``Theorem`` command. It is a good practice to @@ -119,13 +118,13 @@ closing ``Qed``. See also: ``Proof with tactic.`` in Section -:ref:`setimpautotactics`. +:ref:`tactics-implicit-automation`. .. cmd:: Proof using @ident1 ... @identn. This command applies in proof editing mode. It declares the set of -section variables (see :ref:`TODO-gallina-assumptions`) used by the proof. At ``Qed`` time, the +section variables (see :ref:`gallina-assumptions`) used by the proof. At ``Qed`` time, the system will assert that the set of section variables actually used in the proof is a subset of the declared one. @@ -136,7 +135,7 @@ example if ``T`` is variable and a is a variable of type ``T``, the commands .. cmdv:: Proof using @ident1 ... @identn with @tactic. -in Section :ref:`setimpautotactics`. +in Section :ref:`tactics-implicit-automation`. .. cmdv:: Proof using All. @@ -186,49 +185,51 @@ Proof using options The following options modify the behavior of ``Proof using``. -.. cmdv:: Set Default Proof Using "@expression". +.. opt:: Default Proof Using "@expression". -Use :n:`@expression` as the default ``Proof``` using value. E.g. ``Set Default -Proof Using "a b"``. will complete all ``Proof`` commands not followed by a -using part with using ``a`` ``b``. + Use :n:`@expression` as the default ``Proof``` using value. E.g. ``Set Default + Proof Using "a b"``. will complete all ``Proof`` commands not followed by a + using part with using ``a`` ``b``. -.. cmdv:: Set Suggest Proof Using. +.. opt:: Suggest Proof Using. -When ``Qed`` is performed, suggest a using annotation if the user did not -provide one. + When ``Qed`` is performed, suggest a using annotation if the user did not + provide one. .. _`nameaset`: Name a set of section hypotheses for ``Proof using`` ```````````````````````````````````````````````````` +.. cmd:: Collection @ident := @section_subset_expr + The command ``Collection`` can be used to name a set of section hypotheses, with the purpose of making ``Proof using`` annotations more compact. -.. cmdv:: Collection Some := x y z. +.. cmdv:: Collection Some := x y z Define the collection named "Some" containing ``x``, ``y`` and ``z``. -.. cmdv:: Collection Fewer := Some - z. +.. cmdv:: Collection Fewer := Some - z Define the collection named "Fewer" containing only ``x`` and ``y``. -.. cmdv:: Collection Many := Fewer + Some. -.. cmdv:: Collection Many := Fewer - Some. +.. cmdv:: Collection Many := Fewer + Some +.. cmdv:: Collection Many := Fewer - Some Define the collection named "Many" containing the set union or set difference of "Fewer" and "Some". -.. cmdv:: Collection Many := Fewer - (x y). +.. cmdv:: Collection Many := Fewer - (x y) Define the collection named "Many" containing the set difference of -"Fewer" and the unnamed collection ``x`` ``y``. +"Fewer" and the unnamed collection ``x`` ``y`` .. cmd:: Abort. @@ -262,11 +263,11 @@ Existentials`` (described in Section :ref:`requestinginformation`). This command is intended to be used to instantiate existential variables when the proof is completed but some uninstantiated existential variables remain. To instantiate existential variables -during proof edition, you should use the tactic instantiate. +during proof edition, you should use the tactic :tacn:`instantiate`. See also: ``instantiate (num:= term).`` in Section -:ref:`TODO-controllingtheproofflow`. +:ref:`controllingtheproofflow`. See also: ``Grab Existential Variables.`` below. @@ -292,6 +293,7 @@ backtracks one step. Repeats Undo :n:`@num` times. .. cmdv:: Restart. + :name: Restart This command restores the proof editing process to the original goal. @@ -327,6 +329,7 @@ last ``Focus`` command. Succeeds if the proof is fully unfocused, fails is there are some goals out of focus. +.. _curly-braces: .. cmd:: %{ %| %} @@ -351,12 +354,14 @@ Error messages: You are trying to use ``}`` but the current subproof has not been fully solved. .. exn:: No such goal + :name: No such goal (focusing) .. exn:: Brackets only support the single numbered goal selector - See also error messages about bullets below. +.. _bullets: + Bullets ``````` @@ -425,15 +430,16 @@ Set Bullet Behavior The bullet behavior can be controlled by the following commands. -.. opt:: Bullet Behavior "None". +.. opt:: Bullet Behavior "None" This makes bullets inactive. -.. opt:: Bullet Behavior "Strict Subproofs". +.. opt:: Bullet Behavior "Strict Subproofs" This makes bullets active (this is the default behavior). +.. _requestinginformation: Requesting information ---------------------- @@ -456,7 +462,7 @@ Displays only the :n:`@num`-th subgoal. Displays the named goal :n:`@ident`. This is useful in particular to display a shelved goal but only works if the corresponding existential variable has been named by the user -(see :ref:`exvariables`) as in the following example. +(see :ref:`existential-variables`) as in the following example. .. example:: @@ -536,7 +542,7 @@ debugging universe inconsistencies. .. cmd:: Guarded. -Some tactics (e.g. refine :ref:`applyingtheorems`) allow to build proofs using +Some tactics (e.g. :tacn:`refine` :ref:`applyingtheorems`) allow to build proofs using fixpoint or co-fixpoint constructions. Due to the incremental nature of interactive proof construction, the check of the termination (or guardedness) of the recursive calls in the fixpoint or cofixpoint @@ -551,7 +557,7 @@ Controlling the effect of proof editing commands ------------------------------------------------ -.. opt:: Hyps Limit @num. +.. opt:: Hyps Limit @num This option controls the maximum number of hypotheses displayed in goals after the application of a tactic. All the hypotheses remain usable @@ -560,7 +566,7 @@ When unset, it goes back to the default mode which is to print all available hypotheses. -.. opt:: Automatic Introduction. +.. opt:: Automatic Introduction This option controls the way binders are handled in assertion commands such as ``Theorem ident [binders] : form``. When the @@ -591,4 +597,4 @@ the ongoing proof. This command forces the |OCaml| runtime to perform a heap compaction. This is in general an expensive operation. See: `OCaml Gc <http://caml.inria.fr/pub/docs/manual-ocaml/libref/Gc.html#VALcompact>`_ -There is also an analogous tactic ``optimize_heap`` (see~:ref:`tactic-optimizeheap`) +There is also an analogous tactic :tac:`optimize_heap`. diff --git a/doc/sphinx/proof-engine/ssreflect-proof-language.rst b/doc/sphinx/proof-engine/ssreflect-proof-language.rst index df5b362970..977a5b8fad 100644 --- a/doc/sphinx/proof-engine/ssreflect-proof-language.rst +++ b/doc/sphinx/proof-engine/ssreflect-proof-language.rst @@ -493,7 +493,10 @@ inferred from the whole context of the goal (see for example section Definitions ~~~~~~~~~~~ -The pose tactic allows to add a defined constant to a proof context. +.. tacn:: pose + :name: pose (ssreflect) + +This tactic allows to add a defined constant to a proof context. |SSR| generalizes this tactic in several ways. In particular, the |SSR| pose tactic supports *open syntax*: the body of the definition does not need surrounding parentheses. For instance: @@ -1349,6 +1352,7 @@ Discharge The general syntax of the discharging tactical ``:`` is: .. tacn:: @tactic {? @ident } : {+ @d_item } {? @clear_switch } + :name: ... : ... (ssreflect) .. prodn:: d_item ::= {? @occ_switch %| @clear_switch } @term @@ -1500,9 +1504,11 @@ side of an equation. The abstract tactic ``````````````````` -The ``abstract`` tactic assigns an ``abstract`` constant previously -introduced with the ``[: name ]`` intro pattern -(see section :ref:`introduction_ssr`). +.. tacn:: abstract: {+ d_item} + :name abstract (ssreflect) + +This tactic assigns an abstract constant previously introduced with the ``[: +name ]`` intro pattern (see section :ref:`introduction_ssr`). In a goal like the following:: @@ -1809,6 +1815,8 @@ of a :token:`d_item` immediately following this ``/`` switch, using the syntax: .. tacv:: case: {+ @d_item } / {+ @d_item } + :name: case (ssreflect) + .. tacv:: elim: {+ @d_item } / {+ @d_item } The :token:`d_item` on the right side of the ``/`` switch are discharged as @@ -2132,7 +2140,7 @@ tactic using the given second tactic, and fails if it does not succeed. Its analogue .. tacn:: @tactic ; first by @tactic - :name: first + :name: first (ssreflect) tries to solve the first subgoal generated by the first tactic using the second given tactic, and fails if it does not succeed. @@ -2212,7 +2220,7 @@ Iteration thanks to the do tactical, whose general syntax is: .. tacn:: do {? @mult } ( @tactic | [ {+| @tactic } ] ) - :name: do + :name: do (ssreflect) where :token:`mult` is a *multiplier*. @@ -2749,12 +2757,9 @@ type classes inference. No inference for ``t``. Unresolved instances are quantified in the (inferred) type of ``t`` and abstracted in ``t``. +.. opt:: SsrHave NoTCResolution -The behavior of |SSR| 1.4 and below (never resolve type classes) -can be restored with the option - -.. cmd:: Set SsrHave NoTCResolution. - + This option restores the behavior of |SSR| 1.4 and below (never resolve type classes). Variants: the suff and wlog tactics ``````````````````````````````````` @@ -3727,6 +3732,7 @@ We provide a special tactic unlock for unfolding such definitions while removing “locks”, e.g., the tactic: .. tacn:: unlock {? @occ_switch } @ident + :name: unlock replaces the occurrence(s) of :token:`ident` coded by the :token:`occ_switch` with the corresponding body. @@ -5185,6 +5191,7 @@ equivalences are indeed taken into account, otherwise only single |SSR| proposes an extension of the Search command. Its syntax is: .. cmd:: Search {? @pattern } {* {? - } %( @string %| @pattern %) {? % @ident} } {? in {+ {? - } @qualid } } + :name: Search (ssreflect) where :token:`qualid` is the name of an open module. This command returns the list of lemmas: diff --git a/doc/sphinx/proof-engine/tactics.rst b/doc/sphinx/proof-engine/tactics.rst index 2af73c28e5..7a45272f25 100644 --- a/doc/sphinx/proof-engine/tactics.rst +++ b/doc/sphinx/proof-engine/tactics.rst @@ -24,7 +24,7 @@ Each (sub)goal is denoted with a number. The current goal is numbered 1. By default, a tactic is applied to the current goal, but one can address a particular goal in the list by writing n:tactic which means “apply tactic tactic to goal number n”. We can show the list of -subgoals by typing Show (see Section :ref:`TODO-7.3.1-Show`). +subgoals by typing Show (see Section :ref:`requestinginformation`). Since not every rule applies to a given statement, every tactic cannot be used to reduce any goal. In other words, before applying a tactic @@ -34,15 +34,16 @@ satisfied. If it is not the case, the tactic raises an error message. Tactics are built from atomic tactics and tactic expressions (which extends the folklore notion of tactical) to combine those atomic tactics. This chapter is devoted to atomic tactics. The tactic -language will be described in Chapter :ref:`TODO-9-Thetacticlanguage`. +language will be described in Chapter :ref:`ltac`. + +.. _invocation-of-tactics: Invocation of tactics ------------------------- A tactic is applied as an ordinary command. It may be preceded by a -goal selector (see Section :ref:`TODO-9.2-Semantics`). If no selector is -specified, the default selector (see Section -:ref:`TODO-8.1.1-Setdefaultgoalselector`) is used. +goal selector (see Section :ref:`ltac-semantics`). If no selector is +specified, the default selector is used. .. _tactic_invocation_grammar: @@ -50,20 +51,15 @@ specified, the default selector (see Section tactic_invocation : toplevel_selector : tactic. : |tactic . -.. cmd:: Set Default Goal Selector @toplevel_selector. - -After using this command, the default selector – used when no selector -is specified when applying a tactic – is set to the chosen value. The -initial value is 1, hence the tactics are, by default, applied to the -first goal. Using Set Default Goal Selector ‘‘all’’ will make is so -that tactics are, by default, applied to every goal simultaneously. -Then, to apply a tactic tac to the first goal only, you can write -1:tac. Although more selectors are available, only ‘‘all’’ or a single -natural number are valid default goal selectors. - -.. cmd:: Test Default Goal Selector. +.. opt:: Default Goal Selector @toplevel_selector -This command displays the current default selector. + This option controls the default selector – used when no selector is + specified when applying a tactic – is set to the chosen value. The initial + value is 1, hence the tactics are, by default, applied to the first goal. + Using value ``all`` will make is so that tactics are, by default, applied to + every goal simultaneously. Then, to apply a tactic tac to the first goal + only, you can write ``1:tac``. Although more selectors are available, only + ``all`` or a single natural number are valid default goal selectors. .. _bindingslist: @@ -94,7 +90,7 @@ bindings_list`` where ``bindings_list`` may be of two different forms: + A bindings list can also be a simple list of terms :n:`{* term}`. In that case the references to which these terms correspond are determined by the tactic. In case of ``induction``, ``destruct``, ``elim`` - and ``case`` (see :ref:`TODO-9-Thetacticlanguage`) the terms have to + and ``case`` (see :ref:`ltac`) the terms have to provide instances for all the dependent products in the type of term while in the case of ``apply``, or of ``constructor`` and its variants, only instances for the dependent products that are not bound in the conclusion of the type @@ -122,14 +118,12 @@ following syntax: The role of an occurrence clause is to select a set of occurrences of a term in a goal. In the first case, the :n:`@ident {? at {* num}}` parts indicate that -occurrences have to be selected in the hypotheses named :n:`@ident`. If no numbers -are given for hypothesis :n:`@ident`, then all the occurrences of `term` in the -hypothesis are selected. If numbers are given, they refer to occurrences of -`term` when the term is printed using option ``Set Printing All`` (see -:ref:`TODO-2.9-Printingconstructionsinfull`), counting from left to right. In -particular, occurrences of `term` in implicit arguments (see -:ref:`TODO-2.7-Implicitarguments`) or coercions (see :ref:`TODO-2.8-Coercions`) -are counted. +occurrences have to be selected in the hypotheses named :n:`@ident`. If no +numbers are given for hypothesis :n:`@ident`, then all the occurrences of `term` +in the hypothesis are selected. If numbers are given, they refer to occurrences +of `term` when the term is printed using option :opt:`Printing All`, counting +from left to right. In particular, occurrences of `term` in implicit arguments +(see :ref:`ImplicitArguments`) or coercions (see :ref:`Coercions`) are counted. If a minus sign is given between at and the list of occurrences, it negates the condition so that the clause denotes all the occurrences @@ -154,10 +148,11 @@ Here are some tactics that understand occurrences clauses: ``set``, ``remember`` , ``induction``, ``destruct``. -See also: :ref:`TODO-8.3.7-Managingthelocalcontext`, -:ref:`TODO-8.5.2-Caseanalysisandinduction`, -:ref:`TODO-2.9-Printingconstructionsinfull`. +See also: :ref:`Managingthelocalcontext`, +:ref:`caseanalysisandinduction`, +:ref:`printing_constructions_full`. +.. _applyingtheorems: Applying theorems --------------------- @@ -168,11 +163,12 @@ Applying theorems This tactic applies to any goal. It gives directly the exact proof term of the goal. Let ``T`` be our goal, let ``p`` be a term of type ``U`` then ``exact p`` succeeds iff ``T`` and ``U`` are convertible (see -:ref:`TODO-4.3-Conversionrules`). +:ref:`Conversion-rules`). .. exn:: Not an exact proof. .. tacv:: eexact @term. + :name: eexact This tactic behaves like exact but is able to handle terms and goals with meta-variables. @@ -186,6 +182,7 @@ the goal. If it is the case, the subgoal is proved. Otherwise, it fails. .. exn:: No such assumption. .. tacv:: eassumption + :name: eassumption This tactic behaves like assumption but is able to handle goals with meta-variables. @@ -238,6 +235,7 @@ useful to advanced users. cast around it. .. tacv:: simple refine @term + :name: simple refine This tactic behaves like refine, but it does not shelve any subgoal. It does not perform any beta-reduction either. @@ -248,6 +246,7 @@ useful to advanced users. resolution of typeclasses. .. tacv:: simple notypeclasses refine @term + :name: simple notypeclasses refine This tactic behaves like ``simple refine`` except it performs typechecking without resolution of typeclasses. @@ -277,7 +276,7 @@ gets the form :g:`(fun x => Q) u`:sub:`1` :g:`...` :g:`u`:sub:`n`. The apply tactic failed to match the conclusion of term and the current goal. You can help the apply tactic by transforming your goal with the -:ref:`change <change_term>` or :tacn:`pattern` tactics. +:tacn:`change` or :tacn:`pattern` tactics. .. exn:: Unable to find an instance for the variables {+ @ident}. @@ -285,7 +284,7 @@ This occurs when some instantiations of the premises of term are not deducible from the unification. This is the case, for instance, when you want to apply a transitivity property. In this case, you have to use one of the variants below: -.. cmd:: apply @term with {+ @term} +.. tacv:: apply @term with {+ @term} Provides apply with explicit instantiations for all dependent premises of the type of term that do not occur in the conclusion and consequently cannot be @@ -314,10 +313,11 @@ generated by ``apply term``:sub:`i` , starting from the application of The tactic ``eapply`` behaves like ``apply`` but it does not fail when no instantiations are deducible for some variables in the premises. Rather, it turns these variables into existential variables which are variables still to -instantiate (see :ref:`TODO-2.11-ExistentialVariables`). The instantiation is +instantiate (see :ref:`Existential-Variables`). The instantiation is intended to be found later in the proof. .. tacv:: simple apply @term. + :name: simple apply This behaves like ``apply`` but it reasons modulo conversion only on subterms that contain no variables to instantiate. For instance, the following example @@ -340,11 +340,12 @@ does. .. tacv:: {? simple} apply {+, @term {? with @bindings_list}} .. tacv:: {? simple} eapply {+, @term {? with @bindings_list}} + :name: simple eapply This summarizes the different syntaxes for ``apply`` and ``eapply``. .. tacv:: lapply @term - :name: `lapply + :name: lapply This tactic applies to any goal, say :g:`G`. The argument term has to be well-formed in the current context, its type being reducible to a non-dependent @@ -435,7 +436,7 @@ sequence ``cut B. 2:apply H.`` where ``cut`` is described below. ``forall A, ... -> A``. Excluding this kind of lemma can be avoided by setting the following option: -.. opt:: Set Universal Lemma Under Conjunction. +.. opt:: Universal Lemma Under Conjunction This option, which preserves compatibility with versions of Coq prior to 8.4 is also available for :n:`apply @term in @ident` (see :tacn:`apply ... in`). @@ -520,8 +521,8 @@ sequence ``cut B. 2:apply H.`` where ``cut`` is described below. constructor of :g:`I`, then ``constructor i`` is equivalent to ``intros; apply c``:sub:`i`. -.. exn:: Not an inductive product. -.. exn:: Not enough constructors. +.. exn:: Not an inductive product +.. exn:: Not enough constructors .. tacv:: constructor @@ -539,34 +540,39 @@ sequence ``cut B. 2:apply H.`` where ``cut`` is described below. The terms in the @bindings_list are checked in the context where constructor is executed and not in the context where @apply is executed (the introductions are not taken into account). .. tacv:: split + :name: split This applies only if :g:`I` has a single constructor. It is then equivalent to :n:`constructor 1.`. It is typically used in the case of a conjunction :g:`A` :math:`\wedge` :g:`B`. -.. exn:: Not an inductive goal with 1 constructor. +.. exn:: Not an inductive goal with 1 constructor .. tacv:: exists @val + :name: exists This applies only if :g:`I` has a single constructor. It is then equivalent to :n:`intros; constructor 1 with @bindings_list.` It is typically used in the case of an existential quantification :math:`\exists`:g:`x, P(x).` -.. exn:: Not an inductive goal with 1 constructor. +.. exn:: Not an inductive goal with 1 constructor .. tacv:: exists @bindings_list This iteratively applies :n:`exists @bindings_list`. .. tacv:: left + :name: left + .. tacv:: right + :name: right These tactics apply only if :g:`I` has two constructors, for instance in the case of a disjunction :g:`A` :math:`\vee` :g:`B`. Then, they are respectively equivalent to ``constructor 1`` and ``constructor 2``. -.. exn:: Not an inductive goal with 2 constructors. +.. exn:: Not an inductive goal with 2 constructors .. tacv:: left with @bindings_list .. tacv:: right with @bindings_list @@ -577,15 +583,25 @@ sequence ``cut B. 2:apply H.`` where ``cut`` is described below. for the appropriate ``i``. .. tacv:: econstructor + :name: econstructor + .. tacv:: eexists + :name: eexists + .. tacv:: esplit + :name: esplit + .. tacv:: eleft + :name: eleft + .. tacv:: eright + :name: eright - These tactics and their variants behave like ``constructor``, ``exists``, - ``split``, ``left``, ``right`` and their variants but they introduce - existential variables instead of failing when the instantiation of a - variable cannot be found (cf. :tacn:`eapply` and :tacn:`apply`). + These tactics and their variants behave like :tacn:`constructor`, + :tacn:`exists`, :tacn:`split`, :tacn:`left`, :tacn:`right` and their variants + but they introduce existential variables instead of failing when the + instantiation of a variable cannot be found (cf. :tacn:`eapply` and + :tacn:`apply`). .. _managingthelocalcontext: @@ -598,7 +614,7 @@ Managing the local context This tactic applies to a goal that is either a product or starts with a let binder. If the goal is a product, the tactic implements the "Lam" rule given in -:ref:`TODO-4.2-Typing-rules` [1]_. If the goal starts with a let binder, then the +:ref:`Typing-rules` [1]_. If the goal starts with a let binder, then the tactic implements a mix of the "Let" and "Conv". If the current goal is a dependent product :math:`\forall` :g:`x:T, U` (resp @@ -616,7 +632,7 @@ the tactic ``intro`` applies the tactic ``hnf`` until the tactic ``intro`` can be applied or the goal is not head-reducible. .. exn:: No product even after head-reduction. -.. exn:: ident is already used. +.. exn:: @ident is already used. .. tacv:: intros @@ -632,14 +648,14 @@ be applied or the goal is not head-reducible. .. note:: If a name used by intro hides the base name of a global constant then the latter can still be referred to by a qualified name - (see :ref:`TODO-2.6.2-Qualified-names`). + (see :ref:`Qualified-names`). .. tacv:: intros {+ @ident}. This is equivalent to the composed tactic :n:`intro @ident; ... ; intro @ident`. More generally, the ``intros`` tactic takes a pattern as argument in order to introduce names for components of an inductive definition or to clear introduced hypotheses. This is - explained in :ref:`TODO-8.3.2`. + explained in :ref:`Managingthelocalcontext`. .. tacv:: intros until @ident @@ -827,15 +843,10 @@ quantification or an implication. so that all the arguments of the i-th constructors of the corresponding inductive type are introduced can be controlled with the following option: - .. cmd:: Set Bracketing Last Introduction Pattern. + .. opt:: Bracketing Last Introduction Pattern - Force completion, if needed, when the last introduction pattern is a - disjunctive or conjunctive pattern (this is the default). - - .. cmd:: Unset Bracketing Last Introduction Pattern. - - Deactivate completion when the last introduction pattern is a disjunctive or - conjunctive pattern. + Force completion, if needed, when the last introduction pattern is a + disjunctive or conjunctive pattern (on by default). .. tacn:: clear @ident :name: clear @@ -855,6 +866,7 @@ quantification or an implication. This is equivalent to :n:`clear @ident. ... clear @ident.` .. tacv:: clearbody @ident + :name: clearbody This tactic expects :n:`@ident` to be a local definition then clears its body. Otherwise said, this tactic turns a definition into an assumption. @@ -876,7 +888,7 @@ quantification or an implication. it. .. tacn:: revert {+ @ident} - :name: revert ... + :name: revert This applies to any goal with variables :n:`{+ @ident}`. It moves the hypotheses (possibly defined) to the goal, if this respects dependencies. This tactic is @@ -992,6 +1004,7 @@ The name of the hypothesis in the proof-term, however, is left unchanged. .. tacv:: eset (@ident {+ @binder} := @term ) in @goal_occurrences .. tacv:: eset @term in @goal_occurrences + :name: eset While the different variants of :tacn:`set` expect that no existential variables are generated by the tactic, :n:`eset` removes this constraint. In @@ -999,6 +1012,7 @@ The name of the hypothesis in the proof-term, however, is left unchanged. :tacn:`epose`, i.e. when the :`@term` does not occur in the goal. .. tacv:: remember @term as @ident + :name: remember This behaves as :n:`set (@ident:= @term ) in *` and using a logical (Leibniz’s) equality instead of a local definition. @@ -1016,6 +1030,8 @@ The name of the hypothesis in the proof-term, however, is left unchanged. .. tacv:: eremember @term as @ident .. tacv:: eremember @term as @ident in @goal_occurrences .. tacv:: eremember @term as @ident eqn:@ident + :name: eremember + While the different variants of :n:`remember` expect that no existential variables are generated by the tactic, :n:`eremember` removes this constraint. @@ -1067,7 +1083,7 @@ The name of the hypothesis in the proof-term, however, is left unchanged. This decomposes record types (inductive types with one constructor, like "and" and "exists" and those defined with the Record macro, see - :ref:`TODO-2.1`). + :ref:`record-types`). .. _controllingtheproofflow: @@ -1089,7 +1105,7 @@ Controlling the proof flow .. tacv:: assert form - This behaves as :n:`assert (@ident : form ) but :n:`@ident` is generated by + This behaves as :n:`assert (@ident : form)` but :n:`@ident` is generated by Coq. .. tacv:: assert form by tactic @@ -1098,6 +1114,7 @@ Controlling the proof flow generated by assert. .. exn:: Proof is not complete + :name: Proof is not complete (assert) .. tacv:: assert form as intro_pattern @@ -1121,6 +1138,7 @@ Controlling the proof flow .. exn:: Variable @ident is already declared .. tacv:: eassert form as intro_pattern by tactic + :name: eassert .. tacv:: assert (@ident := @term) @@ -1130,6 +1148,7 @@ Controlling the proof flow to prove it. .. tacv:: pose proof @term {? as intro_pattern} + :name: pose proof This tactic behaves like :n:`assert T {? as intro_pattern} by exact @term` where :g:`T` is the type of :g:`term`. In particular, @@ -1143,6 +1162,7 @@ Controlling the proof flow the tactic, :n:`epose proof` removes this constraint. .. tacv:: enough (@ident : form) + :name: enough This adds a new hypothesis of name :n:`@ident` asserting :n:`form` to the goal the tactic :n:`enough` is applied to. A new subgoal stating :n:`form` is @@ -1168,22 +1188,27 @@ Controlling the proof flow applied to all of them. .. tacv:: eenough (@ident : form) by tactic + :name: eenough + .. tacv:: eenough form by tactic + .. tacv:: eenough form as intro_pattern by tactic While the different variants of :n:`enough` expect that no existential variables are generated by the tactic, :n:`eenough` removes this constraint. -.. tacv:: cut form +.. tacv:: cut @form + :name: cut This tactic applies to any goal. It implements the non-dependent case of - the “App” rule given in :ref:`TODO-4.2`. (This is Modus Ponens inference + the “App” rule given in :ref:`typing-rules`. (This is Modus Ponens inference rule.) :n:`cut U` transforms the current goal :g:`T` into the two following subgoals: :g:`U -> T` and :g:`U`. The subgoal :g:`U -> T` comes first in the list of remaining subgoal to prove. .. tacv:: specialize (ident {* @term}) {? as intro_pattern} .. tacv:: specialize ident with @bindings_list {? as intro_pattern} + :name: specialize The tactic :n:`specialize` works on local hypothesis :n:`@ident`. The premises of this hypothesis (either universal quantifications or @@ -1236,7 +1261,7 @@ name of the variable (here :g:`n`) is chosen based on :g:`T`. This is equivalent to :n:`generalize @term` but it generalizes only over the specified occurrences of :n:`@term` (counting from left to right on the - expression printed using option :g:`Set Printing All`). + expression printed using option :opt:`Printing All`). .. tacv:: generalize @term as @ident @@ -1268,7 +1293,7 @@ name of the variable (here :g:`n`) is chosen based on :g:`T`. :n:`refine @term` (preferred alternative). .. note:: To be able to refer to an existential variable by name, the user - must have given the name explicitly (see :ref:`TODO-2.11`). + must have given the name explicitly (see :ref:`Existential-Variables`). .. note:: When you are referring to hypotheses which you did not name explicitly, be aware that Coq may make a different decision on how to @@ -1353,11 +1378,13 @@ goals cannot be closed with :g:`Qed` but only with :g:`Admitted`. then required to prove that False is indeed provable in the current context. This tactic is a macro for :n:`elimtype False`. +.. _CaseAnalysisAndInduction: + Case analysis and induction ------------------------------- The tactics presented in this section implement induction or case -analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). +analysis on inductive or co-inductive objects (see :ref:`inductive-definitions`). .. tacn:: destruct @term :name: destruct @@ -1423,6 +1450,7 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). dependent premises of the type of :n:`@term` (see :ref:`syntax of bindings <bindingslist>`). .. tacv:: edestruct @term + :name: edestruct This tactic behaves like :n:`destruct @term` except that it does not fail if the instance of a dependent premises of the type of :n:`@term` is not @@ -1449,6 +1477,7 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). the effects of the `with`, `as`, `eqn:`, `using`, and `in` clauses. .. tacv:: case term + :name: case The tactic :n:`case` is a more basic tactic to perform case analysis without recursion. It behaves as :n:`elim @term` but using a case-analysis @@ -1458,14 +1487,15 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). Analogous to :n:`elim @term with @bindings_list` above. -.. tacv:: ecase @term -.. tacv:: ecase @term with @bindings_list +.. tacv:: ecase @term {? with @bindings_list } + :name: ecase In case the type of :n:`@term` has dependent premises, or dependent premises whose values are not inferable from the :n:`with @bindings_list` clause, :n:`ecase` turns them into existential variables to be resolved later on. .. tacv:: simple destruct @ident + :name: simple destruct This tactic behaves as :n:`intros until @ident; case @ident` when :n:`@ident` is a quantified variable of the goal. @@ -1556,6 +1586,7 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). premises of the type of :n:`term` (see :ref:`bindings list <bindingslist>`). .. tacv:: einduction @term + :name: einduction This tactic behaves like :tacn:`induction` except that it does not fail if some dependent premise of the type of :n:`@term` is not inferable. Instead, @@ -1628,6 +1659,7 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). (see :ref:`bindings list <bindingslist>`). .. tacv:: eelim @term + :name: eelim In case the type of :n:`@term` has dependent premises, this turns them into existential variables to be resolved later on. @@ -1646,7 +1678,8 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). These are the most general forms of ``elim`` and ``eelim``. It combines the effects of the ``using`` clause and of the two uses of the ``with`` clause. -.. tacv:: elimtype form +.. tacv:: elimtype @form + :name: elimtype The argument :n:`form` must be inductively defined. :n:`elimtype I` is equivalent to :n:`cut I. intro Hn; elim Hn; clear Hn.` Therefore the @@ -1656,6 +1689,7 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). :n:`elimtype I; 2:exact t.` .. tacv:: simple induction @ident + :name: simple induction This tactic behaves as :n:`intros until @ident; elim @ident` when :n:`@ident` is a quantified variable of the goal. @@ -1740,13 +1774,14 @@ analysis on inductive or co-inductive objects (see :ref:`TODO-4.5`). other ones need not be further generalized. .. tacv:: dependent destruction @ident + :name: dependent destruction This performs the generalization of the instance :n:`@ident` but uses ``destruct`` instead of induction on the generalized hypothesis. This gives results equivalent to ``inversion`` or ``dependent inversion`` if the hypothesis is dependent. -See also :ref:`TODO-10.1-dependentinduction` for a larger example of ``dependent induction`` +See also the larger example of :tacn:`dependent induction` and an explanation of the underlying technique. .. tacn:: function induction (@qualid {+ @term}) @@ -1754,8 +1789,8 @@ and an explanation of the underlying technique. The tactic functional induction performs case analysis and induction following the definition of a function. It makes use of a principle - generated by ``Function`` (see :ref:`TODO-2.3-Advancedrecursivefunctions`) or - ``Functional Scheme`` (see :ref:`TODO-13.2-Generationofinductionschemeswithfunctionalscheme`). + generated by ``Function`` (see :ref:`advanced-recursive-functions`) or + ``Functional Scheme`` (see :ref:`functional-scheme`). Note that this tactic is only available after a .. example:: @@ -1781,22 +1816,22 @@ and an explanation of the underlying technique. :n:`functional induction (f x1 x2 x3)` is actually a wrapper for :n:`induction x1, x2, x3, (f x1 x2 x3) using @qualid` followed by a cleaning phase, where :n:`@qualid` is the induction principle registered for :g:`f` - (by the ``Function`` (see :ref:`TODO-2.3-Advancedrecursivefunctions`) or - ``Functional Scheme`` (see :ref:`TODO-13.2-Generationofinductionschemeswithfunctionalscheme`) + (by the ``Function`` (see :ref:`advanced-recursive-functions`) or + ``Functional Scheme`` (see :ref:`functional-scheme`) command) corresponding to the sort of the goal. Therefore ``functional induction`` may fail if the induction scheme :n:`@qualid` is not - defined. See also :ref:`TODO-2.3-Advancedrecursivefunctions` for the function + defined. See also :ref:`advanced-recursive-functions` for the function terms accepted by ``Function``. .. note:: There is a difference between obtaining an induction scheme - for a function by using :g:`Function` (see :ref:`TODO-2.3-Advancedrecursivefunctions`) + for a function by using :g:`Function` (see :ref:`advanced-recursive-functions`) and by using :g:`Functional Scheme` after a normal definition using - :g:`Fixpoint` or :g:`Definition`. See :ref:`TODO-2.3-Advancedrecursivefunctions` + :g:`Fixpoint` or :g:`Definition`. See :ref:`advanced-recursive-functions` for details. -See also: :ref:`TODO-2.3-Advancedrecursivefunctions` - :ref:`TODO-13.2-Generationofinductionschemeswithfunctionalscheme` +See also: :ref:`advanced-recursive-functions` + :ref:`functional-scheme` :tacn:`inversion` .. exn:: Cannot find induction information on @qualid @@ -1849,6 +1884,7 @@ See also: :ref:`TODO-2.3-Advancedrecursivefunctions` .. tacv:: ediscriminate @num .. tacv:: ediscriminate @term {? with @bindings_list} + :name: ediscriminate This works the same as ``discriminate`` but if the type of :n:`@term`, or the type of the hypothesis referred to by :n:`@num`, has uninstantiated @@ -1902,7 +1938,7 @@ injected object has a dependent type :g:`P` with its two instances in different types :g:`(P t`:sub:`1` :g:`... t`:sub:`n` :g:`)` and :g:`(P u`:sub:`1` :g:`... u`:sub:`n` :sub:`)`. If :g:`t`:sub:`1` and :g:`u`:sub:`1` are the same and have for type an inductive type for which a decidable -equality has been declared using the command ``Scheme Equality`` (see :ref:`TODO-13.1-GenerationofinductionprincipleswithScheme`), +equality has been declared using the command ``Scheme Equality`` (see :ref:`proofschemes-induction-principles`), the use of a sigma type is avoided. .. note:: @@ -1928,6 +1964,7 @@ the use of a sigma type is avoided. .. tacv:: einjection @num .. tacv:: einjection @term {? with @bindings_list} + :name: einjection This works the same as :n:`injection` but if the type of :n:`@term`, or the type of the hypothesis referred to by :n:`@num`, has uninstantiated @@ -1955,17 +1992,19 @@ the use of a sigma type is avoided. to the number of new equalities. The original equality is erased if it corresponds to an hypothesis. -It is possible to ensure that :n:`injection @term` erases the original -hypothesis and leaves the generated equalities in the context rather -than putting them as antecedents of the current goal, as if giving -:n:`injection @term as` (with an empty list of names). To obtain this -behavior, the option ``Set Structural Injection`` must be activated. This -option is off by default. +.. opt:: Structural Injection -By default, ``injection`` only creates new equalities between :n:`@terms` whose -type is in sort :g:`Type` or :g:`Set`, thus implementing a special behavior for -objects that are proofs of a statement in :g:`Prop`. This behavior can be -turned off by setting the option ``Set Keep Proof Equalities``. + This option ensure that :n:`injection @term` erases the original hypothesis + and leaves the generated equalities in the context rather than putting them + as antecedents of the current goal, as if giving :n:`injection @term as` + (with an empty list of names). This option is off by default. + +.. opt:: Keep Proof Equalities + + By default, :tacn:`injection` only creates new equalities between :n:`@terms` + whose type is in sort :g:`Type` or :g:`Set`, thus implementing a special + behavior for objects that are proofs of a statement in :g:`Prop`. This option + controls this behavior. .. tacn:: inversion @ident :name: inversion @@ -1984,15 +2023,15 @@ turned off by setting the option ``Set Keep Proof Equalities``. .. note:: As ``inversion`` proofs may be large in size, we recommend the user to stock the lemmas whenever the same instance needs to be - inverted several times. See :ref:`TODO-13.3-Generationofinversionprincipleswithderiveinversion`. + inverted several times. See :ref:`derive-inversion`. .. note:: Part of the behavior of the ``inversion`` tactic is to generate equalities between expressions that appeared in the hypothesis that is being processed. By default, no equalities are generated if they relate two proofs (i.e. equalities between :n:`@terms` whose type is in sort - :g:`Prop`). This behavior can be turned off by using the option ``Set Keep - Proof Equalities``. + :g:`Prop`). This behavior can be turned off by using the option + :opt`Keep Proof Equalities`. .. tacv:: inversion @num @@ -2117,6 +2156,7 @@ turned off by setting the option ``Set Keep Proof Equalities``. :n:`dependent inversion_clear @ident with @term`. .. tacv:: simple inversion @ident + :name: simple inversion It is a very primitive inversion tactic that derives all the necessary equalities but it does not simplify the constraints as ``inversion`` does. @@ -2300,7 +2340,7 @@ turned off by setting the option ``Set Keep Proof Equalities``. arguments are correct is done only at the time of registering the lemma in the environment. To know if the use of induction hypotheses is correct at some time of the interactive development of a proof, use - the command ``Guarded`` (see :ref:`TODO-7.3.2-Guarded`). + the command ``Guarded`` (see Section :ref:`requestinginformation`). .. tacv:: fix @ident @num with {+ (ident {+ @binder} [{struct @ident}] : @type)} @@ -2321,7 +2361,7 @@ turned off by setting the option ``Set Keep Proof Equalities``. done only at the time of registering the lemma in the environment. To know if the use of coinduction hypotheses is correct at some time of the interactive development of a proof, use the command ``Guarded`` - (see :ref:`TODO-7.3.2-Guarded`). + (see Section :ref:`requestinginformation`). .. tacv:: cofix @ident with {+ (@ident {+ @binder} : @type)} @@ -2335,7 +2375,7 @@ Rewriting expressions --------------------- These tactics use the equality :g:`eq:forall A:Type, A->A->Prop` defined in -file ``Logic.v`` (see :ref:`TODO-3.1.2-Logic`). The notation for :g:`eq T t u` is +file ``Logic.v`` (see :ref:`coq-library-logic`). The notation for :g:`eq T t u` is simply :g:`t=u` dropping the implicit type of :g:`t` and :g:`u`. .. tacn:: rewrite @term @@ -2417,6 +2457,7 @@ subgoals. leading to failure if these n rewrites are not possible. .. tacv:: erewrite @term + :name: erewrite This tactic works as :n:`rewrite @term` but turning unresolved bindings into existential variables, if any, instead of @@ -2463,6 +2504,7 @@ subgoals. clause argument must not contain any type of nor value of. .. tacv:: cutrewrite <- (@term = @term) + :cutrewrite: This tactic is deprecated. It acts like :n:`replace @term with @term`, or, equivalently as :n:`enough (@term = @term) as <-`. @@ -2506,30 +2548,30 @@ unfolded and cleared. context for which an equality of the form :n:`@ident = t` or :n:`t = @ident` or :n:`@ident := t` exists, with :n:`@ident` not occurring in `t`. - .. note:: - The behavior of subst can be controlled using option ``Set Regular Subst - Tactic.`` When this option is activated, subst also deals with the - following corner cases: + .. opt:: Regular Subst Tactic + + This option controls the behavior of :tacn:`subst`. When it is + activated, :tacn:`subst` also deals with the following corner cases: - + A context with ordered hypotheses :n:`@ident`:sub:`1` :n:`= @ident`:sub:`2` - and :n:`@ident`:sub:`1` :n:`= t`, or :n:`t′ = @ident`:sub:`1`` with `t′` not - a variable, and no other hypotheses of the form :n:`@ident`:sub:`2` :n:`= u` - or :n:`u = @ident`:sub:`2`; without the option, a second call to - subst would be necessary to replace :n:`@ident`:sub:`2` by `t` or - `t′` respectively. - + The presence of a recursive equation which without the option would - be a cause of failure of :tacn:`subst`. - + A context with cyclic dependencies as with hypotheses :n:`@ident`:sub:`1` :n:`= f @ident`:sub:`2` - and :n:`@ident`:sub:`2` :n:`= g @ident`:sub:`1` which without the - option would be a cause of failure of :tacn:`subst`. + + A context with ordered hypotheses :n:`@ident`:sub:`1` :n:`= @ident`:sub:`2` + and :n:`@ident`:sub:`1` :n:`= t`, or :n:`t′ = @ident`:sub:`1`` with `t′` not + a variable, and no other hypotheses of the form :n:`@ident`:sub:`2` :n:`= u` + or :n:`u = @ident`:sub:`2`; without the option, a second call to + subst would be necessary to replace :n:`@ident`:sub:`2` by `t` or + `t′` respectively. + + The presence of a recursive equation which without the option would + be a cause of failure of :tacn:`subst`. + + A context with cyclic dependencies as with hypotheses :n:`@ident`:sub:`1` :n:`= f @ident`:sub:`2` + and :n:`@ident`:sub:`2` :n:`= g @ident`:sub:`1` which without the + option would be a cause of failure of :tacn:`subst`. - Additionally, it prevents a local definition such as :n:`@ident := t` to be - unfolded which otherwise it would exceptionally unfold in configurations - containing hypotheses of the form :n:`@ident = u`, or :n:`u′ = @ident` - with `u′` not a variable. Finally, it preserves the initial order of - hypotheses, which without the option it may break. The option is on by - default. + Additionally, it prevents a local definition such as :n:`@ident := t` to be + unfolded which otherwise it would exceptionally unfold in configurations + containing hypotheses of the form :n:`@ident = u`, or :n:`u′ = @ident` + with `u′` not a variable. Finally, it preserves the initial order of + hypotheses, which without the option it may break. The option is on by + default. .. tacn:: stepl @term @@ -2543,30 +2585,37 @@ where `eq` is typically a setoid equality. The application of :n:`stepl @term` then replaces the goal by :n:`R @term @term` and adds a new goal stating :n:`eq @term @term`. -Lemmas are added to the database using the command ``Declare Left Step @term.`` +.. cmd:: Declare Left Step @term + + Adds :n:`@term` to the database used by :tacn:`stepl`. + The tactic is especially useful for parametric setoids which are not accepted as regular setoids for :tacn:`rewrite` and :tacn:`setoid_replace` (see -:ref:`TODO-27-Generalizedrewriting`). +:ref:`Generalizedrewriting`). .. tacv:: stepl @term by tactic - This applies :n:`stepl @term` then applies tactic to the second goal. + This applies :n:`stepl @term` then applies tactic to the second goal. .. tacv:: stepr @term stepr @term by tactic + :name: stepr + + This behaves as :tacn:`stepl` but on the right-hand-side of the binary + relation. Lemmas are expected to be of the form :g:`forall x y z, R x y -> eq + y z -> R x z`. - This behaves as :tacn:`stepl` but on the right-hand-side of the binary - relation. Lemmas are expected to be of the form :g:`forall x y z, R x y -> eq - y z -> R x z` and are registered using the command ``Declare Right Step - @term.`` + .. cmd:: Declare Right Step @term + + Adds :n:`@term` to the database used by :tacn:`stepr`. .. tacn:: change @term :name: change - This tactic applies to any goal. It implements the rule ``Conv`` given in - :ref:`TODO-4.4-Subtypingrules`. :g:`change U` replaces the current goal `T` - with `U` providing that `U` is well-formed and that `T` and `U` are - convertible. + This tactic applies to any goal. It implements the rule ``Conv`` given in + :ref:`subtyping-rules`. :g:`change U` replaces the current goal `T` + with `U` providing that `U` is well-formed and that `T` and `U` are + convertible. .. exn:: Not convertible @@ -2637,7 +2686,7 @@ the conversion in hypotheses :n:`{+ @ident}`. the normalization of the goal according to the specified flags. In correspondence with the kinds of reduction considered in Coq namely :math:`\beta` (reduction of functional application), :math:`\delta` - (unfolding of transparent constants, see :ref:`TODO-6.10.2-Transparent`), + (unfolding of transparent constants, see :ref:`vernac-controlling-the-reduction-strategies`), :math:`\iota` (reduction of pattern-matching over a constructed term, and unfolding of :g:`fix` and :g:`cofix` expressions) and :math:`\zeta` (contraction of local definitions), the @@ -2649,7 +2698,7 @@ the conversion in hypotheses :n:`{+ @ident}`. second case the constant to unfold to all but the ones explicitly mentioned. Notice that the ``delta`` flag does not apply to variables bound by a let-in construction inside the :n:`@term` itself (use here the ``zeta`` flag). In - any cases, opaque constants are not unfolded (see :ref:`TODO-6.10.1-Opaque`). + any cases, opaque constants are not unfolded (see :ref:`vernac-controlling-the-reduction-strategies`). Normalization according to the flags is done by first evaluating the head of the expression into a *weak-head* normal form, i.e. until the @@ -2704,6 +2753,7 @@ the conversion in hypotheses :n:`{+ @ident}`. and :n:`lazy beta delta -{+ @qualid} iota zeta`. .. tacv:: vm_compute + :name: vm_compute This tactic evaluates the goal using the optimized call-by-value evaluation bytecode-based virtual machine described in :cite:`CompiledStrongReduction`. @@ -2713,6 +2763,7 @@ the conversion in hypotheses :n:`{+ @ident}`. reflection-based tactics. .. tacv:: native_compute + :name: native_compute This tactic evaluates the goal by compilation to Objective Caml as described in :cite:`FullReduction`. If Coq is running in native code, it can be @@ -2768,7 +2819,7 @@ the conversion in hypotheses :n:`{+ @ident}`. :n:`hnf`. .. note:: - The :math:`\delta` rule only applies to transparent constants (see :ref:`TODO-6.10.1-Opaque` + The :math:`\delta` rule only applies to transparent constants (see :ref:`vernac-controlling-the-reduction-strategies` on transparency and opacity). .. tacn:: cbn @@ -2906,7 +2957,7 @@ the conversion in hypotheses :n:`{+ @ident}`. This tactic applies to any goal. The argument qualid must denote a defined transparent constant or local definition (see - :ref:`TODO-1.3.2-Definitions` and :ref:`TODO-6.10.2-Transparent`). The tactic + :ref:`gallina-definitions` and :ref:`vernac-controlling-the-reduction-strategies`). The tactic ``unfold`` applies the :math:`\delta` rule to each occurrence of the constant to which :n:`@qualid` refers in the current goal and then replaces it with its :math:`\beta`:math:`\iota`-normal form. @@ -2942,7 +2993,7 @@ the conversion in hypotheses :n:`{+ @ident}`. This is variant of :n:`unfold @string` where :n:`@string` gets its interpretation from the scope bound to the delimiting key :n:`key` - instead of its default interpretation (see :ref:`TODO-12.2.2-Localinterpretationrulesfornotations`). + instead of its default interpretation (see :ref:`Localinterpretationrulesfornotations`). .. tacv:: unfold {+, qualid_or_string at {+, @num}} This is the most general form, where :n:`qualid_or_string` is either a @@ -3103,7 +3154,7 @@ the :tacn:`auto` and :tacn:`trivial` tactics: .. opt:: Info Auto .. opt:: Debug Auto .. opt:: Info Trivial -.. opt:: Info Trivial +.. opt:: Debug Trivial See also: :ref:`The Hints Databases for auto and eauto <thehintsdatabasesforautoandeauto>` @@ -3258,188 +3309,203 @@ observationally different from the legacy one. The general command to add a hint to some databases :n:`{+ @ident}` is -.. cmd:: Hint hint_definition : {+ @ident} +.. cmd:: Hint @hint_definition : {+ @ident} -**Variants:** + .. cmdv:: Hint @hint_definition -.. cmd:: Hint hint_definition + No database name is given: the hint is registered in the core database. - No database name is given: the hint is registered in the core database. + .. cmdv:: Local Hint @hint_definition : {+ @ident} -.. cmd:: Local Hint hint_definition : {+ @ident} + This is used to declare hints that must not be exported to the other modules + that require and import the current module. Inside a section, the option + Local is useless since hints do not survive anyway to the closure of + sections. - This is used to declare hints that must not be exported to the other modules - that require and import the current module. Inside a section, the option - Local is useless since hints do not survive anyway to the closure of - sections. + .. cmdv:: Local Hint @hint_definition -.. cmd:: Local Hint hint_definition + Idem for the core database. - Idem for the core database. + .. cmdv:: Hint Resolve @term {? | {? @num} {? @pattern}} + :name: Hint Resolve -The ``hint_definition`` is one of the following expressions: + This command adds :n:`simple apply @term` to the hint list with the head + symbol of the type of :n:`@term`. The cost of that hint is the number of + subgoals generated by :n:`simple apply @term` or :n:`@num` if specified. The + associated :n:`@pattern` is inferred from the conclusion of the type of + :n:`@term` or the given :n:`@pattern` if specified. In case the inferred type + of :n:`@term` does not start with a product the tactic added in the hint list + is :n:`exact @term`. In case this type can however be reduced to a type + starting with a product, the tactic :n:`simple apply @term` is also stored in + the hints list. If the inferred type of :n:`@term` contains a dependent + quantification on a variable which occurs only in the premisses of the type + and not in its conclusion, no instance could be inferred for the variable by + unification with the goal. In this case, the hint is added to the hint list + of :tacn:`eauto` instead of the hint list of auto and a warning is printed. A + typical example of a hint that is used only by :tacn:`eauto` is a transitivity + lemma. -+ :n:`Resolve @term {? | {? @num} {? @pattern}}` - This command adds :n:`simple apply @term` to the hint list with the head symbol of the type of - :n:`@term`. The cost of that hint is the number of subgoals generated by - :n:`simple apply @term` or :n:`@num` if specified. The associated :n:`@pattern` - is inferred from the conclusion of the type of :n:`@term` or the given - :n:`@pattern` if specified. In case the inferred type of :n:`@term` does not - start with a product the tactic added in the hint list is :n:`exact @term`. - In case this type can however be reduced to a type starting with a product, - the tactic :n:`simple apply @term` is also stored in the hints list. If the - inferred type of :n:`@term` contains a dependent quantification on a variable - which occurs only in the premisses of the type and not in its conclusion, no - instance could be inferred for the variable by unification with the goal. In - this case, the hint is added to the hint list of :tacn:`eauto` instead of the - hint list of auto and a warning is printed. A typical example of a hint that - is used only by ``eauto`` is a transitivity lemma. + .. exn:: @term cannot be used as a hint - .. exn:: @term cannot be used as a hint + The head symbol of the type of :n:`@term` is a bound variable such that + this tactic cannot be associated to a constant. - The head symbol of the type of :n:`@term` is a bound variable such that - this tactic cannot be associated to a constant. + .. cmdv:: Hint Resolve {+ @term} - **Variants:** + Adds each :n:`Hint Resolve @term`. - + :n:`Resolve {+ @term}` - Adds each :n:`Resolve @term`. + .. cmdv:: Hint Resolve -> @term - + :n:`Resolve -> @term` - Adds the left-to-right implication of an equivalence as a hint (informally - the hint will be used as :n:`apply <- @term`, although as mentionned - before, the tactic actually used is a restricted version of ``apply``). + Adds the left-to-right implication of an equivalence as a hint (informally + the hint will be used as :n:`apply <- @term`, although as mentionned + before, the tactic actually used is a restricted version of + :tacn:`apply`). - + :n:`Resolve <- @term` - Adds the right-to-left implication of an equivalence as a hint. + .. cmdv:: Resolve <- @term -+ :n:`Immediate @term` - This command adds :n:`simple apply @term; trivial` to the hint list associated - with the head symbol of the type of :n:`@ident` in the given database. This - tactic will fail if all the subgoals generated by :n:`simple apply @term` are - not solved immediately by the ``trivial`` tactic (which only tries tactics - with cost 0).This command is useful for theorems such as the symmetry of - equality or :g:`n+1=m+1 -> n=m` that we may like to introduce with a limited - use in order to avoid useless proof-search.The cost of this tactic (which - never generates subgoals) is always 1, so that it is not used by ``trivial`` - itself. + Adds the right-to-left implication of an equivalence as a hint. - .. exn:: @term cannot be used as a hint + .. cmdv:: Hint Immediate @term + :name: Hint Immediate - **Variants:** + This command adds :n:`simple apply @term; trivial` to the hint list associated + with the head symbol of the type of :n:`@ident` in the given database. This + tactic will fail if all the subgoals generated by :n:`simple apply @term` are + not solved immediately by the ``trivial`` tactic (which only tries tactics + with cost 0).This command is useful for theorems such as the symmetry of + equality or :g:`n+1=m+1 -> n=m` that we may like to introduce with a limited + use in order to avoid useless proof-search. The cost of this tactic (which + never generates subgoals) is always 1, so that it is not used by :tacn:`trivial` + itself. - + :n:`Immediate {+ @term}` - Adds each :n:`Immediate @term`. + .. exn:: @term cannot be used as a hint -+ :n:`Constructors @ident` - If :n:`@ident` is an inductive type, this command adds all its constructors as - hints of type Resolve. Then, when the conclusion of current goal has the form - :n:`(@ident ...)`, ``auto`` will try to apply each constructor. + .. cmdv:: Immediate {+ @term} - .. exn:: @ident is not an inductive type + Adds each :n:`Hint Immediate @term`. - **Variants:** + .. cmdv:: Hint Constructors @ident + :name: Hint Constructors - + :n:`Constructors {+ @ident}` - Adds each :n:`Constructors @ident`. + If :n:`@ident` is an inductive type, this command adds all its constructors as + hints of type ``Resolve``. Then, when the conclusion of current goal has the form + :n:`(@ident ...)`, :tacn:`auto` will try to apply each constructor. -+ :n:`Unfold @qualid` - This adds the tactic :n:`unfold @qualid` to the hint list that will only be - used when the head constant of the goal is :n:`@ident`. - Its cost is 4. + .. exn:: @ident is not an inductive type - **Variants:** + .. cmdv:: Hint Constructors {+ @ident} - + :n:`Unfold {+ @ident}` - Adds each :n:`Unfold @ident`. + Adds each :n:`Hint Constructors @ident`. -+ :n:`Transparent`, :n:`Opaque @qualid` - This adds a transparency hint to the database, making :n:`@qualid` a - transparent or opaque constant during resolution. This information is used - during unification of the goal with any lemma in the database and inside the - discrimination network to relax or constrain it in the case of discriminated - databases. + .. cmdv:: Hint Unfold @qualid + :name: Hint Unfold - **Variants:** + This adds the tactic :n:`unfold @qualid` to the hint list that will only be + used when the head constant of the goal is :n:`@ident`. + Its cost is 4. - + :n:`Transparent`, :n:`Opaque {+ @ident}` - Declares each :n:`@ident` as a transparent or opaque constant. + .. cmdv:: Hint Unfold {+ @ident} -+ :n:`Extern @num {? @pattern} => tactic` - This hint type is to extend ``auto`` with tactics other than ``apply`` and - ``unfold``. For that, we must specify a cost, an optional :n:`@pattern` and a - :n:`tactic` to execute. Here is an example:: - - Hint Extern 4 (~(_ = _)) => discriminate. - - Now, when the head of the goal is a disequality, ``auto`` will try - discriminate if it does not manage to solve the goal with hints with a - cost less than 4. One can even use some sub-patterns of the pattern in - the tactic script. A sub-pattern is a question mark followed by an - identifier, like ``?X1`` or ``?X2``. Here is an example: - - .. example:: - .. coqtop:: reset all - - Require Import List. - Hint Extern 5 ({?X1 = ?X2} + {?X1 <> ?X2}) => generalize X1, X2; decide equality : eqdec. - Goal forall a b:list (nat * nat), {a = b} + {a <> b}. - Info 1 auto with eqdec. - -+ :n:`Cut @regexp` - - .. warning:: these hints currently only apply to typeclass - proof search and the ``typeclasses eauto`` tactic (:ref:`TODO-20.6.5-typeclasseseauto`). - - This command can be used to cut the proof-search tree according to a regular - expression matching paths to be cut. The grammar for regular expressions is - the following. Beware, there is no operator precedence during parsing, one can - check with ``Print HintDb`` to verify the current cut expression: - - .. productionlist:: `regexp` - e : ident hint or instance identifier - :|_ any hint - :| e\|e′ disjunction - :| e e′ sequence - :| e * Kleene star - :| emp empty - :| eps epsilon - :| ( e ) - - The `emp` regexp does not match any search path while `eps` - matches the empty path. During proof search, the path of - successive successful hints on a search branch is recorded, as a - list of identifiers for the hints (note Hint Extern’s do not have - an associated identifier). - Before applying any hint :n:`@ident` the current path `p` extended with - :n:`@ident` is matched against the current cut expression `c` associated to - the hint database. If matching succeeds, the hint is *not* applied. The - semantics of ``Hint Cut e`` is to set the cut expression to ``c | e``, the - initial cut expression being `emp`. - -+ :n:`Mode @qualid {* (+ | ! | -)}` - This sets an optional mode of use of the identifier :n:`@qualid`. When - proof-search faces a goal that ends in an application of :n:`@qualid` to - arguments :n:`@term ... @term`, the mode tells if the hints associated to - :n:`@qualid` can be applied or not. A mode specification is a list of n ``+``, - ``!`` or ``-`` items that specify if an argument of the identifier is to be - treated as an input (``+``), if its head only is an input (``!``) or an output - (``-``) of the identifier. For a mode to match a list of arguments, input - terms and input heads *must not* contain existential variables or be - existential variables respectively, while outputs can be any term. Multiple - modes can be declared for a single identifier, in that case only one mode - needs to match the arguments for the hints to be applied.The head of a term - is understood here as the applicative head, or the match or projection - scrutinee’s head, recursively, casts being ignored. ``Hint Mode`` is - especially useful for typeclasses, when one does not want to support default - instances and avoid ambiguity in general. Setting a parameter of a class as an - input forces proof-search to be driven by that index of the class, with ``!`` - giving more flexibility by allowing existentials to still appear deeper in the - index but not at its head. + Adds each :n:`Hint Unfold @ident`. -.. note:: - One can use an ``Extern`` hint with no pattern to do pattern-matching on - hypotheses using ``match goal`` with inside the tactic. + .. cmdv:: Hint %( Transparent %| Opaque %) @qualid + :name: Hint ( Transparent | Opaque ) + + This adds a transparency hint to the database, making :n:`@qualid` a + transparent or opaque constant during resolution. This information is used + during unification of the goal with any lemma in the database and inside the + discrimination network to relax or constrain it in the case of discriminated + databases. + + .. cmdv:: Hint %(Transparent | Opaque) {+ @ident} + + Declares each :n:`@ident` as a transparent or opaque constant. + + .. cmdv:: Hint Extern @num {? @pattern} => tactic + + This hint type is to extend :tacn:`auto` with tactics other than :tacn:`apply` and + :tacn:`unfold`. For that, we must specify a cost, an optional :n:`@pattern` and a + :n:`@tactic` to execute. + + .. example:: + + .. coqtop:: in + + Hint Extern 4 (~(_ = _)) => discriminate. + + Now, when the head of the goal is a disequality, ``auto`` will try + discriminate if it does not manage to solve the goal with hints with a + cost less than 4. One can even use some sub-patterns of the pattern in + the tactic script. A sub-pattern is a question mark followed by an + identifier, like ``?X1`` or ``?X2``. Here is an example: + + .. example:: + + .. coqtop:: reset all + + Require Import List. + Hint Extern 5 ({?X1 = ?X2} + {?X1 <> ?X2}) => generalize X1, X2; decide equality : eqdec. + Goal forall a b:list (nat * nat), {a = b} + {a <> b}. + Info 1 auto with eqdec. + + .. cmdv:: Hint Cut @regexp + + .. warning:: + + These hints currently only apply to typeclass proof search and the + :tacn:`typeclasses eauto` tactic. + + This command can be used to cut the proof-search tree according to a regular + expression matching paths to be cut. The grammar for regular expressions is + the following. Beware, there is no operator precedence during parsing, one can + check with :cmd:`Print HintDb` to verify the current cut expression: + + .. productionlist:: `regexp` + e : ident hint or instance identifier + :|_ any hint + :| e\|e′ disjunction + :| e e′ sequence + :| e * Kleene star + :| emp empty + :| eps epsilon + :| ( e ) + + The `emp` regexp does not match any search path while `eps` + matches the empty path. During proof search, the path of + successive successful hints on a search branch is recorded, as a + list of identifiers for the hints (note Hint Extern’s do not have + an associated identifier). + Before applying any hint :n:`@ident` the current path `p` extended with + :n:`@ident` is matched against the current cut expression `c` associated to + the hint database. If matching succeeds, the hint is *not* applied. The + semantics of ``Hint Cut e`` is to set the cut expression to ``c | e``, the + initial cut expression being `emp`. + + .. cmdv:: Hint Mode @qualid {* (+ | ! | -)} + + This sets an optional mode of use of the identifier :n:`@qualid`. When + proof-search faces a goal that ends in an application of :n:`@qualid` to + arguments :n:`@term ... @term`, the mode tells if the hints associated to + :n:`@qualid` can be applied or not. A mode specification is a list of n ``+``, + ``!`` or ``-`` items that specify if an argument of the identifier is to be + treated as an input (``+``), if its head only is an input (``!``) or an output + (``-``) of the identifier. For a mode to match a list of arguments, input + terms and input heads *must not* contain existential variables or be + existential variables respectively, while outputs can be any term. Multiple + modes can be declared for a single identifier, in that case only one mode + needs to match the arguments for the hints to be applied.The head of a term + is understood here as the applicative head, or the match or projection + scrutinee’s head, recursively, casts being ignored. ``Hint Mode`` is + especially useful for typeclasses, when one does not want to support default + instances and avoid ambiguity in general. Setting a parameter of a class as an + input forces proof-search to be driven by that index of the class, with ``!`` + giving more flexibility by allowing existentials to still appear deeper in the + index but not at its head. + + .. note:: + + One can use an ``Extern`` hint with no pattern to do pattern-matching on + hypotheses using ``match goal`` with inside the tactic. Hint databases defined in the Coq standard library @@ -3521,7 +3587,7 @@ at every moment. (left to right). Notice that the rewriting bases are distinct from the ``auto`` hint bases and thatauto does not take them into account. - This command is synchronous with the section mechanism (see :ref:`TODO-2.4-Sectionmechanism`): + This command is synchronous with the section mechanism (see :ref:`section-mechanism`): when closing a section, all aliases created by ``Hint Rewrite`` in that section are lost. Conversely, when loading a module, all ``Hint Rewrite`` declarations at the global level of that module are loaded. @@ -3573,69 +3639,65 @@ We propose a smooth transitional path by providing the ``Loose Hint Behavior`` option which accepts three flags allowing for a fine-grained handling of non-imported hints. -**Variants:** +.. opt:: Loose Hint Behavior %( "Lax" %| "Warn" %| "Strict" %) -.. cmd:: Set Loose Hint Behavior "Lax" + This option accepts three values, which control the behavior of hints w.r.t. + :cmd:`Import`: - This is the default, and corresponds to the historical behavior, that - is, hints defined outside of a section have a global scope. + - "Lax": this is the default, and corresponds to the historical behavior, + that is, hints defined outside of a section have a global scope. -.. cmd:: Set Loose Hint Behavior "Warn" + - "Warn": outputs a warning when a non-imported hint is used. Note that this + is an over-approximation, because a hint may be triggered by a run that + will eventually fail and backtrack, resulting in the hint not being + actually useful for the proof. - When set, it outputs a warning when a non-imported hint is used. Note that - this is an over-approximation, because a hint may be triggered by a run that - will eventually fail and backtrack, resulting in the hint not being actually - useful for the proof. + - "Strict": changes the behavior of an unloaded hint to a immediate fail + tactic, allowing to emulate an import-scoped hint mechanism. -.. cmd:: Set Loose Hint Behavior "Strict" - - When set, it changes the behavior of an unloaded hint to a immediate fail - tactic, allowing to emulate an import-scoped hint mechanism. +.. _tactics-implicit-automation: Setting implicit automation tactics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. cmd:: Proof with tactic +.. cmd:: Proof with @tactic This command may be used to start a proof. It defines a default tactic to be used each time a tactic command ``tactic``:sub:`1` is ended by ``...``. In this case the tactic command typed by the user is equivalent to ``tactic``:sub:`1` ``;tactic``. -See also: Proof. in :ref:`TODO-7.1.4-Proofterm`. - -**Variants:** + See also: ``Proof.`` in :ref:`proof-editing-mode`. -.. cmd:: Proof with tactic using {+ @ident} - Combines in a single line ``Proof with`` and ``Proof using``, see :ref:`TODO-7.1.5-Proofusing` + .. cmdv:: Proof with tactic using {+ @ident} -.. cmd:: Proof using {+ @ident} with tactic + Combines in a single line ``Proof with`` and ``Proof using``, see :ref:`proof-editing-mode` - Combines in a single line ``Proof with`` and ``Proof using``, see :ref:`TODO-7.1.5-Proofusing` + .. cmdv:: Proof using {+ @ident} with @tactic -.. cmd:: Declare Implicit Tactic tactic + Combines in a single line ``Proof with`` and ``Proof using``, see :ref:`proof-editing-mode` - This command declares a tactic to be used to solve implicit arguments - that Coq does not know how to solve by unification. It is used every - time the term argument of a tactic has one of its holes not fully - resolved. + .. cmd:: Declare Implicit Tactic @tactic -Here is an example: + This command declares a tactic to be used to solve implicit arguments + that Coq does not know how to solve by unification. It is used every + time the term argument of a tactic has one of its holes not fully + resolved. -.. example:: + .. example:: - .. coqtop:: all + .. coqtop:: all - Parameter quo : nat -> forall n:nat, n<>0 -> nat. - Notation "x // y" := (quo x y _) (at level 40). - Declare Implicit Tactic assumption. - Goal forall n m, m<>0 -> { q:nat & { r | q * m + r = n } }. - intros. - exists (n // m). + Parameter quo : nat -> forall n:nat, n<>0 -> nat. + Notation "x // y" := (quo x y _) (at level 40). + Declare Implicit Tactic assumption. + Goal forall n m, m<>0 -> { q:nat & { r | q * m + r = n } }. + intros. + exists (n // m). - The tactic ``exists (n // m)`` did not fail. The hole was solved - by ``assumption`` so that it behaved as ``exists (quo n m H)``. + The tactic ``exists (n // m)`` did not fail. The hole was solved + by ``assumption`` so that it behaved as ``exists (quo n m H)``. .. _decisionprocedures: @@ -3680,11 +3742,12 @@ Therefore, the use of :tacn:`intros` in the previous proof is unnecessary. an instantiation of `x` is necessary. .. tacv:: dtauto + :name: dtauto - While :tacn:`tauto` recognizes inductively defined connectives isomorphic to - the standard connective ``and, prod, or, sum, False, Empty_set, unit, True``, - :tacn:`dtauto` recognizes also all inductive types with one constructors and - no indices, i.e. record-style connectives. + While :tacn:`tauto` recognizes inductively defined connectives isomorphic to + the standard connective ``and, prod, or, sum, False, Empty_set, unit, True``, + :tacn:`dtauto` recognizes also all inductive types with one constructors and + no indices, i.e. record-style connectives. .. tacn:: intuition @tactic :name: intuition @@ -3713,7 +3776,7 @@ and then uses :tacn:`auto` which completes the proof. Originally due to César Muñoz, these tactics (:tacn:`tauto` and :tacn:`intuition`) have been completely re-engineered by David Delahaye using -mainly the tactic language (see :ref:`TODO-9-thetacticlanguage`). The code is +mainly the tactic language (see :ref:`ltac`). The code is now much shorter and a significant increase in performance has been noticed. The general behavior with respect to dependent types, unfolding and introductions has slightly changed to get clearer semantics. This may lead to @@ -3730,17 +3793,10 @@ some incompatibilities. Empty_set, unit, True``, :tacn:`dintuition` recognizes also all inductive types with one constructors and no indices, i.e. record-style connectives. -Some aspects of the tactic :tacn:`intuition` can be controlled using options. -To avoid that inner negations which do not need to be unfolded are -unfolded, use: - -.. cmd:: Unset Intuition Negation Unfolding +.. opt:: Intuition Negation Unfolding - -To do that all negations of the goal are unfolded even inner ones -(this is the default), use: - -.. cmd:: Set Intuition Negation Unfolding + Controls whether :tacn:`intuition` unfolds inner negations which do not need + to be unfolded. This option is on by default. .. tacn:: rtauto :name: rtauto @@ -3764,14 +3820,15 @@ first- order reasoning, written by Pierre Corbineau. It is not restricted to usual logical connectives but instead may reason about any first-order class inductive definition. -The default tactic used by :tacn:`firstorder` when no rule applies is :g:`auto -with \*`, it can be reset locally or globally using the ``Set Firstorder -Solver`` tactic vernacular command and printed using ``Print Firstorder -Solver``. +.. opt:: Firstorder Solver + + The default tactic used by :tacn:`firstorder` when no rule applies is + :g:`auto with *`, it can be reset locally or globally using this option and + printed using :cmd:`Print Firstorder Solver`. .. tacv:: firstorder @tactic - Tries to solve the goal with :n:`@tactic` when no logical rule may apply. + Tries to solve the goal with :n:`@tactic` when no logical rule may apply. .. tacv:: firstorder using {+ @qualid} @@ -3788,8 +3845,9 @@ Solver``. This combines the effects of the different variants of :tacn:`firstorder`. -Proof-search is bounded by a depth parameter which can be set by -typing the ``Set Firstorder Depth n`` vernacular command. +.. opt:: Firstorder Depth @natural + + This option controls the proof-search depth bound. .. tacn:: congruence :name: congruence @@ -3878,7 +3936,7 @@ succeeds, and results in an error otherwise. .. tacv:: unify @term @term with @ident Unification takes the transparency information defined in the hint database - :n:`@ident` into account (see :ref:`the hints databases for auto and eauto <the-hints-databases-for-auto-and-eauto>`). + :n:`@ident` into account (see :ref:`the hints databases for auto and eauto <thehintsdatabasesforautoandeauto>`). .. tacn:: is_evar @term :name: is_evar @@ -4009,6 +4067,7 @@ symbol :g:`=`. .. tacv:: esimplify_eq @num .. tacv:: esimplify_eq @term {? with @bindings_list} + :name: esimplify_eq This works the same as ``simplify_eq`` but if the type of :n:`@term`, or the type of the hypothesis referred to by :n:`@num`, has uninstantiated @@ -4020,7 +4079,7 @@ symbol :g:`=`. :n:`intro @ident; simplify_eq @ident`. .. tacn:: dependent rewrite -> @ident - :name: dependent rewrite -> + :name: dependent rewrite This tactic applies to any goal. If :n:`@ident` has type :g:`(existT B a b)=(existT B a' b')` in the local context (i.e. each @@ -4044,7 +4103,7 @@ Inversion :tacn:`functional inversion` is a tactic that performs inversion on hypothesis :n:`@ident` of the form :n:`@qualid {+ @term} = @term` or :n:`@term = @qualid {+ @term}` where :n:`@qualid` must have been defined using Function (see -:ref:`TODO-2.3-advancedrecursivefunctions`). Note that this tactic is only +:ref:`advanced-recursive-functions`). Note that this tactic is only available after a ``Require Import FunInd``. @@ -4077,7 +4136,7 @@ This kind of inversion has nothing to do with the tactic :tacn:`inversion` above. This tactic does :g:`change (@ident t)`, where `t` is a term built in order to ensure the convertibility. In other words, it does inversion of the function :n:`@ident`. This function must be a fixpoint on a simple recursive -datatype: see :ref:`TODO-10.3-quote` for the full details. +datatype: see :ref:`quote` for the full details. .. exn:: quote: not a simple fixpoint @@ -4109,6 +4168,8 @@ using the ``Require Import`` command. Use ``classical_right`` to prove the right part of the disjunction with the assumption that the negation of left part holds. +.. _tactics-automatizing: + Automatizing ------------ @@ -4148,7 +4209,7 @@ formulas built with `~`, `\/`, `/\`, `->` on top of equalities, inequalities and disequalities on both the type :g:`nat` of natural numbers and :g:`Z` of binary integers. This tactic must be loaded by the command ``Require Import Omega``. See the additional documentation about omega -(see Chapter :ref:`TODO-21-omega`). +(see Chapter :ref:`omega`). .. tacn:: ring @@ -4168,7 +4229,7 @@ given in the conclusion of the goal by their normal forms. If no term is given, then the conclusion should be an equation and both hand sides are normalized. -See :ref:`TODO-Chapter-25-Theringandfieldtacticfamilies` for more information on +See :ref:`Theringandfieldtacticfamilies` for more information on the tactic and how to declare new ring structures. All declared field structures can be printed with the ``Print Rings`` command. @@ -4194,7 +4255,7 @@ denominators. So it produces an equation without division nor inverse. All of these 3 tactics may generate a subgoal in order to prove that denominators are different from zero. -See :ref:`TODO-Chapter-25-Theringandfieldtacticfamilies` for more information on the tactic and how to +See :ref:`Theringandfieldtacticfamilies` for more information on the tactic and how to declare new field structures. All declared field structures can be printed with the Print Fields command. @@ -4286,7 +4347,7 @@ This tactics reverses the list of the focused goals. This tactic moves all goals under focus to a shelf. While on the shelf, goals will not be focused on. They can be solved by unification, or they can be called back into focus with the command - :tacn:`Unshelve`. + :cmd:`Unshelve`. .. tacv:: shelve_unifiable @@ -4302,8 +4363,7 @@ This tactics reverses the list of the focused goals. all:shelve_unifiable. reflexivity. -.. tacn:: Unshelve - :name: Unshelve +.. cmd:: Unshelve This command moves all the goals on the shelf (see :tacn:`shelve`) from the shelf into focus, by appending them to the end of the current @@ -4334,11 +4394,11 @@ A simple example has more value than a long explanation: The tactics macros are synchronous with the Coq section mechanism: a tactic definition is deleted from the current environment when you -close the section (see also :ref:`TODO-2.4Sectionmechanism`) where it was +close the section (see also :ref:`section-mechanism`) where it was defined. If you want that a tactic macro defined in a module is usable in the modules that require it, you should put it outside of any section. -:ref:`TODO-9-Thetacticlanguage` gives examples of more complex +:ref:`ltac` gives examples of more complex user-defined tactics. .. [1] Actually, only the second subgoal will be generated since the diff --git a/doc/sphinx/proof-engine/vernacular-commands.rst b/doc/sphinx/proof-engine/vernacular-commands.rst index 0bb6eea233..692ff294a6 100644 --- a/doc/sphinx/proof-engine/vernacular-commands.rst +++ b/doc/sphinx/proof-engine/vernacular-commands.rst @@ -39,6 +39,7 @@ This is a synonym to ``Print`` :n:`@qualid` when :n:`@qualid` denotes a global constant. .. cmdv:: About @qualid. + :name: About This displays various information about the object denoted by :n:`@qualid`: its kind (module, constant, assumption, inductive, @@ -61,6 +62,7 @@ Variants: .. cmdv:: Inspect @num. + :name: Inspect This command displays the :n:`@num` last objects of the current environment, including sections and modules. @@ -77,13 +79,11 @@ section. Flags, Options and Tables ----------------------------- -|Coq| configurability is based on flags (e.g. Set Printing All in -Section :ref:`TODO-2.9-printing-full`), options (e.g. ``Set Printing Widthinteger`` in Section -:ref:`TODO-6.9.6-set-printing-width`), or tables (e.g. ``Add Printing Record ident``, in Section -:ref:`TODO-2.2.4-add-printing-record`). The names of flags, options and tables are made of non-empty sequences of identifiers -(conventionally with capital initial -letter). The general commands handling flags, options and tables are -given below. +|Coq| configurability is based on flags (e.g. :opt:`Printing All`), options +(e.g. :opt:`Printing Width`), or tables (e.g. :cmd:`Add Printing Record`). The +names of flags, options and tables are made of non-empty sequences of +identifiers (conventionally with capital initial letter). The general commands +handling flags, options and tables are given below. .. TODO : flag is not a syntax entry @@ -92,10 +92,8 @@ given below. This command switches :n:`@flag` on. The original state of :n:`@flag` is restored when the current module ends. - Variants: - .. cmdv:: Local Set @flag. This command switches :n:`@flag` on. The original state @@ -107,6 +105,11 @@ This command switches :n:`@flag` on. The original state of :n:`@flag` is *not* restored at the end of the module. Additionally, if set in a file, :n:`@flag` is switched on when the file is `Require`-d. +.. cmdv:: Export Set @flag. + + This command switches :n:`@flag` on. The original state + of :n:`@flag` is restored at the end of the current module, but :n:`@flag` + is switched on when this module is imported. .. cmd:: Unset @flag. @@ -128,6 +131,11 @@ This command switches :n:`@flag` off. The original state of :n:`@flag` is *not* restored at the end of the module. Additionally, if set in a file, :n:`@flag` is switched off when the file is `Require`-d. +.. cmdv:: Export Unset @flag. + + This command switches :n:`@flag` off. The original state + of :n:`@flag` is restored at the end of the current module, but :n:`@flag` + is switched off when this module is imported. .. cmd:: Test @flag. @@ -157,11 +165,16 @@ original value of :n:`@option` is *not* restored at the end of the module. Additionally, if set in a file, :n:`@option` is set to value when the file is `Require`-d. +.. cmdv:: Export Set @option. + + This command set :n:`@option` to :n:`@value`. The original state + of :n:`@option` is restored at the end of the current module, but :n:`@option` + is set to :n:`@value` when this module is imported. .. cmd:: Unset @option. -This command resets option to its default value. + This command turns off :n:`@option`. Variants: @@ -169,17 +182,20 @@ Variants: .. cmdv:: Local Unset @option. -This command resets :n:`@option` to its default -value. The original state of :n:`@option` is restored when the current -*section* ends. + This command turns off :n:`@option`. The original state of :n:`@option` is restored when the current + *section* ends. .. cmdv:: Global Unset @option. -This command resets :n:`@option` to its default -value. The original state of :n:`@option` is *not* restored at the end of the -module. Additionally, if unset in a file, :n:`@option` is reset to its -default value when the file is `Require`-d. + This command turns off :n:`@option`. The original state of :n:`@option` is *not* restored at the end of the + module. Additionally, if unset in a file, :n:`@option` is reset to its + default value when the file is `Require`-d. + +.. cmdv:: Export Unset @option. + This command turns off :n:`@option`. The original state of :n:`@option` is restored at the end of the + current module, but :n:`@option` is set to its default value when this module + is imported. .. cmd:: Test @option. @@ -190,9 +206,17 @@ This command prints the current value of :n:`@option`. .. TODO : table is not a syntax entry .. cmd:: Add @table @value. + :name: Add `table` `value` + .. cmd:: Remove @table @value. + :name: Remove `table` `value` + .. cmd:: Test @table @value. + :name: Test `table` `value` + .. cmd:: Test @table for @value. + :name: Test `table` for `value` + .. cmd:: Print Table @table. These are general commands for tables. @@ -228,7 +252,7 @@ Variants: .. cmdv:: @selector: Check @term. specifies on which subgoal to perform typing -(see Section :ref:`TODO-8.1-invocation-of-tactics`). +(see Section :ref:`invocation-of-tactics`). .. TODO : convtactic is not a syntax entry @@ -240,7 +264,7 @@ hypothesis introduced in the first subgoal (if a proof is in progress). -See also: Section :ref:`TODO-8.7-performing-computations`. +See also: Section :ref:`performingcomputations`. .. cmd:: Compute @term. @@ -250,17 +274,16 @@ bytecode-based virtual machine. It is a shortcut for ``Eval vm_compute in`` :n:`@term`. -See also: Section :ref:`TODO-8.7-performing-computations`. +See also: Section :ref:`performingcomputations`. .. cmd::Extraction @term. This command displays the extracted term from :n:`@term`. The extraction is -processed according to the distinction between ``Set`` and ``Prop``; that is -to say, between logical and computational content (see Section -:ref:`TODO-4.1.1-sorts`). The extracted term is displayed in OCaml -syntax, -where global identifiers are still displayed as in |Coq| terms. +processed according to the distinction between :g:`Set` and :g:`Prop`; that is +to say, between logical and computational content (see Section :ref:`sorts`). +The extracted term is displayed in OCaml syntax, where global identifiers are +still displayed as in |Coq| terms. Variants: @@ -272,7 +295,7 @@ Recursively extracts all the material needed for the extraction of the qualified identifiers. -See also: Chapter ref:`TODO-23-chapter-extraction`. +See also: Chapter :ref:`extraction`. .. cmd:: Print Assumptions @qualid. @@ -326,13 +349,13 @@ displays the name and type of all objects (theorems, axioms, etc) of the current context whose name contains string. If string is a notation’s string denoting some reference :n:`@qualid` (referred to by its main symbol as in `"+"` or by its notation’s string as in `"_ + _"` or -`"_ 'U' _"`, see Section :ref:`TODO-12.1-notations`), the command works like ``Search`` :n:`@qualid`. +`"_ 'U' _"`, see Section :ref:`notations`), the command works like ``Search`` :n:`@qualid`. .. cmdv:: Search @string%@key. The string string must be a notation or the main symbol of a notation which is then interpreted in the scope bound to -the delimiting key :n:`@key` (see Section :ref:`TODO-12.2.2-local-interpretation-rules-for-notations`). +the delimiting key :n:`@key` (see Section :ref:`LocalInterpretationRulesForNotations`). .. cmdv:: Search @term_pattern. @@ -364,7 +387,7 @@ This restricts the search to constructions not defined in the modules named by t .. cmdv:: @selector: Search [-]@term_pattern_string … [-]@term_pattern_string. This specifies the goal on which to search hypothesis (see -Section :ref:`TODO-8.1-invocation-of-tactics`). +Section :ref:`invocation-of-tactics`). By default the 1st goal is searched. This variant can be combined with other variants presented here. @@ -382,11 +405,11 @@ be combined with other variants presented here. Search (?x * _ + ?x * _)%Z outside OmegaLemmas. .. note:: Up to |Coq| version 8.4, ``Search`` had the behavior of current -``SearchHead`` and the behavior of current Search was obtained with -command ``SearchAbout``. For compatibility, the deprecated name -SearchAbout can still be used as a synonym of Search. For -compatibility, the list of objects to search when using ``SearchAbout`` -may also be enclosed by optional[ ] delimiters. + ``SearchHead`` and the behavior of current Search was obtained with + command ``SearchAbout``. For compatibility, the deprecated name + SearchAbout can still be used as a synonym of Search. For + compatibility, the list of objects to search when using ``SearchAbout`` + may also be enclosed by optional ``[ ]`` delimiters. .. cmd:: SearchHead @term. @@ -420,12 +443,12 @@ Error messages: .. exn:: Module/section @qualid not found No module :n:`@qualid` has been required -(see Section :ref:`TODO-6.5.1-require`). +(see Section :ref:`compiled-files`). .. cmdv:: @selector: SearchHead @term. This specifies the goal on which to -search hypothesis (see Section :ref:`TODO-8.1-invocation-of-tactics`). +search hypothesis (see Section :ref:`invocation-of-tactics`). By default the 1st goal is searched. This variant can be combined with other variants presented here. @@ -479,7 +502,7 @@ This restricts the search to constructions not defined in the modules named by t .. cmdv:: @selector: SearchPattern @term. This specifies the goal on which to -search hypothesis (see Section :ref:`TODO-8.1-invocation-of-tactics`). By default the 1st goal is +search hypothesis (see Section :ref:`invocation-of-tactics`). By default the 1st goal is searched. This variant can be combined with other variants presented here. @@ -514,7 +537,7 @@ This restricts the search to constructions not defined in the modules named by t .. cmdv:: @selector: SearchRewrite @term. This specifies the goal on which to -search hypothesis (see Section :ref:`TODO-8.1-invocation-of-tactics`). By default the 1st goal is +search hypothesis (see Section :ref:`invocation-of-tactics`). By default the 1st goal is searched. This variant can be combined with other variants presented here. @@ -569,7 +592,7 @@ As Locate but restricted to modules. As Locate but restricted to tactics. -See also: Section :ref:`TODO-12.1.10-LocateSymbol` +See also: Section :ref:`locating-notations` .. _loading-files: @@ -589,7 +612,7 @@ toplevel. This kind of file is called a *script* for |Coq|. The standard This command loads the file named :n:`ident`.v, searching successively in each of the directories specified in the *loadpath*. (see Section -:ref:`TODO-2.6.3-libraries-and-filesystem`) +:ref:`libraries-and-filesystem`) Files loaded this way cannot leave proofs open, and the ``Load`` command cannot be used inside a proof either. @@ -610,7 +633,7 @@ will use the default extension ``.v``. Display, while loading, the answers of |Coq| to each command (including tactics) contained in -the loaded file See also: Section :ref:`TODO-6.9.1-silent`. +the loaded file See also: Section :ref:`controlling-display`. Error messages: @@ -626,7 +649,7 @@ Compiled files ------------------ This section describes the commands used to load compiled files (see -Chapter :ref:`TODO-14-coq-commands` for documentation on how to compile a file). A compiled +Chapter :ref:`thecoqcommands` for documentation on how to compile a file). A compiled file is a particular case of module called *library file*. @@ -644,7 +667,7 @@ replayed nor rechecked. To locate the file in the file system, :n:`@qualid` is decomposed under the form `dirpath.ident` and the file `ident.vo` is searched in the physical directory of the file system that is mapped in |Coq| loadpath to the -logical path dirpath (see Section :ref:`TODO-2.6.3-libraries-and-filesystem`). The mapping between +logical path dirpath (see Section :ref:`libraries-and-filesystem`). The mapping between physical directories and logical names at the time of requiring the file must be consistent with the mapping used to compile the file. If several files match, one of them is picked in an unspecified fashion. @@ -656,7 +679,7 @@ Variants: This loads and declares the module :n:`@qualid` and its dependencies then imports the contents of :n:`@qualid` as described -in Section :ref:`TODO-2.5.8-import`.It does not import the modules on which +:ref:`here <import_qualid>`. It does not import the modules on which qualid depends unless these modules were themselves required in module :n:`@qualid` using ``Require Export``, as described below, or recursively required @@ -696,11 +719,11 @@ Error messages: The command did not find the file foo.vo. Either foo.v exists but is not compiled or foo.vo is in a -directory which is not in your LoadPath (see Section :ref:`TODO-2.6.3-libraries-and-filesystem`). +directory which is not in your LoadPath (see Section :ref:`libraries-and-filesystem`). -.. exn:: Compiled library ident.vo makes inconsistent assumptions over library qualid +.. exn:: Compiled library @ident.vo makes inconsistent assumptions over library qualid -The command tried to load library file `ident.vo` that +The command tried to load library file :n:`@ident`.vo that depends on some specific version of library :n:`@qualid` which is not the one already loaded in the current |Coq| session. Probably `ident.v` was not properly recompiled with the last version of the file containing @@ -725,12 +748,12 @@ the time it was compiled. This command is not allowed inside a module or a module type being defined. It is meant to describe a dependency between compilation units. Note however -that the commands Import and Export alone can be used inside modules -(see Section :ref:`TODO-2.5.8-import`). +that the commands ``Import`` and ``Export`` alone can be used inside modules +(see Section :ref:`Import <import_qualid>`). -See also: Chapter :ref:`TODO-14-coq-commands` +See also: Chapter :ref:`thecoqcommands` .. cmd:: Print Libraries. @@ -746,8 +769,8 @@ This commands loads the OCaml compiled files with names given by the :n:`@string` sequence (dynamic link). It is mainly used to load tactics dynamically. The files are searched into the current OCaml loadpath (see the -command ``Add ML Path`` in Section :ref:`TODO-2.6.3-libraries-and-filesystem`). Loading of OCaml files is only possible under the bytecode version of ``coqtop`` (i.e. -``coqtop`` called with option ``-byte``, see chapter :ref:`TODO-14-coq-commands`), or when |Coq| has been compiled with a +command ``Add ML Path`` in Section :ref:`libraries-and-filesystem`). Loading of OCaml files is only possible under the bytecode version of ``coqtop`` (i.e. +``coqtop`` called with option ``-byte``, see chapter :ref:`thecoqcommands`), or when |Coq| has been compiled with a version of OCaml that supports native Dynlink (≥ 3.11). @@ -766,7 +789,7 @@ Error messages: .. exn:: File not found on loadpath : @string -.. exn:: Loading of ML object file forbidden in a native |Coq| +.. exn:: Loading of ML object file forbidden in a native Coq @@ -774,7 +797,7 @@ Error messages: This prints the name of all OCaml modules loaded with ``Declare ML Module``. To know from where these module were loaded, the user -should use the command Locate File (see Section :ref:`TODO-6.6.10-locate-file`) +should use the command ``Locate File`` (see :ref:`here <locate-file>`) .. _loadpath: @@ -783,7 +806,7 @@ Loadpath ------------ Loadpaths are preferably managed using |Coq| command line options (see -Section `2.6.3-libraries-and-filesystem`) but there remain vernacular commands to manage them +Section `libraries-and-filesystem`) but there remain vernacular commands to manage them for practical purposes. Such commands are only meant to be issued in the toplevel, and using them in source files is discouraged. @@ -862,14 +885,14 @@ the paths that extend the :n:`@dirpath` prefix. .. cmd:: Add ML Path @string. This command adds the path :n:`@string` to the current OCaml -loadpath (see the command `Declare ML Module`` in Section :ref:`TODO-6.5-compiled-files`). +loadpath (see the command `Declare ML Module`` in Section :ref:`compiled-files`). .. cmd:: Add Rec ML Path @string. This command adds the directory :n:`@string` and all its subdirectories to the current OCaml loadpath (see the command ``Declare ML Module`` -in Section :ref:`TODO-6.5-compiled-files`). +in Section :ref:`compiled-files`). .. cmd:: Print ML Path @string. @@ -877,8 +900,9 @@ in Section :ref:`TODO-6.5-compiled-files`). This command displays the current OCaml loadpath. This command makes sense only under the bytecode version of ``coqtop``, i.e. using option ``-byte`` -(see the command Declare ML Module in Section :ref:`TODO-6.5-compiled-files`). +(see the command Declare ML Module in Section :ref:`compiled-files`). +.. _locate-file: .. cmd:: Locate File @string. @@ -929,7 +953,7 @@ of the interactive session. This commands undoes all the effects of the last vernacular command. Commands read from a vernacular file via a ``Load`` are considered as a single command. Proof management commands are also handled by this -command (see Chapter :ref:`TODO-7-proof-handling`). For that, Back may have to undo more than +command (see Chapter :ref:`proofhandling`). For that, Back may have to undo more than one command in order to reach a state where the proof management information is available. For instance, when the last command is a ``Qed``, the management information about the closed proof has been @@ -978,9 +1002,9 @@ three numbers represent the following: + *first number* : State label to reach, as for BackTo. + *second number* : *Proof state number* to unbury once aborts have been done. - |Coq| will compute the number of Undo to perform (see Chapter :ref:`TODO-7-proof-handling`). + |Coq| will compute the number of Undo to perform (see Chapter :ref:`proofhandling`). + *third number* : Number of Abort to perform, i.e. the number of currently - opened nested proofs that must be canceled (see Chapter :ref:`TODO-7-proof-handling`). + opened nested proofs that must be canceled (see Chapter :ref:`proofhandling`). @@ -1029,16 +1053,13 @@ to |Coq| with the command: go();; +.. warning:: - -Warnings: - - -#. It only works with the bytecode version of |Coq| (i.e. `coqtop.byte`, - see Section `TODO-14.1-interactive-use`). -#. You must have compiled |Coq| from the source package and set the - environment variable COQTOP to the root of your copy of the sources - (see Section `14.3.2-customization-by-envionment-variables`). + #. It only works with the bytecode version of |Coq| (i.e. `coqtop.byte`, + see Section `interactive-use`). + #. You must have compiled |Coq| from the source package and set the + environment variable COQTOP to the root of your copy of the sources + (see Section `customization-by-environment-variables`). @@ -1064,20 +1085,11 @@ expressed in seconds), then it is interrupted and an error message is displayed. -.. cmd:: Set Default Timeout @num. - -After using this command, all subsequent commands behave as if they -were passed to a Timeout command. Commands already starting by a -`Timeout` are unaffected. - +.. opt:: Default Timeout @num -.. cmd:: Unset Default Timeout. - -This command turns off the use of a default timeout. - -.. cmd:: Test Default Timeout. - -This command displays whether some default timeout has been set or not. + This option controls a default timeout for subsequent commands, as if they + were passed to a :cmd:`Timeout` command. Commands already starting by a + :cmd:`Timeout` are unaffected. .. cmd:: Fail @command. @@ -1098,129 +1110,60 @@ Error messages: Controlling display ----------------------- +.. opt:: Silent -.. cmd:: Set Silent. - -This command turns off the normal displaying. - - -.. cmd:: Unset Silent. - -This command turns the normal display on. - -TODO : check that spaces are handled well - -.. cmd:: Set Warnings ‘‘(@ident {* , @ident } )’’. - -This command configures the display of warnings. It is experimental, -and expects, between quotes, a comma-separated list of warning names -or categories. Adding - in front of a warning or category disables it, -adding + makes it an error. It is possible to use the special -categories all and default, the latter containing the warnings enabled -by default. The flags are interpreted from left to right, so in case -of an overlap, the flags on the right have higher priority, meaning -that `A,-A` is equivalent to `-A`. - - -.. cmd:: Set Search Output Name Only. - -This command restricts the output of search commands to identifier -names; turning it on causes invocations of ``Search``, ``SearchHead``, -``SearchPattern``, ``SearchRewrite`` etc. to omit types from their output, -printing only identifiers. - - -.. cmd:: Unset Search Output Name Only. - -This command turns type display in search results back on. - - -.. cmd:: Set Printing Width @integer. - -This command sets which left-aligned part of the width of the screen -is used for display. - - -.. cmd:: Unset Printing Width. - -This command resets the width of the screen used for display to its -default value (which is 78 at the time of writing this documentation). - - -.. cmd:: Test Printing Width. - -This command displays the current screen width used for display. - - -.. cmd:: Set Printing Depth @integer. - -This command sets the nesting depth of the formatter used for pretty- -printing. Beyond this depth, display of subterms is replaced by dots. - - -.. cmd:: Unset Printing Depth. - -This command resets the nesting depth of the formatter used for -pretty-printing to its default value (at the time of writing this -documentation, the default value is 50). - - -.. cmd:: Test Printing Depth. - -This command displays the current nesting depth used for display. - - -.. cmd:: Unset Printing Compact Contexts. - -This command resets the displaying of goals contexts to non compact -mode (default at the time of writing this documentation). Non compact -means that consecutive variables of different types are printed on -different lines. - - -.. cmd:: Set Printing Compact Contexts. - -This command sets the displaying of goals contexts to compact mode. -The printer tries to reduce the vertical size of goals contexts by -putting several variables (even if of different types) on the same -line provided it does not exceed the printing width (See Set Printing -Width above). - - -.. cmd:: Test Printing Compact Contexts. - -This command displays the current state of compaction of goal. + This option controls the normal displaying. +.. opt:: Warnings "{+, {? %( - %| + %) } @ident }" -.. cmd:: Unset Printing Unfocused. + This option configures the display of warnings. It is experimental, and + expects, between quotes, a comma-separated list of warning names or + categories. Adding - in front of a warning or category disables it, adding + + makes it an error. It is possible to use the special categories all and + default, the latter containing the warnings enabled by default. The flags are + interpreted from left to right, so in case of an overlap, the flags on the + right have higher priority, meaning that `A,-A` is equivalent to `-A`. -This command resets the displaying of goals to focused goals only -(default). Unfocused goals are created by focusing other goals with -bullets (see :ref:`TODO-7.2.7-bullets`) or curly braces (see `7.2.6-curly-braces`). +.. opt:: Search Output Name Only + This option restricts the output of search commands to identifier names; + turning it on causes invocations of :cmd:`Search`, :cmd:`SearchHead`, + :cmd:`SearchPattern`, :cmd:`SearchRewrite` etc. to omit types from their + output, printing only identifiers. -.. cmd:: Set Printing Unfocused. +.. opt:: Printing Width @integer -This command enables the displaying of unfocused goals. The goals are -displayed after the focused ones and are distinguished by a separator. + This command sets which left-aligned part of the width of the screen is used + for display. At the time of writing this documentation, the default value + is 78. +.. opt:: Printing Depth @integer -.. cmd:: Test Printing Unfocused. + This option controls the nesting depth of the formatter used for pretty- + printing. Beyond this depth, display of subterms is replaced by dots. At the + time of writing this documentation, the default value is 50. -This command displays the current state of unfocused goals display. +.. opt:: Printing Compact Contexts + This option controls the compact display mode for goals contexts. When on, + the printer tries to reduce the vertical size of goals contexts by putting + several variables (even if of different types) on the same line provided it + does not exceed the printing width (see :opt:`Printing Width`). At the time + of writing this documentation, it is off by default. -.. cmd:: Set Printing Dependent Evars Line. +.. opt:: Printing Unfocused -This command enables the printing of the “(dependent evars: …)” line -when -emacs is passed. + This option controls whether unfocused goals are displayed. Such goals are + created by focusing other goals with bullets (see :ref:`bullets` or + :ref:`curly braces <curly-braces>`). It is off by default. +.. opt:: Printing Dependent Evars Line -.. cmd:: Unset Printing Dependent Evars Line. + This option controls the printing of the “(dependent evars: …)” line when + ``-emacs`` is passed. -This command disables the printing of the “(dependent evars: …)” line -when -emacs is passed. +.. _vernac-controlling-the-reduction-strategies: Controlling the reduction strategies and the conversion algorithm ---------------------------------------------------------------------- @@ -1232,7 +1175,7 @@ conversion algorithm lazily compares applicative terms while the other is a brute-force but efficient algorithm that first normalizes the terms before comparing them. The second algorithm is based on a bytecode representation of terms similar to the bytecode -representation used in the ZINC virtual machine [`98`]. It is +representation used in the ZINC virtual machine :cite:`Leroy90`. It is especially useful for intensive computation of algebraic values, such as numbers, and for reflection-based tactics. The commands to fine- tune the reduction strategies and the lazy conversion algorithm are @@ -1249,14 +1192,14 @@ a constant is replacing it by its definition). ``Opaque`` has also an effect on the conversion algorithm of |Coq|, telling it to delay the unfolding of a constant as much as possible when |Coq| -has to check the conversion (see Section :ref:`TODO-4.3-conversion-rules`) of two distinct +has to check the conversion (see Section :ref:`conversion-rules`) of two distinct applied constants. The scope of ``Opaque`` is limited to the current section, or current file, unless the variant ``Global Opaque`` is used. -See also: sections :ref:`TODO-8.7-performing-computations`, :ref:`TODO-8.16-automatizing`, :ref:`TODO-7.1-switching-on-off-proof-editing-mode` +See also: sections :ref:`performingcomputations`, :ref:`tactics-automatizing`, :ref:`proof-editing-mode` Error messages: @@ -1294,8 +1237,9 @@ There is no constant referred by :n:`@qualid` in the environment. -See also: sections :ref:`TODO-8.7-performing-computations`, :ref:`TODO-8.16-automatizing`, :ref:`TODO-7.1-switching-on-off-proof-editing-mode` +See also: sections :ref:`performingcomputations`, :ref:`tactics-automatizing`, :ref:`proof-editing-mode` +.. _vernac-strategy: .. cmd:: Strategy @level [ {+ @qualid } ]. @@ -1367,7 +1311,7 @@ nothing prevents the user to also perform a ``Ltac`` `ident` ``:=`` `convtactic`. -See also: sections :ref:`TODO-8.7-performing-computations` +See also: sections :ref:`performingcomputations` .. _controlling-locality-of-commands: @@ -1387,23 +1331,22 @@ scope of their effect. There are four kinds of commands: section and the module or library file they occur in. For these commands, the Local modifier limits the effect of the command to the current section or module it occurs in. As an example, the ``Coercion`` - (see Section :ref:`TODO-2.8-coercions`) and ``Strategy`` (see Section :ref:`TODO-6.10.3-strategy`) commands belong - to this category. + (see Section :ref:`coercions`) and ``Strategy`` (see :ref:`here <vernac-strategy>`) + commands belong to this category. + Commands whose default behavior is to stop their effect at the end - of the section they occur in but to extent their effect outside the - module or library file they occur in. For these commands, the Local - modifier limits the effect of the command to the current module if the - command does not occur in a section and the Global modifier extends - the effect outside the current sections and current module if the - command occurs in a section. As an example, the ``Implicit Arguments`` (see - Section :ref:`TODO-2.7-implicit-arguments`), Ltac (see Chapter :ref:`TODO-9-tactic-language`) or ``Notation`` (see Section - :ref:`TODO-12.1-notations`) commands belong to this category. Notice that a subclass of - these commands do not support extension of their scope outside - sections at all and the Global is not applicable to them. + of the section they occur in but to extent their effect outside the module or + library file they occur in. For these commands, the Local modifier limits the + effect of the command to the current module if the command does not occur in a + section and the Global modifier extends the effect outside the current + sections and current module if the command occurs in a section. As an example, + the :cmd:`Implicit Arguments`, :cmd:`Ltac` or :cmd:`Notation` commands belong + to this category. Notice that a subclass of these commands do not support + extension of their scope outside sections at all and the Global is not + applicable to them. + Commands whose default behavior is to stop their effect at the end of the section or module they occur in. For these commands, the Global modifier extends their effect outside the sections and modules they - occurs in. The ``Transparent`` and ``Opaque`` (see Section :ref:`TODO-6.10-opaque`) commands belong to this category. + occurs in. The ``Transparent`` and ``Opaque`` (see Section :ref:`vernac-controlling-the-reduction-strategies`) commands belong to this category. + Commands whose default behavior is to extend their effect outside sections but not outside modules when they occur in a section and to extend their effect outside the module or library file they occur in diff --git a/doc/sphinx/replaces.rst b/doc/sphinx/replaces.rst index 1b2e172216..28a04f90ce 100644 --- a/doc/sphinx/replaces.rst +++ b/doc/sphinx/replaces.rst @@ -35,7 +35,9 @@ .. |ident_n,1| replace:: `ident`\ :math:`_{n,1}` .. |ident_n,k_n| replace:: `ident`\ :math:`_{n,k_n}` .. |ident_n| replace:: `ident`\ :math:`_{n}` +.. |Latex| replace:: :smallcaps:`LaTeX` .. |L_tac| replace:: `L`:sub:`tac` +.. |Ltac| replace:: `L`:sub:`tac` .. |ML| replace:: :smallcaps:`ML` .. |mod_0| replace:: `mod`\ :math:`_{0}` .. |mod_1| replace:: `mod`\ :math:`_{1}` @@ -54,7 +56,7 @@ .. |module_type_n| replace:: `module_type`\ :math:`_{n}` .. |N| replace:: ``N`` .. |nat| replace:: ``nat`` -.. |Ocaml| replace:: :smallcaps:`OCaml` +.. |OCaml| replace:: :smallcaps:`OCaml` .. |p_1| replace:: `p`\ :math:`_{1}` .. |p_i| replace:: `p`\ :math:`_{i}` .. |p_n| replace:: `p`\ :math:`_{n}` diff --git a/doc/sphinx/user-extensions/proof-schemes.rst b/doc/sphinx/user-extensions/proof-schemes.rst index 583b73e53d..e12e4d897a 100644 --- a/doc/sphinx/user-extensions/proof-schemes.rst +++ b/doc/sphinx/user-extensions/proof-schemes.rst @@ -3,6 +3,8 @@ Proof schemes =============== +.. _proofschemes-induction-principles: + Generation of induction principles with ``Scheme`` -------------------------------------------------------- @@ -10,7 +12,7 @@ The ``Scheme`` command is a high-level tool for generating automatically (possibly mutual) induction principles for given types and sorts. Its syntax follows the schema: -.. cmd:: Scheme ident := Induction for ident' Sort sort {* with ident := Induction for ident' Sort sort} +.. cmd:: Scheme @ident := Induction for @ident Sort sort {* with @ident := Induction for @ident Sort sort} where each `ident'ᵢ` is a different inductive type identifier belonging to the same package of mutual inductive definitions. This @@ -18,17 +20,17 @@ command generates the `identᵢ`s to be mutually recursive definitions. Each term `identᵢ` proves a general principle of mutual induction for objects in type `identᵢ`. -.. cmdv:: Scheme ident := Minimality for ident' Sort sort {* with ident := Minimality for ident' Sort sort} +.. cmdv:: Scheme @ident := Minimality for @ident Sort sort {* with @ident := Minimality for @ident' Sort sort} Same as before but defines a non-dependent elimination principle more natural in case of inductively defined relations. -.. cmdv:: Scheme Equality for ident +.. cmdv:: Scheme Equality for @ident Tries to generate a Boolean equality and a proof of the decidability of the usual equality. If `ident` involves some other inductive types, their equality has to be defined first. -.. cmdv:: Scheme Induction for ident Sort sort {* with Induction for ident Sort sort} +.. cmdv:: Scheme Induction for @ident Sort sort {* with Induction for @ident Sort sort} If you do not provide the name of the schemes, they will be automatically computed from the sorts involved (works also with Minimality). @@ -101,26 +103,34 @@ induction for objects in type `identᵢ`. Automatic declaration of schemes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. opt:: Elimination Schemes + It is possible to deactivate the automatic declaration of the induction principles when defining a new inductive type with the ``Unset Elimination Schemes`` command. It may be reactivated at any time with ``Set Elimination Schemes``. -The types declared with the keywords ``Variant`` (see :ref:`TODO-1.3.3`) and ``Record`` -(see :ref:`Record Types <record-types>`) do not have an automatic declaration of the induction -principles. It can be activated with the command -``Set Nonrecursive Elimination Schemes``. It can be deactivated again with -``Unset Nonrecursive Elimination Schemes``. - -In addition, the ``Case Analysis Schemes`` flag governs the generation of -case analysis lemmas for inductive types, i.e. corresponding to the -pattern-matching term alone and without fixpoint. -You can also activate the automatic declaration of those Boolean -equalities (see the second variant of ``Scheme``) with respectively the -commands ``Set Boolean Equality Schemes`` and ``Set Decidable Equality -Schemes``. However you have to be careful with this option since Coq may -now reject well-defined inductive types because it cannot compute a -Boolean equality for them. +.. opt:: Nonrecursive Elimination Schemes + +This option controls whether types declared with the keywords :cmd:`Variant` and +:cmd:`Record` get an automatic declaration of the induction principles. + +.. opt:: Case Analysis Schemes + + This flag governs the generation of case analysis lemmas for inductive types, + i.e. corresponding to the pattern-matching term alone and without fixpoint. + +.. opt:: Boolean Equality Schemes + +.. opt:: Decidable Equality Schemes + +These flags control the automatic declaration of those Boolean equalities (see +the second variant of ``Scheme``). + +.. warning:: + + You have to be careful with this option since Coq may now reject well-defined + inductive types because it cannot compute a Boolean equality for them. .. opt:: Rewriting Schemes @@ -133,7 +143,7 @@ The ``Combined Scheme`` command is a tool for combining induction principles generated by the ``Scheme command``. Its syntax follows the schema : -.. cmd:: Combined Scheme ident from {+, ident} +.. cmd:: Combined Scheme @ident from {+, ident} where each identᵢ after the ``from`` is a different inductive principle that must belong to the same package of mutual inductive principle definitions. @@ -163,6 +173,8 @@ concluded by the conjunction of their conclusions. Check tree_forest_mutind. +.. _functional-scheme: + Generation of induction principles with ``Functional`` ``Scheme`` ----------------------------------------------------------------- @@ -172,7 +184,7 @@ generating automatically induction principles corresponding to available via ``Require Import FunInd``. Its syntax then follows the schema: -.. cmd:: Functional Scheme ident := Induction for ident' Sort sort {* with ident := Induction for ident' Sort sort} +.. cmd:: Functional Scheme @ident := Induction for ident' Sort sort {* with @ident := Induction for @ident Sort sort} where each `ident'ᵢ` is a different mutually defined function name (the names must be in the same order as when they were defined). This @@ -229,7 +241,7 @@ definition written by the user. simpl; auto with arith. Qed. - We can use directly the functional induction (:ref:`TODO-8.5.5`) tactic instead + We can use directly the functional induction (:tacn:`function induction`) tactic instead of the pattern/apply trick: .. coqtop:: all @@ -305,13 +317,15 @@ definition written by the user. .. coqtop:: all Check tree_size_ind2. + +.. _derive-inversion: Generation of inversion principles with ``Derive`` ``Inversion`` ----------------------------------------------------------------- The syntax of ``Derive`` ``Inversion`` follows the schema: -.. cmd:: Derive Inversion ident with forall (x : T), I t Sort sort +.. cmd:: Derive Inversion @ident with forall (x : T), I t Sort sort This command generates an inversion principle for the `inversion … using` tactic. Let `I` be an inductive predicate and `x` the variables occurring @@ -320,17 +334,17 @@ sort `sort` corresponding to the instance `∀ (x:T), I t` with the name `ident` in the global environment. When applied, it is equivalent to having inverted the instance with the tactic `inversion`. -.. cmdv:: Derive Inversion_clear ident with forall (x:T), I t Sort sort +.. cmdv:: Derive Inversion_clear @ident with forall (x:T), I t Sort sort When applied, it is equivalent to having inverted the instance with the tactic inversion replaced by the tactic `inversion_clear`. -.. cmdv:: Derive Dependent Inversion ident with forall (x:T), I t Sort sort +.. cmdv:: Derive Dependent Inversion @ident with forall (x:T), I t Sort sort When applied, it is equivalent to having inverted the instance with the tactic `dependent inversion`. -.. cmdv:: Derive Dependent Inversion_clear ident with forall(x:T), I t Sort sort +.. cmdv:: Derive Dependent Inversion_clear @ident with forall(x:T), I t Sort sort When applied, it is equivalent to having inverted the instance with the tactic `dependent inversion_clear`. diff --git a/doc/sphinx/user-extensions/syntax-extensions.rst b/doc/sphinx/user-extensions/syntax-extensions.rst index 531295b63a..c4a7121ce4 100644 --- a/doc/sphinx/user-extensions/syntax-extensions.rst +++ b/doc/sphinx/user-extensions/syntax-extensions.rst @@ -32,6 +32,8 @@ Notations Basic notations ~~~~~~~~~~~~~~~ +.. cmd:: Notation + A *notation* is a symbolic expression denoting some term or term pattern. @@ -345,13 +347,13 @@ inductive type or a recursive constant and a notation for it. Simultaneous definition of terms and notations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Thanks to reserved notations, the inductive, co-inductive, record, recursive -and corecursive definitions can benefit of customized notations. To do -this, insert a ``where`` notation clause after the definition of the -(co)inductive type or (co)recursive term (or after the definition of -each of them in case of mutual definitions). The exact syntax is given -on Figure 12.1 for inductive, co-inductive, recursive and corecursive -definitions and on Figure :ref:`record-syntax` for records. Here are examples: +Thanks to reserved notations, the inductive, co-inductive, record, recursive and +corecursive definitions can benefit of customized notations. To do this, insert +a ``where`` notation clause after the definition of the (co)inductive type or +(co)recursive term (or after the definition of each of them in case of mutual +definitions). The exact syntax is given by :token:`decl_notation` for inductive, +co-inductive, recursive and corecursive definitions and in :ref:`record-types` +for records. Here are examples: .. coqtop:: in @@ -381,23 +383,21 @@ Displaying informations about notations :opt:`Printing All` To disable other elements in addition to notations. +.. _locating-notations: + Locating notations ~~~~~~~~~~~~~~~~~~ -.. cmd:: Locate @symbol +To know to which notations a given symbol belongs to, use the :cmd:`Locate` +command. You can call it on any (composite) symbol surrounded by double quotes. +To locate a particular notation, use a string where the variables of the +notation are replaced by “_” and where possible single quotes inserted around +identifiers or tokens starting with a single quote are dropped. - To know to which notations a given symbol belongs to, use the command - ``Locate symbol``, where symbol is any (composite) symbol surrounded by double - quotes. To locate a particular notation, use a string where the variables of the - notation are replaced by “_” and where possible single quotes inserted around - identifiers or tokens starting with a single quote are dropped. - - .. coqtop:: all - - Locate "exists". - Locate "exists _ .. _ , _". +.. coqtop:: all - .. todo:: See also: Section 6.3.10. + Locate "exists". + Locate "exists _ .. _ , _". Notations and binders ~~~~~~~~~~~~~~~~~~~~~ @@ -435,8 +435,7 @@ Binders bound in the notation and parsed as patterns In the same way as patterns can be used as binders, as in :g:`fun '(x,y) => x+y` or :g:`fun '(existT _ x _) => x`, notations can be -defined so that any pattern (in the sense of the entry :n:`@pattern` of -Figure :ref:`term-syntax-aux`) can be used in place of the +defined so that any :n:`@pattern` can be used in place of the binder. Here is an example: .. coqtop:: in reset @@ -475,7 +474,7 @@ variable. Here is an example showing the difference: The default level for a ``pattern`` is 0. One can use a different level by using ``pattern at level`` :math:`n` where the scale is the same as the one for -terms (Figure :ref:`init-notations`). +terms (see :ref:`init-notations`). Binders bound in the notation and parsed as terms +++++++++++++++++++++++++++++++++++++++++++++++++ @@ -491,7 +490,7 @@ the following: This is so because the grammar also contains rules starting with :g:`{}` and followed by a term, such as the rule for the notation :g:`{ A } + { B }` for the -constant :g:`sumbool` (see Section :ref:`sumbool`). +constant :g:`sumbool` (see Section :ref:`specification`). Then, in the rule, ``x ident`` is replaced by ``x at level 99 as ident`` meaning that ``x`` is parsed as a term at level 99 (as done in the notation for @@ -829,6 +828,8 @@ lonely notations. These scopes, in opening order, are ``core_scope``, These variants survive sections. They behave as if Global were absent when not inside a section. +.. _LocalInterpretationRulesForNotations: + Local interpretation rules for notations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -859,6 +860,7 @@ Binding arguments of a constant to an interpretation scope +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. cmd:: Arguments @qualid {+ @name%@scope} + :name: Arguments (scopes) It is possible to set in advance that some arguments of a given constant have to be interpreted in a given scope. The command is @@ -897,7 +899,7 @@ Binding arguments of a constant to an interpretation scope .. cmdv:: Arguments @qualid {+ @name%scope} : extra scopes Defines extra argument scopes, to be used in case of coercion to Funclass - (see Chapter :ref:`Coercions-full`) or with a computed type. + (see Chapter :ref:`implicitcoercions`) or with a computed type. .. cmdv:: Global Arguments @qualid {+ @name%@scope} @@ -957,7 +959,7 @@ Binding types of arguments to an interpretation scope type :g:`t` in :g:`f t a` is not recognized as an argument to be interpreted in scope ``scope``. - More generally, any coercion :n:`@class` (see Chapter :ref:`Coercions-full`) + More generally, any coercion :n:`@class` (see Chapter :ref:`implicitcoercions`) can be bound to an interpretation scope. The command to do it is :n:`Bind Scope @scope with @class` @@ -1200,7 +1202,7 @@ Tactic notations allow to customize the syntax of the tactics of the tactic language. Tactic notations obey the following syntax: .. productionlist:: coq - tacn : [Local] Tactic Notation [`tactic_level`] [`prod_item` … `prod_item`] := `tactic`. + tacn : Tactic Notation [`tactic_level`] [`prod_item` … `prod_item`] := `tactic`. prod_item : `string` | `tactic_argument_type`(`ident`) tactic_level : (at level `natural`) tactic_argument_type : ident | simple_intropattern | reference @@ -1211,7 +1213,7 @@ tactic language. Tactic notations obey the following syntax: : | tactic | tactic0 | tactic1 | tactic2 | tactic3 : | tactic4 | tactic5 -.. cmd:: {? Local} Tactic Notation {? (at level @level)} {+ @prod_item} := @tactic. +.. cmd:: Tactic Notation {? (at level @level)} {+ @prod_item} := @tactic. A tactic notation extends the parser and pretty-printer of tactics with a new rule made of the list of production items. It then evaluates into the |
