Chapter 9  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 [41]. Chapter 10 is devoted to giving examples of use of this language on small but also with non-trivial problems.

9.1  Syntax

The syntax of the tactic language is given Figures 9.1 and 9.2. See Chapter 1 for a description of the BNF metasyntax used in these grammar rules. Various already defined entries will be used in this chapter: entries natural, integer, ident, qualid, term, cpattern and atomic_tactic represent respectively the natural and integer numbers, the authorized identificators and qualified names, Coq’s terms and patterns and all the atomic tactics described in Chapter 8. The syntax of cpattern is the same as that of terms, but it is extended with pattern matching metavariables. In cpattern, a pattern-matching metavariable is represented with the syntax ?id where id is an ident. The notation _ can also be used to denote metavariable whose instance is irrelevant. In the notation ?id, the identifier allows us to keep instantiations and to make constraints whereas _ 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 @?id id1 …idn, the variable id matches any complex expression with (possible) dependencies in the variables id1 …idn and returns a functional term of the form fun id1 …idn => term.

The main entry of the grammar is expr. This language is used in proof mode but it can also be used in toplevel definitions as shown in Figure 9.3.


Remarks:

  1. The infix tacticals “… || …” and “… ; …” are associative.
  2. In tacarg, there is an overlap between qualid as a direct tactic argument and 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 ltac : qualid. To force the resolution as a reference to a term, use the syntax (qualid).
  3. As shown by the figure, tactical || binds more than the prefix tacticals try, repeat, do, info and abstract which themselves bind more than the postfix tactical “… ;[ … ]” which binds more than “… ; …”.

    For instance

    try repeat tactic1 || tactic2;tactic3;[tactic31|…|tactic3n];tactic4.

    is understood as

    (try (repeat (tactic1 || tactic2)));
    ((tactic3;[tactic31|…|tactic3n]);tactic4).

expr::= expr ; expr
 |expr ; [ expr || expr ]
 |tacexpr3
 
tacexpr3::= do (natural | ident) tacexpr3
 |info tacexpr3
 |progress tacexpr3
 |repeat tacexpr3
 |try tacexpr3
 |tacexpr2
 
tacexpr2::= tacexpr1 || tacexpr3
 |tacexpr1
 
tacexpr1::=fun namename => 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
 |abstract atom
 |abstract atom using ident
 |first [ expr || expr ]
 |solve [ expr || expr ]
 |idtac [message_tokenmessage_token]
 |fail [natural] [message_tokenmessage_token]
 |fresh  |  fresh string
 |context ident [ term ]
 |eval redexpr in term
 |type of term
 |external string string tacargtacarg
 |constr : term
 |atomic_tactic
 |qualid tacargtacarg
 |atom
 
atom::= qualid
 |()
 |integer
 |( expr )
 
message_token::=string  |  term  |  integer
Figure 9.1: Syntax of the tactic language


tacarg::= qualid
 |()
 |ltac : atom
 |term
 
let_clause::=ident [namename] := expr
 
context_rule::= context_hyp ,, context_hyp |-cpattern => expr
 ||- cpattern => expr
 |_ => expr
 
context_hyp::=name : cpattern
 |name := cpattern [: cpattern]
 
match_rule::= cpattern => expr
 |context [ident] [ cpattern ] => expr
 |_ => expr
Figure 9.2: Syntax of the tactic language (continued)


top::=Ltac ltac_def withwith ltac_def
 
ltac_def::=ident [identident] := expr
 |qualid [identident] ::=expr
Figure 9.3: Tactic toplevel definitions

9.2  Semantics

Tactic expressions can only be applied in the context of a goal. 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 current goal.

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:

expr1 ; expr2

The expressions expr1 and expr2 are evaluated to v1 and v2 which have to be tactic values. The tactic v1 is then applied and v2 is applied to every subgoal generated by the application of v1. Sequence is left-associative.

General sequence

A general sequence has the following form:

expr0 ; [ expr1 | ... | exprn ]

The expressions expri are evaluated to vi, for i=0,...,n and all have to be tactics. The tactic v0 is applied and vi is applied to the i-th generated subgoal by the application of v0, for =1,...,n. It fails if the application of v0 does not generate exactly n subgoals.


Variants:

  1. If no tactic is given for the i-th generated subgoal, it behaves as if the tactic idtac were given. For instance, split ; [ | auto ] is a shortcut for split ; [ idtac | auto ].
  2. expr0 ; [ expr1 | ... | expri | .. | expri+1+j | ... | exprn ]

    In this variant, idtac is used for the subgoals numbered from i+1 to i+j (assuming n is the number of subgoals).

    Note that .. is part of the syntax, while ... is the meta-symbol used to describe a list of expr of arbitrary length.

  3. expr0 ; [ expr1 | ... | expri | expr .. | expri+1+j | ... | exprn ]

    In this variant, expr is used instead of idtac for the subgoals numbered from i+1 to i+j.

For loop

There is a for loop that repeats a tactic num times:

do num expr

expr is evaluated to v. v must be a tactic value. v is applied num times. Supposing 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:

repeat expr

expr is evaluated to v. If v denotes a tactic, this tactic is applied to the goal. If the application fails, 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. The tactic repeat expr itself never fails.

Error catching

We can catch the tactic errors with:

try expr

expr is evaluated to v. v must be a tactic value. v is applied. If the application of v fails, 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:

progress expr

expr is evaluated to v. v must be a tactic value. v is applied. If the application of v produced one subgoal equal to the initial goal (up to syntactical equality), then an error of level 0 is raised.


Error message: Failed to progress

Branching

We can easily branch with the following structure:

expr1 || expr2

expr1 and expr2 are evaluated to v1 and v2. v1 and v2 must be tactic values. v1 is applied and if it fails to progress then v2 is applied. Branching is left-associative.

First tactic to work

We may consider the first tactic to work (i.e. which does not fail) among a panel of tactics:

first [ expr1 | ... | exprn ]

expri are evaluated to vi and vi must be tactic values, for i=1,...,n. Supposing n>1, it applies v1, if it works, it stops else it tries to apply v2 and so on. It fails when there is no applicable tactic.


Error message: No applicable tactic

Solving

We may consider the first to solve (i.e. which generates no subgoal) among a panel of tactics:

solve [ expr1 | ... | exprn ]

expri are evaluated to vi and vi must be tactic values, for i=1,...,n. Supposing n>1, it applies v1, if it solves, it stops else it tries to apply v2 and so on. It fails if there is no solving tactic.


Error message: Cannot solve the goal

Identity

The constant idtac is the identity tactic: it leaves any goal unchanged but it appears in the proof script.


Variant: idtac message_token message_token

This prints the given tokens. Strings and integers are printed literally. If a term is given, it is printed, its variables being interpreted in the current environment. In particular, if a variable is given, its value is printed.

Failing

The tactic fail is the always-failing tactic: it does not solve any goal. It is useful for defining other tacticals since it can be catched by try or match goal.


Variants:

  1. fail n
    The number n is the failure level. If no level is specified, it defaults to 0. The level is used by try and match goal. If 0, it makes match goal considering the next clause (backtracking). If non zero, the current match goal block or try command is aborted and the level is decremented.
  2. fail message_token message_token
    The given tokens are used for printing the failure message.
  3. fail n message_token message_token
    This is a combination of the previous variants.


Error message: Tactic Failure message (level n).

Local definitions

Local definitions can be done as follows:

let ident1 := expr1
with ident2 := expr2
...
with identn := exprn in
expr

each expri is evaluated to vi, then, expr is evaluated by substituting vi to each occurrence of identi, for i=1,...,n. There is no dependencies between the expri and the identi.

Local definitions can be recursive by using let rec instead of 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.

Application

An application is an expression of the following form:

qualid tacarg1 ... tacargn

The reference qualid must be bound to some defined tactic definition expecting at least n arguments. The expressions expri are evaluated to vi, for i=1,...,n.

Function construction

A parameterized tactic can be built anonymously (without resorting to local definitions) with:

fun ident1 ... identn => expr

Indeed, local definitions of functions are a syntactic sugar for binding a fun tactic to an identifier.

Pattern matching on terms

We can carry out pattern matching on terms with:

match expr with
   cpattern1 => expr1
 | cpattern2 => expr2
 ...
 | cpatternn => exprn
 | _ => exprn+1
end

The expression expr is evaluated and should yield a term which is matched against cpattern1. 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 @?id that occur in head position of an application. For these variables, the matching is second-order and returns a functional term.

If the matching with cpattern1 succeeds, then expr1 is evaluated into some value by substituting the pattern matching instantiations to the metavariables. If expr1 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 let in), then this tactic is applied. If the tactic succeeds, the list of resulting subgoals is the result of the match expression. If expr1 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 expr1 is the result of the match expression.

If the matching with cpattern1 fails, or if it succeeds but the evaluation of expr1 fails, or if the evaluation of expr1 succeeds but returns a tactic in execution position whose execution fails, then cpattern2 is used and so on. The pattern _ matches any term and shunts all remaining patterns if any. If all clauses fail (in particular, there is no pattern _) then a no-matching-clause error is raised.


Error messages:

  1. No matching clauses for match

    No pattern can be used and, in particular, there is no _ pattern.

  2. Argument of match does not evaluate to a term

    This happens when expr does not denote a term.


Variants:

  1. There is a special form of patterns to match a subterm against the pattern:
    context ident [ cpattern ]
    It matches any term which one subterm matches cpattern. If there is a match, the optional ident is assign the “matched context”, that is the initial term where the matched subterm is replaced by a hole. The definition of context in expressions 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 Printing All, see Section 2.9).

    Coq < Ltac f x :=
    Coq <   match x with
    Coq <     context f [S ?X] => 
    Coq <     idtac X;                    (* To display the evaluation order *)
    Coq <     assert (p := refl_equal 1 : X=1);    (* To filter the case X=1 *)
    Coq <     let x:= context f[O] in assert (x=O) (* To observe the context *)
    Coq <   end.
    f is defined

    Coq < Goal True.
    1 subgoal
      
      ============================
       True

    Coq < f (3+4).
    2
    1
    2 subgoals
      
      p : 1 = 1
      ============================
       1 + 4 = 0
    subgoal 2 is:
     True
  2. Using lazymatch instead of match has an effect if the right-hand-side of a clause returns a tactic. With match, the tactic is applied to the current goal (and the next clause is tried if it fails). With lazymatch, the tactic is directly returned as the result of the whole lazymatch block without being first tried to be applied to the goal. Typically, if the lazymatch block is bound to some variable x in a let in, then tactic expression gets bound to the variable x.

Pattern matching on goals

We can make pattern matching on goals using the following expression:

match goal with
  | hyp1,1,...,hyp1,m1   |-cpattern1=> expr1
| hyp2,1,...,hyp2,m2   |-cpattern2=> expr2
  ...
| hypn,1,...,hypn,mn   |-cpatternn=> exprn
|_    => exprn+1
end

If each hypothesis pattern hyp1,i, with i=1,...,m1 is matched (non-linear first-order unification) by an hypothesis of the goal and if cpattern1 is matched by the conclusion of the goal, then expr1 is evaluated to v1 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 v1 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 exprn+1 is evaluated to vn+1 and vn+1 is applied. Note also that matching against subterms (using the context ident [ cpattern ]) is available and may itself induce extra backtrackings.


Error message: 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.


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. hypi,mi before hypi,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 match reverse goal with variant.


Variant: Using lazymatch instead of match has an effect if the right-hand-side of a clause returns a tactic. With match, the tactic is applied to the current goal (and the next clause is tried if it fails). With lazymatch, the tactic is directly returned as the result of the whole lazymatch block without being first tried to be applied to the goal. Typically, if the lazymatch block is bound to some variable x in a let in, then tactic expression gets bound to the variable x.

Coq < Ltac test_lazy :=
Coq <   lazymatch goal with
Coq <   | _ => idtac "here"; fail 
Coq <   | _ => idtac "wasn’t lazy"; trivial
Coq <   end.
test_lazy is defined

Coq < Ltac test_eager :=
Coq <   match goal with
Coq <   | _ => idtac "here"; fail 
Coq <   | _ => idtac "wasn’t lazy"; trivial
Coq <   end.
test_eager is defined

Coq < Goal True.
1 subgoal
  
  ============================
   True

Coq < test_lazy || idtac "was lazy".
here
was lazy
1 subgoal
  
  ============================
   True

Coq < test_eager || idtac "was lazy".
here
wasn’t lazy
Proof completed.

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:

context ident [ expr ]

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 ident by the value of expr.


Error message: 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:

fresh componentcomponent

It evaluates to an identifier unbound in the goal. This fresh identifier is obtained by concatenating the value of the component’s (each of them is, either an ident which has to refer to a name, or directly a name denoted by a string). 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:

eval redexpr in term

where redexpr is a reduction tactic among red, hnf, compute, simpl, cbv, lazy, unfold, fold, pattern.

Type-checking a term

The following returns the type of term:

type of term

Accessing tactic decomposition

Tactical “info expr” is not really a tactical. For elementary tactics, this is equivalent to expr. For complex tactic like auto, it displays the operations performed by the tactic.

Proving a subgoal as a separate lemma

From the outside “abstract expr” is the same as 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.

This tactical is useful with tactics such as omega or 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.


Variants:

  1. abstract expr using ident.
    Give explicitly the name of the auxiliary lemma.


Error message: Proof is not complete

Calling an external tactic

The tactic external allows to run an executable outside the Coq executable. The communication is done via an XML encoding of constructions. The syntax of the command is

external "command" "request" tacargtacarg

The string command, to be interpreted in the default execution path of the operating system, is the name of the external command. The string request is the name of a request to be sent to the external command. Finally the list of tactic arguments have to evaluate to terms. An XML tree of the following form is sent to the standard input of the external command.

<REQUEST req="request">
the XML tree of the first argument
the XML tree of the last argument
</REQUEST>


Conversely, the external command must send on its standard output an XML tree of the following forms:


<TERM>
the XML tree of a term
</TERM>


or


<CALL uri="ltac_qualified_ident">
the XML tree of a first argument
the XML tree of a last argument
</CALL>


where ltac_qualified_ident is the name of a defined Ltac function and each subsequent XML tree is recursively a CALL or a TERM node.

The Document Type Definition (DTD) for terms of the Calculus of Inductive Constructions is the one developed as part of the MoWGLI European project. It can be found in the file dev/doc/cic.dtd of the Coq source archive.

An example of parser for this DTD, written in the Objective Caml - Camlp4 language, can be found in the file parsing/g_xml.ml4 of the Coq source archive.

9.3  Tactic toplevel definitions

9.3.1  Defining Ltac functions

Basically, Ltac toplevel definitions are made as follows:

Ltac ident ident1 ... identn := expr

This defines a new Ltac function that can be used in any tactic script or new Ltac toplevel definition.


Remark: The preceding definition can equivalently be written:

Ltac ident := fun ident1 ... identn => expr

Recursive and mutual recursive function definitions are also possible with the syntax:

Ltac ident1 ident1,1 ... ident1,m1  := expr1
with ident2 ident2,1 ... ident2,m2  := expr2
...
with identn identn,1 ... identn,mn  := exprn


It is also possible to redefine an existing user-defined tactic using the syntax:

Ltac qualid ident1 ... identn ::= expr

A previous definition of qualidmust exist in the environment. The new definition will always be used instead of the old one and it goes accross module boundaries.

9.3.2  Printing Ltac tactics

Defined Ltac functions can be displayed using the command

Print Ltac qualid.

9.4  Debugging Ltac tactics

The Ltac interpreter comes with a step-by-step debugger. The debugger can be activated using the command

Set Ltac Debug.

and deactivated using the command

Unset Ltac Debug.

To know if the debugger is on, use the command Test Ltac Debug. 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
rn:advance n steps further