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 [Del00]. Chapter Detailed examples of tactics is devoted to giving examples of use of this language on small but also with non-trivial problems.
Syntax¶
The syntax of the tactic language is given below. See Chapter
The Gallina specification language 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 terms and patterns and all the atomic
tactics described in Chapter Tactics. 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 below.
Note
- The infix tacticals “… || …”, “… + …”, and “… ; …” are associative. 
- In - tacarg, there is an overlap between qualid as a direct tactic argument and- qualidas 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).
- 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 - try repeat tac1 || tac2; tac3; [tac31 | ... | tac3n]; tac4.
- Toplevel input, characters 0-3: > try repeat tac1 || tac2; tac3; [tac31 | ... > ^^^ Error: Syntax error: illegal begin of vernac. Toplevel input, characters 44-45: > try repeat tac1 || tac2; tac3; [tac31 | ... | tac3n]; tac4. > ^ Error: Syntax error: illegal begin of vernac.
 - is understood as - try (repeat (tac1 || tac2)); ((tac3; [tac31 | ... | tac3n]); tac4).
- Toplevel input, characters 0-3: > try (repeat (tac1 || tac2)); ((tac3; [tac31 | ... > ^^^ Error: Syntax error: illegal begin of vernac. Toplevel input, characters 52-53: > try (repeat (tac1 || tac2)); ((tac3; [tac31 | ... | tac3n]); tac4). > ^ Error: Syntax error: illegal begin of vernac.
 
expr ::=expr;expr| [>expr| ... |expr] |expr; [expr| ... |expr] |tacexpr3tacexpr3 ::= do (natural|ident) tacexpr3 | progresstacexpr3| repeattacexpr3| trytacexpr3| oncetacexpr3| exactly_oncetacexpr3| timeout (natural|ident)tacexpr3| time [string]tacexpr3| onlyselector:tacexpr3|tacexpr2tacexpr2 ::=tacexpr1||tacexpr3|tacexpr1+tacexpr3| tryiftacexpr1thentacexpr1elsetacexpr1|tacexpr1tacexpr1 ::= funname...name=>atom| let [rec]let_clausewith ... withlet_clauseinatom| match goal withcontext_rule| ... |context_ruleend | match reverse goal withcontext_rule| ... |context_ruleend | matchexprwithmatch_rule| ... |match_ruleend | lazymatch goal withcontext_rule| ... |context_ruleend | lazymatch reverse goal withcontext_rule| ... |context_ruleend | lazymatchexprwithmatch_rule| ... |match_ruleend | multimatch goal withcontext_rule| ... |context_ruleend | multimatch reverse goal withcontext_rule| ... |context_ruleend | multimatchexprwithmatch_rule| ... |match_ruleend | abstractatom| abstractatomusingident| first [expr| ... |expr] | solve [expr| ... |expr] | idtac [message_token...message_token] | fail [natural] [message_token...message_token] | fresh | freshstring| freshqualid| contextident[term] | evalredexprinterm| type ofterm| constr :term| uconstr :term| type_termterm| numgoals | guardtest| assert_failstacexpr3| assert_suceedstacexpr3|atomic_tactic|qualidtacarg...tacarg|atomatom ::=qualid| () |integer| (expr) message_token ::=string|ident|integertacarg ::=qualid| () | ltac :atom|termlet_clause ::=ident[name...name] :=exprcontext_rule ::=context_hyp, ...,context_hyp|-cpattern=>expr|cpattern=>expr| |-cpattern=>expr| _ =>exprcontext_hyp ::=name:cpattern|name:=cpattern[:cpattern] match_rule ::=cpattern=>expr| context [ident] [cpattern] =>expr| _ =>exprtest ::=integer=integer|integer(< | <= | > | >=)integerselector ::= [ident] |integer(integer|integer-integer), ..., (integer|integer-integer) toplevel_selector ::=selector|all|par
top ::= [Local] Ltacltac_defwith ... withltac_defltac_def ::=ident[ident...ident] :=expr|qualid[ident...ident] ::=expr
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:
- 
expr ; expr¶
- The expression - expr1is evaluated to- v1, which must be a tactic value. The tactic- v1is applied to the current goal, possibly producing more goals. Then- expr2is evaluated to produce- v2, which must be a tactic value. The tactic- v2is 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:
- 
[> expr*|]¶
- The expressions - expriare evaluated to- vi, for i=0,...,n and all have to be tactics. The- viis 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 ].- 
Variant [> expr*| | expr .. | expr*|]
- In this variant, token:expr is used for each goal coming after those covered by the first list of - exprbut before those coevered by the last list of- expr.
 - 
Variant [> expr*| | .. | expr*|]
- In this variant, idtac is used for the goals not covered by the two lists of - expr.
 - 
Variant [> expr .. ]
- In this variant, the tactic - expris 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.
 - 
Variant expr ; [expr*|]
- This variant of local tactic application is paired with a sequence. In this variant, there must be as many - exprin the list as goals generated by the application of the first- exprto each of the individual goals independently. All the above variants work in this form too. Formally,- expr ; [ ... ]is equivalent to- [> expr ; [> ... ] .. ].
 
- 
Variant 
Goal selectors¶
We can restrict the application of a tactic to a subset of the currently focused goals with:
- 
toplevel_selector : expr¶
- We can also use selectors as a tactical, which allows to use them nested in a tactic expression, by using the keyword - only:- 
Variant only selector : expr¶
- When selecting several goals, the tactic expr is applied globally to all selected goals. 
 - 
Variant [ident] : expr
- In this variant, - expris applied locally to a goal previously named by the user (see Existential variables).
 - 
Variant num-num+, : expr
- In this variant, - expris applied globally to the subset of goals described by the given ranges. You can write a single- nas a shortcut for- n-nwhen specifying multiple ranges.
 - 
Variant all: expr¶
- In this variant, - expris applied to all focused goals.- all:can only be used at the toplevel of a tactic expression.
 - 
Variant par: expr¶
- In this variant, - expris applied to all focused goals in parallel. The number of workers can be controlled via the command line option- -async-proofs-tac-jtaking as argument the desired number of workers. Limitations:- par:only works on goals containing no existential variables and- exprmust 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.
 - 
Error No such goal.¶
 
- 
Variant 
For loop¶
There is a for loop that repeats a tactic num times:
- 
do num expr¶
- expris evaluated to- vwhich must be a tactic value. This tactic value- vis applied- numtimes. Supposing- num> 1, after the first application of- v,- vis applied, at least once, to the generated subgoals and so on. It fails if the application of- vfails before the num applications have been completed.
Repeat loop¶
We have a repeat loop with:
- 
repeat expr¶
- expris evaluated to- v. If- vdenotes 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- repeat expritself never fails.
Error catching¶
We can catch the tactic errors with:
- 
try expr¶
- expris evaluated to- vwhich must be a tactic value. The tactic value- vis applied to each focused goal independently. If the application of- vfails 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:
- 
progress expr¶
- expris evaluated to v which must be a tactic value. The tactic value- vis applied to each focued subgoal independently. If the application of- vto one of the focused subgoal produced subgoals equal to the initial goals (up to syntactical equality), then an error of level 0 is raised.- 
Error Failed to progress.¶
 
- 
Error 
Backtracking branching¶
We can branch with the following structure:
- 
expr1 + expr2¶
- expr1and- expr2are evaluated respectively to- v1and- v2which must be tactic values. The tactic value- v1is applied to each focused goal independently and if it fails or a later tactic fails, then the proof backtracks to the current goal and- v2is applied.- Tactics can be seen as having several successes. When a tactic fails it asks for more successes of the prior tactics. - expr1 + expr2has all the successes of- v1followed by all the successes of- v2. Algebraically,- (expr1 + expr2); expr3 = (expr1; expr3) + (expr2; expr3).- 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:
- 
first [expr*|]¶
- The - expriare evaluated to- viand- vimust be tactic values, for i=1,...,n. Supposing n>1, it applies, in each focused goal independently,- v1, if it works, it stops otherwise it tries to apply- v2and so on. It fails when there is no applicable tactic. In other words,- first [:expr1 | ... | exprn]behaves, in each goal, as the the first- vito have at least one success.- 
Error No applicable tactic.¶
 - 
Variant 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 - Tactic Notation "foo" tactic_list(tacs) := first tacs.
 
 
- 
Error 
Left-biased branching¶
Yet another way of branching without backtracking is the following structure:
- 
expr1 || expr2¶
- expr1and- expr2are evaluated respectively to- v1and- v2which must be tactic values. The tactic value- v1is applied in each subgoal independently and if it fails to progress then- v2is applied.- expr1 || expr2is equivalent to- first [ progress expr1 | expr2 ](except that if it fails, it fails like- v2). Branching is left-associative.
Generalized biased branching¶
The tactic
- 
tryif expr1 then expr2 else expr3¶
- is a generalization of the biased-branching tactics above. The expression - expr1is evaluated to- v1, which is then applied to each subgoal independently. For each goal where- v1succeeds at least once,- expr2is evaluated to- v2which is then applied collectively to the generated subgoals. The- v2tactic can trigger backtracking points in- v1: where- v1succeeds at least once,- tryif expr1 then expr2 else expr3is equivalent to- v1; v2. In each of the goals where- v1does not succeed at least once,- expr3is evaluated in- v3which 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:
Checking the successes¶
Coq provides an experimental way to check that a tactic has exactly one success:
- 
exactly_once expr¶
- expris evaluated to- vwhich must be a tactic value. The tactic value- vis applied if it has at most one success. If- vfails,- exactly_once exprfails like- v. If- vhas a exactly one success,- exactly_once exprsucceeds like- v. If- vhas two or more successes, exactly_once expr fails.- Warning - The experimental status of this tactic pertains to the fact if - vperforms side effects, they may occur in a unpredictable way. Indeed, normally- vwould 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.- 
Error This tactic has more than one success.¶
 
- 
Error 
Checking the failure¶
Coq provides a derived tactic to check that a tactic fails:
Checking the success¶
Coq provides a derived tactic to check that a tactic has at least one success:
Solving¶
We may consider the first to solve (i.e. which generates no subgoal) among a panel of tactics:
- 
solve [expr*|]¶
- The - expriare evaluated to- viand- vimust be tactic values, for i=1,...,n. Supposing n>1, it applies- v1to each goal independently, if it doesn’t solve the goal then it tries to apply- v2and so on. It fails if there is no solving tactic.- 
Error Cannot solve the goal.¶
 - 
Variant solve expr
- This is an Ltac alias that gives a primitive access to the - solve:tactical. See the- firsttactical for more information.
 
- 
Error 
Identity¶
The constant idtac is the identity tactic: it leaves any goal unchanged but
it appears in the proof script.
- 
idtac message_token*¶
- This prints the given tokens. Strings and integers are printed literally. If a (term) variable is given, its contents are printed. 
Failing¶
- 
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 - try,- repeat,- match goal, or the branching tacticals. The- failtactic will, however, succeed if all the goals have already been solved.- 
Variant fail num
- The number is the failure level. If no level is specified, it defaults to 0. The level is used by - try,- repeat,- match goaland the branching tacticals. If 0, it makes- match goalconsidering the next clause (backtracking). If non zero, the current- match goalblock,- try,- repeat, or branching command is aborted and the level is decremented. In the case of- +, a non-zero level skips the first backtrack point, even if the call to- fail numis not enclosed in a- +command, respecting the algebraic identity.
 - 
Variant fail message_token*
- The given tokens are used for printing the failure message. 
 - 
Variant fail num message_token*
- This is a combination of the previous variants. 
 - 
Variant gfail¶
- This variant fails even if there are no goals left. 
 - 
Variant gfail message_token*
 - 
Variant gfail num 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 - let x:=H in fail 0 xwill succeed.
 
- 
Variant 
Timeout¶
We can force a tactic to stop if it has not finished after a certain amount of time:
- 
timeout num expr¶
- expris evaluated to- vwhich must be a tactic value. The tactic value- vis applied normally, except that it is interrupted after- numseconds 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:
- 
time string expr¶
- evaluates - exprand 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- stringargument 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
- 
time_constr expr¶
- which evaluates - 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 - and - which (re)set and display an optionally named timer, respectively. The parenthesized string argument to - finish_timingis also optional, and determines the label associated with the timer for printing.- By copying the definition of - time_constrfrom the standard library, users can achive support for a fixed pattern of nesting by passing different- stringparameters to- restart_timerand- finish_timingat each level of nesting.- Example - 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.
- time_constr1 is defined
- Goal True.
- 1 subgoal ============================ 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.
- Tactic evaluation (depth 1) ran for 0. secs (0.u,0.s) Tactic evaluation (depth 1) ran for 0. secs (0.u,0.s) Tactic evaluation ran for 0.001 secs (0.001u,0.s) 1 subgoal n := 100 : nat ============================ True
- Abort.
 
Local definitions¶
Local definitions can be done as follows:
- 
let ident1 := expr1 with identi := expri* in expr
- each - expriis evaluated to- vi, then,- expris evaluated by substituting- vito each occurrence of- identi, for i=1,...,n. There is no dependencies between the- expriand the- identi.- Local definitions can be recursive by using - let recinstead 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:
Function construction¶
A parameterized tactic can be built anonymously (without resorting to local definitions) with:
Pattern matching on terms¶
We can carry out pattern matching on terms with:
- 
match expr with cpatterni => expri+| end
- The expression - expris 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- @?idthat 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 - ?idoccurs under binders, say- x1, …, xnand the expression matches, the metavariable is instantiated by a term which can then be used in any context which also binds the variables- x1, …, xnwith same types. This provides with a primitive form of matching under context which does not require manipulating a functional term.- If the matching with - cpattern1succeeds, then- expr1is evaluated into some value by substituting the pattern matching instantiations to the metavariables. If- expr1evaluates 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- expr1does 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- expr1is the result of the match expression.- If the matching with - cpattern1fails, or if it succeeds but the evaluation of- expr1fails, or if the evaluation of- expr1succeeds but returns a tactic in execution position whose execution fails, then- cpattern2is 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.- 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. - 
Error No matching clauses for match.¶
- No pattern can be used and, in particular, there is no - _pattern.
 - 
Error Argument of match does not evaluate to a term.¶
- This happens when - exprdoes not denote a term.
 - 
Variant multimatch expr with cpatterni => expri+| 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 - match …is, in fact, a shorthand for- once multimatch ….
 - 
Variant lazymatch expr with cpatterni => expri+| 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. 
 - 
Variant context ident [cpattern]
- This special form of patterns matches any term with a subterm matching cpattern. If there is a match, the optional - identis 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 - Printing All).
 - Example - Ltac f x := match x with context f [S ?X] => idtac X; assert (p := eq_refl 1 : X=1); let x:= context f[O] in assert (x=O) end.
- f is defined
- Goal True.
- 1 subgoal ============================ True
- f (3+4).
- 2 1 2 subgoals p : 1 = 1 ============================ 1 + 4 = 0 subgoal 2 is: True
 
- 
Error 
Pattern matching on goals¶
We can make pattern matching on goals using the following expression:
- 
match goal with hyp+ |- cpattern => expr+| | _ => expr 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- cpattern_1is matched by the conclusion of the goal, then- expr1is evaluated to- v1by substituting the pattern matching to the metavariables and the real hypothesis names bound to the possible hypothesis names occurring in the hypothesis patterns. If- v1is 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- expris evaluated to- vand- vis applied. Note also that matching against subterms (using the- 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. - 
Error 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. 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 withvariant.- 
Variant multimatch goal with hyp+ |- cpattern => expr+| | _ => expr end
- Using - multimatchinstead of- matchwill 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 - match [reverse] goal …is, in fact, a shorthand for- once multimatch [reverse] goal ….
 - 
Variant 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. 
 
- 
Error 
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:
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 component*
- 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 a :n:`qualidwhich has to refer to a (unqualified) 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:
Manipulating untyped terms¶
- 
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 - uconstr : termsyntax.
- 
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 uconstr : can also be used as arguments to the
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¶
- 
numgoals
- The number of goals under focus can be recovered using the - numgoalsfunction. Combined with the guard command below, it can be used to branch over the number of goals produced by previous tactics.- Example - Ltac pr_numgoals := let n := numgoals in idtac "There are" n "goals".
- pr_numgoals is defined
- Goal True /\ True /\ True.
- pr_numgoals is defined 1 subgoal ============================ True /\ True /\ True
- split;[|split].
- 3 subgoals ============================ True subgoal 2 is: True subgoal 3 is: True
 - all:pr_numgoals.
- There are 3 goals
 
Testing boolean expressions¶
- 
guard test¶
- The - guardtactic 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 - Goal True /\ True /\ True.
- 1 subgoal ============================ True /\ True /\ True
- split;[|split].
- 3 subgoals ============================ True subgoal 2 is: True subgoal 3 is: True
 - all:let n:= numgoals in guard n<4.
- Fail all:let n:= numgoals in guard n=2.
- The command has indeed failed with message: Ltac call to "guard (test)" failed. Condition not satisfied: 3=2
 - 
Error Condition not satisfied.¶
 
Proving a subgoal as a separate lemma¶
- 
abstract expr¶
- From the outside, - abstract expris the same as- solve expr. Internally it saves an auxiliary lemma called- ident_subproofnwhere- identis the name of the current goal and- nis 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 - omegaor- discriminatethat 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. - 
Variant 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. 
 - 
Variant transparent_abstract expr¶
- 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. 
 - 
Variant 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. 
 - 
Error Proof is not complete.¶
 
- 
Variant 
Tactic toplevel definitions¶
Defining Ltac functions¶
Basically, Ltac toplevel definitions are made as follows:
- 
Command Ltac ident ident* := expr¶
- This defines a new Ltac function that can be used in any tactic script or new Ltac toplevel definition. - Recursive and mutual recursive function definitions are also possible with the syntax: - 
Variant Ltac ident ident* with ident ident** := expr
- It is also possible to redefine an existing user-defined tactic using the syntax: 
 - 
Variant 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. 
- 
Variant 
Debugging Ltac tactics¶
Info trace¶
- 
Command 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 - Infocommand can be used with the following syntax.- The number - numis 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 - Ltac t x := exists x; reflexivity.
- t is defined
- Goal exists n, n=0.
- 1 subgoal ============================ exists n : nat, n = 0
 - Info 0 t 1||t 0.
- t <constr:(0)> No more subgoals.
 - Undo.
- 1 subgoal ============================ exists n : nat, n = 0
 - Info 1 t 1||t 0.
- exists with 0;reflexivity No more subgoals.
 - The trace produced by - Infotries 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 - Infocontains (in comments) the messages produced by the- idtactactical at the right position in the script. In particular, the calls to idtac in branches which failed are not printed.
Interactive debugger¶
- 
Option 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:
- 
Option 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.
- 
Option Ltac Profiling¶
- This option enables and disables the profiler. 
- 
Command Show Ltac Profile¶
- Prints the profile 
- 
Command Reset Ltac Profile¶
- Resets the profile, that is, deletes all accumulated information. - Warning - Backtracking across a - Reset Ltac Profilewill not restore the information.
- Require Import Coq.omega.Omega.
- [Loading ML file z_syntax_plugin.cmxs ... done] [Loading ML file quote_plugin.cmxs ... done] [Loading ML file newring_plugin.cmxs ... done] [Loading ML file omega_plugin.cmxs ... done]
- Ltac mytauto := tauto.
- mytauto is defined
- Ltac tac := intros; repeat split; omega || mytauto.
- tac is defined
- 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).
- 1 subgoal ============================ forall (x y z : nat) (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 : Prop), x + (y + (z - y) - x) = x + (y - x) + (z - (x + (y - x))) /\ x + (y + (z - y) - x) = x + (y - x) + (z - (x + (y - x))) /\ (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.
- Set Ltac Profiling.
- tac.
- No more subgoals.
- Show Ltac Profile.
- total time: 7.284s tactic local total calls max ────────────────────────────────────────┴──────┴──────┴───────┴─────────┘ ─tac ----------------------------------- 0.1% 100.0% 1 7.284s ─<Coq.Init.Tauto.with_uniform_flags> --- 0.0% 76.4% 26 0.264s ─<Coq.Init.Tauto.tauto_gen> ------------ 0.0% 76.4% 26 0.264s ─<Coq.Init.Tauto.tauto_intuitionistic> - 0.1% 76.3% 26 0.264s ─t_tauto_intuit ------------------------ 0.1% 76.2% 26 0.264s ─<Coq.Init.Tauto.simplif> -------------- 49.4% 73.4% 26 0.255s ─omega --------------------------------- 23.2% 23.2% 28 0.732s ─<Coq.Init.Tauto.is_conj> -------------- 15.2% 15.2% 28756 0.050s ─elim id ------------------------------- 5.3% 5.3% 650 0.052s ─<Coq.Init.Tauto.axioms> --------------- 2.0% 2.7% 0 0.008s tactic local total calls max ────────────────────────────────────────┴──────┴──────┴───────┴─────────┘ ─tac ----------------------------------- 0.1% 100.0% 1 7.284s ├─<Coq.Init.Tauto.with_uniform_flags> - 0.0% 76.4% 26 0.264s │└<Coq.Init.Tauto.tauto_gen> ---------- 0.0% 76.4% 26 0.264s │└<Coq.Init.Tauto.tauto_intuitionistic> 0.1% 76.3% 26 0.264s │└t_tauto_intuit ---------------------- 0.1% 76.2% 26 0.264s │ ├─<Coq.Init.Tauto.simplif> ---------- 49.4% 73.4% 26 0.255s │ │ ├─<Coq.Init.Tauto.is_conj> -------- 15.2% 15.2% 28756 0.050s │ │ └─elim id ------------------------- 5.3% 5.3% 650 0.052s │ └─<Coq.Init.Tauto.axioms> ----------- 2.0% 2.7% 0 0.008s └─omega ------------------------------- 23.2% 23.2% 28 0.732s
- Show Ltac Profile "omega".
- total time: 7.284s tactic local total calls max ────────────────────────────────────────┴──────┴──────┴───────┴─────────┘ ─omega --------------------------------- 23.2% 23.2% 28 0.732s tactic local total calls max
- Abort.
- Unset Ltac Profiling.
- 
stop ltac profiling¶
- Similarly to - start ltac profiling, this tactic behaves like- idtac. Together, they allow you to exclude parts of a proof script from profiling.
- 
reset ltac profile¶
- This tactic behaves like the corresponding vernacular command and allow displaying and resetting the profile from tactic scripts for benchmarking purposes. 
- 
show ltac profile¶
- This tactic behaves like the corresponding vernacular command and allow displaying and resetting the profile from tactic scripts for benchmarking purposes. 
- 
show ltac profile string
- 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
turns the Ltac Profiling option on at the beginning of each document,
and performs 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¶
- 
optimize_heap¶
This tactic behaves like idtac, except that running it compacts the
heap in the OCaml run-time system. It is analogous to the Vernacular
command Optimize Heap.