Debian Codegraph @

examples/tutorial_elpi_lang.v

raw
1 (*|
2
3 Tutorial on the Elpi programming language
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 modes and constraints in order
18 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 This little tutorial does not talk about Coq, but rather focuses on
31 Elpi as a programming language. It assumes no previous knowledge of
32 Prolog, λProlog or Elpi. Coq is used as an environment for stepping trough
33 the tutorial one paragraph at a time. The text between `lp:{{` and `}}` is
34 Elpi code, while the rest are Coq directives to drive the Elpi interpreter.
35
36 .. contents::
37
38 |*)
39
40 Set Warnings "-elpi.linear-variable". (* .none *)
41 From elpi Require Import elpi. (* .none *)
42
43 (*|
44
45 =================
46 Logic programming
47 =================
48
49 Elpi is a dialect of λProlog enriched with constraints. We start by introducing
50 the first order fragment of λProlog, i.e. the terms will not contain binders.
51 Later we cover terms with binders and constraints.
52
53 Our first program is called `tutorial`.
54 We begin by declaring the signature of our terms.
55 Here we declare that :e:`person` is a type, and that
56 :e:`mallory`, :e:`bob` and :e:`alice` are terms of that type.
57
58 |*)
59
60 Elpi Program tutorial lp:{{
61
62 kind person type.
63 type mallory, bob, alice person.
64
65 }}.
66
67 (*|
68
69 An Elpi program is made of rules that declare
70 when predicates hold and that are accumulated one after the
71 other. Rules are also called clauses in Prolog's slang, so we may use both
72 terms interchangeably.
73
74 The next code snippet accumulates on top
75 of the current `tutorial` program a predicate declaration for :e:`age`
76 and three rules representing our knowledge about our terms.
77
78 |*)
79
80 Elpi Accumulate lp:{{
81
82 pred age o:person, o:int.
83
84 age mallory 23.
85 age bob 23.
86 age alice 20.
87
88 }}.
89
90 (*|
91
92 The predicate :e:`age` has two arguments, the former is a person while
93 the latter is an integer. The label :e:`o:` (standing for output)
94 is a mode declaration, which we will explain later (ignore it for now).
95
96 .. note:: :stdtype:`int` is the built-in data type of integers
97
98 Integers come with usual arithmetic operators, see the :stdlib:`calc` built-in.
99
100 In order to run our program we have to write a query,
101 i.e. a predicate expression containing variables such as:
102
103 .. code:: elpi
104
105 age alice A
106
107 The execution of the program is expected to assign a value to :e:`A`, which
108 represents the age of :e:`alice`.
109
110 .. important::
111
112 Syntactic conventions:
113
114 * variables are identifiers starting with a capital letter, eg
115 :e:`A`, :e:`B`, :e:`FooBar`, :e:`Foo_bar`, :e:`X1`
116 * constants (for individuals or predicates) are identifiers
117 starting with a lowercase letter, eg
118 :e:`foo`, :e:`bar`, :e:`this_that`, :e:`camelCase`,
119 :e:`dash-allowed`, :e:`qmark_too?`, :e:`arrows->and.dots.as<-well`
120
121 A query can be composed of many predicate expressions separated by :e:`,`
122 that stands for conjunction: we want to get an answer to all the
123 predicate expressions.
124
125 |*)
126
127 Elpi Query lp:{{
128
129 age alice A, coq.say "The age of alice is" A
130
131 }}.
132
133 (*|
134
135 :builtin:`coq.say` is a built-in predicate provided by Coq-Elpi which
136 prints its arguments.
137 You can look at the output buffer of Coq to see the value for :e:`A` or hover
138 or toggle the little bubble after `}}.` if you are reading the tutorial with a
139 web browser.
140
141 .. note:: :stdtype:`string` is a built-in data type
142
143 Strings are delimited by double quotes and ``\`` is the escape symbol.
144
145 The predicate :e:`age` represents a *relation* (in contrast to a function)
146 and it computes both ways: we can ask Elpi which person :e:`P` is 23 years old.
147
148 |*)
149
150 Elpi Query lp:{{
151
152 age P 23, coq.say P "is 23 years old"
153
154 }}.
155
156 (*|
157
158 -----------
159 Unification
160 -----------
161
162 Operationally the query :e:`age P 23` is *unified* with each
163 and every rule present in the program starting from the first one.
164
165 Unification compares two
166 terms structurally and eventually assigns variables.
167 For example for the first rule of the program we obtain
168 the following unification problem:
169
170 .. code:: elpi
171
172 age P 23 = age mallory 23
173
174 This problem can be simplified into smaller unification problems following
175 the structure of the terms:
176
177 .. code:: elpi
178
179 age = age
180 P = mallory
181 23 = 23
182
183 The first and last are trivial, while the second one can be satisfied by
184 assigning :e:`mallory` to :e:`P`. All equations are solved,
185 hence unification succeeds.
186
187 See also the `Wikipedia page on Unification <https://en.wikipedia.org/wiki/Unification_(computer_science)#Syntactic_unification_of_first-order_terms>`_.
188
189 Since the first part of the query is successful the rest of
190 the query is run: the value of :e:`P` is printed as well as
191 the :e:`"is 23 years old"` string.
192
193 .. note:: :e:`=` is a regular predicate
194
195 The query :e:`age P 23` can be also written as follows:
196
197 .. code:: elpi
198
199 A = 23, age P A, Msg = "is 23 years old", coq.say P Msg
200
201
202 Let's try a query harder to solve!
203
204 |*)
205
206 Elpi Query lp:{{
207
208 age P 20, coq.say P "is 20 years old"
209
210 }}.
211
212 (*|
213
214 This time the unification problem for the first rule
215 in the program is:
216
217 .. code:: elpi
218
219 age P 20 = age mallory 23
220
221 that is simplified to:
222
223 .. code:: elpi
224
225 age = age
226 P = mallory
227 20 = 23
228
229 The second equation can be solved by assigning :e:`mallory` to :e:`P`,
230 but the third one has no solution, so unification fails.
231
232 ------------
233 Backtracking
234 ------------
235
236 When failure occurs all assignments are undone (i.e. :e:`P` is unset again)
237 and the next rule in the program is tried. This operation is called
238 *backtracking*.
239
240 The unification problem for the next rule is:
241
242 .. code:: elpi
243
244 age P 20 = age bob 23
245
246 This one also fails. The unification problem for the last rule is:
247
248 .. code:: elpi
249
250 age P 20 = age alice 20
251
252 This one works, and the assignment :e:`P = alice` is kept as the result
253 of the first part of the query. Then :e:`P` is printed and the program
254 ends.
255
256 An even harder query is the following one where we ask for two distinct
257 individuals to have the same age.
258
259 |*)
260
261 Elpi Query lp:{{
262
263 age P A, age Q A, not(P = Q),
264 coq.say P "and" Q "are" A "years old"
265
266 }}.
267
268 (*|
269
270 This example shows that backtracking is global. The first solution for
271 :e:`age P A` and :e:`age Q A` picks :e:`P` and :e:`Q` to
272 be the same individual :e:`mallory`,
273 but then :e:`not(P = Q)` fails and forces the last choice that was made to be
274 reconsidered, so :e:`Q` becomes :e:`bob`.
275
276 Look at the output of the following code to better understand
277 how backtracking works.
278
279 |*)
280
281 Elpi Query lp:{{
282
283 age P A, coq.say "I picked P =" P,
284 age Q A, coq.say "I picked Q =" Q,
285 not(P = Q),
286 coq.say "the last choice worked!",
287 coq.say P "and" Q "are" A "years old"
288
289 }}.
290
291 (*|
292
293 .. note:: :e:`not` is a black hole
294
295 The :e:`not(P)` predicate tries to solve the query :e:`P`: it fails if
296 :e:`P` succeeds, and succeeds if :e:`P` fails. In any case no trace is left
297 of the computation for :e:`P`. E.g. :e:`not(X = 1, 2 < 1)` succeeds, but
298 the assignment for :e:`X` is undone. See also the section
299 about the `foundations`_ of λProlog.
300
301 ---------------------------
302 Facts and conditional rules
303 ---------------------------
304
305 The rules we have seen so far are *facts*: they always hold.
306 In general rules can only be applied if some *condition* holds. Conditions are
307 also called premises, we may use the two terms interchangeably.
308
309 Here we add to our program a rule that defines what :e:`older P Q` means
310 in terms of the :e:`age` of :e:`P` and :e:`Q`.
311
312 .. note:: :e:`:-` separates the *head* of a rule from the *premises*
313
314 |*)
315
316 Elpi Accumulate lp:{{
317
318 pred older o:person, o:person.
319 older P Q :- age P N, age Q M, N > M.
320
321 }}.
322
323 (*|
324
325 The rule reads: :e:`P` is older than :e:`Q` if
326 :e:`N` is the age of :e:`P`
327 *and* :e:`M` is the age of :e:`Q`
328 *and* :e:`N` is greater than :e:`M`.
329
330 Let's run a query using older:
331
332 |*)
333
334 Elpi Query lp:{{
335
336 older bob X,
337 coq.say "bob is older than" X
338
339 }}.
340
341 (*|
342
343 The query :e:`older bob X` is unified with the head of
344 the program rule :e:`older P Q`
345 assigning :e:`P = bob` and :e:`X = Q`. Then three new queries are run:
346
347 .. code:: elpi
348
349 age bob N
350 age Q M
351 N > M
352
353 The former assigns :e:`N = 23`, the second one first
354 sets :e:`Q = mallory` and :e:`M = 23`. This makes the last
355 query to fail, since :e:`23 > 23` is false. Hence the
356 second query is run again and again until :e:`Q` is
357 set to :e:`alice` and :e:`M` to :e:`20`.
358
359 Variables in the query are said to be existentially
360 quantified because Elpi will try to find one
361 possible value for them.
362
363 Conversely, the variables used in rules are
364 universally quantified in the front of the rule.
365 This means that the same program rule can be used
366 multiple times, and each time the variables are fresh.
367
368 In the following example the variable :e:`P` in :e:`older P Q :- ...`
369 once takes :e:`bob` and another time takes :e:`mallory`.
370
371 |*)
372
373 Elpi Query lp:{{
374
375 older bob X, older mallory X,
376 coq.say "both bob and mallory are older than" X
377
378 }}.
379
380 (*|
381 ---------------------------
382 Predicates v.s. functions
383 ---------------------------
384
385 It is often the case that predicates are intended to describe functions,
386 i.e. associate only one "output" to a given "input".
387
388 |*)
389
390 Elpi Program tutorial_functions lp:{{
391
392 kind person type.
393 type mallory, bob, alice person.
394
395 func age person -> int.
396 age mallory 23.
397 age bob 23.
398 age alice 20.
399
400 }}.
401
402 (*|
403
404 The function declaration for :e:`age` separates the domain of the function
405 from the codomain with the :e:`->` symbol: the function associates to each
406 person a single age (or fail if the person has no rule for it).
407
408 After this declaration Elpi refuses to add rules that would break this property:
409
410 |*)
411
412 Fail Elpi Accumulate lp:{{
413 age mallory 24.
414
415 }}. (* .fails *)
416
417 (*|
418
419 In this case it is easy to tell that the two rules overlap: both
420 apply to a query like :e:`age mallory A`.
421
422 In general is not possible to decide if two rules really overlap. For example
423 this legit function is rejected.
424
425 |*)
426
427 Fail Elpi Program tutorial_functions2 lp:{{
428
429 func prime int -> . % code omitted
430
431 func f int -> int.
432 f X Y :- prime X, Y is 2 * X.
433 f 16 Y :- Y is 3 * X.
434
435 }}. (* .fails *)
436
437 (*|
438
439 In order to accept this function Elpi would need to deduce that 16 is not
440 a prime number, and also deduce that :e:`prime` is really implementing a
441 primality test (like proving its code correct, or at least that it would fail
442 on 16).
443
444 In order to have the code accepted by Elpi, as a function, one has to use
445 the cut operator :e:`!` to enforce the following operational reading to the
446 rules: when the cut operator is reached the other rules are discarded.
447
448 |*)
449
450 Elpi Program tutorial_functions3 lp:{{
451
452 func prime int -> . % code omitted
453
454 func f int -> int.
455 f X Y :- prime X, !, Y = 2.
456 f 16 Y :- Y = 4.
457
458 }}.
459
460 (*|
461
462 Elpi accepts the code because:
463
464 * the two rules are mutually exclusive (thanks to the cut)
465 * because the code after the cut is itself a function call
466 (:e:`Y = 2` is a call to unification that is a function)
467
468 The following code is rejected because the second condition does not hold.
469
470 |*)
471
472
473 Fail Elpi Program tutorial_functions4 lp:{{
474
475 func prime int -> . % code omitted
476 pred one_or_two o:int.
477 one_or_two 1.
478 one_or_two 2.
479
480 func f int -> int.
481 f X Y :- prime X, !, one_or_two Y.
482 f 16 Y :- Y = 4.
483
484 }}. (* .fails *)
485
486 (*|
487
488 Since :e:`one_or_two` can produce many results, also :e:`f` can.
489
490 At the same time the code below is accepted.
491
492 |*)
493
494 Elpi Program tutorial_functions5 lp:{{
495
496 func prime int -> .
497 pred one_or_two o:int.
498 one_or_two 1.
499 one_or_two 2.
500
501 func f int -> int.
502 f X Y :- one_or_two Y, !, prime X.
503 f 16 Y :- Y = 4.
504
505 }}.
506
507 (*|
508
509 The reson why it is accepted is because, operationally, the cut
510 operator does not only discard the other rules for the current predicated,
511 but also the (yet to be used) rules for all the predicates that preceeds it.
512 In this case :e:`one_or_two`'s second rule would be discarded, turning the
513 predicate call :e:`one_or_two Y` into a "function" call (committing to the
514 first result given by the predicate :e:`one_or_two`).
515
516 ++++++++++++++++++
517 Modes and matching
518 ++++++++++++++++++
519
520 The syntax
521
522 .. code:: elpi
523
524 func age person -> int.
525
526 desugars to
527
528 .. code:: elpi
529
530 :functional % this is an attribute (a special comment)
531 pred age i:person, o:int.
532
533 that asserts two things. First :e:`age` is expected to behave like a function.
534 Second its first argument is flagged with the *input mode*.
535
536 Query arguments in input mode are *matched* against the rule's corresponding
537 argument that we call a *pattern*.
538 The difference w.r.t. unification is that only variables occurring in the
539 pattern can be assigned. Matching is not symmetric: the pattern and the
540 query argument play different roles, in particular the query argument can
541 only be inspected (destructed) by the pattern, and never assigned (constructed).
542 For example:
543
544 |*)
545
546 Fail Elpi Query tutorial_functions lp:{{
547
548 age P 23
549
550 }}. (* .fails *)
551
552 (*|
553
554 The query fails because :e:`P` (occurring in the query)
555 does not match :e:`bob` nor :e:`mallory`: there is no way to
556 make :e:`P = bob` hold without assigning :e:`P` but that is forbidden by
557 the :e:`i:` directive in the signature of :e:`age`.
558
559 .. note:: Pattern matching API
560
561 As unification is available via the :stdlib:`(=)`, pattern matching
562 is available via :stdlib:`pattern_match`.
563
564 .. code:: elpi
565
566 f 1 = f X % ok
567 f X = f 1 % ok
568 pattern_match (f X) (f 1) % ok
569 pattern_match (f 1) (f X) % ko (the pattern is the first argument)
570
571 The only drawback of marking the first argument of :e:`age` as an imput
572 is that it will prevent to use the predicate in the other direction, e.g. to
573 find any person of age 23. For that one would need a different predicate,
574 since Elpi does not support multiple signatures for the same symbol.
575 We often use the `R` suffix to denote the non-function version of a predicate,
576 for example see :stdlib:`std.append` and :stdlib:`std.appendR`.
577
578 ==================
579 Terms with binders
580 ==================
581
582 So far the syntax of terms is based on constants
583 (eg :e:`age` or :e:`mallory`) and variables (eg :e:`X`).
584
585 λProlog adds another term constructor:
586 λ-abstraction (written :e:`x\ ...`).
587
588 .. note:: the variable name before the ``\`` can be a capital
589
590 Given that it is explicitly bound Elpi needs not to guess if it is a global
591 symbol or a rule variable (that required the convention of using capitals for
592 variables in the first place).
593
594 -------------
595 λ-abstraction
596 -------------
597
598 Functions built using λ-abstraction can be applied
599 to arguments and honor the usual β-reduction rule
600 (the argument is substituted for the bound variable).
601
602 In the following example :e:`F 23` reads, once
603 the β-reduction is performed, :e:`age alice 23`.
604
605 |*)
606
607 Elpi Query tutorial lp:{{
608
609 F = (x\ age alice x),
610 coq.say "F =" F,
611 coq.say "F 20 =" (F 20),
612 coq.say "F 23 =" (F 23)
613
614 }}.
615
616 (*|
617
618 Let's now write the "hello world" of λProlog: an
619 interpreter and type checker for the simply
620 typed λ-calculus. We call this program `stlc`.
621
622 We start by declaring that :e:`term` is a type and
623 that :e:`app` and :e:`fun` are constructors of that type.
624
625 |*)
626
627 Elpi Program stlc lp:{{
628
629 kind term type.
630
631 type app term -> term -> term.
632 type fun (term -> term) -> term.
633
634 }}.
635
636 (*|
637
638 The constructor :e:`app` takes two terms
639 while :e:`fun` only one (of functional type).
640
641 Note that
642
643 * there is no constructor for variables, we will
644 use the notion of bound variable of λProlog in order
645 to represent variables
646 * :e:`fun` takes a function as subterm, i.e. something
647 we can build using the λ-abstraction :e:`x\ ...`
648
649 As a consequence, the identity function λx.x is written like this:
650
651 .. code:: elpi
652
653 fun (x\ x)
654
655 while the first projection λx.λy.x is written:
656
657 .. code:: elpi
658
659 fun (x\ fun (y\ x))
660
661 Another consequence of this approach is that there is no
662 such thing as a free variable in our representation of the λ-calculus.
663 Variables are only available under the λ-abstraction of the
664 programming language, that gives them a well defined scope and
665 substitution operation (β-reduction).
666
667 This approach is called `HOAS <https://en.wikipedia.org/wiki/Higher-order_abstract_syntax>`_.
668
669 We can now implement weak head reduction, that is we stop reducing
670 when the term is a :e:`fun` or a global constant (potentially applied).
671 If the term is :e:`app (fun F) A` then we compute the reduct :e:`F A`.
672 Note that :e:`F` is a λProlog function, so passing an argument to it
673 implements the substitution of the actual argument for the bound variable.
674
675 We first give a type and a mode for our predicate :e:`whd`. It reads
676 "whd takes a term in input and gives a term in output". We will
677 explain what input means precisely later, for now just think about it
678 as a comment.
679
680 |*)
681
682 Elpi Accumulate lp:{{
683
684 pred whd i:term, o:term.
685
686 % when the head "Hd" of an "app" (lication) is a
687 % "fun" we substitute and continue
688 whd (app Hd Arg) Reduct :- whd Hd (fun F), !,
689 whd (F Arg) Reduct.
690
691 % otherwise a term X is already in normal form.
692 whd X Reduct :- Reduct = X.
693
694 }}.
695
696 (*|
697
698 Recall that, due to backtracking, all rules are potentially used.
699 Here whenever the first premise of the first rule succeeds
700 we want the second rule to be skipped, since we found a redex.
701
702 The premises of a rule are run in order and the :e:`!` operator discards all
703 other rules following the current one. Said otherwise it commits to
704 the currently chosen rule for the current query (but leaves
705 all rules available for subsequent queries, they are not erased from the
706 program). So, as soon as :e:`whd Hd (fun F)` succeeds we discard the second
707 rule.
708
709 |*)
710
711 Elpi Query lp:{{
712
713 I = (fun x\x),
714 whd I T, coq.say "λx.x ~>" T,
715 whd (app I I) T1, coq.say "(λx.x) (λx.x) ~>" T1
716
717 }}.
718
719 (*|
720
721 Another little test using global constants:
722
723 |*)
724 Elpi Accumulate lp:{{
725
726 type foo, bar term.
727
728 }}.
729
730 Elpi Query lp:{{
731
732 Fst = fun (x\ fun y\ x),
733 T = app (app Fst foo) bar,
734 whd T T1, coq.say "(Fst foo bar) ~>" T1,
735 S = app foo bar,
736 whd S S1, coq.say "(foo bar) ~>" S1
737
738 }}.
739
740 (*|
741
742 A last test with a lambda term that has no weak head normal form:
743
744 |*)
745
746 Elpi Bound Steps 1000. (* Let's be cautious *)
747 Fail Elpi Query lp:{{
748
749 Delta = fun (x\ app x x),
750 Omega = app Delta Delta,
751 whd Omega Hummm, coq.say "not going to happen"
752
753 }}. (* .fails *)
754 Elpi Bound Steps 0.
755
756 (*|
757
758 -------------------------
759 :e:`pi x\ ` and :e:`==>`
760 -------------------------
761
762 We have seen how to implement substitution using the binders of λProlog.
763 More often than not we need to move under binders rather than remove them by
764 substituting some term in place of the bound variable.
765
766 In order to move under a binder and inspect the body of a function λProlog
767 provides the :e:`pi` quantifier and the :e:`==>` connective.
768
769 A good showcase for these features is to implement a type checker
770 for the simply typed lambda calculus.
771 See also `the Wikipedia page on the simply typed lambda calculus <https://en.wikipedia.org/wiki/Simply_typed_lambda_calculus>`_.
772
773 We start by defining the data type of simple types.
774 We then declare a new predicate :e:`of` (for "type of") and finally
775 we provide two rules, one for each term constructor.
776
777 |*)
778
779 Elpi Accumulate lp:{{
780
781 kind ty type. % the data type of types
782 type arr ty -> ty -> ty. % our type constructor
783
784 pred of i:term, o:ty. % the type checking algorithm
785
786 % for the app node we ensure the head is a function from
787 % A to B, and that the argument is of type A
788 of (app Hd Arg) B :-
789 of Hd (arr A B), of Arg A.
790
791 % for lambda, instead of using a context (a list) of bound
792 % variables we use pi and ==> , explained below
793 of (fun F) (arr A B) :-
794 pi x\ of x A ==> of (F x) B.
795
796 }}.
797
798 (*|
799
800 The :e:`pi name\ code` syntax is reserved, as well as
801 :e:`rule ==> code`.
802
803 Operationally :e:`pi x\ code` introduces a fresh
804 constant :e:`c` for :e:`x` and then runs :e:`code`.
805 Operationally :e:`rule ==> code` adds :e:`rule` to
806 the program and runs :e:`code`. Such extra rule is
807 said to be hypothetical.
808 Both the constant for :e:`x` and :e:`rule` are
809 removed once :e:`code` terminates.
810
811 .. important:: hypothetical rules are added at the *top* of the program
812
813 Hypothetical rules hence take precedence over static rules, since
814 they are tried first.
815
816 Note that in this last example the hypothetical rule is going to be
817 :e:`of c A` for a fixed :e:`A` and a fresh constant :e:`c`.
818 The variable :e:`A` is fixed but not assigned yet, meaning
819 that :e:`c` has a type, and only one, but we may not know it yet.
820
821
822 Now let's assign a type to λx.λy.x:
823
824 |*)
825
826 Elpi Query lp:{{
827
828 of (fun (x\ fun y\ x)) Ty, coq.say "The type of λx.λy.x is:" Ty
829
830 }}.
831
832 (*|
833
834 Let's run this example step by step:
835
836 The rule for :e:`fun` is used:
837
838 * :e:`arrow A1 B1` is assigned to :e:`Ty` by unification
839 * the :e:`pi x\ ` quantifier creates a fresh constant :e:`c1` to play
840 the role of :e:`x`
841 * the :e:`==>` connective adds the rule :e:`of c1 A1` the program
842 * the new query :e:`of (fun y\ c1) B1` is run.
843
844 Again, the rule for :e:`fun` is used (since its variables are
845 universally quantified, we use :e:`A2`, :e:`B2`... this time):
846
847 * :e:`arrow A2 B2` is assigned to :e:`B1` by unification
848 * the :e:`pi x\ ` quantifier creates a fresh constant :e:`c2` to play
849 the role of :e:`x`
850 * the :e:`==>` connective adds the rule :e:`of c2 A2` the program
851 * the new query :e:`of c1 B2` is run.
852
853 The (hypothetical) rule :e:`of c1 A1` is used:
854
855 * unification assigns :e:`A1` to :e:`B2`
856
857 The value of :e:`Ty` is hence :e:`arr A1 (arr A2 A1)`, a good type
858 for λx.λy.x (the first argument and the output have the same type :e:`A1`).
859
860 What about the term λx.(x x) ?
861
862 |*)
863
864 Elpi Query lp:{{
865
866 Delta = fun (x\ app x x),
867 (of Delta Ty ; coq.say "Error:" Delta "has no type")
868
869 }}.
870
871 (*|
872
873 The :e:`;` infix operator stands for disjunction. Since we see the message
874 :e:`of` failed: the term :e:`fun (x\ app x x)` is not well typed.
875
876 First, the rule for elpi:`fun` is selected:
877
878 * :e:`arrow A1 B1` is assigned to :e:`Ty` by unification
879 * the :e:`pi x\ ` quantifier creates a fresh constant :e:`c1` to play the
880 role of :e:`x`
881 * the :e:`==>` connective adds the rule :e:`of c1 A1` the program
882 * the new query :e:`of (app c1 c1) B1` is run.
883
884 Then it's the turn of typing the application:
885
886 * the query :e:`of c1 (arr A2 B2)` assigns to :e:`A1` the
887 value :e:`arr A2 B2`. This means that the
888 hypothetical rule is now :e:`of c1 (arr A2 B2)`.
889 * the query :e:`of c1 A2` fails because the unification
890
891 .. code:: elpi
892
893 of c1 A2 = of c1 (arr A2 B2)
894
895 has no solution, in particular the sub problem :e:`A2 = (arr A2 B2)`
896 fails the so called occur check.
897
898
899 .. _foundations:
900
901 ===================
902 Logical foundations
903 ===================
904
905 This section tries to link, informally, λProlog with logic, assuming the reader
906 has some familiarity with first order intuitionistic logic and proof theory.
907 The reader which is not familiar with that can probably skip this section,
908 although section `functional-style`_ contains some explanations about
909 the scope of variables which are based on the logical foundations of
910 the language.
911
912 The semantics of a λProlog program is given by interpreting
913 it in terms of logical formulas and proof search in intuitionistic logic.
914
915 A rule
916
917 .. code:: elpi
918
919 p A B :- q A C, r C B.
920
921 has to be understood as a formula
922
923 .. math::
924
925 ∀A~B~C, (\mathrm{q}~A~C ∧ \mathrm{r}~C~B) → \mathrm{p}~A~B
926
927 A query is a goal that is proved by backchaining
928 rules. For example :e:`p 3 X`
929 is solved by unifying it with the conclusion of
930 the formula above (that sets :e:`A` to :e:`3`) and
931 generating two new goals, :e:`q 3 C` and
932 :e:`r C B`. Note that :e:`C` is an argument to both
933 :e:`q` and :e:`r` and acts as a link: if solving :e:`q`
934 fixes :e:`C` then the query for :e:`r` sees that.
935 Similarly for :e:`B`, that is identified with :e:`X`,
936 and is hence a link from the solution of :e:`r` to
937 the solution of :e:`p`.
938
939 A rule like:
940
941 .. code:: elpi
942
943 of (fun F) (arr A B) :-
944 pi x\ of x A ==> of (F x) B.
945
946 reads, as a logical formula:
947
948 .. math::
949
950 ∀F~A~B, (∀x, \mathrm{of}~x~A → \mathrm{of}~(F~x)~B) → \mathrm{of}~(\mathrm{fun}~F)~(\mathrm{arr}~A~B)
951
952 where :math:`F` stands for a function.
953 Alternatively, using the inference rule notation typically used for
954 type systems:
955
956 .. math::
957
958 \frac{\Gamma, \mathrm{of}~x~A \vdash \mathrm{of}~(F~x)~B \quad x~\mathrm{fresh}}{\Gamma \vdash \mathrm{of}~(\mathrm{fun}~F)~(\mathrm{arr}~A~B)}
959
960 Hence, :e:`x` and :e:`of x A` are available only
961 temporarily to prove :e:`of (F x) B` and this is
962 also why :e:`A` cannot change during this sub proof (:e:`A` is
963 quantified once and forall outside).
964
965 Each program execution is a proof (tree) of the query
966 and is made of the program rules seen as proof rules or axioms.
967
968 As we hinted before negation is a black hole, indeed the usual definition of
969 :math:`\neg A` as :math:`A \to \bot` is the one of a function with no output
970 (see also the `the Wikipedia page on the Curry-Howard correspondence <https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence#Natural_deduction_and_lambda_calculus>`_).
971
972 =====================
973 Constraints
974 =====================
975
976 Elpi extends λProlog with *syntactic constraints*
977 and rules to manipulate the store of constraints.
978
979 Syntactic constraints are goals suspended on
980 a variable which are resumed as soon as that variable
981 gets instantiated. While suspended they are kept in a store
982 which can be manipulated by dedicated rules.
983
984 A companion facility is the declaration of *modes*.
985 The argument of a predicate can be marked as input
986 to avoid instantiating the goal when it is unified
987 with the head of a rule (an input argument
988 is matched, rather than unified).
989
990 A simple example: Peano's addition:
991
992 |*)
993
994 Elpi Program peano lp:{{
995
996 kind nat type.
997 type z nat.
998 type s nat -> nat.
999
1000 pred add o:nat, o:nat, o:nat.
1001
1002 add (s X) Y (s Z) :- add X Y Z.
1003 add z X X.
1004
1005 }}.
1006
1007 Elpi Query lp:{{
1008
1009 add (s (s z)) (s z) R, coq.say "2 + 1 =" R
1010
1011 }}.
1012
1013 (*|
1014
1015 Unfortunately the relation does not work well
1016 when the first argument is a variable. Depending on the
1017 order of the rules for :e:`add` Elpi can either diverge or pick
1018 :e:`z` as a value for :e:`X` (that may not be what one wants)
1019
1020 |*)
1021
1022 Elpi Bound Steps 100.
1023 Fail Elpi Query lp:{{ add X (s z) Y }}. (* .fails *)
1024 Elpi Bound Steps 0.
1025
1026 (*|
1027
1028 Indeed the first rule for add can be applied forever.
1029 If one exchanges the two rules in the program, then Elpi
1030 terminates picking :e:`z` for :e:`X`.
1031
1032 We can use the mode directive in order to
1033 *match* arguments marked as :e:`i:` against the patterns
1034 in the head of rules, rather than unifying them.
1035
1036 |*)
1037
1038 Elpi Program peano2 lp:{{
1039
1040 kind nat type.
1041 type z nat.
1042 type s nat -> nat.
1043
1044 pred sum i:nat, i:nat, o:nat.
1045
1046 sum (s X) Y (s Z) :- sum X Y Z.
1047 sum z X X.
1048 sum _ _ _ :-
1049 coq.error "nothing matched but for this catch all clause!".
1050
1051 }}.
1052
1053 Fail Elpi Query lp:{{ sum X (s z) Y }}. (* .fails *)
1054
1055 (*|
1056
1057 The query fails because no rule first argument matches :e:`X`.
1058
1059 Instead of failing we can suspend goals and turn them into
1060 syntactic constraints
1061
1062 |*)
1063
1064 Elpi Program peano3 lp:{{
1065
1066 kind nat type.
1067 type z nat.
1068 type s nat -> nat.
1069
1070 func sum nat, nat -> nat.
1071
1072 sum (s X) Y (s Z) :- !, sum X Y Z.
1073 sum z X X :- !.
1074 sum X Y Z :-
1075 % the head of the rule always unifies with the query, so
1076 % we double check X is a variable (we could also be
1077 % here because the other rules failed)
1078 var X,
1079 % then we declare the constraint and schedule its resumption
1080 % on the assignment of X
1081 declare_constraint (sum X Y Z) [X].
1082
1083 }}.
1084
1085 Elpi Query lp:{{ sum X (s z) Z }}.
1086
1087 (*|
1088
1089 Syntactic constraints are resumed when the variable
1090 they are suspended on is assigned:
1091
1092 |*)
1093
1094 Elpi Query lp:{{
1095
1096 sum X (s z) Z, X = z,
1097 coq.say "The result is:" Z
1098
1099 }}.
1100
1101 (*|
1102
1103 Here a couple more examples. Keep in mind that:
1104
1105 * resumption can cause failure
1106 * recall that :e:`;` stands for disjunction
1107
1108 |*)
1109
1110 Fail Elpi Query lp:{{ sum X (s z) (s (s z)), X = z }}. (* .fails *)
1111 Elpi Query lp:{{ sum X (s z) (s (s z)), (X = z ; X = s z) }}.
1112
1113 (*|
1114
1115 In this example the computation suspends, then makes progress,
1116 then suspends again...
1117
1118 |*)
1119
1120 Elpi Query lp:{{
1121
1122 sum X (s z) Y,
1123 print_constraints, coq.say "Currently Y =" Y,
1124 X = s Z,
1125 print_constraints, coq.say "Currently Y =" Y,
1126 Z = z,
1127 coq.say "Finally Y =" Y
1128
1129 }}.
1130
1131 (*|
1132
1133 Sometimes the set of syntactic constraints becomes unsatisfiable
1134 and we would like to be able to fail early.
1135
1136 |*)
1137
1138 Elpi Accumulate lp:{{
1139
1140 func even nat.
1141 func odd nat.
1142
1143 even z :- !.
1144 even (s X) :- !, odd X.
1145 odd (s X) :- !, even X.
1146
1147 odd X :- var X, declare_constraint (odd X) [X].
1148 even X :- var X, declare_constraint (even X) [X].
1149
1150 }}.
1151
1152 Elpi Query lp:{{ even (s X), odd (s X) }}. (* hum, not nice *)
1153
1154 (*|
1155
1156 -------------------------
1157 Constraint Handling Rules
1158 -------------------------
1159
1160 A constraint (handling) rule can see the store of syntactic constraints
1161 as a whole, remove constraints and/or create new goals:
1162
1163 |*)
1164
1165 Elpi Accumulate lp:{{
1166
1167 constraint even odd {
1168 % if two distinct, conflicting, constraints about the same X
1169 % are part of the constraint store
1170 rule (even X) (odd X) <=>
1171 % generate the following goal
1172 (coq.say X "can't be even and odd at the same time", fail).
1173 }
1174
1175 }}.
1176
1177 Fail Elpi Query lp:{{ even (s X), odd (s X) }}. (* .fails *)
1178
1179 (*|
1180
1181 .. note:: :e:`fail` is a predicate with no solution
1182
1183 See also the Wikipedia page on `Constraint Handling Rules <https://en.wikipedia.org/wiki/Constraint_Handling_Rules>`_
1184 for an introduction to the sub language to manipulate constraints.
1185
1186 .. _functional-style:
1187
1188 ================
1189 Functional style
1190 ================
1191
1192 Elpi is a relational language, not a functional one. Still some features
1193 typical of functional programming are available, with some caveats.
1194
1195 -------------------------------
1196 Spilling (relation composition)
1197 -------------------------------
1198
1199 Chaining "relations" can be painful, especially when
1200 they look like functions. Here we use :stdlib:`std.append`
1201 and :stdlib:`std.rev` to build a palindrome:
1202
1203 |*)
1204
1205 Elpi Program function lp:{{
1206
1207 pred make-palindrome i:list A, o:list A.
1208
1209 make-palindrome L Result :-
1210 std.rev L TMP,
1211 std.append L TMP Result.
1212
1213 }}.
1214
1215 Elpi Query lp:{{
1216
1217 make-palindrome [1,2,3] A
1218
1219 }}.
1220
1221 (*|
1222
1223
1224 The :e:`make-palindrome` predicate has to use a temporary variable
1225 just to pass the output of a function as the input to another function.
1226
1227 Spilling is a syntactic elaboration which does that for you.
1228 Expressions between `{` and `}` are
1229 said to be spilled out and placed just before the predicate
1230 that contains them.
1231
1232 *)
1233
1234 Elpi Accumulate lp:{{
1235
1236 pred make-palindrome2 i:list A, o:list A.
1237
1238 make-palindrome2 L Result :-
1239 std.append L {std.rev L} Result.
1240
1241 }}.
1242
1243 Elpi Query lp:{{
1244
1245 make-palindrome2 [1,2,3] A
1246
1247 }}.
1248
1249 (*|
1250
1251 The two versions of :e:`make-palindrome` are equivalent.
1252 Actually the latter is elaborated into the former.
1253
1254 ----------------------
1255 APIs for built-in data
1256 ----------------------
1257
1258 Functions about built-in data types are available via the
1259 :stdlib:`calc` predicate or its infix version :e:`is`. Example:
1260
1261 |*)
1262
1263 Elpi Query lp:{{
1264
1265 calc ( "result " ^ "=" ) X,
1266 Y is 3 + 2,
1267 coq.say X Y
1268
1269 }}.
1270
1271 (*|
1272
1273 The :stdlib:`calc` predicate works nicely with spilling:
1274
1275 |*)
1276
1277 Elpi Query lp:{{ coq.say "result =" {calc (2 + 3)} }}.
1278
1279 (*|
1280
1281 -----------------------
1282 Allocation of variables
1283 -----------------------
1284
1285 The language lets one use λ-abstraction also to write anonymous rules
1286 but one has to be wary of where variables are bound (allocated really).
1287
1288 In our example we use the higher order predicate :stdlib:`std.map`:
1289
1290 .. code:: elpi
1291
1292 pred std.map i:list A, i:(A -> B -> prop), o:list B.
1293
1294 .. note:: :e:`prop` is the type of predicates
1295
1296 The actual type of the :e:`std.map` symbol is:
1297
1298 .. code:: elpi
1299
1300 type std.map list A -> (A -> B -> prop) -> list B -> prop.
1301
1302 The :e:`pred` directive complements a type declaration for predicates
1303 (the trailing :e:`-> prop` is implicit) with a mode declaration for
1304 each argument.
1305
1306 The type of the second argument of :e:`std.map`
1307 is the one of a predicate relating :e:`A` with :e:`B`.
1308
1309 Let's try to call :e:`std.map` passing an anonymous rule (as we
1310 would do in a functional language by passing an anonymous function):
1311
1312 |*)
1313
1314 Elpi Accumulate lp:{{
1315
1316 pred bad i:list int, o:list int.
1317
1318 bad L Result :-
1319 std.map L (x\ r\ TMP is x + 1, r = TMP) Result.
1320
1321 pred good i:list int, o:list int.
1322 good L Result :-
1323 std.map L good.aux Result.
1324 good.aux X R :- TMP is X + 1, R = TMP.
1325
1326 pred good2 i:list int, o:list int.
1327 good2 L Result :-
1328 std.map L (x\ r\ sigma TMP\ TMP is x + 1, r = TMP) Result.
1329
1330 }}.
1331
1332 Elpi Query lp:{{
1333
1334 not(bad [1,2,3] R1),
1335 good [1,2,3] R2,
1336 good2 [1,2,3] R3
1337
1338 }}.
1339
1340 (*|
1341
1342 The problem with :e:`bad` is that :e:`TMP` is fresh each time the rule
1343 is used, but not every time the anonymous rule passed to :stdlib:`map`
1344 is used. Technically :e:`TMP` is quantified (allocated) where :e:`L`
1345 and :e:`Result` are.
1346
1347 There are two ways to quantify :e:`TMP` correctly, that is inside the
1348 anonymous predicate. One is to actually name the predicate. Another one is
1349 to use the :e:`sigma x\ ` quantifier to allocate :e:`TMP` at every call.
1350 We recommend to name the auxiliary predicate.
1351
1352 .. tip:: predicates whose name ends in `.aux` don't trigger a missing type
1353 declaration warning
1354
1355 One last way to skin the cat is to use :e:`==>` as follows. It gives us
1356 the occasion to clarify further the scope of variables.
1357
1358 |*)
1359
1360 Elpi Accumulate lp:{{
1361
1362 pred good3 i:list int, o:list int.
1363 good3 L Result :-
1364 pi aux\
1365 (pi TMP X R\ aux X R :- TMP is X + 1, R = TMP) ==>
1366 std.map L aux Result.
1367
1368 }}.
1369
1370 Elpi Query lp:{{
1371
1372 good3 [1,2,3] R
1373
1374 }}.
1375
1376 (*|
1377
1378 In this case the auxiliary predicate :e:`aux`
1379 is only visible inside :e:`good3`.
1380 What is interesting to remark is that the quantifications are explicit
1381 in the hypothetical rule, and they indicate clearly that each and every
1382 time :e:`aux` is used :e:`TMP`, :e:`X` and :e:`R` are fresh.
1383
1384 The :e:`pi x\ ` quantifier is dual to :e:`sigma x\ `: since here it
1385 occurs negatively it has the same meaning. That is, the hypothetical rule
1386 could be written :e:`pi X R\ aux X R :- sigma TMP\ TMP is X + 1, R = TMP`.
1387
1388 .. tip:: :e:`pi x\ ` and :e:`sigma x\ ` can quantify on a bunch of variables
1389 at once
1390
1391 That is, :e:`pi x y\ ...` is equivalent to :e:`pi x\ pi y\ ...` and
1392 :e:`sigma x y\ ...` is equivalent to :e:`sigma x\ sigma y\ ...`.
1393
1394 .. tip:: :e:`==>` can load more than one clause at once
1395
1396 It is sufficient to put a list on the left hand side, eg :e:`[ rule1, rule2 ] ==> code`.
1397 Moreover one can synthesize a rule before loading it, eg:
1398
1399 .. code:: elpi
1400
1401 Rules = [ one-more-rule | ExtraRules ], Rules ==> code
1402
1403 The last remark worth making is that bound variables are intimately related
1404 to universal quantification, while unification variables are related to
1405 existential quantification. It goes without saying that the following
1406 two formulas are not equivalent and while the former is trivial the latter
1407 is in general false:
1408
1409 .. math::
1410
1411 ∀x, ∃Y, Y = x\\
1412 ∃Y, ∀x, Y = x
1413
1414 Let's run these two corresponding queries:
1415
1416 |*)
1417
1418 Elpi Query lp:{{ pi x\ sigma Y\ Y = x, coq.say "Y =" Y }}.
1419 Fail Elpi Query lp:{{ sigma Y\ pi x\ Y = x, coq.say "Y =" Y }}. (* .fails *)
1420
1421 (*|
1422
1423 Another way to put it: :e:`x` is in the scope of :e:`Y` only in the first
1424 formula since it is quantified before it. Hence :e:`x` can be assigned to
1425 :e:`Y` in that case, but not in the second query, where it is quantified
1426 after.
1427
1428 More in general, λProlog tracks the bound variables that are in scope of each
1429 unification variable. There are only two ways to put a bound variable
1430 in the scope:
1431
1432 * quantify the unification variable under the bound one (first formula)
1433 * pass the bound variable to the unification variable explicitly: in this
1434 case the unification variable needs to have a functional type.
1435 Indeed :math:`∃Y, ∀x, (Y x) = x` has a solution: :e:`Y` can be
1436 the identity function.
1437
1438 .. coq::
1439
1440 Elpi Query lp:{{ sigma Y\ pi x\ Y x = x, coq.say "Y =" Y }}.
1441
1442 If we look again at the rule for type checking
1443 λ-abstraction:
1444
1445 .. code:: elpi
1446
1447 of (fun F) (arr A B) :-
1448 pi x\ of x A ==> of (F x) B.
1449
1450 we can see that the only unification variable that sees the fresh
1451 `x` is :e:`F`, because we pass :e:`x` to :e:`F` explicitly
1452 (recall all unification variables such as :e:`F`, :e:`A`, :e:`B` are
1453 quantified upfront, before the :e:`pi x\ `).
1454 Indeed when we write:
1455
1456 .. math::
1457
1458 \frac{\Gamma, x : A \vdash f : B}{\Gamma \vdash λx.f : A → B}
1459
1460 on paper, the variable denoted by :e:`x` being bound there can only occur in
1461 :math:`f`, not in :math:`\Gamma` or :math:`B` for example (although a
1462 *different* variable could be named the same, hence the usual freshness side
1463 conditions which are not really necessary using HOAS).
1464
1465 Remark that in the premise the variable :math:`x` is still bound, this time
1466 not by a λ-abstraction but by the context :math:`\Gamma, x : A`.
1467 In λProlog the context is the set of hypothetical rules and :e:`pi\ `
1468 -quantified variables and is implicitly handled by the runtime of the
1469 programming language.
1470
1471 A slogan to keep in mind is that:
1472
1473 .. important:: There is no such thing as a free variable!
1474
1475 Indeed the variable bound by the λ-abstraction (of our data) is
1476 replaced by a fresh variable bound by the context (of our program). This is
1477 called binder mobility. See also the paper
1478 `Mechanized metatheory revisited <https://hal.inria.fr/hal-01884210/>`_ by
1479 Dale Miller which is an excellent
1480 introduction to these concepts.
1481
1482 =========
1483 Debugging
1484 =========
1485
1486 The most sophisticated debugging feature can be used via
1487 the Visual Studio Code extension ``gares.elpi-lang`` and its
1488 ``Elpi Tracer`` tab.
1489
1490 ---------------
1491 Trace browser
1492 ---------------
1493
1494 In order to generate a trace one needs to execute the
1495 ``Elpi Trace Browser.`` command and then run any Elpi code.
1496
1497 |*)
1498
1499 (* Elpi Trace Browser. *)
1500
1501 Elpi Query stlc lp:{{ % We run the query in the stlc program
1502
1503 of (fun (x\ fun y\ x)) Ty, coq.say Ty
1504
1505 }}.
1506
1507 (*|
1508
1509 The trace file is generated in ``/tmp/traced.tmp.json``.
1510 If it does not load automatically one can do it manually by clicking on
1511 the load icon, in the upper right corner of the Elpi Tracer panel.
1512
1513 .. note:: partial display of goals
1514
1515 At the time of writing one may need to disable syntax highlighting in
1516 the extension settings in order to get a correct display.
1517
1518 The trace browser displays, on the left column, a list of cards corresponding
1519 to a step performed by the interpreter. The right side of the
1520 panel gives more details about the selected step. In the image below one
1521 can see the goal, the rule being applied, the assignments performed by the
1522 unification of the rule's head with the goal, the subgoals generated.
1523
1524 .. image:: tracer.png
1525 :width: 800
1526
1527 One can also look at the trace in text format (if VSCode is not an option,
1528 for example).
1529
1530 |*)
1531 Elpi Trace.
1532
1533 Elpi Query stlc lp:{{ % We run the query in the stlc program
1534
1535 of (fun (x\ fun y\ x)) Ty, coq.say Ty
1536
1537 }}.
1538
1539 Fail Elpi Query stlc lp:{{
1540
1541 of (fun (x\ app x x)) Ty, coq.say Ty
1542
1543 }}. (* .fails *)
1544
1545 (*|
1546
1547 The trace can be limited to a range of steps. Look at the
1548 numbers ``run HERE {{{``.
1549
1550 |*)
1551
1552 Elpi Trace 6 8.
1553 Elpi Query stlc lp:{{
1554
1555 of (fun (x\ fun y\ x)) Ty, coq.say Ty
1556
1557 }}.
1558
1559 (*|
1560
1561 The trace can be limited to a (list of) predicates as follows:
1562
1563 |*)
1564
1565 Elpi Trace "of".
1566 Elpi Query stlc lp:{{
1567
1568 of (fun (x\ fun y\ x)) Ty, coq.say Ty
1569
1570 }}.
1571
1572 (*|
1573
1574 One can combine the range of steps with the predicate:
1575
1576 |*)
1577
1578 Elpi Trace 6 8 "of".
1579 Elpi Query stlc lp:{{
1580
1581 of (fun (x\ fun y\ x)) Ty, coq.say Ty
1582
1583 }}.
1584
1585 (*|
1586
1587 To switch traces off:
1588
1589 |*)
1590
1591 Elpi Trace Off.
1592
1593 (*|
1594
1595 ---------------
1596 Good old print
1597 ---------------
1598
1599 A common λProlog idiom is to have a debug rule
1600 lying around. The :e:`:if` attribute can be used to
1601 make the rule conditionally interpreted (only if the
1602 given debug variable is set).
1603
1604 |*)
1605
1606 Elpi Debug "DEBUG_MYPRED".
1607 Elpi Program debug lp:{{
1608
1609 pred mypred i:int.
1610
1611 :if "DEBUG_MYPRED"
1612 mypred X :-
1613 coq.say "calling mypred on " X, fail.
1614
1615 mypred 0 :- coq.say "ok".
1616 mypred M :- N is M - 1, mypred N.
1617
1618 }}.
1619 Elpi Query lp:{{ mypred 3 }}.
1620
1621 (*|
1622
1623 ------------------------
1624 Printing entire programs
1625 ------------------------
1626
1627 Given that programs are not written in a single place, but rather obtained by
1628 accumulating code, Elpi is able to print a (full) program to an text file
1629 as follows. The obtained file provides a facility to filter rules by their
1630 predicate. Note that the first component of the path is a Coq Load Path (i.e.
1631 coqc options -R and -Q), the text file will be placed in the directory
1632 bound to it.
1633
1634 |*)
1635
1636 Elpi Print stlc "elpi_examples/stlc".
1637
1638 (*|
1639
1640 -----------------------------
1641 Bounding the number of steps
1642 -----------------------------
1643
1644 Finally, one can bound the number of backchaining steps
1645 performed by the interpreter:
1646
1647 |*)
1648
1649 Elpi Query lp:{{ 0 = 0, 1 = 1 }}.
1650 Elpi Bound Steps 1.
1651 Fail Elpi Query lp:{{ 0 = 0, 1 = 1 }}. (* .fails *) (* it needs 2 steps! *)
1652 Elpi Bound Steps 0. (* Go back to no bound *)
1653
1654 (*|
1655
1656 ===================
1657 Pitfalls and tricks
1658 ===================
1659
1660 Well, no programming language is perfect.
1661
1662 ---------------------------------------------
1663 Precedence of :e:`,`, :e:`==>` and :e:`=>`
1664 ---------------------------------------------
1665
1666 In this tutorial we only used :e:`==>` but Elpi also provides
1667 the standard λProlog implication :e:`=>`. They have the same meaning
1668 but different precedences w.r.t. :e:`,`.
1669
1670 The code :e:`a, c ==> d, e` reads :e:`a, (c ==> (d,e))`, that means that
1671 the rule :e:`c` is available to both :e:`d` and :e:`e`.
1672
1673 On the contrary the code :e:`a, c => d, e` reads :e:`a, (c ==> d), e`,
1674 making :e:`c` only available to :e:`d`.
1675
1676 So, :e:`=>` binds stronger than :e:`,`, while :e:`==>` binds stronger only
1677 on the left.
1678
1679 According to our experience the precedence of :e:`=>` is a common source
1680 of mistakes for beginners, if only because it is not stable by adding of
1681 debug prints, that is :e:`a => b` and :e:`a => print "doing b", b` have
1682 very different meaning (:e:`a` becomes only available to `print`!).
1683
1684 In this tutorial we only used :e:`==>` that was introduced in Elpi 2.0, but
1685 there is code out there using :e:`=>`. Elpi 2.0 raises a warning if the
1686 right hand side of :e:`=>` is a conjenction with no parentheses.
1687
1688 A concrete example:
1689
1690 |*)
1691
1692 Fail Elpi Query stlc lp:{{
1693
1694 pi x\
1695 of x A => of x B, of x C
1696
1697 }}. (* .fails *)
1698
1699 Elpi Query stlc lp:{{
1700
1701 pi x\
1702 of x A => (of x B, of x C) % both goals see of x A
1703
1704 }}.
1705
1706 Elpi Query stlc lp:{{
1707
1708 pi x\
1709 of x A ==> of x B, of x C
1710
1711 }}.
1712
1713
1714 (*|
1715
1716 -------------------------------------------------
1717 The :e:`=!=>` operator and functional predicates
1718 -------------------------------------------------
1719
1720 When an hypothetical rule is added to a functional predicate the determinacy
1721 may fail to detect its mutual exclusiveness, especially if the rule is
1722 generated dynamically as below:
1723
1724 .. code:: elpi
1725
1726 X = f P, X ==> q % static error, X could be anything
1727
1728 Elpi 3.0 provides the :e:`=!=>` connective that adds a tail cut to the
1729 hypothetical rule, be it explicitly given or computed at run time. For example:
1730
1731 .. code:: elpi
1732
1733 (f P :- !) ==> q % fine, new rule for f cuts all the others, f still a function
1734 f P =!=> q % desugars to the above
1735
1736 (f P :- h P, !) ==> q % fine as before
1737 (f P :- h P) =!=> q % desugars to the above
1738
1739 X = f P, X =!=> q % at run time it evaluates as below
1740 X = f P, X' = (X :- !), X' ==> q
1741
1742 X = (f P :- h P), X =!=> q % at run time it evaluates as below
1743 X = f P, X' = (X :- h P, !), X' ==> q
1744
1745 --------------------
1746 Taming backtracking
1747 --------------------
1748
1749
1750 Backtracking can lead to weird execution traces and bad performances.
1751 The main tool to eliminate backtracking is the cut operator, but one
1752 may forget to use it. Elpi provides two mechanisms to help with that.
1753
1754 The former one is functional predicates: by declaring a predicate as
1755 functional one is typically forced to use cut. This is the recommended
1756 way of writing code since Elpi 3.0.
1757
1758 The latter mechanism is the e :stdlib:`std.do!` predicate that can
1759 be used as follows.
1760
1761 .. code:: elpi
1762
1763 pred not-a-backtracking-one.
1764 not-a-backtracking-one :- condition, !, std.do! [
1765 step,
1766 (generate, test),
1767 step,
1768 ].
1769
1770 In the example above once :e:`condition` holds we start a sequence of
1771 steps which we will not reconsider. Locally, backtracking is still
1772 available, e.g. between :e:`generate` and :e:`test`.
1773
1774 See also the :stdlib:`std.spy-do!` predicate which prints each and every step,
1775 and the :stdlib:`std.spy` one which can be used to spy on a single one.
1776
1777 -----------------------------------------------
1778 Unification variables v.s. Imperative variables
1779 -----------------------------------------------
1780
1781 Unification variables sit in between variables in imperative programming and
1782 functional programming. In imperative programming a variable can hold a value,
1783 and that value can change over time via assignment. In functional languages
1784 variables always hold a value, and that value never changes. In logic programming
1785 a unification variable can either be unset (no value) or set to a value that
1786 never changes. Backtracking goes back in time, it is not visible to the program.
1787
1788 As a result of this, code like
1789
1790 .. code:: elpi
1791
1792 pred bad-example.
1793 bad-example :- X is 1 + 2, X is 4 + 5.
1794
1795 fails, because :e:`X` cannot be at the same time 3 and 9. Initially
1796 :e:`X` is unset, then it is set to 3, and finally the programmer is
1797 asserting that 3 (the value hold by :e:`X`) is equal to 9.
1798 The second call to :e:`is` does not change the value carried by :e:`X`!
1799
1800 Unification, and hence the :e:`=` predicate, plays two roles.
1801 When :e:`X` is unset, :e:`X = v` sets the variable.
1802 When :e:`X` is set to :e:`u`, :e:`X = v` checks if the value
1803 of :e:`X` is equal to :e:`u`: it is equivalent to :e:`u = v`.
1804
1805 ===============
1806 Further reading
1807 ===============
1808
1809 The `λProlog website <http://www.lix.polytechnique.fr/~dale/lProlog/>`_
1810 contains useful links to λProlog related material.
1811
1812 Papers and other documentation about Elpi can be found at
1813 the `Elpi home on github <https://github.com/LPCIC/elpi/>`_.
1814
1815 Three more tutorials specific to Elpi as an extension language for Coq
1816 can be found in the `examples folder <https://github.com/LPCIC/coq-elpi/blob/master/examples/>`_.
1817 You can continue by reading the one about the
1818 `HOAS for Coq terms <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_HOAS.html>`_.
1819
1820 |*)
1821
1822