| 1 |
(*| |
| 2 |
|
| 3 |
Tutorial on Coq commands |
| 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 |
This tutorial assumes the reader is familiar with Elpi and the HOAS |
| 31 |
representation of Coq terms; if it is not the case, please take a look at |
| 32 |
these other tutorials first: |
| 33 |
`Elpi tutorial <https://lpcic.github.io/coq-elpi/tutorial_elpi_lang.html>`_ |
| 34 |
and |
| 35 |
`Coq HOAS tutorial <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_HOAS.html>`_. |
| 36 |
|
| 37 |
.. contents:: |
| 38 |
|
| 39 |
================= |
| 40 |
Defining commands |
| 41 |
================= |
| 42 |
|
| 43 |
Let's create a simple command, called "hello", which prints :e:`"Hello"` |
| 44 |
followed by the arguments we pass to it: |
| 45 |
|
| 46 |
|*) |
| 47 |
Set Warnings "-elpi.linear-variable". (* .none *) |
| 48 |
From elpi Require Import elpi. |
| 49 |
|
| 50 |
Elpi Command hello. |
| 51 |
Elpi Accumulate lp:{{ |
| 52 |
|
| 53 |
% main is, well, the entry point |
| 54 |
main Arguments :- coq.say "Hello" Arguments. |
| 55 |
|
| 56 |
}}. |
| 57 |
|
| 58 |
|
| 59 |
(*| |
| 60 |
|
| 61 |
The program declaration is made of 3 parts. |
| 62 |
|
| 63 |
The first one `Elpi Command hello.` sets the current program to hello. |
| 64 |
Since it is declared as a `Command` some code is loaded automatically: |
| 65 |
|
| 66 |
* APIs (eg :builtin:`coq.say`) and data types (eg Coq :type:`term` s) are loaded from |
| 67 |
`coq-builtin.elpi <https://github.com/LPCIC/coq-elpi/blob/master/builtin-doc/coq-builtin.elpi>`_ |
| 68 |
* some utilities, like :lib:`copy` or :libred:`whd1` are loaded from |
| 69 |
`elpi-command-template.elpi <https://github.com/LPCIC/coq-elpi/blob/master/elpi/elpi-command-template.elpi>`_ |
| 70 |
|
| 71 |
|
| 72 |
The second one `Elpi Accumulate ...` loads some extra code. |
| 73 |
The `Elpi Accumulate ...` family of commands lets one accumulate code |
| 74 |
taken from: |
| 75 |
|
| 76 |
* verbatim text `Elpi Accumulate lp:{{ code }}` |
| 77 |
* source files `Elpi Accumulate File path` |
| 78 |
* data bases (Db) `Elpi Accumulate Db name` |
| 79 |
|
| 80 |
Accumulating code via inline text or file is equivalent, the AST of `code` |
| 81 |
is stored in the .vo file (the external file does not need to be installed). |
| 82 |
We postpone the description of data bases to a dedicated section. |
| 83 |
|
| 84 |
When some code is accumulated Elpi verifies that the |
| 85 |
code does not contain the most frequent kind of mistakes, via some |
| 86 |
type checking and linting. Some mistakes are minor and Elpi only warns about |
| 87 |
them. You can pass `-w +elpi.typecheck` to `coqc` to turn these warnings into |
| 88 |
errors. |
| 89 |
|
| 90 |
We can now run our program! |
| 91 |
|
| 92 |
|*) |
| 93 |
|
| 94 |
Elpi hello "world!". |
| 95 |
|
| 96 |
(*| |
| 97 |
|
| 98 |
You should see the following output (hover the bubble next to the |
| 99 |
code if you are reading this online): |
| 100 |
|
| 101 |
.. mquote:: .s(Elpi hello).msg(str world) |
| 102 |
:language: text |
| 103 |
|
| 104 |
The string `"world!"` we passed to the command is received by the code |
| 105 |
as :e:`(str "world!")`. |
| 106 |
|
| 107 |
.. note:: :builtin:`coq.say` won't print quotes around strings |
| 108 |
|
| 109 |
================= |
| 110 |
Command arguments |
| 111 |
================= |
| 112 |
|
| 113 |
Let's pass different kind of arguments to `hello`: |
| 114 |
|
| 115 |
|*) |
| 116 |
|
| 117 |
Elpi hello 46. |
| 118 |
Elpi hello there. |
| 119 |
|
| 120 |
(*| |
| 121 |
|
| 122 |
This time we passed to the command a number and an identifier. |
| 123 |
Identifiers are received as strings, and can contain dots, but no spaces. |
| 124 |
|
| 125 |
|*) |
| 126 |
|
| 127 |
Elpi hello my friend. |
| 128 |
Elpi hello this.is.a.qualified.name. |
| 129 |
|
| 130 |
(*| |
| 131 |
|
| 132 |
Indeed the first invocation passes two arguments, of type string, while |
| 133 |
the second a single one, again a string containing dots. |
| 134 |
|
| 135 |
There are a few more types of arguments a command can receive: |
| 136 |
|
| 137 |
* terms, delimited by `(` and `)` |
| 138 |
* toplevel declarations, like `Inductive ..`, `Definition ..`, etc.. |
| 139 |
which are introduced by their characterizing keyword. |
| 140 |
|
| 141 |
Let's try with a term. |
| 142 |
|
| 143 |
|*) |
| 144 |
|
| 145 |
Elpi hello (0 = 1). |
| 146 |
|
| 147 |
(*| |
| 148 |
|
| 149 |
Since Coq-Elpi 1.15, terms are received in elaborated form, meaning |
| 150 |
that the elaborator of Coq is used to pre-process them. |
| 151 |
In the example above the type argument to `eq` has |
| 152 |
been synthesized to be `nat`. |
| 153 |
|
| 154 |
|*) |
| 155 |
|
| 156 |
Elpi hello Definition test := 0 = 1. |
| 157 |
Elpi hello Record test := { f1 : nat; f2 : f1 = 1 }. |
| 158 |
|
| 159 |
(*| |
| 160 |
|
| 161 |
Global declarations are received in elaborated form as well. |
| 162 |
In the case of `Definition test` the optional body (would be |
| 163 |
:e:`none` for an `Axiom` declaration) is present |
| 164 |
while the omitted type is inferred (to be `Prop`). |
| 165 |
|
| 166 |
In the case of the `Record` declaration remark that each field has a few |
| 167 |
attributes, like being a coercions (the `:>` in Coq's syntax). Also note that |
| 168 |
the type of the record (which was omitted) defaults to `Type`. |
| 169 |
Finally note that the type of the second field |
| 170 |
sees :e:`c0` (the value of the first field). |
| 171 |
|
| 172 |
See the :type:`argument` data type |
| 173 |
for a detailed description of all the arguments a command can receive. |
| 174 |
|
| 175 |
------------------------ |
| 176 |
Processing raw arguments |
| 177 |
------------------------ |
| 178 |
|
| 179 |
It is sometimes useful to receive arguments in raw format, |
| 180 |
so that no elaboration has been performed. |
| 181 |
This can be achieved by using the |
| 182 |
`#[arguments(raw)]` attributed when the command is declared. |
| 183 |
|
| 184 |
Then, there are two ways to process term arguments: |
| 185 |
typechecking and elaboration. |
| 186 |
|
| 187 |
|*) |
| 188 |
|
| 189 |
#[arguments(raw)] Elpi Command check_arg. |
| 190 |
Elpi Accumulate lp:{{ |
| 191 |
|
| 192 |
main [trm T] :- |
| 193 |
std.assert-ok! (coq.typecheck T Ty) "argument illtyped", |
| 194 |
coq.say "The type of" T "is" Ty. |
| 195 |
|
| 196 |
}}. |
| 197 |
|
| 198 |
|
| 199 |
Elpi check_arg (1 = 0). |
| 200 |
Fail Elpi check_arg (1 = true). (* .fails *) |
| 201 |
|
| 202 |
(*| |
| 203 |
|
| 204 |
The command `check_arg` receives a term :e:`T` and type checks it, then it |
| 205 |
prints the term and its type. |
| 206 |
|
| 207 |
The :builtin:`coq.typecheck` API has 3 arguments: a term, its type and a |
| 208 |
:stdtype:`diagnostic` which can either be :e:`ok` or :e:`(error Message)`. |
| 209 |
The :stdlib:`assert-ok!` combinator checks if the diagnostic is :e:`ok`, |
| 210 |
and if not it prints the error message and bails out. |
| 211 |
|
| 212 |
The first invocation succeeds while the second one fails and prints |
| 213 |
the type checking error (given by Coq) following the string passed to |
| 214 |
:e:`std.assert-ok!`. |
| 215 |
|
| 216 |
|*) |
| 217 |
|
| 218 |
Coercion bool2nat (b : bool) := if b then 1 else 0. |
| 219 |
Fail Elpi check_arg (1 = true). (* .fails *) |
| 220 |
Check (1 = true). |
| 221 |
|
| 222 |
(*| |
| 223 |
|
| 224 |
The command still fails even if we told Coq how to inject booleans values |
| 225 |
into the natural numbers. Indeed the `Check` commands works. |
| 226 |
|
| 227 |
The call to :builtin:`coq.typecheck` modifies the term in place, it can assign |
| 228 |
implicit arguments (like the type parameter of `eq`) but it cannot modify the |
| 229 |
structure of the term. To do so, one has to use the |
| 230 |
:builtin:`coq.elaborate-skeleton` API. |
| 231 |
|
| 232 |
|*) |
| 233 |
|
| 234 |
#[arguments(raw)] |
| 235 |
Elpi Command elaborate_arg. |
| 236 |
Elpi Accumulate lp:{{ |
| 237 |
|
| 238 |
main [trm T] :- |
| 239 |
std.assert-ok! (coq.elaborate-skeleton T Ty T1) "illtyped arg", |
| 240 |
coq.say "T=" T, |
| 241 |
coq.say "T1=" T1, |
| 242 |
coq.say "Ty=" Ty. |
| 243 |
|
| 244 |
}}. |
| 245 |
|
| 246 |
|
| 247 |
Elpi elaborate_arg (1 = true). |
| 248 |
|
| 249 |
(*| |
| 250 |
|
| 251 |
Remark how :e:`T` is not touched by the call to this API, and how :e:`T1` |
| 252 |
is a copy of :e:`T` where the hole after `eq` is synthesized and the value |
| 253 |
`true` injected to `nat` by using `bool2nat`. |
| 254 |
|
| 255 |
It is also possible to manipulate term arguments before typechecking |
| 256 |
them, but note that all the considerations on holes in the tutorial about |
| 257 |
the HOAS representation of Coq terms apply here. An example of tool |
| 258 |
taking advantage of this possibility is Hierarchy Builder: the declarations |
| 259 |
it receives would not typecheck in the current context, but do once the |
| 260 |
context is temporarily augmented with ad-hoc canonical structure instances. |
| 261 |
|
| 262 |
======== |
| 263 |
Examples |
| 264 |
======== |
| 265 |
|
| 266 |
------------------- |
| 267 |
Synthesizing a term |
| 268 |
------------------- |
| 269 |
|
| 270 |
Synthesizing a term typically involves reading an existing declaration |
| 271 |
and writing a new one. The relevant APIs are in the `coq.env.*` namespace |
| 272 |
and are named after the global reference they manipulate, eg :builtin:`coq.env.const` |
| 273 |
for reading and :builtin:`coq.env.add-const` for writing. |
| 274 |
|
| 275 |
Here we implement a little command that given an inductive type name |
| 276 |
generates a term of type `nat` whose value is the number of constructors |
| 277 |
of the given inductive type. |
| 278 |
|
| 279 |
|*) |
| 280 |
|
| 281 |
Elpi Command constructors_num. |
| 282 |
|
| 283 |
Elpi Accumulate lp:{{ |
| 284 |
|
| 285 |
pred int->nat i:int, o:term. |
| 286 |
int->nat 0 {{ 0 }}. |
| 287 |
int->nat N {{ S lp:X }} :- M is N - 1, int->nat M X. |
| 288 |
|
| 289 |
main [str IndName, str Name] :- |
| 290 |
std.assert! (coq.locate IndName (indt GR)) "not an inductive type", |
| 291 |
coq.env.indt GR _ _ _ _ Kn _, % the names of the constructors |
| 292 |
std.length Kn N, % count them |
| 293 |
int->nat N Nnat, % turn the integer into a nat |
| 294 |
coq.env.add-const Name Nnat _ _ _. % save it |
| 295 |
|
| 296 |
}}. |
| 297 |
|
| 298 |
|
| 299 |
Elpi constructors_num bool nK_bool. |
| 300 |
Print nK_bool. |
| 301 |
|
| 302 |
Elpi constructors_num False nK_False. |
| 303 |
Print nK_False. |
| 304 |
|
| 305 |
Fail Elpi constructors_num plus nK_plus. (* .fails *) |
| 306 |
Fail Elpi constructors_num not_there bla. (* .fails *) |
| 307 |
|
| 308 |
(*| |
| 309 |
|
| 310 |
The command starts by locating the first argument and asserting it points to |
| 311 |
an inductive type. This line is idiomatic: :builtin:`coq.locate` aborts if |
| 312 |
the string cannot be located, and if it relates it to a :e:`gref` which is not |
| 313 |
:e:`indt` (for example :e:`const plus`) :stdlib:`assert!` aborts with the given |
| 314 |
error message. |
| 315 |
|
| 316 |
:builtin:`coq.env.indt` lets one access all the details of an inductive type, |
| 317 |
here we just use the list of constructors. |
| 318 |
The twin API :builtin:`coq.env.indt-decl` lets |
| 319 |
one access the declaration of the inductive in HOAS form, which might be |
| 320 |
easier to manipulate in other situations, like the next example. |
| 321 |
|
| 322 |
Then the program crafts a natural number and declares a constant for it. |
| 323 |
|
| 324 |
------------------------ |
| 325 |
Abstracting an inductive |
| 326 |
------------------------ |
| 327 |
|
| 328 |
For the sake of introducing :lib:`copy`, the swiss army knife of λProlog, we |
| 329 |
write a command which takes an inductive type declaration and builds a new |
| 330 |
one abstracting the former one on a given term. The new inductive has a |
| 331 |
parameter in place of the occurrences of that term. |
| 332 |
|
| 333 |
|*) |
| 334 |
|
| 335 |
Elpi Command abstract. |
| 336 |
|
| 337 |
Elpi Accumulate lp:{{ |
| 338 |
|
| 339 |
% a renaming function which adds a ' to an ident (a string) |
| 340 |
pred prime i:id, o:id. |
| 341 |
prime S S1 :- S1 is S ^ "'". |
| 342 |
|
| 343 |
pred id i:id, o:id. |
| 344 |
id X X. |
| 345 |
|
| 346 |
main [str Ind, trm Param] :- |
| 347 |
|
| 348 |
% the term to be abstracted out, P of type PTy |
| 349 |
std.assert-ok! |
| 350 |
(coq.elaborate-skeleton Param PTy P) |
| 351 |
"illtyped parameter", |
| 352 |
|
| 353 |
% fetch the old declaration |
| 354 |
std.assert! (coq.locate Ind (indt I)) "not an inductive type", |
| 355 |
coq.env.indt-decl I Decl, |
| 356 |
|
| 357 |
% let's start to craft the new declaration by putting a |
| 358 |
% parameter A which has the type of P |
| 359 |
(NewDecl : indt-decl) = parameter "A" explicit PTy Decl', |
| 360 |
|
| 361 |
% let's make a copy, capturing all occurrences of P with a |
| 362 |
% (which stands for the parameter) |
| 363 |
(pi a\ (copy P a :- !) ==> copy-indt-decl Decl (Decl' a)), |
| 364 |
|
| 365 |
% to avoid name clashes, we rename the type and its constructors |
| 366 |
% (we don't need to rename the parameters) |
| 367 |
coq.rename-indt-decl id prime prime NewDecl DeclRenamed, |
| 368 |
|
| 369 |
% we type check the inductive declaration, since abstracting |
| 370 |
% random terms may lead to illtyped declarations (type theory |
| 371 |
% is hard) |
| 372 |
std.assert-ok! |
| 373 |
(coq.typecheck-indt-decl DeclRenamed) |
| 374 |
"can't be abstracted", |
| 375 |
|
| 376 |
coq.env.add-indt DeclRenamed _. |
| 377 |
|
| 378 |
}}. |
| 379 |
|
| 380 |
|
| 381 |
Inductive tree := leaf | node : tree -> option nat -> tree -> tree. |
| 382 |
|
| 383 |
Elpi abstract tree (option nat). |
| 384 |
Print tree'. |
| 385 |
|
| 386 |
(*| |
| 387 |
|
| 388 |
As expected `tree'` has a parameter `A`. |
| 389 |
|
| 390 |
Now let's focus on :lib:`copy`. The standard |
| 391 |
coq library (loaded by the command template) contains a definition of copy |
| 392 |
for terms and declarations. |
| 393 |
|
| 394 |
An excerpt: |
| 395 |
|
| 396 |
.. code:: elpi |
| 397 |
|
| 398 |
copy X X :- name X. % checks X is a bound variable |
| 399 |
copy (global _ as C) C. |
| 400 |
copy (fun N T F) (fun N T1 F1) :- |
| 401 |
copy T T1, pi x\ copy (F x) (F1 x). |
| 402 |
copy (app L) (app L1) :- std.map L copy L1. |
| 403 |
|
| 404 |
:e:`copy` implements the identity: it builds, recursively, a copy of the first |
| 405 |
term into the second argument. Unless one loads in the context a new rule, |
| 406 |
which takes precedence over the identity ones. Here we load: |
| 407 |
|
| 408 |
.. code:: elpi |
| 409 |
|
| 410 |
copy P a |
| 411 |
|
| 412 |
which, at run time, looks like |
| 413 |
|
| 414 |
.. code:: elpi |
| 415 |
|
| 416 |
copy (app [global (indt «option»), global (indt «nat»)]) c0 |
| 417 |
|
| 418 |
and that rule masks the one for `app` when the sub-term being copied is |
| 419 |
exactly `option nat`. The API :lib:`copy-indt-decl` copies an inductive |
| 420 |
declaration and calls `copy` on all the terms it contains (e.g. the |
| 421 |
type of the constructors). |
| 422 |
|
| 423 |
The :lib:`copy` predicate is very flexible, but sometimes one needs to collect |
| 424 |
some data along the way. The sibling API :lib:`fold-map` lets one do that. |
| 425 |
|
| 426 |
An excerpt: |
| 427 |
|
| 428 |
.. code:: elpi |
| 429 |
|
| 430 |
fold-map (fun N T F) A (fun N T1 F1) A2 :- |
| 431 |
fold-map T A T1 A1, pi x\ fold-map (F x) A1 (F1 x) A2. |
| 432 |
|
| 433 |
For example one can use :lib:`fold-map` to collect into a list all the occurrences |
| 434 |
of inductive type constructors in a given term, then use the list to postulate |
| 435 |
the right number of binders for them, and finally use :lib:`copy` to capture them. |
| 436 |
|
| 437 |
|
| 438 |
==================================== |
| 439 |
Using DBs to store data across calls |
| 440 |
==================================== |
| 441 |
|
| 442 |
A Db can be created with the command: |
| 443 |
|
| 444 |
|*) |
| 445 |
|
| 446 |
Elpi Db name.db lp:{{ pred some-pred. }}. |
| 447 |
|
| 448 |
(*| |
| 449 |
|
| 450 |
and a Db can be later extended via `Elpi Accumulate`. |
| 451 |
As a convention, we like Db names to end in a .db suffix. |
| 452 |
|
| 453 |
A Db is pretty much like a regular program but can be *shared* among |
| 454 |
other programs and is accumulated *by name*. |
| 455 |
Since is a Db is accumulated *when a program runs* the *current |
| 456 |
contents of the Db are used*. |
| 457 |
Moreover the Db can be extended by Elpi programs themselves |
| 458 |
thanks to the API :builtin:`coq.elpi.accumulate`, enabling code to save a state |
| 459 |
which is then visible at subsequent runs. |
| 460 |
|
| 461 |
The initial contents of a Db, `pred some-pred.` in the example |
| 462 |
above, is usually just the type declaration for the predicates part of the Db, |
| 463 |
and maybe a few default rules. |
| 464 |
Let's define a Db. |
| 465 |
|
| 466 |
|*) |
| 467 |
|
| 468 |
Elpi Db age.db lp:{{ |
| 469 |
|
| 470 |
% A typical Db is made of one main predicate |
| 471 |
pred age o:string, o:int. |
| 472 |
|
| 473 |
% the Db is empty for now, we put a rule giving a |
| 474 |
% descriptive error and we name that rule "age.fail". |
| 475 |
:name "age.fail" |
| 476 |
age Name _ :- coq.error "I don't know who" Name "is!". |
| 477 |
|
| 478 |
}}. |
| 479 |
|
| 480 |
(*| |
| 481 |
|
| 482 |
Elpi rules can be given a name via the :e:`:name` attribute. Named rules |
| 483 |
serve as anchor-points for new rules when added to the Db. |
| 484 |
|
| 485 |
Let's define a `Command` that makes use of a Db. |
| 486 |
|
| 487 |
|*) |
| 488 |
|
| 489 |
Elpi Command age. |
| 490 |
Elpi Accumulate Db age.db. (* we accumulate the Db *) |
| 491 |
Elpi Accumulate lp:{{ |
| 492 |
|
| 493 |
main [str Name] :- |
| 494 |
age Name A, |
| 495 |
coq.say Name "is" A "years old". |
| 496 |
|
| 497 |
}}. |
| 498 |
|
| 499 |
|
| 500 |
Fail Elpi age bob. (* .fails *) |
| 501 |
|
| 502 |
(*| |
| 503 |
|
| 504 |
Let's put some data in the Db. Given that the Db contains a catch-all rule, |
| 505 |
we need the new ones to be put before it. |
| 506 |
|
| 507 |
|*) |
| 508 |
|
| 509 |
Elpi Accumulate age.db lp:{{ |
| 510 |
|
| 511 |
:before "age.fail" % we place this rule before the catch all |
| 512 |
age "bob" 24. |
| 513 |
|
| 514 |
}}. |
| 515 |
|
| 516 |
Elpi age bob. |
| 517 |
|
| 518 |
(*| |
| 519 |
|
| 520 |
Extending data bases this way is fine, but requires the user of our command |
| 521 |
to be familiar with Elpi's syntax, which is not very nice. Instead, |
| 522 |
we can write a new program that uses the :builtin:`coq.elpi.accumulate` API |
| 523 |
to extend the Db. |
| 524 |
|
| 525 |
|*) |
| 526 |
|
| 527 |
Elpi Command set_age. |
| 528 |
Elpi Accumulate Db age.db. |
| 529 |
Elpi Accumulate lp:{{ |
| 530 |
main [str Name, int Age] :- |
| 531 |
TheNewRule = age Name Age, |
| 532 |
coq.elpi.accumulate _ "age.db" |
| 533 |
(clause _ (before "age.fail") TheNewRule). |
| 534 |
|
| 535 |
}}. |
| 536 |
|
| 537 |
|
| 538 |
Elpi set_age "alice" 21. |
| 539 |
Elpi age "alice". |
| 540 |
|
| 541 |
(*| |
| 542 |
|
| 543 |
Additions to a Db are a Coq object, a bit like a Notation or a Type Class |
| 544 |
instance: these object live inside a Coq module (or a Coq file) and become |
| 545 |
active when that module is Imported. |
| 546 |
|
| 547 |
Deciding to which Coq module these |
| 548 |
extra rules belong is important and :builtin:`coq.elpi.accumulate` provides |
| 549 |
a few options to tune that. Here we passed :e:`_`, that uses the default |
| 550 |
setting. See the :type:`scope` and :type:`clause` data types for more info. |
| 551 |
|
| 552 |
.. _inspecting: |
| 553 |
|
| 554 |
--------------- |
| 555 |
Inspecting a Db |
| 556 |
--------------- |
| 557 |
|
| 558 |
So far we did query a Db but sometimes one needs to inspect the whole |
| 559 |
contents. |
| 560 |
|
| 561 |
|*) |
| 562 |
|
| 563 |
Elpi Command print_all_ages. |
| 564 |
Elpi Accumulate Db age.db. |
| 565 |
Elpi Accumulate lp:{{ |
| 566 |
|
| 567 |
:before "age.fail" |
| 568 |
age _ _ :- !, fail. % softly |
| 569 |
|
| 570 |
main [] :- |
| 571 |
std.findall (age _ _) Rules, |
| 572 |
std.forall Rules print-rule. |
| 573 |
|
| 574 |
pred print-rule i:prop. |
| 575 |
print-rule (age P N) :- coq.say P "is" N "years old". |
| 576 |
|
| 577 |
}}. |
| 578 |
|
| 579 |
Elpi print_all_ages. |
| 580 |
|
| 581 |
(*| |
| 582 |
|
| 583 |
The :stdlib:`std.findall` predicate gathers in a list all solutions to |
| 584 |
a query, while :stdlib:`std.forall` iterates a predicate over a list. |
| 585 |
It is important to notice that :builtin:`coq.error` is a fatal error which |
| 586 |
aborts an Elpi program. Here we shadow the catch all clause with a regular |
| 587 |
failure so that :stdlib:`std.findall` can complete to list all the results. |
| 588 |
|
| 589 |
=================== |
| 590 |
Polishing a command |
| 591 |
=================== |
| 592 |
|
| 593 |
The details do make the difference, some times. |
| 594 |
|
| 595 |
---------- |
| 596 |
Attributes |
| 597 |
---------- |
| 598 |
|
| 599 |
Elpi programs can be prefixed with attributes, like `#[local]`. |
| 600 |
Attributes are not passed as arguments but rather as a rule in the context, |
| 601 |
a bit like the option :e:`@holes!` we have seen before. |
| 602 |
|
| 603 |
|*) |
| 604 |
|
| 605 |
Elpi Command attr. |
| 606 |
Elpi Accumulate lp:{{ |
| 607 |
|
| 608 |
main _ :- |
| 609 |
attributes A, % we fetch the list of attributes from the context |
| 610 |
coq.say A. |
| 611 |
|
| 612 |
}}. |
| 613 |
|
| 614 |
#[this, more(stuff="33")] Elpi attr. |
| 615 |
|
| 616 |
(*| |
| 617 |
|
| 618 |
The first attribute, :e:`elpi.loc` is always present and corresponds to the |
| 619 |
location in the source file of the command. Then we find an attribute for |
| 620 |
:e:`"this"` holding the empty string and an attribute for :e:`"more.stuff"` holding |
| 621 |
the string :e:`"33"`. |
| 622 |
|
| 623 |
Attributes are usually validated (parsed) and turned into regular options |
| 624 |
using :lib-common:`coq.parse-attributes` and a description of their types using |
| 625 |
the :libtype-common:`attribute-type` data type: |
| 626 |
|
| 627 |
|*) |
| 628 |
|
| 629 |
Elpi Command parse_attr. |
| 630 |
Elpi Accumulate lp:{{ |
| 631 |
|
| 632 |
pred some-code. |
| 633 |
some-code :- |
| 634 |
get-option "more.stuff" N, get-option "this" B, coq.say N B. |
| 635 |
|
| 636 |
main _ :- |
| 637 |
attributes A, |
| 638 |
coq.parse-attributes A [ |
| 639 |
att "this" bool, |
| 640 |
att "more.stuff" int, |
| 641 |
] Opts, |
| 642 |
coq.say "options=" Opts, |
| 643 |
(Opts =!=> some-code). |
| 644 |
|
| 645 |
}}. |
| 646 |
#[this, more(stuff="33")] Elpi parse_attr. |
| 647 |
Fail #[unknown] Elpi parse_attr. (* .fails *) |
| 648 |
|
| 649 |
(*| |
| 650 |
|
| 651 |
Note that :e:`get-option` links a string with a datum of type :e:`any`, which means |
| 652 |
no type checking is performed on it. It is recommended to wrap calls to |
| 653 |
get-option into other predicates typed in a more precise way. Eg: |
| 654 |
|
| 655 |
.. code:: elpi |
| 656 |
|
| 657 |
pred get-my-option o:int. |
| 658 |
get-my-option I :- get-option "my-option-name" I. |
| 659 |
|
| 660 |
----------------------------- |
| 661 |
Extending the command grammar |
| 662 |
----------------------------- |
| 663 |
|
| 664 |
Elpi programs can be exported as regular Coq commands, so that the |
| 665 |
final user does not need to type `Elpi` to invoke them. |
| 666 |
|
| 667 |
|*) |
| 668 |
|
| 669 |
Elpi Command Say. |
| 670 |
Elpi Accumulate lp:{{ main [str S] :- coq.say S. }}. |
| 671 |
|
| 672 |
|
| 673 |
Elpi Export Say. (* extend the Coq command grammar *) |
| 674 |
|
| 675 |
Say "That is all folks!". |
| 676 |
|
| 677 |
(*| |
| 678 |
|
| 679 |
Not yet... |
| 680 |
|
| 681 |
Coq offers no equivalent of `Tactic Notation` for commands. |
| 682 |
Still Elpi commands accept any symbol or keyword as strings. |
| 683 |
It is up to the programmer to catch and report parse errors. |
| 684 |
|
| 685 |
|*) |
| 686 |
|
| 687 |
Elpi Command Go. |
| 688 |
Elpi Accumulate lp:{{ |
| 689 |
main [str Src, str "=>", str Tgt, str "/", str F] :- !, |
| 690 |
coq.say "going from" Src "to" Tgt "via" F. |
| 691 |
main _ :- |
| 692 |
coq.error "Parse error! Use: go <from> => <to> / <via>". |
| 693 |
}}. |
| 694 |
|
| 695 |
Elpi Export Go. |
| 696 |
|
| 697 |
Go source => target / plane. |
| 698 |
Fail Go nowhere. (* .fails *) |
| 699 |
|
| 700 |
(*| |
| 701 |
|
| 702 |
---------------- |
| 703 |
Reporting errors |
| 704 |
---------------- |
| 705 |
|
| 706 |
Last, (good) Elpi programs should fail reporting intelligible error messages, |
| 707 |
as the previous one. |
| 708 |
|
| 709 |
|*) |
| 710 |
|
| 711 |
Elpi Command bad. |
| 712 |
Elpi Accumulate lp:{{ main []. }}. |
| 713 |
|
| 714 |
Elpi Export bad. |
| 715 |
|
| 716 |
Fail bad 1. (* .fails *) |
| 717 |
|
| 718 |
(*| |
| 719 |
|
| 720 |
If they just fail, they produce the following generic |
| 721 |
error: |
| 722 |
|
| 723 |
.. mquote:: .s(bad 1).msg(inconvenience) |
| 724 |
:language: text |
| 725 |
|
| 726 |
You should use the :builtin:`coq.error` API or the :stdlib:`assert!` one |
| 727 |
to abort a program. There is a dedicated :builtin:`coq.ltac.fail` API to abort |
| 728 |
tactics. |
| 729 |
|
| 730 |
Warnings can be reported using the :builtin:`coq.warning` which lets you |
| 731 |
pick a name and category. In turn these can be used to disable or make fatal |
| 732 |
your warnings (as any other Coq warning). |
| 733 |
|
| 734 |
===================== |
| 735 |
Parsing and Execution |
| 736 |
===================== |
| 737 |
|
| 738 |
Since version 8.18 Coq has separate parsing and execution phases, |
| 739 |
respectively called synterp and interp. |
| 740 |
|
| 741 |
Since Coq has an extensible grammar the parsing phase is not entirely |
| 742 |
performed by the parser: after parsing one sentence Coq evaluates its |
| 743 |
synterp action. The synterp actions of a command like `Import A.` are |
| 744 |
the subset of its effect which affect parsing, like enabling a notation. |
| 745 |
Later, during the execution phase, Coq evaluates its |
| 746 |
interp actions, which include effects like putting lemma in scope or |
| 747 |
enabling type class instances etc. Synterp actions are quick, if only because |
| 748 |
they don't really manipulate Coq terms, hence no type checking and the like. |
| 749 |
|
| 750 |
Being able to parse an entire document quickly |
| 751 |
is important for developing reactive |
| 752 |
user interfaces, but requires some extra work when defining new commands, |
| 753 |
in particular to identify their synterp. |
| 754 |
Each command defined with Coq-Elpi is split into two programs, |
| 755 |
one running during the parsing phase and the other one during the execution |
| 756 |
phase. Each API that affects the parser, i.e. APIs dealing with modules |
| 757 |
and sections like begin/end-module or import/export, is available to both the |
| 758 |
synterp and the interp program under the same name, but its actual effect is |
| 759 |
limited to what concerns the current phase. Hence all these APIs have to be |
| 760 |
called at *both* synterp and interp time and *in the same order*. |
| 761 |
|
| 762 |
At synterp time the data types and the APIs are restricted, in particular |
| 763 |
Coq terms are not available. When a command argument contains a term, that |
| 764 |
term is replaced by `_` at synterp time. In the following example, the synterp |
| 765 |
program can see the name of the definition and the fact that a body was given, |
| 766 |
but not the value of the body. |
| 767 |
|
| 768 |
|*) |
| 769 |
|
| 770 |
|
| 771 |
Elpi Command hello_synterp. |
| 772 |
#[synterp] Elpi Accumulate lp:{{ |
| 773 |
main [const-decl Name Body _] :- coq.say "synterp" Name ":=" Body. |
| 774 |
}}. |
| 775 |
Elpi Accumulate lp:{{ |
| 776 |
main [const-decl Name Body _] :- coq.say "interp" Name ":=" Body. |
| 777 |
}}. |
| 778 |
|
| 779 |
|
| 780 |
Elpi hello_synterp Definition x := 2. |
| 781 |
|
| 782 |
(*| |
| 783 |
|
| 784 |
This simple command has no real synterp action, one could safely remove |
| 785 |
the synterp code. On the contrary when a command performs actions affecting |
| 786 |
the parser then it must come equipped with some synterp code performing |
| 787 |
the corresponding actions. |
| 788 |
|
| 789 |
|*) |
| 790 |
|
| 791 |
Module Notations. |
| 792 |
Notation "x '>>' y" := (x > y) (at level 40). |
| 793 |
Definition w := 3. |
| 794 |
End Notations. |
| 795 |
|
| 796 |
Elpi Command import_module. |
| 797 |
Elpi Accumulate lp:{{ |
| 798 |
main [str M] :- |
| 799 |
coq.locate-module M MP, |
| 800 |
coq.env.import-module MP, |
| 801 |
coq.locate "w" (const GR), |
| 802 |
coq.env.const GR (some {{ 3 }}) _. |
| 803 |
}}. |
| 804 |
|
| 805 |
|
| 806 |
Fail Elpi import_module Notations. (* .fails *) |
| 807 |
|
| 808 |
(*| |
| 809 |
|
| 810 |
Elpi reports a descriptive error message if actions affecting the parser are |
| 811 |
not declared in the synterp code of the command. |
| 812 |
|
| 813 |
Thanks to the synterp code below, Coq can parse the document without even looking |
| 814 |
at the interp code. |
| 815 |
|
| 816 |
|*) |
| 817 |
|
| 818 |
(* oops, we forgot to declare code for the synterp phase. Here it is *) |
| 819 |
#[synterp] Elpi Accumulate lp:{{ |
| 820 |
main [str M] :- |
| 821 |
coq.locate-module M MP, |
| 822 |
coq.env.import-module MP. |
| 823 |
}}. |
| 824 |
|
| 825 |
|
| 826 |
(* Elpi import_module Notations. *) |
| 827 |
|
| 828 |
(*| |
| 829 |
|
| 830 |
Sometimes it is necessary to pass data from the synterp code to the interp one. |
| 831 |
Passing data can be done in two ways. the former is by using the :e:`main-synterp` |
| 832 |
and :e:`main-interp` entry points. |
| 833 |
|
| 834 |
.. code:: elpi |
| 835 |
|
| 836 |
pred main-synterp i:list argument, o:any. |
| 837 |
pred main-interp i:list argument, i:any. |
| 838 |
|
| 839 |
Unlike :e:`main` the former outputs a datum while the latter receives it |
| 840 |
in input. In the following command we create a (empty) module with a random |
| 841 |
name. Even if the name is random, the two phases need to agree on it, hence |
| 842 |
we pass the name from one to the other. |
| 843 |
|
| 844 |
|*) |
| 845 |
|
| 846 |
Elpi Command mk_random_module. |
| 847 |
#[synterp] Elpi Accumulate lp:{{ |
| 848 |
main-synterp [] M :- |
| 849 |
random.self_init, |
| 850 |
random.int 99 N, |
| 851 |
M is "Module" ^ {std.any->string N}, |
| 852 |
coq.env.begin-module M none, |
| 853 |
coq.env.end-module _. |
| 854 |
}}. |
| 855 |
Elpi Accumulate lp:{{ |
| 856 |
main-interp [] M :- |
| 857 |
coq.env.begin-module M none, |
| 858 |
coq.env.end-module MP, |
| 859 |
coq.say "The module is" MP. |
| 860 |
}}. |
| 861 |
|
| 862 |
|
| 863 |
Elpi mk_random_module. |
| 864 |
|
| 865 |
(*| |
| 866 |
|
| 867 |
If the only data to be passed to the interp phase is the list of |
| 868 |
synterp actions, then a few APIs can come in handy. |
| 869 |
The synterp phase has access to the API :builtin-synterp:`coq.synterp-actions` |
| 870 |
that lists the actions performed so far. The interp phase can use |
| 871 |
:lib:`coq.replay-synterp-action` and :builtin:`coq.next-synterp-action` to |
| 872 |
replay an action or peek the next one to be performed. |
| 873 |
|
| 874 |
An excerpt of the :type:`synterp-action`. |
| 875 |
|
| 876 |
.. code:: elpi |
| 877 |
|
| 878 |
% Action executed during the parsing phase (aka synterp) |
| 879 |
kind synterp-action type. |
| 880 |
type begin-module id -> synterp-action. |
| 881 |
type end-module modpath -> synterp-action. |
| 882 |
|
| 883 |
The following command creates a stack of modules and puts in there |
| 884 |
the given definition. The synterp phase saves the actions when the top of the |
| 885 |
stack is reached, and passes them to the interp phase that replays them before |
| 886 |
putting a definition inside. Finally the interp phase replays all the missing |
| 887 |
actions. |
| 888 |
|
| 889 |
|*) |
| 890 |
|
| 891 |
Elpi Command put_inside. |
| 892 |
#[synterp] Elpi Accumulate lp:{{ |
| 893 |
main-synterp [int N, A] ActionsUpToNow :- N > 0, M is N - 1, |
| 894 |
coq.env.begin-module "Box" none, |
| 895 |
main-synterp [int M, A] ActionsUpToNow, |
| 896 |
coq.env.end-module _. |
| 897 |
main-synterp [int 0, _] ActionsUpToNow :- |
| 898 |
coq.synterp-actions ActionsUpToNow. |
| 899 |
}}. |
| 900 |
Elpi Accumulate lp:{{ |
| 901 |
main-interp [int _, const-decl Name (some BO) _] Before :- |
| 902 |
std.forall Before coq.replay-synterp-action, |
| 903 |
coq.env.add-const Name BO _ _ _, |
| 904 |
replay-missing. |
| 905 |
pred replay-missing. |
| 906 |
replay-missing :- |
| 907 |
coq.replay-synterp-action {coq.next-synterp-action}, |
| 908 |
replay-missing. |
| 909 |
replay-missing. |
| 910 |
}}. |
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
Elpi put_inside 4 Definition foo (n : nat) := n + 2. |
| 915 |
|
| 916 |
Print Box.Box.Box.Box.foo. |
| 917 |
|
| 918 |
(*| |
| 919 |
|
| 920 |
This last example delegates to the synterp phase the creation of an arbitrary |
| 921 |
complex module structure, a structure the interp phase does not need to be aware |
| 922 |
of. The data passed to the interp phase is sufficient to replicate it without |
| 923 |
too much effort. |
| 924 |
|
| 925 |
Finally, as regular commands, data bases can be used to store a state which |
| 926 |
is available at subsequent calls. Data bases used in the two phases live |
| 927 |
in different name spaces, and are only available to the corresponding phase. |
| 928 |
The `#[synterp]` attribute tells `Elpi Db` to create a data base for the |
| 929 |
synterp phase. Here a simple command saving a state in the synterp phase. |
| 930 |
|
| 931 |
|*) |
| 932 |
|
| 933 |
#[synterp] Elpi Db counter.db lp:{{ pred tick. }}. |
| 934 |
|
| 935 |
Elpi Command mk_next_module. |
| 936 |
#[synterp] Elpi Accumulate Db counter.db. |
| 937 |
#[synterp] Elpi Accumulate lp:{{ |
| 938 |
main [] :- |
| 939 |
std.findall tick L, |
| 940 |
std.length L N, |
| 941 |
M is "NextModule" ^ {std.any->string N}, |
| 942 |
coq.env.begin-module M none, |
| 943 |
coq.env.end-module _, |
| 944 |
coq.elpi.accumulate _ "counter.db" (clause _ _ tick). |
| 945 |
}}. |
| 946 |
Elpi Accumulate lp:{{ |
| 947 |
main [] :- replay-missing. |
| 948 |
pred replay-missing. |
| 949 |
replay-missing :- |
| 950 |
coq.replay-synterp-action {coq.next-synterp-action}, |
| 951 |
replay-missing. |
| 952 |
replay-missing. |
| 953 |
}}. |
| 954 |
|
| 955 |
|
| 956 |
Elpi mk_next_module. |
| 957 |
Elpi mk_next_module. |
| 958 |
Elpi mk_next_module. |
| 959 |
|
| 960 |
Print Module NextModule2. |
| 961 |
|
| 962 |
(*| |
| 963 |
|
| 964 |
This is really the end, unless you want to learn more about writing |
| 965 |
`tactics <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_tactic.html>`_ |
| 966 |
in Elpi, in that case look at that tutorial ;-) |
| 967 |
|
| 968 |
|*) |