Debian Codegraph @

examples/tutorial_coq_elpi_tactic.v

raw
1 (*|
2
3 Tutorial on Coq tactics
4 ***********************
5
6 :author: Enrico Tassi
7
8 .. include:: ../etc/tutorial_style.rst
9
10 ..
11 Elpi is an extension language that comes as a library
12 to be embedded into host applications such as Coq.
13
14 Elpi is a variant of λProlog enriched with constraints.
15 λProlog is a programming language designed to make it easy
16 to manipulate abstract syntax trees containing binders.
17 Elpi extends λProlog with programming constructs that are
18 designed to make it easy to manipulate abstract syntax trees
19 containing metavariables (also called unification variables, or
20 evars in the Coq jargon).
21
22 This software, "coq-elpi", is a Coq plugin embedding Elpi and
23 exposing to the extension language Coq specific data types (e.g. terms)
24 and API (e.g. to declare a new inductive type).
25
26 In order to get proper syntax highlighting using VSCode please install the
27 "gares.coq-elpi-lang" extension. In CoqIDE please chose "coq-elpi" in
28 Edit -> Preferences -> Colors.
29
30
31 This tutorial focuses on the implementation of Coq tactics.
32
33 This tutorial assumes the reader is familiar with Elpi and the HOAS
34 representation of Coq terms; if it is not the case, please take a look at
35 these other tutorials first:
36 `Elpi tutorial <https://lpcic.github.io/coq-elpi/tutorial_elpi_lang.html>`_
37 and `Coq HOAS tutorial <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_HOAS.html>`_.
38
39 .. contents::
40
41 ================
42 Defining tactics
43 ================
44
45 In Coq a proof is just a term, and an incomplete proof is just a term
46 with holes standing for the open goals.
47
48 When a proof starts there is just one hole (one goal) and its type
49 is the statement one wants to prove. Then proof construction makes
50 progress by instantiation: a term possibly containing holes is
51 grafted to the hole corresponding to the current goal. What a tactic
52 does behind the scenes is to synthesize this partial term.
53
54 Let's define a simple tactic that prints the current goal.
55
56 |*)
57
58 Set Warnings "-elpi.linear-variable". (* .none *)
59 From elpi Require Import elpi.
60
61 Elpi Tactic show.
62 Elpi Accumulate lp:{{
63
64 solve (goal Ctx _Trigger Type Proof _) _ :-
65 coq.say "Goal:" Ctx "|-" Proof ":" Type.
66
67 }}.
68
69
70 (*|
71
72 The tactic declaration is made of 3 parts.
73
74 The first one `Elpi Tactic show.` sets the current program to `show`.
75 Since it is declared as a `Tactic` some code is loaded automatically:
76
77 * APIs (eg :builtin:`coq.say`) and data types (eg Coq :type:`term` s) are loaded from
78 `coq-builtin.elpi <https://github.com/LPCIC/coq-elpi/blob/master/builtin-doc/coq-builtin.elpi>`_
79 * some utilities, like :lib:`copy` or :libred:`whd1` are loaded from
80 `elpi-command-template.elpi <https://github.com/LPCIC/coq-elpi/blob/master/elpi/elpi-tactic-template.elpi>`_
81
82
83 The second one `Elpi Accumulate ...` loads some extra code.
84 The `Elpi Accumulate ...` family of commands lets one accumulate code
85 taken from:
86
87 * verbatim text `Elpi Accumulate lp:{{ code }}`
88 * source files `Elpi Accumulate File path`
89 * data bases (Db) `Elpi Accumulate Db name`
90
91 Accumulating code via inline text or file is equivalent, the AST of `code`
92 is stored in the .vo file (the external file does not need to be installed).
93 We invite the reader to look up the description of data bases in the tutorial
94 about commands.
95
96 When some code is accumulated Elpi verifies that the
97 code does not contain the most frequent kind of mistakes, via some
98 type checking and linting. Some mistakes are minor and Elpi only warns about
99 them. You can pass `-w +elpi.typecheck` to `coqc` to turn these warnings into
100 errors.
101
102 The entry point for tactics is called :builtin:`solve` which maps a :type:`goal`
103 into a list of :type:`sealed-goal` (representing subgoals).
104
105 Tactics written in Elpi can be invoked by prefixing its name with `elpi`.
106
107 |*)
108
109 Lemma tutorial x y : x + 1 = y.
110 elpi show. (* .in .messages *)
111 Abort.
112
113 (*|
114
115 In the Elpi code up there :e:`Proof` is the hole for the current goal,
116 :e:`Type` the statement to be proved and :e:`Ctx` the proof context (the list of
117 hypotheses). Since we don't assign :e:`Proof` the tactic makes no progress.
118 Elpi prints somethinglike this:
119
120 .. mquote:: .s(elpi).msg{Goal:*X0 c0 c1*}
121 :language: text
122
123 The first line is the proof context:
124 proof variables are bound Elpi variables (here :e:`c0` and :e:`c1`), the context
125 is a list of predicates holding on them (their type in Coq). For example:
126
127 .. code::
128
129 decl c0 `x` (global (indt «nat»))
130
131 asserts that :e:`c0` (pretty printed as `x`) has type `nat`.
132
133 Then we see that the value of :e:`Proof` is :e:`X0 c0 c1`. This means that the
134 proof of the current goal is represented by Elpi's variable :e:`X0` and that
135 the variable has :e:`c0` and :e:`c1` in scope (the proof term can use them).
136
137 Finally we see the type of the goal `x + 1 = y`.
138
139 The :e:`_Trigger` component, which we did not print, is a variable that, when
140 assigned, triggers the elaboration of its value against the type of the goal
141 and obtains a value for :e:`Proof` this way.
142
143 Keeping in mind that the :builtin:`solve` predicate relates one goal to a list of
144 subgoals, we implement our first tactic which blindly tries to solve the goal.
145
146 |*)
147
148 Elpi Tactic blind.
149 Elpi Accumulate lp:{{
150 solve (goal _ Trigger _ _ _) [] :- Trigger = {{0}}.
151 solve (goal _ Trigger _ _ _) [] :- Trigger = {{I}}.
152 }}.
153
154
155 Lemma test_blind : True * nat.
156 Proof. (* .in *)
157 split.
158 - elpi blind.
159 - elpi blind.
160 Show Proof. (* .in .messages *)
161 Qed.
162
163 (*|
164
165 Since the assignment of a term to :e:`Trigger` triggers its elaboration against
166 the expected type (the goal statement), assigning the wrong proof term
167 results in a failure which in turn results in the other rule being tried.
168
169 For now, this is all about the low level mechanics of tactics which is
170 developed further in the section `The-proof-engine`_.
171
172 We now focus on how to better integrate tactics written in Elpi with Ltac.
173
174 ---------------------
175 Integration with Ltac
176 ---------------------
177
178 For a simple tactic like `blind` the list of subgoals is easy to write, since
179 it is empty, but in general one should collect all the holes in
180 the value of :e:`Proof` (the checked proof term) and build goals out of them.
181
182 There is a family of APIs named after :libtac:`refine`, the mother of all
183 tactics, in
184 `elpi-ltac.elpi <https://github.com/LPCIC/coq-elpi/blob/master/elpi/elpi-ltac.elpi>`_
185 which does this job for you.
186
187 Usually a tactic builds a (possibly partial) term and calls
188 :libtac:`refine` on it.
189
190 Let's rewrite the `blind` tactic using this schema.
191
192 |*)
193
194
195 Elpi Tactic blind2.
196 Elpi Accumulate lp:{{
197 solve G GL :- refine {{0}} G GL.
198 solve G GL :- refine {{I}} G GL.
199 }}.
200
201
202 Lemma test_blind2 : True * nat.
203 Proof. (* .in *)
204 split.
205 - elpi blind2.
206 - elpi blind2.
207 Qed.
208
209 (*|
210
211 This schema works even if the term is partial, that is if it contains holes
212 corresponding to missing sub proofs.
213
214 Let's write a tactic which opens a few subgoals, for example
215 let's implement the `split` tactic.
216
217 .. important::
218
219 Elpi's equality (that is, unification) on Coq terms corresponds to
220 alpha equivalence, we can use that to make our tactic less blind.
221
222 The head of a rule for the solve predicate is *matched* against the
223 goal. This operation cannot assign unification variables in the goal, only
224 variables in the rule's head.
225 As a consequence the following rule for `solve` is only used when
226 the statement features an explicit conjunction.
227
228 |*)
229
230 About conj. (* remark the implicit arguments *)
231
232 Elpi Tactic split.
233 Elpi Accumulate lp:{{
234 solve (goal _ _ {{ _ /\ _ }} _ _ as G) GL :- !,
235 % conj has 4 arguments, but two are implicits
236 % (_ are added for them and are inferred from the goal)
237 refine {{ conj _ _ }} G GL.
238
239 solve _ _ :-
240 % This signals a failure in the Ltac model. A failure
241 % in Elpi, that is no more clauses to try, is a fatal
242 % error that cannot be caught by Ltac combinators like repeat.
243 coq.ltac.fail _ "not a conjunction".
244 }}.
245
246
247 Lemma test_split : exists t : Prop, True /\ True /\ t.
248 Proof. (* .in *)
249 eexists.
250 repeat elpi split. (* The failure is caught by Ltac's repeat *)
251 (* Remark that the last goal is left untouched, since
252 it did not match the pattern {{ _ /\ _ }}. *)
253 all: elpi blind.
254 Show Proof. (* .in .messages *)
255 Qed.
256
257 (*|
258
259 The tactic `split` succeeds twice, stopping on the two identical goals `True` and
260 the one which is an evar of type `Prop`.
261
262 We then invoke `blind` on all goals. In the third case the type checking
263 constraint triggered by assigning `{{0}}` to `Trigger` fails because
264 its type `nat` is not of sort `Prop`, so it backtracks and picks `{{I}}`.
265
266 Another common way to build an Elpi tactic is to synthesize a term and
267 then call some Ltac piece of code finishing the work.
268
269 The API :libtac:`coq.ltac.call` invokes some Ltac piece
270 of code passing to it the desired
271 arguments. Then it builds the list of subgoals.
272
273 Here we pass an integer, which in turn is passed to `fail`, and a term,
274 which in turn is passed to `apply`.
275
276 |*)
277
278 Ltac helper_split2 n t := fail n || apply t.
279
280 Elpi Tactic split2.
281 Elpi Accumulate lp:{{
282 solve (goal _ _ {{ _ /\ _ }} _ _ as G) GL :-
283 coq.ltac.call "helper_split2" [int 0, trm {{ conj }}] G GL ok.
284 solve _ _ :-
285 coq.ltac.fail _ "not a conjunction".
286 }}.
287
288
289 Lemma test_split2 : exists t : Prop, True /\ True /\ t.
290 Proof. (* .in *)
291 eexists.
292 repeat elpi split2.
293 all: elpi blind.
294 Qed.
295
296 (*|
297
298 =============================
299 Arguments and Tactic Notation
300 =============================
301
302 Elpi tactics can receive arguments. Arguments are received as a list, which
303 is the last argument of the goal constructor. This suggests that arguments
304 are attached to the current goal being observed, but we will dive into
305 this detail later on.
306
307 |*)
308
309 Elpi Tactic print_args.
310 Elpi Accumulate lp:{{
311 solve (goal _ _ _ _ Args) _ :- coq.say Args.
312 }}.
313
314
315 Lemma test_print_args : True. (* .in *)
316 elpi print_args 1 x "a b" (1 = 0). (* .in .messages *)
317 Abort.
318
319 (*|
320
321 The convention is that numbers like `1` are passed as :e:`int 1`,
322 identifiers or strings are passed as :e:`str "arg"` and terms
323 have to be put between parentheses.
324
325 .. important:: terms are received in raw format, eg before elaboration
326
327 Indeed the type argument to `eq` is a variable.
328 One can use APIs like :builtin:`coq.elaborate-skeleton` to infer holes like
329 :e:`X0`.
330
331 See the :type:`argument` data type
332 for a detailed description of all the arguments a tactic can receive.
333
334 Now let's write a tactic which behaves pretty much like the :libtac:`refine`
335 one from Coq, but prints what it does using the API :builtin:`coq.term->string`.
336
337 |*)
338
339 Elpi Tactic refine.
340 Elpi Accumulate lp:{{
341 solve (goal _ _ Ty _ [trm S] as G) GL :-
342 % check S elaborates to T of type Ty (the goal)
343 coq.elaborate-skeleton S Ty T ok,
344
345 coq.say "Using" {coq.term->string T}
346 "of type" {coq.term->string Ty},
347
348 % since T is already checked, we don't check it again
349 refine.no_check T G GL.
350
351 solve (goal _ _ _ _ [trm S]) _ :-
352 Msg is {coq.term->string S} ^ " does not fit",
353 coq.ltac.fail _ Msg.
354 }}.
355
356
357 Lemma test_refine (P Q : Prop) (H : P -> Q) : Q.
358 Proof. (* .in *)
359 Fail elpi refine (H). (* .fails *)
360 elpi refine (H _).
361 Abort.
362
363 (*|
364
365 --------------------------------
366 Ltac arguments to Elpi arguments
367 --------------------------------
368
369 It is customary to use the Tactic Notation command to attach a nicer syntax
370 to Elpi tactics.
371
372 In particular `elpi tacname` accepts as arguments the following `bridges
373 for Ltac values <https://coq.inria.fr/doc/master/refman/proof-engine/ltac.html#syntactic-values>`_ :
374
375 * `ltac_string:(v)` (for `v` of type `string` or `ident`)
376 * `ltac_int:(v)` (for `v` of type `int` or `integer`)
377 * `ltac_term:(v)` (for `v` of type `constr` or `open_constr` or `uconstr` or `hyp`)
378 * `ltac_(string|int|term)_list:(v)` (for `v` of type `list` of ...)
379
380 Note that the Ltac type associates some semantics to the action of passing
381 the arguments. For example `hyp` will accept an identifier only if it is
382 an hypotheses of the context. While `uconstr` does not type check the term,
383 which is the recommended way to pass terms to an Elpi tactic (since it is
384 likely to be typed anyway by the Elpi tactic).
385
386 |*)
387
388 Tactic Notation "use" uconstr(t) :=
389 elpi refine ltac_term:(t).
390
391 Tactic Notation "use" hyp(t) :=
392 elpi refine ltac_term:(t).
393
394 Lemma test_use (P Q : Prop) (H : P -> Q) (p : P) : Q.
395 Proof. (* .in *)
396 use (H _).
397 Fail use q. (* .fails .in .messages *)
398 use p.
399 Qed.
400
401 Tactic Notation "print" uconstr_list_sep(l, ",") :=
402 elpi print_args ltac_term_list:(l).
403
404 Lemma test_print (P Q : Prop) (H : P -> Q) (p : P) : Q.
405 print P, p, (H p). (* .in .messages *)
406 Abort.
407
408 (*|
409
410 ========
411 Failure
412 ========
413
414 The :builtin:`coq.error` aborts the execution of both
415 Elpi and any enclosing Ltac context. This failure cannot be caught
416 by Ltac.
417
418 On the contrary the :builtin:`coq.ltac.fail` builtin can be used to
419 abort the execution of Elpi code in such a way that Ltac can catch it.
420 This API takes an integer akin to Ltac's fail depth together with
421 the error message to be displayed to the user.
422
423 Library functions of the `assert!` family call, by default, :builtin:`coq.error`.
424 The flag `@ltacfail! N` can be set to alter this behavior and turn errors into
425 calls to `coq.ltac.fail N`.
426
427 |*)
428
429 Elpi Tactic abort.
430 Elpi Accumulate lp:{{
431 solve _ _ :- coq.error "uncatchable".
432 }}.
433
434 Goal True.
435 Fail elpi abort || idtac.
436 Abort.
437
438 Elpi Tactic fail.
439 Elpi Accumulate lp:{{
440 solve (goal _ _ _ _ [int N]) _ :- coq.ltac.fail N "catchable".
441 }}.
442
443 Goal True.
444 elpi fail 0 || idtac.
445 Fail elpi fail 1 || idtac.
446 Abort.
447
448
449 (*|
450
451 ========
452 Examples
453 ========
454
455 -------------------------------
456 Let's code `assumption` in Elpi
457 -------------------------------
458
459 `assumption` is a very simple tactic: we look up in the proof
460 context for an hypothesis which unifies with the goal.
461 Recall that `Ctx` is made of :builtin:`decl` and :builtin:`def`
462 (here, for simplicity, we ignore the latter case).
463
464 |*)
465
466 Elpi Tactic assumption.
467 Elpi Accumulate lp:{{
468 solve (goal Ctx _ Ty _ _ as G) GL :-
469 % H is the name for hyp, Ty is the goal
470 std.mem Ctx (decl H _ Ty),
471 refine H G GL.
472 solve _ _ :-
473 coq.ltac.fail _ "no such hypothesis".
474 }}.
475
476
477 Lemma test_assumption (P Q : Prop) (p : P) (q : Q) : P /\ id Q.
478 Proof. (* .in *)
479 split.
480 elpi assumption.
481 Fail elpi assumption. (* .fails *)
482 Abort.
483
484 (*|
485
486 As we hinted before, Elpi's equality is alpha equivalence. In the second
487 goal the assumption has type `Q` but the goal has type `id Q` which is
488 convertible (unifiable, for Coq's unification) to `Q`.
489
490 Let's improve our tactic by looking for an assumption which is unifiable with
491 the goal, and not just alpha convertible. The :builtin:`coq.unify-leq`
492 calls Coq's unification for types (on which cumulativity applies, hence the
493 `-leq` suffix). The :stdlib:`std.mem` utility, thanks to backtracking,
494 eventually finds an hypothesis that satisfies the following predicate
495 (ie unifies with the goal).
496
497 |*)
498
499 Elpi Tactic assumption2.
500 Elpi Accumulate lp:{{
501 solve (goal Ctx _ Ty _ _ as G) GL :-
502 % std.mem is backtracking (std.mem! would stop at the first hit)
503 std.mem Ctx (decl H _ Ty'), coq.unify-leq Ty' Ty ok,
504 refine H G GL.
505 solve _ _ :-
506 coq.ltac.fail _ "no such hypothesis".
507 }}.
508
509
510 Lemma test_assumption2 (P Q : Prop) (p : P) (q : Q) : P /\ id Q.
511 Proof. (* .in *)
512 split.
513 all: elpi assumption2.
514 Qed.
515
516 (*|
517
518 :libtac:`refine` does unify the type of goal with the type of the term,
519 hence we can simplify the code further. We obtain a
520 tactic very similar to our initial `blind` tactic, which picks
521 candidates from the context rather than from the program itself.
522
523 |*)
524
525 Elpi Tactic assumption3.
526 Elpi Accumulate lp:{{
527 solve (goal Ctx _ _ _ _ as G) GL :-
528 std.mem Ctx (decl H _ _),
529 refine H G GL.
530 solve _ _ :-
531 coq.ltac.fail _ "no such hypothesis".
532 }}.
533
534
535 Lemma test_assumption3 (P Q : Prop) (p : P) (q : Q) : P /\ id Q.
536 Proof. (* .in *)
537 split.
538 all: elpi assumption3.
539 Qed.
540
541 (*|
542
543 ------------------------
544 Let's code `set` in Elpi
545 ------------------------
546
547 The `set` tactic takes a term, possibly with holes, and
548 makes a let-in out of it.
549
550 It gives us the occasion to explain the :lib:`copy` utility.
551
552 |*)
553
554 Elpi Tactic find.
555 Elpi Accumulate lp:{{
556
557 solve (goal _ _ T _ [trm X]) _ :-
558 pi x\
559 ((copy X x :- !) ==> copy T (Tabs x)),
560 if (occurs x (Tabs x))
561 (coq.say "found" {coq.term->string X})
562 (coq.ltac.fail _ "not found").
563 }}.
564
565
566 Lemma test_find (P Q : Prop) : (P /\ P) \/ (P /\ Q).
567 Proof. (* .in *)
568 elpi find (P).
569 Fail elpi find (Q /\ _). (* .fails .in .messages *)
570 elpi find (P /\ _).
571 Abort.
572
573 (*|
574
575 This first approximation only prints the term it found, or better the first
576 instance of the given term.
577
578 Now lets focus on :lib:`copy`. An excerpt:
579
580 .. code:: elpi
581
582 copy X X :- name X. % checks X is a bound variable
583 copy (global _ as C) C.
584 copy (fun N T F) (fun N T1 F1).
585 copy T T1, pi x\ copy (F x) (F1 x).
586 copy (app L) (app L1) :- !, std.map L copy L1.
587
588 Copy implements the identity: it builds, recursively, a copy of the first
589 term into the second argument. Unless one loads in the context a new rule,
590 which takes precedence over the identity ones. Here we load:
591
592 .. code:: elpi
593
594 copy X x
595
596 which, at run time, looks like
597
598 .. code:: elpi
599
600 copy (app [global (indt «andn»), sort prop, sort prop, c0, X0 c0 c1]) c2
601
602 and that rule masks the one for :constructor:`app` when the
603 sub-term being copied matches `(P /\ _)`. The first time this rule
604 is used :e:`X0` is assigned, making the rule represent the term `(P /\ P)`.
605
606 Now let's refine the tactic to build a let-in, and complain if the
607 desired name is already taken.
608
609 |*)
610
611 Elpi Tactic set.
612 Elpi Accumulate lp:{{
613
614 solve (goal _ _ T _ [str ID, trm X] as G) GL :-
615 pi x\
616 ((copy X x :- !) ==> copy T (Tabs x)),
617 if (occurs x (Tabs x))
618 (if (coq.ltac.id-free? ID G) true
619 (coq.warn ID "is already taken, Elpi will make a name up"),
620 coq.id->name ID Name,
621 Hole x = {{ _ : lp:{{ Tabs x }} }}, % a hole with a type
622 refine (let Name _ X x\ Hole x) G GL)
623 (coq.ltac.fail _ "not found").
624
625 }}.
626
627
628 Lemma test_set (P Q : Prop) : (P /\ P) \/ (P /\ Q).
629 Proof. (* .in *)
630 elpi set "x" (P).
631 unfold x.
632 Fail elpi set "x" (Q /\ _). (* .fails .in .messages *)
633 elpi set "x" (P /\ _).
634 Abort.
635
636 (*|
637
638 For more examples of (basic) tactics written in Elpi see the
639 `eltac app <https://github.com/LPCIC/coq-elpi/tree/master/apps/eltac>`_.
640
641
642 .. _The-proof-engine:
643
644 ================
645 The proof engine
646 ================
647
648 In this section we dive into the details of the proof engine, that is
649 how goals are represented in Elpi and how things are wired up behind the scenes.
650
651 Let's inspect the proof state a bit deeper:
652
653 |*)
654
655 Elpi Tactic show_more.
656 Elpi Accumulate lp:{{
657
658 solve (goal Ctx _Trigger Type Proof _) _ :-
659 coq.say "Goal:" Ctx "|-" Proof ":" Type,
660 coq.say "Proof state:",
661 coq.sigma.print.
662
663 }}.
664
665
666 Lemma test_show_more x : x + 1 = 0.
667 elpi show_more. (* .in .messages *)
668 Abort.
669
670 (*|
671
672 In addition to the goal we print the Elpi and Coq proof state,
673 plus the link between them.
674 The proof state is the collection of goals together with their types.
675
676 On the Elpi side this state is represented by constraints for the :e:`evar`
677 predicate.
678
679 .. mquote:: .s(elpi show_more).msg{*c0*evar (X1 c0)*suspended on X1, X0*}
680 :language: text
681
682 One can recognize the set of bound variables `{c0}`, the hypothetical
683 context of rules about these variable (that also corresponds to the proof
684 context), and finally the suspended goal :e:`evar (X1 c0) .. (X0 c0)`.
685
686 The set of constraints on `evar` represents the Coq data structure called
687 sigma (sometimes also called evd or evar_map) that is used to
688 represent the proof state in Coq. It is printed just afterwards:
689
690 .. mquote:: .s(elpi show_more).msg{EVARS:*[?]X97*x + 1 = 0*}
691 :language: text
692
693 .. mquote:: .s(elpi show_more).msg{Rocq-Elpi mapping:*RAW:*[?]X97 <-> *X1*ELAB:*[?]X97 <-> *X0*}
694 :language: text
695
696 Here `?X97` is a Coq evar linked with Elpi's :e:`X0` and :e:`X1`.
697 :e:`X1` represents the goal (the trigger) while :e:`X0` represent the proof.
698 The meaning of the :e:`evar` Elpi predicate linking the two is that the term
699 assigned to the trigger :e:`X1` has to be elaborated to the final proof term
700 :e:`X0`, that should be a well typed term of type `x + 1 = 0`.
701 This means that when an Elpi tactic assigns a value to :e:`X1` some procedure to
702 turn that value into :e:`X0` is triggered. That procedure is called
703 elaboration and it is currently implemented by calling the
704 :builtin:`coq.elaborate-skeleton` API.
705
706 Given this set up, it is impossible to use a term of the wrong type as a
707 Proof. Let's rewrite the `split` tactic without using :libtac:`refine`.
708
709 |*)
710
711 Elpi Tactic split_ll.
712 Elpi Accumulate lp:{{
713 solve (goal Ctx Trigger {{ lp:A /\ lp:B }} Proof []) GL :- !,
714 Trigger = {{ conj _ _ }}, % triggers elaboration, filling Proof
715 Proof = {{ conj lp:Pa lp:Pb }},
716 GL = [seal G1, seal G2],
717 G1 = goal Ctx _ A Pa [],
718 G2 = goal Ctx _ B Pb [].
719 solve _ _ :-
720 coq.ltac.fail _ "not a conjunction".
721 }}.
722
723
724 Lemma test_split_ll : exists t : Prop, True /\ True /\ t.
725 Proof. (* .in *)
726 eexists.
727 repeat elpi split_ll.
728 all: elpi blind.
729 Qed.
730
731 (*|
732
733 Crafting by hand the list of subgoal is not easy.
734 In particular here we did not set up the new trigger for :e:`Pa` and :e:`Pb`,
735 nor seal the goals appropriately (we did not bind proof variables).
736
737 The :builtin:`coq.ltac.collect-goals` API helps us doing this.
738
739 |*)
740
741 Elpi Tactic split_ll_bis.
742 Elpi Accumulate lp:{{
743 solve (goal Ctx Trigger {{ lp:A /\ lp:B }} Proof []) GL :- !,
744 % this triggers the elaboration
745 Trigger = {{ conj _ _ }},
746 % we only take main goals
747 coq.ltac.collect-goals Proof GL _ShelvedGL.
748 solve _ _ :-
749 coq.ltac.fail _ "not a conjunction".
750 }}.
751
752
753 Lemma test_split_ll_bis : exists t : Prop, True /\ True /\ t.
754 Proof. (* .in *)
755 eexists.
756 repeat elpi split_ll_bis.
757 all: elpi blind.
758 Qed.
759
760 (*|
761
762 At the light of that, :libtac:`refine` is simply:
763
764 .. code:: elpi
765
766 refine T (goal _ RawEv _ Ev _) GS :-
767 RawEv = T, coq.ltac.collect-goals Ev GS _.
768
769 Now that we know the low level plumbing, we can use :libtac:`refine` ;-)
770
771 The only detail we still have to explain is what exactly a
772 :type:`sealed-goal` is. A sealed goal wraps into a single object all
773 the proof variables and the assumptions about them, making this object easy
774 (or better, sound) to pass around.
775
776 ------------------
777 multi-goal tactics
778 ------------------
779
780 Since Coq 8.4 tactics can see more than one goal (multi-goal tactics).
781 You can access this feature by using `all:` goal selector:
782
783 * if the tactic is a regular one, it will be used on each goal independently
784 * if the tactic is a multi-goal one, it will receive all goals
785
786 In Elpi you can implement a multi-goal tactic by providing a rule for
787 the :builtin:`msolve` predicate. Since such a tactic will need to manipulate
788 multiple goals, potentially living in different proof context, it receives
789 a list of :type:`sealed-goal`, a data type which seals a goal and
790 its proof context.
791
792 |*)
793
794 Elpi Tactic ngoals.
795 Elpi Accumulate lp:{{
796
797 msolve GL _ :-
798 coq.say "#goals =" {std.length GL},
799 coq.say GL.
800
801 }}.
802
803
804 Lemma test_undup (P Q : Prop) : P /\ Q.
805 Proof. (* .in *)
806 split.
807 all: elpi ngoals.
808 Abort.
809
810 (*|
811
812 This simple tactic prints the number of goals it receives, as well as
813 the list itself. We see something like:
814
815 .. mquote:: .s(elpi ngoals).msg{*goals =*}
816 :language: text
817
818 .. mquote:: .s(elpi ngoals).msg{*nabla*}
819 :language: elpi
820
821 :constructor:`nabla` binds all proof variables, then :constructor:`seal`
822 holds a regular goal, which in turn carries the proof context.
823
824 In order to operate inside a goal one can use the :libtac:`coq.ltac.open` utility,
825 which postulates all proof variables using :e:`pi x\ ` and loads the proof
826 context using :e:`=>`.
827
828 Operating on multiple goals at the same time is doable, but not easy.
829 In particular the two proof context have to be related in some way.
830
831 The following simple multi goal tactic shrinks the list of goals by
832 removing duplicates. As one can see, there is much room for improvement
833 in the :e:`same-ctx` predicate.
834
835 |*)
836
837 Elpi Tactic undup.
838 Elpi Accumulate lp:{{
839
840 pred same-goal i:sealed-goal, i:sealed-goal.
841 same-goal (nabla G1) (nabla G2) :-
842 % TODO: proof variables could be permuted
843 pi x\ same-goal (G1 x) (G2 x).
844 same-goal (seal (goal Ctx1 _ Ty1 P1 _) as G1)
845 (seal (goal Ctx2 _ Ty2 P2 _) as G2) :-
846 same-ctx Ctx1 Ctx2,
847 % this is an elpi builtin, aka same_term, which does not
848 % unify but rather compare two terms without assigning variables
849 Ty1 == Ty2,
850 P1 = P2.
851
852 pred same-ctx i:goal-ctx, i:goal-ctx.
853 same-ctx [] [].
854 same-ctx [decl V _ T1|C1] [decl V _ T2|C2] :-
855 % TODO: we could compare up to permutation...
856 % TODO: we could try to relate def and decl
857 T1 == T2,
858 same-ctx C1 C2.
859
860 pred undup i:sealed-goal, i:list sealed-goal, o:list sealed-goal.
861 undup _ [] [].
862 undup G [G1|GN] GN :- same-goal G G1.
863 undup G [G1|GN] [G1|GL] :- undup G GN GL.
864
865 msolve [G1|GS] [G1|GL] :-
866 % TODO: we could find all duplicates, not just
867 % copies of the first goal...
868 undup G1 GS GL.
869
870 }}.
871
872
873 Lemma test_undup (P Q : Prop) (p : P) (q : Q) : P /\ Q /\ P.
874 Proof. (* .in *)
875 repeat split.
876 Show Proof. (* .in .messages *)
877 all: elpi undup.
878 Show Proof. (* .in .messages *)
879 - apply p.
880 - apply q.
881 Qed.
882
883 (*|
884
885 The two calls to show proof display, respectively:
886
887 .. mquote:: .s(Show Proof).msg{*conj [?]Goal (conj [?]Goal0 [?]Goal1)*}
888 :language: text
889
890 .. mquote:: .s(Show Proof).msg{*conj [?]Goal (conj [?]Goal0 [?]Goal)*}
891 :language: text
892
893 the proof term is the same but for the fact that after the tactic the first
894 and last missing subterm (incomplete proof tree branch) are represented by
895 the same hole `?Goal`. Indeed by solving one, we can also solve the other.
896
897 -------------
898 LCF tacticals
899 -------------
900
901 On the notion of sealed-goal it is easy to define the usual LCF combinators,
902 also known as Ltac tacticals. Tacticals usually take in input one or more
903 tactic, here the precise type definition:
904
905 .. code:: elpi
906
907 typeabbrev tactic (sealed-goal -> (list sealed-goal -> prop)).
908
909 A few tacticals can be found in the
910 `elpi-ltac.elpi file <https://github.com/LPCIC/coq-elpi/blob/master/elpi/elpi-ltac.elpi>`_.
911 For example this is the code of :libtac:`try`:
912
913 .. code:: elpi
914
915 pred try i:tactic, i:sealed-goal, o:list sealed-goal.
916 try T G GS :- T G GS.
917 try _ G [G].
918
919 ------------------------------
920 Setting arguments for a tactic
921 ------------------------------
922
923 As we hinted before, tactic arguments are attached to the goal since
924 they can mention proof variables. So the Ltac code:
925
926 .. code:: coq
927
928 intro H; apply H.
929
930 has to be seen as 3 steps, starting from a goal `G`:
931
932 * introduction of `H`, obtaining `G1`
933 * setting the argument `H`, obtaining `G2`
934 * calling apply, obtaining `G3`
935
936 |*)
937
938 Elpi Tactic argpass.
939 Elpi Accumulate lp:{{
940
941 % this directive lets you use short names
942 shorten coq.ltac.{ open, thenl, all }.
943
944 type intro open-tactic. % goal -> list sealed-goal
945 intro G GL :- refine {{ fun H => _ }} G GL.
946
947 type set-arg-n-hyp int -> open-tactic.
948 set-arg-n-hyp N (goal Ctx _ _ _ _ as G) [SG1] :-
949 std.nth N Ctx (decl X _ _),
950 coq.ltac.set-goal-arguments [trm X] G (seal G) SG1.
951
952 type apply open-tactic.
953 apply (goal _ _ _ _ [trm T] as G) GL :- refine T G GL.
954
955 msolve SG GL :-
956 all (thenl [ open intro,
957 open (set-arg-n-hyp 0),
958 open apply ]) SG GL.
959
960 }}.
961
962
963 Lemma test_argpass (P : Prop) : P -> P.
964 Proof. (* .in *)
965 elpi argpass.
966 Qed.
967
968 (*|
969
970 Of course the tactic playing the role of `intro` could communicate back
971 a datum to be passed to what follows
972
973 .. code:: elpi
974
975 thenl [ open (tac1 Datum), open (tac2 Datum) ]
976
977 but the binder structure of :type:`sealed-goal` would prevent :e:`Datum`
978 to mention proof variables, that would otherwise escape the sealing.
979
980 The utility :libtac:`set-goal-arguments`:
981
982 .. code:: elpi
983
984 coq.ltac.set-goal-arguments Args G G1 G1wArgs
985
986 tries to move :e:`Args` from the context of :e:`G` to the one of :e:`G1`.
987 Relating the two proof contexts is not obvious: you may need to write your
988 own procedure if the two contexts are very distant.
989
990 ================
991 Tactics in terms
992 ================
993
994 Elpi tactics can be used inside terms via the usual `ltac:(...)`
995 quotation, but can also be exported to the term grammar.
996
997 Here we write a simple tactic for default values, which
998 optionally takes a bound to the search depth.
999
1000 |*)
1001
1002 Elpi Tactic default.
1003 Elpi Accumulate lp:{{
1004
1005 pred default i:term, i:int, o:term.
1006
1007 default _ 0 _ :- coq.ltac.fail _ "max search depth reached".
1008 default {{ nat }} _ {{ 46 }}.
1009 default {{ bool }} _ {{ false }}.
1010 default {{ list lp:A }} Max {{ cons lp:D nil }} :-
1011 Max' is Max - 1, default A Max' D.
1012
1013 solve (goal _ _ T _ [] as G) GL :-
1014 default T 9999 P,
1015 refine P G GL.
1016
1017 }}.
1018
1019 Elpi Export default.
1020
1021 Definition foo : nat := default.
1022 Print foo.
1023
1024 Definition bar : list bool := default.
1025 Print bar.
1026
1027 (*|
1028
1029 The grammar entries for Elpi tactics in terms take an arbitrary
1030 number of arguments with the limitation that they are all terms:
1031 you can't pass a string or an integer as one would normally do.
1032
1033 Here we use Coq's primitive integers to pass the search depth
1034 (in a compact way).
1035
1036 |*)
1037
1038 Elpi Accumulate default lp:{{
1039 solve (goal _ _ T _ [trm (primitive (uint63 Max))] as G) GL :-
1040 coq.uint63->int Max MaxI,
1041 default T MaxI P,
1042 refine P G GL.
1043 }}.
1044
1045
1046 From Corelib Require Import PrimInt63.
1047 Open Scope uint63_scope.
1048
1049 Fail Definition baz : list nat := default 1. (* .fails *)
1050
1051 Definition baz : list nat := default 2.
1052 Print baz.
1053
1054 (*|
1055
1056 That is all folks!
1057
1058 |*)