1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
|
.. _ltac:
Ltac
====
This chapter documents the tactic language |Ltac|.
We start by giving the syntax, and next, we present the informal
semantics. To learn more about the language and
especially about its foundations, please refer to :cite:`Del00`.
.. example:: Basic tactic macros
Here are some examples of simple tactic macros that the
language lets you write.
.. coqdoc::
Ltac reduce_and_try_to_solve := simpl; intros; auto.
Ltac destruct_bool_and_rewrite b H1 H2 :=
destruct b; [ rewrite H1; eauto | rewrite H2; eauto ].
See Section :ref:`ltac-examples` for more advanced examples.
.. _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:`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 :production:`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 :n:`?@ident`. The
notation :g:`_` can also be used to denote metavariable whose instance is
irrelevant. In the notation :n:`?@ident`, 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 metavariables 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 :n:`%@?@ident @ident__1 … @ident__n`,
the variable :token:`ident` matches any complex expression with (possible)
dependencies in the variables :n:`@ident__i` and returns a functional term
of the form :n:`fun @ident__1 … ident__n => @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.
.. example::
If you want that :n:`@tactic__2; @tactic__3` be fully run on the first
subgoal generated by :n:`@tactic__1`, before running on the other
subgoals, then you should not write
:n:`@tactic__1; (@tactic__2; @tactic__3)` but rather
:n:`@tactic__1; [> @tactic__2; @tactic__3 .. ]`.
- In :token:`tacarg`, there is an overlap between :token:`qualid` as a
direct tactic argument and :token:`qualid` as a particular case of
:token:`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 :n:`ltac:(@qualid)`. To force the resolution as a reference to a
term, use the syntax :n:`(@qualid)`.
- As shown by the figure, tactical ``… || …`` binds more than the prefix
tacticals :tacn:`try`, :tacn:`repeat`, :tacn:`do` and :tacn:`abstract`
which themselves bind more than the postfix tactical ``… ;[ … ]``
which binds at the same level as ``… ; …`` .
.. example::
:n:`try repeat @tactic__1 || @tactic__2; @tactic__3; [ {+| @tactic } ]; @tactic__4`
is understood as:
:n:`((try (repeat (@tactic__1 || @tactic__2)); @tactic__3); [ {+| @tactic } ]); @tactic__4`
.. 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`]
: gfail [`natural`] [`message_token` ... `message_token`]
: fresh [ `component` … `component` ]
: context `ident` [`term`]
: eval `redexpr` in `term`
: type of `term`
: constr : `term`
: uconstr : `term`
: type_term `term`
: numgoals
: guard `test`
: assert_fails `tacexpr3`
: assert_succeeds `tacexpr3`
: `tactic`
: `qualid` `tacarg` ... `tacarg`
: `atom`
atom : `qualid`
: ()
: `integer`
: ( `expr` )
component : `string` | `qualid`
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. Intermediate
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__1 ; @expr__2
:name: ltac-seq
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 = 1, ..., n and all have to be tactics. The :n:`v__i` is applied to the
i-th goal, for i = 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__i} | @expr .. | {*| @expr__j}]
In this variant, :n:`@expr` is used for each goal coming after those
covered by the list of :n:`@expr__i` but before those covered by the
list of :n:`@expr__j`.
.. 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 goals, 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__0 ; [{*| @expr__i}]
This variant of local tactic application is paired with a sequence. In this
variant, there must be as many :n:`@expr__i` as goals generated
by the application of :n:`@expr__0` 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
:name: only ... : ...
When selecting several goals, the tactic :token:`expr` is applied globally to all
selected goals.
.. tacv:: [@ident] : @expr
In this variant, :token:`expr` is applied locally to a goal previously named
by the user (see :ref:`existential-variables`).
.. tacv:: @num : @expr
In this variant, :token:`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
:name: all: ...
In this variant, :token:`expr` is applied to all focused goals. ``all:`` can only
be used at the toplevel of a tactic expression.
.. tacv:: !: @expr
In this variant, if exactly one goal is focused, :token:`expr` is
applied to it. Otherwise the tactic fails. ``!:`` can only be
used at the toplevel of a tactic expression.
.. tacv:: par: @expr
:name: par: ...
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)
:undocumented:
.. 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.
:undocumented:
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,
:n:`first [@expr__1 | ... | @expr__n]` applies :n:`v__1` in each
focused goal independently and stops if it succeeds; 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 first
:n:`v__i` to have *at least* one success.
.. exn:: No applicable tactic.
:undocumented:
.. tacv:: first @expr
This is an |Ltac| alias that gives a primitive access to the first
tactical as an |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 at 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 an 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.
:undocumented:
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_succeeds
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,
:n:`solve [@expr__1 | ... | @expr__n]` applies :n:`v__1` to
each goal independently and stops if it succeeds; otherwise it tries to
apply :n:`v__2` and so on. It fails if there is no solving tactic.
.. exn:: Cannot solve the goal.
:undocumented:
.. 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.
.. tacv:: fail @num
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` consider the next clause
(backtracking). If nonzero, 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 nonzero level skips the first backtrack point, even if
the call to :n:`fail @num` 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 @num {* @message_token}
This is a combination of the previous variants.
.. tacv:: gfail
:name: gfail
This variant fails even when used after :n:`;` and there are no goals left.
Similarly, ``gfail`` fails even when used after ``all:`` and there are no
goals left. See the example for clarification.
.. tacv:: gfail {* @message_token}
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 :n:`let x := H in fail 0 x` will succeed.
.. exn:: Tactic Failure message (level @num).
:undocumented:
.. exn:: No such goal.
:name: No such goal. (fail)
:undocumented:
.. example::
.. coqtop:: all fail
Goal True.
Proof. fail. Abort.
Goal True.
Proof. trivial; fail. Qed.
Goal True.
Proof. trivial. fail. Abort.
Goal True.
Proof. trivial. all: fail. Qed.
Goal True.
Proof. gfail. Abort.
Goal True.
Proof. trivial; gfail. Abort.
Goal True.
Proof. trivial. gfail. Abort.
Goal True.
Proof. trivial. all: gfail. Abort.
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 debugging 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 running time of the tactic expression, whether it
fails or succeeds. In case of several successes, the time for each successive
run 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 following internal tactics:
.. tacn:: restart_timer @string
:name: restart_timer
Reset a timer
.. tacn:: finish_timing {? (@string)} @string
:name: finish_timing
Display an optionally named timer. The parenthesized string argument
is also optional, and determines the label associated with the timer
for printing.
By copying the definition of :tacn:`time_constr` from the standard library,
users can achieve support for a fixed pattern of nesting by passing
different :token:`string` parameters to :tacn:`restart_timer` and
:tacn:`finish_timing` at each level of nesting.
.. example::
.. coqtop:: all abort
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.
Local definitions
~~~~~~~~~~~~~~~~~
Local definitions can be done as follows:
.. tacn:: let @ident__1 := @expr__1 {* with @ident__i := @expr__i} in @expr
:name: let ... := ...
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 are no dependencies between the :n:`@expr__i` and the
:n:`@ident__i`.
Local definitions can be made 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 shadows 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
:flag:`Printing All`).
.. example::
.. coqtop:: all abort
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 perform pattern matching on goals using the following expression:
.. we should provide the full grammar here
.. tacn:: match goal with {+| {+, @context_hyp} |- @cpattern => @expr } | _ => @expr end
:name: match goal
If each hypothesis pattern :n:`hyp`\ :sub:`1,i`, with i = 1, ..., m\ :sub:`1` is
matched (non-linear first-order unification) by a 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 right to left
(i.e. hyp\ :sub:`i,m`\ :sub:`i`` before hyp\ :sub:`i,1`). For each
hypothesis pattern, the goal hypotheses are matched in order (newest
first), but it possible to reverse this order (oldest first)
with the :n:`match reverse goal with` variant.
.. tacv:: multimatch goal with {+| {+, @context_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 {+| {+, @context_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.
:undocumented:
.. exn:: Unbound context identifier @ident.
:undocumented:
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`).
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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. tacn:: type of @term
This tactic returns the type of :token:`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 abort
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.
:undocumented:
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.
.. warning::
The abstract tactic, while very useful, still has some known
limitations, see https://github.com/coq/coq/issues/9146 for more
details. Thus we recommend using it caution in some
"non-standard" contexts. In particular, ``abstract`` won't
properly work when used inside quotations ``ltac:(...)``, or
if used as part of typeclass resolution, it may produce wrong
terms when in universe polymorphic mode.
.. 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)
:undocumented:
Tactic toplevel definitions
---------------------------
Defining |Ltac| functions
~~~~~~~~~~~~~~~~~~~~~~~~~
Basically, |Ltac| toplevel definitions are made as follows:
.. cmd:: {? Local} Ltac @ident {* @ident} := @expr
:name: Ltac
This defines a new |Ltac| function that can be used in any tactic
script or new |Ltac| toplevel definition.
If preceded by the keyword ``Local``, the tactic definition will not be
exported outside the current module.
.. note::
The preceding definition can equivalently be written:
:n:`Ltac @ident := fun {+ @ident} => @expr`
.. cmdv:: Ltac @ident {* @ident} {* with @ident {* @ident}} := @expr
This syntax allows recursive and mutual recursive function definitions.
.. cmdv:: Ltac @qualid {* @ident} ::= @expr
This syntax *redefines* an existing user-defined tactic.
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.
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.
.. _ltac-examples:
Examples of using |Ltac|
-------------------------
Proof that the natural numbers have at least two elements
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. example:: Proof that the natural numbers have at least two elements
The first example shows how to use pattern matching over the proof
context to prove that natural numbers have at least two
elements. This can be done as follows:
.. coqtop:: reset all
Lemma card_nat :
~ exists x y : nat, forall z:nat, x = z \/ y = z.
Proof.
intros (x & y & Hz).
destruct (Hz 0), (Hz 1), (Hz 2).
At this point, the :tacn:`congruence` tactic would finish the job:
.. coqtop:: all abort
all: congruence.
But for the purpose of the example, let's craft our own custom
tactic to solve this:
.. coqtop:: none
Lemma card_nat :
~ exists x y : nat, forall z:nat, x = z \/ y = z.
Proof.
intros (x & y & Hz).
destruct (Hz 0), (Hz 1), (Hz 2).
.. coqtop:: all abort
all: match goal with
| _ : ?a = ?b, _ : ?a = ?c |- _ => assert (b = c) by now transitivity a
end.
all: discriminate.
Notice that all the (very similar) cases coming from the three
eliminations (with three distinct natural numbers) are successfully
solved by a ``match goal`` structure and, in particular, with only one
pattern (use of non-linear matching).
Proving that a list is a permutation of a second list
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. example:: Proving that a list is a permutation of a second list
Let's first define the permutation predicate:
.. coqtop:: in reset
Section Sort.
Variable A : Set.
Inductive perm : list A -> list A -> Prop :=
| perm_refl : forall l, perm l l
| perm_cons : forall a l0 l1, perm l0 l1 -> perm (a :: l0) (a :: l1)
| perm_append : forall a l, perm (a :: l) (l ++ a :: nil)
| perm_trans : forall l0 l1 l2, perm l0 l1 -> perm l1 l2 -> perm l0 l2.
End Sort.
.. coqtop:: none
Require Import List.
Next we define an auxiliary tactic :g:`perm_aux` which takes an
argument used to control the recursion depth. This tactic works as
follows: If the lists are identical (i.e. convertible), it
completes the proof. Otherwise, if the lists have identical heads,
it looks at their tails. Finally, if the lists have different
heads, it rotates the first list by putting its head at the end.
Every time we perform a rotation, we decrement :g:`n`. When :g:`n`
drops down to :g:`1`, we stop performing rotations and we fail.
The idea is to give the length of the list as the initial value of
:g:`n`. This way of counting the number of rotations will avoid
going back to a head that had been considered before.
From Section :ref:`ltac-syntax` we know that Ltac has a primitive
notion of integers, but they are only used as arguments for
primitive tactics and we cannot make computations with them. Thus,
instead, we use Coq's natural number type :g:`nat`.
.. coqtop:: in
Ltac perm_aux n :=
match goal with
| |- (perm _ ?l ?l) => apply perm_refl
| |- (perm _ (?a :: ?l1) (?a :: ?l2)) =>
let newn := eval compute in (length l1) in
(apply perm_cons; perm_aux newn)
| |- (perm ?A (?a :: ?l1) ?l2) =>
match eval compute in n with
| 1 => fail
| _ =>
let l1' := constr:(l1 ++ a :: nil) in
(apply (perm_trans A (a :: l1) l1' l2);
[ apply perm_append | compute; perm_aux (pred n) ])
end
end.
The main tactic is :g:`solve_perm`. It computes the lengths of the
two lists and uses them as arguments to call :g:`perm_aux` if the
lengths are equal. (If they aren't, the lists cannot be
permutations of each other.)
.. coqtop:: in
Ltac solve_perm :=
match goal with
| |- (perm _ ?l1 ?l2) =>
match eval compute in (length l1 = length l2) with
| (?n = ?n) => perm_aux n
end
end.
And now, here is how we can use the tactic :g:`solve_perm`:
.. coqtop:: out
Goal perm nat (1 :: 2 :: 3 :: nil) (3 :: 2 :: 1 :: nil).
.. coqtop:: all abort
solve_perm.
.. coqtop:: out
Goal perm nat
(0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: nil)
(0 :: 2 :: 4 :: 6 :: 8 :: 9 :: 7 :: 5 :: 3 :: 1 :: nil).
.. coqtop:: all abort
solve_perm.
Deciding intuitionistic propositional logic
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pattern matching on goals allows 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 :cite:`Dyc92`, it is quite natural to code such a tactic using the
tactic language as shown below.
.. coqtop:: in reset
Ltac basic :=
match goal with
| |- True => trivial
| _ : False |- _ => contradiction
| _ : ?A |- ?A => assumption
end.
.. coqtop:: in
Ltac simplify :=
repeat (intros;
match goal with
| H : ~ _ |- _ => red in H
| H : _ /\ _ |- _ =>
elim H; do 2 intro; clear H
| H : _ \/ _ |- _ =>
elim H; intro; clear H
| H : ?A /\ ?B -> ?C |- _ =>
cut (A -> B -> C);
[ intro | intros; apply H; split; assumption ]
| H: ?A \/ ?B -> ?C |- _ =>
cut (B -> C);
[ cut (A -> C);
[ intros; clear H
| intro; apply H; left; assumption ]
| intro; apply H; right; assumption ]
| H0 : ?A -> ?B, H1 : ?A |- _ =>
cut B; [ intro; clear H0 | apply H0; assumption ]
| |- _ /\ _ => split
| |- ~ _ => red
end).
.. coqtop:: in
Ltac my_tauto :=
simplify; basic ||
match goal with
| H : (?A -> ?B) -> ?C |- _ =>
cut (B -> C);
[ intro; cut (A -> B);
[ intro; cut C;
[ intro; clear H | apply H; assumption ]
| clear H ]
| intro; apply H; intro; assumption ]; my_tauto
| H : ~ ?A -> ?B |- _ =>
cut (False -> B);
[ intro; cut (A -> False);
[ intro; cut B;
[ intro; clear H | apply H; assumption ]
| clear H ]
| intro; apply H; red; intro; assumption ]; my_tauto
| |- _ \/ _ => (left; my_tauto) || (right; my_tauto)
end.
The tactic ``basic`` tries to reason using simple rules involving truth, falsity
and available assumptions. The tactic ``simplify`` applies all the reversible
rules of Dyckhoff’s system. Finally, the tactic ``my_tauto`` (the main
tactic to be called) simplifies with ``simplify``, tries to conclude with
``basic`` and tries several paths using the backtracking rules (one of the
four Dyckhoff’s rules for the left implication to get rid of the contraction
and the right ``or``).
Having defined ``my_tauto``, we can prove tautologies like these:
.. coqtop:: in
Lemma my_tauto_ex1 :
forall A B : Prop, A /\ B -> A \/ B.
Proof. my_tauto. Qed.
.. coqtop:: in
Lemma my_tauto_ex2 :
forall A B : Prop, (~ ~ B -> B) -> (A -> B) -> ~ ~ A -> B.
Proof. my_tauto. Qed.
Deciding type isomorphisms
~~~~~~~~~~~~~~~~~~~~~~~~~~
A trickier problem is to decide equalities between types modulo
isomorphisms. Here, we choose to use the isomorphisms of the simply
typed λ-calculus with Cartesian product and unit type (see, for
example, :cite:`RC95`). The axioms of this λ-calculus are given below.
.. coqtop:: in reset
Open Scope type_scope.
.. coqtop:: in
Section Iso_axioms.
.. coqtop:: in
Variables A B C : Set.
.. coqtop:: in
Axiom Com : A * B = B * A.
Axiom Ass : A * (B * C) = A * B * C.
Axiom Cur : (A * B -> C) = (A -> B -> C).
Axiom Dis : (A -> B * C) = (A -> B) * (A -> C).
Axiom P_unit : A * unit = A.
Axiom AR_unit : (A -> unit) = unit.
Axiom AL_unit : (unit -> A) = A.
.. coqtop:: in
Lemma Cons : B = C -> A * B = A * C.
Proof.
intro Heq; rewrite Heq; reflexivity.
Qed.
.. coqtop:: in
End Iso_axioms.
.. coqtop:: in
Ltac simplify_type ty :=
match ty with
| ?A * ?B * ?C =>
rewrite <- (Ass A B C); try simplify_type_eq
| ?A * ?B -> ?C =>
rewrite (Cur A B C); try simplify_type_eq
| ?A -> ?B * ?C =>
rewrite (Dis A B C); try simplify_type_eq
| ?A * unit =>
rewrite (P_unit A); try simplify_type_eq
| unit * ?B =>
rewrite (Com unit B); try simplify_type_eq
| ?A -> unit =>
rewrite (AR_unit A); try simplify_type_eq
| unit -> ?B =>
rewrite (AL_unit B); try simplify_type_eq
| ?A * ?B =>
(simplify_type A; try simplify_type_eq) ||
(simplify_type B; try simplify_type_eq)
| ?A -> ?B =>
(simplify_type A; try simplify_type_eq) ||
(simplify_type B; try simplify_type_eq)
end
with simplify_type_eq :=
match goal with
| |- ?A = ?B => try simplify_type A; try simplify_type B
end.
.. coqtop:: in
Ltac len trm :=
match trm with
| _ * ?B => let succ := len B in constr:(S succ)
| _ => constr:(1)
end.
.. coqtop:: in
Ltac assoc := repeat rewrite <- Ass.
.. coqtop:: in
Ltac solve_type_eq n :=
match goal with
| |- ?A = ?A => reflexivity
| |- ?A * ?B = ?A * ?C =>
apply Cons; let newn := len B in solve_type_eq newn
| |- ?A * ?B = ?C =>
match eval compute in n with
| 1 => fail
| _ =>
pattern (A * B) at 1; rewrite Com; assoc; solve_type_eq (pred n)
end
end.
.. coqtop:: in
Ltac compare_structure :=
match goal with
| |- ?A = ?B =>
let l1 := len A
with l2 := len B in
match eval compute in (l1 = l2) with
| ?n = ?n => solve_type_eq n
end
end.
.. coqtop:: in
Ltac solve_iso := simplify_type_eq; compare_structure.
The tactic to judge equalities modulo this axiomatization is shown above.
The algorithm is quite simple. First types are simplified using axioms that
can be oriented (this is done by ``simplify_type`` and ``simplify_type_eq``).
The normal forms are sequences of Cartesian products without a Cartesian product
in the left component. These normal forms are then compared modulo permutation
of the components by the tactic ``compare_structure``. If they have the same
length, the tactic ``solve_type_eq`` attempts to prove that the types are equal.
The main tactic that puts all these components together is ``solve_iso``.
Here are examples of what can be solved by ``solve_iso``.
.. coqtop:: in
Lemma solve_iso_ex1 :
forall A B : Set, A * unit * B = B * (unit * A).
Proof.
intros; solve_iso.
Qed.
.. coqtop:: in
Lemma solve_iso_ex2 :
forall A B C : Set,
(A * unit -> B * (C * unit)) =
(A * unit -> (C -> unit) * C) * (unit -> A -> B).
Proof.
intros; solve_iso.
Qed.
Debugging |Ltac| tactics
------------------------
Backtraces
~~~~~~~~~~
.. flag:: Ltac Backtrace
Setting this flag displays a backtrace on Ltac failures that can be useful
to find out what went wrong. It is disabled by default for performance
reasons.
Info trace
~~~~~~~~~~
.. cmd:: Info @num @expr
:name: Info
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 :cmd:`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 :cmd:`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 :cmd:`Info` contains
(in comments) the messages produced by the :tacn:`idtac` tactical at the right
position in the script. In particular, the calls to idtac in branches which failed are
not printed.
.. opt:: Info Level @num
:name: Info Level
This option is an alternative to the :cmd:`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
:cmd:`Info` command.
Interactive debugger
~~~~~~~~~~~~~~~~~~~~
.. flag:: 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 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” |
+-----------------+-----------------------------------------------+
.. exn:: Debug mode not available in the IDE
:undocumented:
A non-interactive mode for the debugger is available via the option:
.. flag:: 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 performance 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 on its calling context. Thus
it allows to locate the part of a tactic definition that contains the
performance issue.
.. flag:: 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 :cmd:`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
turns the :flag:`Ltac Profiling` option on at the beginning of each document,
and performs a :cmd:`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`.
|