Debian Codegraph @

apps/tc/README.md

raw symbols SCIP
1 # Type class solver
2
3 This folder contains an alternative implementation of a type class solver for
4 coq written in elpi. This solver is composed by two main parts, the **compiler**
5 and the **solver**. The former takes coq classes and instances and "translates"
6 them into the elpi representation, whereas the latter is the elpi tactic aiming
7 to make instance search on coq goals.
8
9 - [The compiler](#the-compiler)
10 - [Class compilation](#class-compilation)
11 - [Deterministic search](#deterministic-search)
12 - [Hint modes](#hint-modes)
13 - [Instance compilation](#instance-compilation)
14 - [Instance priorities](#instance-priorities)
15 - [Technical details](#technical-details)
16 - [Instance locality](#instance-locality)
17 - [Goal resolution](#goal-resolution)
18 - [Commands](#commands)
19 - [Flags](#flags)
20 - [WIP](#wip)
21
22
23 ## The compiler
24
25 In our implementation by compiler we mean the set of rules abstracting coq
26 terms, *1.* classes and *2* instances, in the elpi world. In the next two
27 paragraphs, we briefly explain these two phases of the compilation, where,
28 intuitively, a type class can be seen as a prolog predicate and the instances of
29 a type class $C$ as rule (clause or fact) of the elpi predicate for $C$.
30
31 For instance, if
32
33 ```coq
34 Class Eqb (T: Type) := {
35 eqb : T -> T -> bool;
36 eq_leibniz : forall (A B: T), eqb A B = true -> A = B
37 }.
38 ```
39
40 is the type class representing the leibniz equality between two objects of type
41 $T$, and
42
43 ```coq
44 Program Instance eqBool : Eqb bool := {
45 eqb A B := if A then B else negb B
46 }.
47 Next Obligation. now intros [] []. Qed.
48 ```
49
50 is an implementation of `Eqb` for the type `bool`, their corresponding elpi
51 representation will be:
52
53 ```prolog
54 pred tc-Eqb i:term, o:term.
55 tc-Eqb {{bool}} {{eqBool}}.
56 ```
57
58 ### Class compilation
59
60 The compilation of a type class creates dynamically (thanks to the
61 `coq.elpi.add-predicate` API) a new predicate called `tc-Path.tc-ClassName` with
62 $N + 1$ terms where:
63
64 - `Path` is the is the logical path in which the type class `ClassName` is
65 located
66 - $N$ is the number of parameter of the `ClassName`. In particular, if a type
67 class $C$ as the parameters $P_1,\dots, P_n$ then the corresponding predicate
68 will have $N$ parameters of type `term` ($1$ per parameter) and a last
69 parameter in output mode containing the result of the instance search.
70 By default, all the first $P_1,\dots,P_n$ parameters are in output mode.
71
72 The set of rules allowing to add new type-class predicates in elpi are grouped
73 in [create_tc_predicate.elpi](elpi/create_tc_predicate.elpi).
74
75 #### Deterministic search
76
77 Sometimes, it could be interesting to disable the backtracking search for some
78 type classes, for performances issues or design choices. In coq the flag
79 *Typeclasses Unique Instances* (see
80 [here](https://coq.inria.fr/refman/addendum/type-classes.html#coq:flag.Typeclasses-Unique-Instances))
81 allows to block any kind of a backtrack on instance search: in this case type
82 classes are supposed to be canonical.
83
84 In the example below, we want the `NoBacktrack` type class not to backtrack if
85 a solution is found.
86
87 ```coq
88 #[deterministic] TC.declare Class NoBacktrack (n: nat).
89
90 Class A (n: nat).
91
92 Instance a0 : A 0. Qed.
93 Instance nb0 : NoBacktrack 0. Qed.
94 Instance nb1 : NoBacktrack 1. Qed.
95 Instance a3 n : NoBacktrack n -> A n -> A 3. Qed.
96
97 Goal A 3. Fail apply _. Abort.
98 ```
99
100 The goal `A 3` fails since the only instance matching it is `a3`, but we are not
101 able to satisfy both its premises. In particular, the instance `nb1` is applied
102 first, which fixes the parameter `n` of `a3` to `1`. Then the algorithm tries to
103 find a solution for `A 1` (the second premise), but no implementation of `A` can
104 solve it. In the classic approach, the type class solver would backtrack on the
105 premise `NoBacktrack n` and try to apply `nb0` (this would find a solution), but
106 since the type class `NoBacktrack` is deterministic, then `nb0` is discarded.
107
108 In this implementation, the elpi rule for the instance `a3` is:
109
110 ```elpi
111 tc-A {{3}} {{a3 lp:A lp:B lp:C}} :-
112 do-once (tc-NoBacktrack A B),
113 tc-A A C.
114 ```
115
116 The predicate `do-once i:prop` has
117
118 ```prolog
119 do-once P :- P, !.
120 ```
121
122 as implementation. The cut (`!`) operator is in charge to avoid backtracking on
123 the query `tc-NoBacktrack A B`
124
125 #### Hint modes
126
127 Instance search is done looking to the arguments passed to the class. If there
128 is an instance $I$ unifying to it, the premises of $I$ are tried to be solved to
129 commit $I$ as the solution of the current goal (modulo backtracking). Concerning
130 the parameters of a type class, coq type class solver allows to constrain the
131 argument to be ground, in input or output modes (see
132 [here](https://coq.inria.fr/refman/proofs/automatic-tactics/auto.html#coq:cmd.Hint-Mode)).
133 We provide a similar behavior in elpi: classes represent elpi predicates where
134 the parameters can be in input `i` or output `o` mode (see
135 [here](https://github.com/LPCIC/elpi/blob/master/ELPI.md#modes)). We translate
136 coq modes in the following way: `+` and `!` become `i` in elpi and `-` becomes
137 `o` (see
138 [here](https://github.com/FissoreD/coq-elpi/blob/c3cce183c3b2727ef82178454f0c583196ee2c21/apps/tc/elpi/create_tc_predicate.elpi#L12)).
139
140 In elpi we allow type classes to have at most one mode, if that mode is not
141 defined, all parameters are considered in `o` mode. The command to be used
142 to let elpi compile classes with modes is done via the command `TC.Declare`.
143
144 ```coq
145 #[mode(i, o, i)] TC.Declare Class (T1: Type) (T2: Type) (N : nat).
146 ```
147
148 The pragma `mode` is taken into account to make `T1` and `N` in input mode and
149 `T2` in output mode. The command `TC.Declare` both create the class in elpi and
150 in coq. Note that the accepted list arguments for the attribute `mode` are
151 `i, o, +, -` and `!` with their respective meaning.
152
153 ### Instance compilation
154
155 Instances are compiled in elpi from their type. In particular, since the
156 $\forall$-quantification and the left hand side of implications of coq are both
157 represented with the `prod` type in elpi, we can say that the type of an
158 instance $I$ is essentially a tower of
159
160 <pre>
161 prod N_1 T_1 (x_1\
162 prod N_2 T_2 (x_2\
163 ...
164 prod N_n T_n (x_n\
165 app [global GR, A_1, A_2, ... A_M])))
166 </pre>
167
168 where $\forall i \in [1, N],\ T_i$ is the type of the quantified variable $x_i$.
169 Each $x_1$ represents a premise $P$ of the current instance and, if its type
170 $T_i$ is a type class, then $P$ is recursively compiled and added to the final
171 clause as a premise. The last `prod` contains `app [global GR, A_1, ..., A_M]`
172 where `GR` is the gref of the type class implemented by $I$ and each $A_j$ is an
173 argument applied to `GR` which sees every $x_i$. Note that during the
174 compilation of the instance the binders $x_i$ are recursively replaced by fresh
175 `pi` elpi variables.
176
177 For example, the instance `eqBool` showed before, has type
178
179 `Eqb bool`, it has no quantified variable and it is directly compiled in the
180 clause `tc-Eqb {{bool}} {{eqBool}}`.
181
182 On the other hand, if we take the instance below,
183
184 ```coq
185 Instance eqProd (A B: Type) : Eqb A -> Eqb B -> Eqb (A * B) := { ... }
186 ```
187
188 we see that its type is
189
190 ```
191 prod `A` (sort (typ eqProd.u0»)) c0 \
192 prod `B` (sort (typ eqProd.u1»)) c1 \
193 prod `H0` (app [global (indt «Eqb»), c0]) c2 \
194 prod `H1` (app [global (indt «Eqb»), c1]) c3 \
195 app [global (indt «Eqb»), app [global (indt «prod»), c0, c1]]
196 ```
197
198 there are in fact four variables that produce the elpi clause:
199
200 ```
201 pi x0 x1 x2 x3\
202 tc-Eqb {{prod lp:A lp:B}} Sol :-
203 tc-Eqb A S1, tc-Eqb B S2,
204 Sol = {{eqProd lp:A lp:B lp:S1 lp:S2}}.
205 ```
206
207 the four variable $c_0,...,c_3$ are quantified with `pi`, the two premises
208 `H0` and `H1` are compiled as premises of the current goal (we need to find a
209 proof that there exists an implementation of the class `Eqb` for the types
210 of $c_0$ and $c_1$). Then the application of `«Eqb»` is used to create the head of
211 the clause with its arguments and `eqProd`, the gref of the current instance,
212 is used as the solution of the current goal applied to all of the quantified
213 variables.
214
215 The set of rules allowing to compile instances in elpi are grouped in
216 [compiler.elpi](elpi/compiler.elpi).
217 ****
218 #### Instance priorities
219
220 To reproduce coq behavior, instances need to respect a notion of priority:
221 sometime multiple instances can be applied on a goal, but, for sake of
222 performances, the order in which they are tried is essential.
223
224 In the previous example, the goal `Eqb ?V` where `?V` is a meta-variable, it
225 is important to first use the rules `eqBool` and then `eqProd`, the latter
226 causing an infinite loop.
227
228 In elpi, we have the possibility to create rules with names and, then, new rules
229 can be added with respect to a particular grafting (see
230 [here](https://github.com/FissoreD/coq-elpi/blob/a11558758de0a1283bd9224b618cc75e40f118fb/coq-builtin.elpi#L1679)).
231
232 Our strategy of instance insertion in the elpi database reposes on a predicate
233 `pred hook o:string` having, by default, $1.001$ implementations each of them
234 having a name going from `"0"` to `"1000"` (bounds included). Roughly what we
235 have is the following:
236
237 ```prolog
238 :name "0" hook "0".
239 :name "1" hook "1".
240 ...
241 :name "999" hook "999".
242 :name "1000" hook "1000".
243 ```
244
245 In this way an instance can be added at the wanting position to respect its
246 priority. In particular, the priority of an instance can be defined in two
247 different ways by the user by coq and we retrieve this piece of
248 information via the `Event` listener from `coq` (see
249 [here](https://github.com/coq/coq/blob/f022d5d194cb42c2321ea91cecbcce703a9bcad3/vernac/classes.mli#L81)).
250 This event contains either a class or an instance and in the latter case we can
251 get its priority (see
252 [here](https://github.com/FissoreD/coq-elpi/blob/a11558758de0a1283bd9224b618cc75e40f118fb/apps/tc/src/coq_elpi_tc_register.ml#L57)).
253
254 #### Technical details
255
256 1. If the instance has no user defined priority, the attribute containing the
257 priority of the instance is set to `None`. In this case, the priority is
258 computed as the number of premises the instance has. For example, `eqBool`
259 has priority $2$, since it has two hypothesis triggering recursive instance
260 search.
261 2. If $P$ is the priority of both the instance $I_1$ and the instance $I_2$ of
262 a class $C$, then the instance that should be tried before is the one which
263 has been defined later (this is coq default behavior). To respect this order,
264 the grafting we use is `after P` for both instances, in this way, elpi will
265 put the second-defined instance before the first one.
266 3. The number of hook in elpi is bounded to $1.000$, it is however possible to
267 extend it via the command `Elpi TC.AddHook G OldName NewName` where `G` is
268 either after or before and `NewName` is the new hook that will be grafted
269 after\before the hook called `OldName`. For instance, `Elpi TC.AddHook after
270 1000 1002` creates a hook named `1002` after `1000` and `Elpi TC.AddHook before
271 1002 1001` insert the hook `1001` before `1002`. Note that `OldName` should
272 be an existing name, otherwise, a blocking error will be thrown at the next
273 invocation of an elpi code.
274 4. The event listener for instance/class creation can be extended with new
275 elpi programs via the command `Elpi Register TC Compiler PROG`, where `PROG`
276 is the name of the new elpi program called by the `Event` listener of coq.
277 Note that in the case of the creation of a
278 - Type class $C$, `PROG` is called with `[str C]` as argument where `C` is the
279 name of the class
280 - Instance $I$, `PROG` is called with `[str I, str C, str Loc, int Prio]`
281 where `I` is the name of the instance, `C` the name of the class it
282 implements, `Loc` is its `Locality` (one among `Local`, `Global`, `Export`)
283 and `Prio` is its priority.
284
285 The default elpi program for instance and class insertion is called
286 `auto_compiler` (see [here](https://github.com/FissoreD/coq-elpi/blob/a11558758de0a1283bd9224b618cc75e40f118fb/apps/tc/theories/tc.v#L61))
287 5. A registered event listener for instance/class can be deactivated, activated
288 respectively with
289 1. `Elpi TC Activate Observer PROG.`
290 2. `Elpi TC Deactivate Observer PROG.`
291
292 by default, once registered, the elpi program `PROG` is activated
293
294 #### Instance locality
295
296 The instances in the elpi database respect the locality given by the user. This
297 is possible thanks to the attributes from
298 [here](https://github.com/FissoreD/coq-elpi/blob/ac036a71f359bc1c1ee3893949d3371df10b0aef/coq-builtin.elpi#L355).
299 When an instance is created the `Event` listener transfer the locality of the
300 instance to the elpi program in charge to make the insertion (see
301 [here](https://github.com/FissoreD/coq-elpi/blob/ac036a71f359bc1c1ee3893949d3371df10b0aef/apps/tc/elpi/compiler.elpi#L154)
302 and
303 [here](https://github.com/FissoreD/coq-elpi/blob/ac036a71f359bc1c1ee3893949d3371df10b0aef/apps/tc/src/coq_elpi_tc_register.ml#L37)).
304
305 As a small remark, we should consider that instances depending on section
306 variables should be *recompiled* on section end in order to abstract them.
307 In the example below
308
309 ```coq
310 Section Foo.
311 Variable (A B: Type) (HA : Eqb A) (HB : Eqb B).
312 Global Instance eqProd' : Eqb (A * B) := {...}.
313
314 Elpi TC.Print_instances eqb.
315 (* Here the elpi database has the instances HA, HB and eqProd' *)
316 (*
317 And the rules for eqProd' is
318 tc-Eqb {{prod A B}} {{eqProd'}}.
319
320 Remark: Here A and B are not elpi variables, but the coq variables from the
321 context
322 *)
323 End Foo.
324
325 Elpi TC.Print_instances eqb.
326 (*
327 Here HA and HB are removed since local to Foo and
328 eqProd' has been recompiled abstracting and A, B, HA and HB. They are now
329 arguments of this instance
330 *)
331 (*
332 The new rules for eqProd' is now
333 tc-Eqb {{prod lp:A lp:B}} {{eqProd' lp:A lp:B lp:HA lp:HB}} :-
334 tc-Eqb A HA, tc-Eqb B HB.
335
336 Remark: Here A and B are elpi variables and HA, PB are the proof that we can
337 prove {{Eqb lp:A}} and {{Eqb lp:B}}
338 *)
339 ```
340
341 Concretely, in a section, we consider all instances as **local** in elpi. On
342 section end, the `Event` listener for instance creation triggers a new call to
343 the elpi program for instance compilation. This trigger contains the same event
344 as the one for the instance creation, but now elpi is capable to compile the
345 instance abstracting the section variable. Finally, if we are not in a section,
346 instance locality will depend on the "real" locality of that instance:
347
348 1. If the instance is *local*, then we accumulate the attribute *@local! =>*
349 2. If the instance is *global*, then we accumulate the attribute *@global! =>*
350 3. If the instance is in *export* mode, then we pass no attribute, since by default,
351 elpi rules have this particular locality
352
353
354 ## Goal resolution
355
356 The resolution of type class goals is done via the `TC_solver` tactic (see
357 [here](https://github.com/FissoreD/coq-elpi/blob/d674089e5f5773d5d922f185e2ff058e595fa8b8/apps/tc/theories/tc.v#L29)
358 and [here](elpi/solver.elpi)). This tactic take the goal and start by
359 introducing the quantified variables if any, then it compiles the hypotheses
360 whose type is a type class and finally start by solving the goal by looking for
361 the instances in the elpi database. Note that the tactic, per se, is not
362 complicated since the search of instances is based on a DFS backtracking on
363 failure which is the builtin search mode of query resolution in elpi.
364
365 The elpi tactic can be called by the classic `elpi TC_solver` on the current
366 goal, however, this can be done implicitly done using the classic tactics of coq
367 doing type class resolution. In particular, we want to make our solver and coq
368 one coexist. The user may whish the elpi solver to solve `Only` goals concerning
369 particular type classes (for example, those defined in its library) and leave
370 coq to solve the other otherwise. To do so we can call the command `Elpi
371 Override TC TC_solver Only Eqb` which activates the resolution of goal of goal
372 concerning `Eqb` which the solver `TC_solver`. Note that multiple solvers can be
373 created and activated to solve different tasks. To do so, we take advantage of
374 the `Typeclasses.set_solve_all_instances` function from coq (see
375 [here](https://github.com/coq/coq/blob/f022d5d194cb42c2321ea91cecbcce703a9bcad3/pretyping/typeclasses.mli#L141))
376 which allows to set a solver to be called on type class goals. We have taken the
377 file [`classes.ml`] from
378 [here](https://github.com/coq/coq/blob/f022d5d194cb42c2321ea91cecbcce703a9bcad3/vernac/classes.ml#L1)
379 and slightly modified the function
380 [`resolve_all_evars`](https://github.com/FissoreD/coq-elpi/blob/17d1f20d3d4f37abfeee7edcf31f3757fd515ff3/apps/tc/src/rocq_elpi_class_tactics_hacked.ml#L1165).
381 Now that function, before solving a goal verifies if the current goal contains
382 only type classes overriden by the user and if so, it uses the elpi solver for
383 its resolution, otherwise, it calls the default coq solver. Note that the choice
384 of using elpi or coq solver is done
385 [here](src/rocq_elpi_class_tactics_takeover.ml). Moreover, we provide different
386 commands to
387
388 1. Override all type class goals and solve them by the solver of elpi, that
389 command is `Elpi Override TC TC_solver All`.
390 2. Override only some type classes, that command is `Elpi Override TC TC_solver
391 Only ClassQualid+` where `ClassQualid+` is a non empty list of type class
392 names. A valid call to this command is, for example, `Elpi Override TC
393 TC_solver Only Eqb Decidable`.
394 3. Override no type class, *i.e.* solve all goals with coq solver with the
395 command `Elpi Override TC TC_solver None`.
396 4. Blacklist some type classes from elpi solver, `Elpi Override TC -
397 ClassQualid+`. For instance `Elpi Override TC TC_solver Only Eqb Decidable.
398 Elpi Override TC - Decidable` in equivalent to `Elpi Override TC TC_solver
399 Only Eqb`.
400 5. Add type classes to be solved by the solver of elpi `Elpi Override TC +
401 ClassQualid+`. For instance, `Elpi Override TC TC_solver Only Eqb. Elpi
402 Override TC + Decidable` is equivalent to `Elpi Override TC TC_solver Only
403 Eqb Decidable`.
404
405 All of these commands are meant to dynamically change the resolution of type
406 classes goal in `.v` files.
407
408 ## Commands
409
410 A small recap of the available elpi commands:
411
412 <details>
413 <summary>
414 <code>TC.Print_instances</code> (click to expand)
415 </summary>
416
417 This commands prints the list of instances inside the elpi database grouped by
418 type class and in order of priority. Note that custom rules will not appear
419 in this list. This command can also be called with the name of a type class
420 to print only the implementation of that type class in elpi. An example of the
421 result for the command `Elpi print_instance Eqb.`
422
423 ```
424 Instances list for const «Eqb» is:
425 const «eqBool»
426 const «eqProd»
427 ```
428
429 </details>
430
431 <details>
432 <summary>
433 <code>TC.Set_deterministic</code> (click to expand)
434 </summary>
435
436 Take the name of a type class in parameter and sets the search mode of that
437 class to deterministic (see [here](#deterministic-search))
438
439 </details>
440
441 <details>
442 <summary>
443 <code>TC.Get_class_info ClassName</code> (click to expand)
444 </summary>
445
446 Prints the name of the predicate associated to the class `ClassName`
447 and its search mode (`deterministic|classic`). This command is useful
448 especially when you want to add a new custom rule for a goal resolution and
449 want to know the name of the predicate of the targeted class.
450
451 Example:
452
453 ```coq
454 Elpi TC.Get_class_info Eqb.
455
456 (* Output:
457 The predicate of indt «Eqb» is tc-Eqb and search mode is classic *)
458 ```
459
460 </details>
461
462 <details>
463 <summary>
464 <code>TC.AddHook G OldName NewName</code> (click to expand)
465 </summary>
466
467 See [here](#technical-details)
468
469 </details>
470
471 <details>
472 <summary>
473 <code>TC.Declare ClassDef</code> (click to expand)
474 </summary>
475
476 See [here](#deterministic-search) and [here](#hint-modes) for respectively
477 deterministic type class and mode declaration
478
479 </details>
480
481 **Note:** in a new library you may wish to automatically compile into your elpi
482 database the existing classes and instances on which you library depends. To
483 do so, the $4$ following commands may be useful:
484
485 - `TC.AddAllClasses`: look for all the defined classes and creates their predicate
486 - `TC.AddClasses ClassName+`: compile the predicate for the classes in argument
487 - `TC.AddAllInstances`: look for all the defined instances and compile them
488 - `TC.AddInstances InstName+`: compiles al the instances passed in argument
489
490 **Note:** it is important to create the predicate of type classes (if not already done)
491 before the insertion of instances otherwise this would throw an exception.
492
493 ## Flags
494
495 Here the list of the flags available (all of them are `off` by default):
496
497 <details>
498 <summary>
499 <code>TC IgnoreEtaReduction</code> (click to expand)
500 </summary>
501
502 Solves the goal ignoring eta-reduction, in that case it will no longer possible
503 to unify `fun x => F x` with `F`
504 </details>
505
506 <details>
507 <summary>
508 <code>TC ResolutionTime</code> (click to expand)
509 </summary>
510
511 Print the time taken to solve a goal by looking into the set of rules in the
512 database of elpi
513 </details>
514
515 <details>
516 <summary>
517 <code>TC NameShortPath</code> (click to expand)
518 </summary>
519
520 Experimental and discouraged, it can be used to compile the predicate of type
521 classes without putting the `tc-Path.` prefix before `tc-ClassName` (see
522 [here](#class-compilation)). For example, the type class `Decidable` from
523 `Coq.Classes` is compiled into the predicate
524 `tc-Coq.Classes.DecidableClass.tc-Decidable`. For small tests, if you want a
525 predicate called simply `tc-Decidable` you can either use the namespace of
526 elpi (see
527 [here](https://github.com/LPCIC/elpi/blob/master/ELPI.md#namespaces)) or
528 activate the option `NameShortPat` which creates the predicate with the
529 short name `tc-Decidable`
530 </details>
531
532 <details>
533 <summary>
534 <code>TC TimeRefine</code> (click to expand)
535 </summary>
536
537 Prints the time taken by coq to refine the elpi solution in to the coq term
538 </details>
539
540 <details>
541 <summary>
542 Experimental: <code>TC CompilerWithPatternFragment</code> (click to expand)
543 </summary>
544
545 Compile instances using the pattern fragment unification of elpi: the coq
546 term applications (`app [HD | TL]`) are replaced with the elpi application
547 `(HDe TLe)` where `HDe` is the elpi representation of `HD` (similarly for `TLe`)
548 </details>
549
550
551 ## WIP
552
553 1. Mode management:
554 - Classes with multiple modes
555 2. Clarify pattern fragment unification
556 3. Topological sort of premises in modes are activated
557