fact
stringlengths 3
13.4k
| type
stringclasses 21
values | library
stringclasses 6
values | imports
listlengths 0
6
| filename
stringclasses 137
values | symbolic_name
stringlengths 1
29
| docstring
stringclasses 1
value |
|---|---|---|---|---|---|---|
test : abs_evars (forall x, x = x). intros t x; reflexivity. Abort.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_abs_evars.v
|
test
| |
test : abs_evars (forall x y, x = y). intros t x y; symmetry. Abort.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_abs_evars.v
|
test
| |
test : True. assert (abs_evars (tt = _)) as H. intro x; destruct x; reflexivity. Abort.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_abs_evars.v
|
test
| |
test : exists x, x = tt. econstructor. (* it is silly, but shows the code above performs the abstraction *) elpi abs_evars. now intros []. exact tt. Qed.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_abs_evars.v
|
test
| |
l0 x y z (H : x < y) : y < z -> x < z. Proof. elpi id. Abort. (* Things are wired up in such a way that assigning a "wrong" value to Ev fails *) Elpi Tactic silly. Elpi Accumulate lp:{{ solve (goal _ Ev _ _ _) _ :- Ev = {{true}}. solve (goal _ Ev _ _ _) _ :- Ev = {{3}}. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_curry_howard_tactics.v
|
l0
| |
l1 : nat. Proof. elpi silly. Show Proof. Qed. (* Now we write "intro" in Curry-Howard style *) Elpi Tactic intro. Elpi Accumulate lp:{{ solve (goal _ _ _ _ [str S] as G) GS :- coq.string->name S N, refine (fun N Src_ Tgt_) G GS. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_curry_howard_tactics.v
|
l1
| |
l2 x y z (H : x < y) : y < z -> x < z. Proof. elpi intro H1. Abort. (* Now let's write a little automation *) Elpi Tactic auto. Elpi Accumulate lp:{{ shorten coq.ltac.{ open , or , repeat }. pred intro i:name, i:goal, o:list sealed-goal. intro S G GS :- refine (fun S Src_ Tgt_) G GS. % Ex falso pred exf i:goal, o:list sealed-goal. exf (goal Ctx _ Ty _ _ as G) [] :- std.exists Ctx (x\ sigma w\ x = decl V w {{False}}), refine {{ match lp:V in False return lp:Ty with end }} G []. % Constructor pred kon i:goal, o:list sealed-goal. kon (goal _ _ Ty _ _ as G) GS :- coq.safe-dest-app Ty (global (indt GR)) _, coq.env.indt GR _ _ _ _ Ks Kt, std.exists2 Ks Kt (k\ t\ coq.saturate t (global (indc k)) P, refine P G GS). % entry point; we assert no goals are left solve G [] :- repeat (or [open exf, open kon, open (intro `H`)]) (seal G) []. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_curry_howard_tactics.v
|
l2
| |
l3 : forall P : Prop, (False -> P) /\ (False \/ True). Proof. elpi auto. Qed.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_curry_howard_tactics.v
|
l3
| |
ty := B | N.
|
Inductive
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_fuzzer.v
|
ty
| |
Exp : ty -> Type := | NUM : nat -> Exp N | BOOL : bool -> Exp B | PLUS : Exp N -> Exp N -> Exp N | AND : Exp B -> Exp B -> Exp B | OR : Exp B -> Exp B-> Exp B | EQ : Exp N -> Exp N -> Exp B.
|
Inductive
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_fuzzer.v
|
Exp
| |
Val : ty -> Set := | iNv : nat -> Val N | iBv : bool -> Val B.
|
Inductive
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_fuzzer.v
|
Val
| |
eval : forall {T: ty}, Exp T -> Val T -> Prop := | E_Num n : eval (NUM n) (iNv n) | E_Bool b : eval (BOOL b) (iBv b) | E_Plus e1 e2 n1 n2 : eval e1 (iNv n1) -> eval e2 (iNv n2) -> eval (PLUS e1 e2) (iNv (n1 + n2)) | E_AND e1 e2 b1 b2 : eval e1 (iBv b1) -> eval e2 (iBv b2) -> eval (AND e1 e2) (iBv (b1 && b2)) | E_OR e1 e2 b1 b2 : eval e1 (iBv b1) -> eval e2 (iBv b2) -> eval (OR e1 e2) (iBv (b1 || b2)) | E_EQ e1 e2 n1 n2 : eval e1 (iNv n1) -> eval e2 (iNv n2) -> eval (EQ e1 e2) (iBv (Nat.eqb n1 n2)). Elpi Command fuzz. Elpi Accumulate lp:{{ pred fuzz i:term, o:term. % fuzzin rule: we look for a Coq term (?Op ?A ?B) and we turn it in (AND ?A ?B) % only if the new term is well typed. fuzz {{ lp:Op lp:A lp:B }} Fuzzed :- coq.say "DEBUG: attempt at fuzzing binary op:" Op, fuzz A A1, fuzz B B1, Fuzzed = {{ AND lp:A1 lp:B1 }}, coq.typecheck Fuzzed _ ok, % we don't care about the type, only that it is ok coq.say "DEBUG: fuzzed!". % rule for the dependent function space fuzz (prod N S T) (prod N S1 T1) :- fuzz S S1, % we load the context with types for x and y, as well as the fact that % we fuzz x to y pi x y\ decl x N S ==> decl y N S1 ==> fuzz x y ==> fuzz (T x) (T1 y). % rule for application fuzz (app L) (app L1) :- std.map L fuzz L1. % rule for global constants fuzz (global X) (global X). % TODO: we should have clauses for all other type formers... pred rename-constructors i:constructor, o:pair constructor string. rename-constructors C (pr C C1) :- coq.gref->id (indc C) S, C1 is S ^ "1". main [str IN, str OUT ] :- % locate the inductive coq.locate IN (indt I), % fetch all its data, in particulat the types of the constructors coq.env.indt I B NP NPU A KN KT, % fuzz all constructor types std.map KT fuzz KT1, % we rename them, otherwise Coq complains the names are already used std.map KN rename-constructors KN1, % declare the new inductive coq.build-indt-decl (pr I OUT) B NP NPU A KN1 KT1 Decl, coq.env.add-indt Decl _. }}. Elpi fuzz eval eval1. (* let's print our new, broken, semantics ;-) *) Print eval1.
|
Inductive
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_fuzzer.v
|
eval
| |
r T (t : T) := Build { p1 : nat; p2 : t = t; _ : p2 = refl_equal; }.
|
Record
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_import_projections.v
|
r
| |
r1 (A : Type) : Type := { f1 : A; f2 : nat; }.
|
Record
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_import_projections.v
|
r1
| |
r := mk { proj1 : T1; proj2 : T2 }.
|
Record
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_record_expansion.v
|
r
| |
f (x : r) := Body(proj1 x,proj2 x). Is expanded to:
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_record_expansion.v
|
f
| |
f1 v1 v2 := Body(v1,v2). And recursively, if g uses f, then g1 must use f1... The idea is to take "f", replace "(x : r)" with as many abstractions as needed in order to write "mk v1 v2", then replace "x" with "mk v1 v2", finally fire iota reductions such as "proj1 (mk v1 v2) = v1" to obtain "f1". Then record a global replacement "f x = f1 v2 v2" whenever "x = mk v1 v2". *) Elpi Db record.expand.db lp:{{ % This data base will contain all the expansions performed previously. % For example, if f was expandded to f1 we would have this clause: % expand (app[f, R | L]) (app[f1, V1, V2 | L1]) :- % expand R (app[k, V1, V2]), std.map L expand L1. % [expand A B] can be used to perform a replacement, eg % (expand (const "foo") (const "bar") :- !) ==> expand A B pred expand i:term, o:term. }}. Elpi Accumulate record.expand.db lp:{{ shorten std.{ map }. :name "expand:start" expand (global _ as C) C :- !. expand (pglobal _ _ as C) C :- !. expand (sort _ as C) C :- !. expand (fun N T F) (fun N T1 F1) :- !, expand T T1, pi x\ expand x x ==> expand (F x) (F1 x). expand (let N T B F) (let N T1 B1 F1) :- !, expand T T1, expand B B1, pi x\ expand x x ==> expand (F x) (F1 x). expand (prod N T F) (prod N T1 F1) :- !, expand T T1, (pi x\ expand x x ==> expand (F x) (F1 x)). expand (app L) (app L1) :- !, map L expand L1. expand (fix N Rno Ty F) (fix N Rno Ty1 F1) :- !, expand Ty Ty1, pi x\ expand x x ==> expand (F x) (F1 x). expand (match T Rty B) (match T1 Rty1 B1) :- !, expand T T1, expand Rty Rty1, map B expand B1. expand (primitive _ as C) C :- !. }}. Elpi Command record.expand. Elpi Accumulate Db record.expand.db. Elpi Accumulate lp:{{ % This builds a clause to replace "proji (k y1..yn)" by "yi" pred build-iotared-clause i:term, i:(pair constant term), o:prop. build-iotared-clause T (pr Proj Var) C :- coq.env.global (const Proj) HD, % HD is the global term for Proj C = (pi L AppVar\ expand(app [HD,T|L]) AppVar :- coq.mk-app Var L AppVar). % The core algorithm ---------------------------------------------------------- % It is idiomatic in λProlog to perform a single recursion over the data and % perform multiple tasks while going. Here we both obtain the expanded term % and the clause that records that expansion. Indeed the binders introduced % in the new term (standing for the record fialds) and the quantifications % introduced in the clause are very similar. % missing in std pred cons_assoc_opt i:option A, i:B, i:list (pair A B), o:list (pair A B). cons_assoc_opt none _ X X. cons_assoc_opt (some A) B X [pr A B|X]. % a package of data that we need to carry but rarely fully access kind info type. type info inductive % the record to expand -> gref % the term being expanded -> gref % the term being expanded and its expanded name -> list (option constant) % canonical projections -> constructor % record constructor -> term % record constructor type -> info. % This predicate turns the OldBo in "fun x : r => OldBo" into % "fun v1 v2 => NewBo". It is fueled by "KTY" (corresponding to the type % of the record constructor). In parallel it consumes the list of projections, % so that it can record that the i-th projection should be replaced by % the variable standing for the i-th record field (accumulator called Iota) pred expand-abstraction i:info, i:term, % the varibale binding the record in the input term % fuel i:term, % the type of the record constructor i:list (option constant), % projections i:term, o:term, % the Old and New body i:term, % constructor applied to all arguments treated so far i:list (pair constant term), % iota rules for reductions so far % used by expand-spine, accumulated here i:list term, i:list term, % variables for the head of the clause (LHS and RHS) i:list prop, o:prop. % accumulator for the premises of the clause, and the clause expand-abstraction Info Rec (prod N S F) [P|PS] OldBo (fun N S Bo) KArgs Iota AccL AccR Premises (pi x\ Clause x) :- !, pi x\ expand x x ==> expand-abstraction Info Rec (F x) PS OldBo (Bo x) {coq.mk-app KArgs [x]} {cons_assoc_opt P x Iota} AccL [x|AccR] Premises (Clause x). expand-abstraction Info Rec (let N S B F) [P|PS] OldBo (let N S B Bo) KArgs Iota AccL AccR Premises Clause :- !, pi x\ expand x x ==> % a let in is not a real argument to KArgs, but may need a "iota" redex, since the projection could exist expand-abstraction Info Rec (F x) PS OldBo (Bo x) KArgs {cons_assoc_opt P x Iota} AccL AccR Premises Clause. expand-abstraction Info Rec _ [] OldBo Result ExpandedRecord Iota AccL AccR Premises Clause :- % generate all substitutions std.map Iota (build-iotared-clause ExpandedRecord) IotaClauses, ExpansionClause = expand Rec ExpandedRecord, % eta expand the record to obtain a new body (that typechecks) (ExpansionClause ==> expand OldBo NewBo), !, % continue, but schedule iota reductions (pre-existing projections became iota redexes) IotaClauses ==> expand-spine Info NewBo Result AccL AccR [ExpansionClause|Premises] Clause. % This predicate travrses the spine of lambdas. When it finds an abstraction % on the record R is calls expand-abstraction. Finally it copies the term, % applying all substitutions accumulated while descending the spine. pred expand-spine i:info, i:term, o:term, % input and output term i:list term, i:list term, % variables for the LHS and RHS of the clause head i:list prop, o:prop. % premises and final clause % if we find a lambda over the record R we expand expand-spine (info R _ _ Projs K KTY as Info) (fun _ LTy Bo) Result AccL AccR Premises (pi r\ Clause r) :- coq.env.global (indt R) LTy, !, pi r\ expand-abstraction Info r KTY Projs (Bo r) Result {coq.env.global (indc K)} [] [r|AccL] AccR Premises (Clause r). % otherwise we traverse the spine expand-spine Info (fun Name Ty Bo) (fun Name Ty1 Bo1) AccL AccR Premises (pi x y\ Clause x y) :- !, expand Ty Ty1, !, pi x y\ expand x y ==> expand y y ==> expand-spine Info (Bo x) (Bo1 y) [x|AccL] [y|AccR] [expand x y|Premises] (Clause x y). expand-spine Info (let Name Ty V Bo) (let Name Ty1 V1 Bo1) AccL AccR Premises (pi x y\ Clause x y) :- !, expand Ty Ty1, !, expand V V1, !, pi x y\ expand x y ==> expand y y ==> expand-spine Info (Bo x) (Bo1 y) [x|AccL] [y|AccR] [expand x y|Premises] (Clause x y). % at the end of the spine we fire the iota redexes and complete the clause expand-spine (info _ GR NGR _ _ _) X Y AccL AccR Premises Clause :- expand X Y, !, % we build "app[f,x1..xn|rest]" (pi rest1\ coq.mk-app (global GR) {std.append {std.rev AccL} rest1} (L rest1)), (pi rest2\ coq.mk-app (global NGR) {std.append {std.rev AccR} rest2} (R rest2)), % we can now build the clause "expand (app[f,L1..Ln|Rest1]) (app[f1,R1..Rn|Rest2])" % here we quantify only the tails, the other variables were quantified during % expand-* Clause = (pi rest1 rest2\ expand (L rest1) (R rest2) :- [!, std.map rest1 expand rest2 | Premises]). % The entry point of the main algorithm, just fetchs some data and passes initial % values for the accumulators. pred expand-record i:inductive, i:gref, i:gref, i:term, o:term, o:prop. expand-record R GR NGR X Y Clause :- std.assert! (coq.env.indt R tt 0 0 _ [K] [KTY]) "record is too complex for this example", coq.env.projections R Projs, expand-spine (info R GR NGR Projs K KTY) X Y [] [] [] Clause. % This simply dispatches between global references ---------------------------- % The only cleverness is that "expand" also builds the clause to be added to % the data base, and that clause has to mention the name of the constant to be % generated. Since we don't know it yet (Coq tells us in response to coq.env.add-const) % we postulate a name for that constant "nc" and later replace it with the real one "NC" pred expand-gref i:inductive, i:gref, i:string, o:prop. expand-gref Record (const C) Name Clause :- !, std.do! [ std.assert! (coq.env.const C (some Bo) _) "only transparent constants can be expanded", (pi nc\ expand-record Record (const C) nc Bo NewBo (NClause nc)), std.assert-ok! (coq.typecheck NewBo _) "illtyped", coq.env.add-const Name NewBo _ _ NC, Clause = NClause (const NC), ]. expand-gref _ (indt _) _ _ :- coq.error "Not implemented yet". expand-gref _ (indc _) _ _ :- coq.error "It makes no sense to expand a constructor alone, expand the inductive instead". % Entry point ----------------------------------------------------------------- main [str R, str In, str Prefix] :- !, std.assert! (coq.locate R (indt Record)) "The first argument must be a record name", std.assert! (coq.locate In GR) "The second argument must be a global term", NewName is Prefix ^ {coq.gref->id GR}, expand-gref Record GR NewName Clause, % We want our clauses to take precensence over the structural ones of "expand" coq.elpi.accumulate _ "record.expand.db" (clause _ (before "expand:start") Clause). main _ :- coq.error "usage: Elpi record.expand record_name global_term prefix". }}.
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_record_expansion.v
|
f1
| |
r := { T :> Type; X := T; op : T -> X -> bool }.
|
Record
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_record_expansion.v
|
r
| |
f b (t : r) (q := negb b) := fix rec (l1 l2 : list t) := match l1, l2 with | nil, nil => b | cons x xs, cons y ys => andb (op _ x y) (rec xs ys) | _, _ => q end. Elpi record.expand r f "expanded_". Print f. Print expanded_f. (* so that we can see the new "expand" clause *) Elpi Print record.expand "elpi_examples/record.expand".
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_record_expansion.v
|
f
| |
g t l s h := (forall x y, op t x y = false) /\ f true t l s = h. Elpi record.expand r g "expanded_". Print expanded_g.
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_record_expansion.v
|
g
| |
x := 1.
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_reduction_surgery.v
|
x
| |
y := 1.
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_reduction_surgery.v
|
y
| |
alias := plus.
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/example_reduction_surgery.v
|
alias
| |
bool2nat (b : bool) := if b then 1 else 0. Fail Elpi check_arg (1 = true). (* .fails *) Check (1 = true). (*| The command still fails even if we told Coq how to inject booleans values into the natural numbers. Indeed the `Check` commands works. The call to :builtin:`coq.typecheck` modifies the term in place, it can assign implicit arguments (like the type parameter of `eq`) but it cannot modify the structure of the term. To do so, one has to use the :builtin:`coq.elaborate-skeleton` API. |*) #[arguments(raw)] Elpi Command elaborate_arg. Elpi Accumulate lp:{{ main [trm T] :- std.assert-ok! (coq.elaborate-skeleton T Ty T1) "illtyped arg", coq.say "T=" T, coq.say "T1=" T1, coq.say "Ty=" Ty. }}. Elpi elaborate_arg (1 = true). (*|
|
Coercion
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_command.v
|
bool2nat
| |
how :e:`T` is not touched by the call to this API, and how :e:`T1` is a copy of :e:`T` where the hole after `eq` is synthesized and the value `true` injected to `nat` by using `bool2nat`. It is also possible to manipulate term arguments before typechecking them, but note that all the considerations on holes in the tutorial about the HOAS representation of Coq terms apply here. An example of tool taking advantage of this possibility is Hierarchy Builder: the declarations it receives would not typecheck in the current context, but do once the context is temporarily augmented with ad-hoc canonical structure instances. ======== Examples ======== ------------------- Synthesizing a term ------------------- Synthesizing a term typically involves reading an existing declaration and writing a new one. The relevant APIs are in the `coq.env.*` namespace and are named after the global reference they manipulate, eg :builtin:`coq.env.const` for reading and :builtin:`coq.env.add-const` for writing. Here we implement a little command that given an inductive type name generates a term of type `nat` whose value is the number of constructors of the given inductive type. |*) Elpi Command constructors_num. Elpi Accumulate lp:{{ pred int->nat i:int, o:term. int->nat 0 {{ 0 }}. int->nat N {{ S lp:X }} :- M is N - 1, int->nat M X. main [str IndName, str Name] :- std.assert! (coq.locate IndName (indt GR)) "not an inductive type", coq.env.indt GR _ _ _ _ Kn _, % the names of the constructors std.length Kn N, % count them int->nat N Nnat, % turn the integer into a nat coq.env.add-const Name Nnat _ _ _. % save it }}. Elpi constructors_num bool nK_bool. Print nK_bool. Elpi constructors_num False nK_False. Print nK_False. Fail Elpi constructors_num plus nK_plus. (* .fails *) Fail Elpi constructors_num not_there bla. (* .fails *) (*| The command starts by locating the first argument and asserting it points to an inductive type. This line is idiomatic: :builtin:`coq.locate` aborts if the string cannot be located, and if it relates it to a :e:`gref` which is not :e:`indt` (for example :e:`const plus`) :stdlib:`assert!` aborts with the given error message. :builtin:`coq.env.indt` lets one access all the details of an inductive type, here we just use the list of constructors. The twin API :builtin:`coq.env.indt-decl` lets one access the declaration of the inductive in HOAS form, which might be easier to manipulate in other situations, like the next example. Then the program crafts a natural number and declares a constant for it. ------------------------ Abstracting an inductive ------------------------ For the sake of introducing :lib:`copy`, the swiss army knife of λProlog, we write a command which takes an inductive type declaration and builds a new one abstracting the former one on a given term. The new inductive has a parameter in place of the occurrences of that term. |*) Elpi Command abstract. Elpi Accumulate lp:{{ % a renaming function which adds a ' to an ident (a string) pred prime i:id, o:id. prime S S1 :- S1 is S ^ "'". pred id i:id, o:id. id X X. main [str Ind, trm Param] :- % the term to be abstracted out, P of type PTy std.assert-ok! (coq.elaborate-skeleton Param PTy P) "illtyped parameter", % fetch the old declaration std.assert! (coq.locate Ind (indt I)) "not an inductive type", coq.env.indt-decl I Decl, % let's start to craft the new declaration by putting a % parameter A which has the type of P (NewDecl : indt-decl) = parameter "A" explicit PTy Decl', % let's make a copy, capturing all occurrences of P with a % (which stands for the parameter) (pi a\ (copy P a :- !) ==> copy-indt-decl Decl (Decl' a)), % to avoid name clashes, we rename the type and its constructors % (we don't need to rename the parameters) coq.rename-indt-decl id prime prime NewDecl DeclRenamed, % we type check the inductive declaration, since abstracting % random terms may lead to illtyped declarations (type theory % is hard) std.assert-ok! (coq.typecheck-indt-decl DeclRenamed) "can't be abstracted", coq.env.add-indt DeclRenamed _. }}.
|
Remark
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_command.v
|
how
| |
tree := leaf | node : tree -> option nat -> tree -> tree. Elpi abstract tree (option nat). Print tree'. (*| As expected `tree'` has a parameter `A`. Now let's focus on :lib:`copy`. The standard coq library (loaded by the command template) contains a definition of copy for terms and declarations. An excerpt: .. code:: elpi copy X X :- name X. % checks X is a bound variable copy (global _ as C) C. copy (fun N T F) (fun N T1 F1) :- copy T T1, pi x\ copy (F x) (F1 x). copy (app L) (app L1) :- std.map L copy L1. :e:`copy` implements the identity: it builds, recursively, a copy of the first term into the second argument. Unless one loads in the context a new rule, which takes precedence over the identity ones. Here we load: .. code:: elpi copy P a which, at run time, looks like .. code:: elpi copy (app [global (indt «option»), global (indt «nat»)]) c0 and that rule masks the one for `app` when the sub-term being copied is exactly `option nat`. The API :lib:`copy-indt-decl` copies an inductive declaration and calls `copy` on all the terms it contains (e.g. the type of the constructors). The :lib:`copy` predicate is very flexible, but sometimes one needs to collect some data along the way. The sibling API :lib:`fold-map` lets one do that. An excerpt: .. code:: elpi fold-map (fun N T F) A (fun N T1 F1) A2 :- fold-map T A T1 A1, pi x\ fold-map (F x) A1 (F1 x) A2. For example one can use :lib:`fold-map` to collect into a list all the occurrences of inductive type constructors in a given term, then use the list to postulate the right number of binders for them, and finally use :lib:`copy` to capture them. ==================================== Using DBs to store data across calls ==================================== A Db can be created with the command: |*) Elpi Db name.db lp:{{ pred some-pred. }}. (*| and a Db can be later extended via `Elpi Accumulate`. As a convention, we like Db names to end in a .db suffix. A Db is pretty much like a regular program but can be *shared* among other programs and is accumulated *by name*. Since is a Db is accumulated *when a program runs* the *current contents of the Db are used*. Moreover the Db can be extended by Elpi programs themselves thanks to the API :builtin:`coq.elpi.accumulate`, enabling code to save a state which is then visible at subsequent runs. The initial contents of a Db, `pred some-pred.` in the example above, is usually just the type declaration for the predicates part of the Db, and maybe a few default rules. Let's define a Db. |*) Elpi Db age.db lp:{{ % A typical Db is made of one main predicate pred age o:string, o:int. % the Db is empty for now, we put a rule giving a % descriptive error and we name that rule "age.fail". :name "age.fail" age Name _ :- coq.error "I don't know who" Name "is!". }}. (*| Elpi rules can be given a name via the :e:`:name` attribute. Named rules serve as anchor-points for new rules when added to the Db. Let's define a `Command` that makes use of a Db. |*) Elpi Command age. Elpi Accumulate Db age.db. (* we accumulate the Db *) Elpi Accumulate lp:{{ main [str Name] :- age Name A, coq.say Name "is" A "years old". }}. Fail Elpi age bob. (* .fails *) (*| Let's put some data in the Db. Given that the Db contains a catch-all rule, we need the new ones to be put before it. |*) Elpi Accumulate age.db lp:{{ :before "age.fail" % we place this rule before the catch all age "bob" 24. }}. Elpi age bob. (*| Extending data bases this way is fine, but requires the user of our command to be familiar with Elpi's syntax, which is not very nice. Instead, we can write a new program that uses the :builtin:`coq.elpi.accumulate` API to extend the Db. |*) Elpi Command set_age. Elpi Accumulate Db age.db. Elpi Accumulate lp:{{ main [str Name, int Age] :- TheNewRule = age Name Age, coq.elpi.accumulate _ "age.db" (clause _ (before "age.fail") TheNewRule). }}. Elpi set_age "alice" 21. Elpi age "alice". (*| Additions to a Db are a Coq object, a bit like a Notation or a Type Class instance: these object live inside a Coq module (or a Coq file) and become active when that module is Imported. Deciding to which Coq module these extra rules belong is important and :builtin:`coq.elpi.accumulate` provides a few options to tune that. Here we passed :e:`_`, that uses the default setting. See the :type:`scope` and :type:`clause` data types for more info. .. _inspecting: --------------- Inspecting a Db --------------- So far we did query a Db but sometimes one needs to inspect the whole contents. |*) Elpi Command print_all_ages. Elpi Accumulate Db age.db. Elpi Accumulate lp:{{ :before "age.fail" age _ _ :- !, fail. % softly main [] :- std.findall (age _ _) Rules, std.forall Rules print-rule. pred print-rule i:prop. print-rule (age P N) :- coq.say P "is" N "years old". }}. Elpi print_all_ages. (*| The :stdlib:`std.findall` predicate gathers in a list all solutions to a query, while :stdlib:`std.forall` iterates a predicate over a list. It is important to notice that :builtin:`coq.error` is a fatal error which aborts an Elpi program. Here we shadow the catch all clause with a regular failure so that :stdlib:`std.findall` can complete to list all the results. =================== Polishing a command =================== The details do make the difference, some times. ---------- Attributes ---------- Elpi programs can be prefixed with attributes, like `#[local]`. Attributes are not passed as arguments but rather as a rule in the context, a bit like the option :e:`@holes!` we have seen before. |*) Elpi Command attr. Elpi Accumulate lp:{{ main _ :- attributes A, % we fetch the list of attributes from the context coq.say A. }}. #[this, more(stuff="33")] Elpi attr. (*| The first attribute, :e:`elpi.loc` is always present and corresponds to the location in the source file of the command. Then we find an attribute for :e:`"this"` holding the empty string and an attribute for :e:`"more.stuff"` holding the string :e:`"33"`. Attributes are usually validated (parsed) and turned into regular options using :lib-common:`coq.parse-attributes` and a description of their types using the :libtype-common:`attribute-type` data type: |*) Elpi Command parse_attr. Elpi Accumulate lp:{{ pred some-code. some-code :- get-option "more.stuff" N, get-option "this" B, coq.say N B. main _ :- attributes A, coq.parse-attributes A [ att "this" bool, att "more.stuff" int, ] Opts, coq.say "options=" Opts, (Opts =!=> some-code). }}. #[this, more(stuff="33")] Elpi parse_attr. Fail #[unknown] Elpi parse_attr. (* .fails *) (*| Note that :e:`get-option` links a string with a datum of type :e:`any`, which means no type checking is performed on it. It is recommended to wrap calls to get-option into other predicates typed in a more precise way. Eg: .. code:: elpi pred get-my-option o:int. get-my-option I :- get-option "my-option-name" I. ----------------------------- Extending the command grammar ----------------------------- Elpi programs can be exported as regular Coq commands, so that the final user does not need to type `Elpi` to invoke them. |*) Elpi Command Say. Elpi Accumulate lp:{{ main [str S] :- coq.say S. }}. Elpi Export Say. (* extend the Coq command grammar *) Say "That is all folks!". (*| Not yet... Coq offers no equivalent of `Tactic Notation` for commands. Still Elpi commands accept any symbol or keyword as strings. It is up to the programmer to catch and report parse errors. |*) Elpi Command Go. Elpi Accumulate lp:{{ main [str Src, str "=>", str Tgt, str "/", str F] :- !, coq.say "going from" Src "to" Tgt "via" F. main _ :- coq.error "Parse error! Use: go <from> => <to> / <via>". }}. Elpi Export Go. Go source => target / plane. Fail Go nowhere. (* .fails *) (*| ---------------- Reporting errors ---------------- Last, (good) Elpi programs should fail reporting intelligible error messages, as the previous one. |*) Elpi Command bad. Elpi Accumulate lp:{{ main []. }}. Elpi Export bad. Fail bad 1. (* .fails *) (*| If they just fail, they produce the following generic error: .. mquote:: .s(bad 1).msg(inconvenience) :language: text You should use the :builtin:`coq.error` API or the :stdlib:`assert!` one to abort a program. There is a dedicated :builtin:`coq.ltac.fail` API to abort tactics. Warnings can be reported using the :builtin:`coq.warning` which lets you pick a name and category. In turn these can be used to disable or make fatal your warnings (as any other Coq warning). ===================== Parsing and Execution ===================== Since version 8.18 Coq has separate parsing and execution phases, respectively called synterp and interp. Since Coq has an extensible grammar the parsing phase is not entirely performed by the parser: after parsing one sentence Coq evaluates its synterp action. The synterp actions of a command like `Import A.` are the subset of its effect which affect parsing, like enabling a notation. Later, during the execution phase, Coq evaluates its interp actions, which include effects like putting lemma in scope or enabling type class instances etc. Synterp actions are quick, if only because they don't really manipulate Coq terms, hence no type checking and the like. Being able to parse an entire document quickly is important for developing reactive user interfaces, but requires some extra work when defining new commands, in particular to identify their synterp. Each command defined with Coq-Elpi is split into two programs, one running during the parsing phase and the other one during the execution phase. Each API that affects the parser, i.e. APIs dealing with modules and sections like begin/end-module or import/export, is available to both the synterp and the interp program under the same name, but its actual effect is limited to what concerns the current phase. Hence all these APIs have to be called at *both* synterp and interp time and *in the same order*. At synterp time the data types and the APIs are restricted, in particular Coq terms are not available. When a command argument contains a term, that term is replaced by `_` at synterp time. In the following example, the synterp program can see the name of the definition and the fact that a body was given, but not the value of the body. |*) Elpi Command hello_synterp. #[synterp] Elpi Accumulate lp:{{ main [const-decl Name Body _] :- coq.say "synterp" Name ":=" Body. }}. Elpi Accumulate lp:{{ main [const-decl Name Body _] :- coq.say "interp" Name ":=" Body. }}. Elpi hello_synterp Definition x := 2. (*| This simple command has no real synterp action, one could safely remove the synterp code. On the contrary when a command performs actions affecting the parser then it must come equipped with some synterp code performing the corresponding actions. |*)
|
Inductive
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_command.v
|
tree
| |
w := 3.
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_command.v
|
w
| |
x := 2. Elpi Query lp:{{ coq.locate "x" GR, % all global references have a type coq.env.typeof GR Ty, % destruct GR to obtain its constant part C GR = const C, % constants may have a body, do have a type coq.env.const C (some Bo) TyC }}. (*| An expression like :e:`indt «nat»` is not a Coq term (or better a type) yet. The :constructor:`global` term constructor turns a :type:`gref` into an actual :type:`term`. .. code:: elpi type global gref -> term. ---------------------------------- Constructors :e:`app` and :e:`fun` ---------------------------------- The :constructor:`app` term constructor takes a list of terms and builds the (n-ary) application. The first term is the head, while the others are the arguments. For example :e:`app [global (indc «S»), global (indc «O»)]` is the representation of `1`. .. code:: elpi type app list term -> term. Let's move to binders! |*)
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_HOAS.v
|
x
| |
f := fun x : nat => x. Elpi Query lp:{{ coq.locate "f" (const C), coq.env.const C (some Bo) _ }}. (*| The :constructor:`fun` constructor carries a pretty printing hint ```x```, the type of the bound variable `nat` and a function describing the body: .. code:: elpi type fun name -> term -> (term -> term) -> term. .. note:: :type:`name` is just for pretty printing: in spite of carrying a value in the Coq world, it has no content in Elpi (like the unit type) Elpi terms of type :type:`name` are just identifiers written between ````` (backticks). .. coq:: Elpi Query lp:{{ fun `foo` T B = fun `bar` T B % names don't matter }}. API such as :builtin:`coq.name-suffix` lets one craft a family of names starting from one, eg ``coq.name-suffix `H` 1 N`` sets :e:`N` to ```H1```. ------------------------------------ Constructors :e:`fix` and :e:`match` ------------------------------------ The other binders :constructor:`prod` (Coq's `forall`, AKA `Π`) and :constructor:`let` are similar, so let's rather focus on :constructor:`fix` here. |*) Elpi Query lp:{{ coq.locate "plus" (const C), coq.env.const C (some Bo) _ }}. (*| The :constructor:`fix` constructor carries a pretty printing hint, the number of the recursive argument (starting at :e:`0`), the type of the recursive function and finally the body where the recursive call is represented via a bound variable .. code:: elpi type fix name -> int -> term -> (term -> term) -> term. A :constructor:`match` constructor carries the term being inspected, the return clause and a list of branches. Each branch is a Coq function expecting in input the arguments of the corresponding constructor. The order follows the order of the constructors in the inductive type declaration. .. code:: elpi type match term -> term -> list term -> term. The return clause is represented as a Coq function expecting in input the indexes of the inductive type, the inspected term and generating the type of the branches. |*)
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_HOAS.v
|
f
| |
m (h : 0 = 1 ) P : P 0 -> P 1 := match h as e in eq _ x return P 0 -> P x with eq_refl => fun (p : P 0) => p end. Elpi Query lp:{{ coq.locate "m" (const C), coq.env.const C (some (fun _ _ h\ fun _ _ p\ match _ (RT h p) _)) _, coq.say "The return type of m is:" RT }}. (*| --------------------- Constructor :e:`sort` --------------------- The last term constructor worth discussing is :constructor:`sort`. .. code:: elpi type sort universe -> term. type prop universe. type typ univ -> universe. The opaque type :type:`univ` is a universe level variable. Elpi holds a store of constraints among these variables and provides APIs named :e:`coq.univ.*` to impose constraints. |*) Elpi Query lp:{{ coq.sort.sup U U1, coq.say U "<" U1, % This constraint can't be allowed in the store! not(coq.sort.leq U1 U) }}. (*| .. note:: the user is not expected to declare universe constraints by hand The type checking primitives update the store of constraints automatically and put Coq universe variables in place of Elpi's unification variables (:e:`U` and :e:`V` below). Let's play a bit more with universe constraints using the :builtin:`coq.typecheck` API: |*) Elpi Query lp:{{ ID = (fun `x` (sort (typ U)) x\ x), A = (sort (typ U)), % the same U as before B = (sort (typ V)), coq.say "(id b) is:" (app [ID, B]), % error, since U : U is not valid coq.typecheck (app [ID, A]) T (error ErrMsg), coq.say "(id a) is illtyped:" ErrMsg, % ok, since V : U is possible coq.typecheck (app [ID, B]) T ok, % remark: U and V are now Coq's univ with constraints coq.say "after typing (id b) is:" (app [ID, B]) ":" T, coq.univ.print }}. (*| The :stdtype:`diagnostic` data type is used by :builtin:`coq.typecheck` to tell if the term is well typed. The constructor :e:`ok` signals success, while :e:`error` carries an error message. In case of success universe constraints are added to the store. ============================= Quotations and Antiquotations ============================= Writing Gallina terms as we did so far is surely possible but very verbose and unhandy. Elpi provides a system of quotations and antiquotations to let one take advantage of the Coq parser to write terms. The antiquotation, from Coq to Elpi, is written `lp:{{ ... }}` and we have been using it since the beginning of the tutorial. The quotation from Elpi to Coq is written :e:`{{:coq ... }}` or also just :e:`{{ ... }}` since the `:coq` is the default quotation (Coq has no default quotation, hence you always need to write `lp:` there). |*) Elpi Query lp:{{ % the ":coq" flag is optional coq.say {{:coq 1 + 2 }} "=" {{ 1 + 2 }} }}. (*| Of course quotations can nest. |*) Elpi Query lp:{{ coq.locate "S" S, coq.say {{ 1 + lp:{{ app[global S, {{ 0 }} ] }} }} % elpi.... coq.. elpi........... coq elpi coq }}. (*| One rule governs bound variables: .. important:: if a variable is bound in a language, Coq or Elpi, then the variable is only visible in that language (not in the other one). The following example is horrible but proves this point. In real code you are encouraged to pick appropriate names for your variables, avoiding gratuitous (visual) clashes. |*) Elpi Query lp:{{ coq.say (fun `x` {{nat}} x\ {{ fun x : nat => x + lp:{{ x }} }}) % e c c e }}. (*| A commodity quotation without parentheses let's one quote identifiers omitting the curly braces. That is `lp:{{ ident }}` can be written just `lp:ident`. |*) Elpi Query lp:{{ coq.say (fun `x` {{nat}} x\ {{ fun x : nat => x + lp:x }}) % e c c e }}. (*| It is quite frequent to put Coq variables in the scope of an Elpi unification variable, and this can be done by simply writing `lp:(X a b)` which is a shorthand for `lp:{{ X {{ a }} {{ b }} }}`. .. warning:: writing `lp:X a b` (without parentheses) would result in a Coq application, not an Elpi one Let's play a bit with these shorthands: |*) Elpi Query lp:{{ X = (x\y\ {{ lp:y + lp:x }}), % x and y live in Elpi coq.say {{ fun a b : nat => lp:(X a b) }} % a and b live in Coq }}. (*| Another commodity quotation lets one access the coqlib feature introduced in Coq 8.10. Rocqlib gives you an indirection between your code and the actual name of constants. |*) Register Coq.Init.Datatypes.nat as my.N. Register Coq.Init.Logic.eq as my.eq. Elpi Query lp:{{ coq.say {{ fun a b : lib:my.N => lib:@my.eq lib:my.N a b }} }}. (*| .. note:: The (optional) `@` in `lib:@some.name` disables implicit arguments. The `{{:gref .. }}` quotation lets one build the gref data type, instead of the term one. It supports `lib:` as well. |*) Elpi Query lp:{{ coq.say {{:gref nat }}, coq.say {{:gref lib:my.N }}. }}. (*| The last thing to keep in mind when using quotations is that implicit arguments are inserted (according to the `Arguments` setting in Coq) but not synthesized automatically. It is the job of the type checker or elaborator to synthesize them. We shall see more on this in the section on `holes`_. |*) Elpi Query lp:{{ T = (fun `ax` {{nat}} a\ {{ fun b : nat => lp:a = b }}), coq.say "before:" T, coq.typecheck T _ ok, coq.say "after:" T }}. (*| =========== The context =========== The context of Elpi (the hypothetical program made of rules loaded via :e:`=>`) is taken into account by the Coq APIs. In particular every time a bound variable is crossed, the programmer *must* load in the context a rule attaching to that variable a type. There are a few facilities to do that, but let's first see what happens if one forgets it. |*) Fail Elpi Query lp:{{ T = {{ fun x : nat => x + 1 }}, coq.typecheck T _ ok, T = fun _ _ Bo, pi x\ coq.typecheck (Bo x) _ _ }}. (* .fails *) (*| This fatal error says that :e:`x` in :e:`(Bo x)` is unknown to Coq. It is a variable postulated in Elpi, but it's type, `nat`, was lost. There is nothing wrong per se in using :e:`pi x\ ` as we did if we don't call Coq APIs under it. But if we do, we have to record the type of :e:`x` somewhere. In some sense Elpi's way of traversing a binder is similar to a Zipper. The context of Elpi must record the part of the Zipper context that is relevant for binders. The two predicates :builtin:`decl` and :builtin:`def` are used for that purpose: .. code:: elpi func decl term -> name, term. % Var Name Ty func def term -> name, term, term. % Var Name Ty Bo where :e:`def` is used to cross a :e:`let`. |*) Elpi Query lp:{{ T = {{ fun x : nat => x + 1 }}, coq.typecheck T _ ok, T = fun N Ty Bo, pi x\ decl x N Ty ==> coq.typecheck (Bo x) _ ok }}. (*| In order to ease this task, Rocq-Elpi provides a few commodity macros such as `@pi-decl`: .. code:: elpi macro @pi-decl N T F :- pi x\ decl x N T ==> F x. .. note:: the precedence of lambda abstraction :e:`x\ ` lets you write the following code without parentheses for :e:`F`. |*) Elpi Query lp:{{ T = {{ fun x : nat => x + 1 }}, coq.typecheck T _ ok, T = fun N Ty Bo, @pi-decl N Ty x\ coq.typecheck (Bo x) _ ok }}. (*| .. tip:: :e:`@pi-decl N Ty x\ ` takes arguments in the same order of :constructor:`fun` and :constructor:`prod`, while :e:`@pi-def N Ty Bo x\ ` takes arguments in the same order of :constructor:`let`. .. _holes: ========================== Holes (implicit arguments) ========================== An "Evar" (Coq slang for existentially quantified meta variable) is represented as a Elpi unification variable and a typing constraint. |*) Elpi Query lp:{{ T = {{ _ }}, coq.say "raw T =" T, coq.sigma.print, coq.say "--------------------------------", coq.typecheck T {{ nat }} ok, coq.sigma.print }}. (*| Before the call to :builtin:`coq.typecheck`, :builtin:`coq.sigma.print` prints nothing interesting, while after the call it also prints the following syntactic constraint: .. mquote:: .s(Elpi).msg(suspended on X0) :language: elpi which indicates that the hole :e:`X0` is linked to a Coq evar and is expected to have type `nat`. Now the bijective mapping from Coq evars to Elpi's unification variables is not empty anymore: .. mquote:: .s(Elpi).msg{Rocq-Elpi mapping:*[?]X11 <-> X0*} :language: text Note that Coq's evar identifiers are of the form `?X<n>`, while the Elpi ones have no leading `?`. The Coq Evar map says that `?X11` has type `nat`: .. mquote:: .s(Elpi).msg{EVARS:*[?]X11==[[] |- nat[]]*} :language: text The intuition is that Coq's Evar map (AKA sigma or evd), which assigns typing judgement to evars, is represented with Elpi constraints which carry the same piece of info. Naked Elpi unification variables, when passed to Coq's API, are automatically linked to a Coq evar. We postpone the explanation of the difference "raw" and "elab" unification variables to the chapter about tactics, here the second copy of :e:`X0` in the evar constraint plays no role. Now, what about the typing context? |*) Elpi Query lp:{{ T = {{ fun x : nat => x + _ }}, coq.say "raw T =" T, T = fun N Ty Bo, @pi-decl N Ty x\ coq.typecheck (Bo x) {{ nat }} ok, coq.sigma.print. }}. (*| In the value of raw :e:`T` we can see that the hole in `x + _`, which occurs under the binder :e:`c0\ `, is represented by an Elpi unification variable :e:`X0 c0`, that means that :e:`X0` sees :e:`c0` (:e:`c0` is in the scope of :e:`X0`). The constraint is this time a bit more complex. Let's dissect it: .. mquote:: .s(Elpi).msg(suspended on X0) :language: elpi Here `{...}` is the set of names (not necessarily minimized) used in the constraint, while `?-` separates the assumptions (the context) from the conclusion (the suspended goal). The mapping between Coq and Elpi is: .. mquote:: .s(Elpi).msg{Rocq-Elpi mapping:*[?]X13 <-> X0*} :language: text where `?X13` can be found in Coq's sigma: .. mquote:: .s(Elpi).msg{EVARS:*[?]X13==[[]x |- nat[]]*} :language: text As expected both Elpi's constraint and Coq's evar map record a context with a variable :e:`x` (of type `nat`) which is in the scope of the hole. Unless one is writing a tactic, Elpi's constraints are just used to represent the evar map. When a term is assigned to a variable the corresponding constraint is dropped. When one is writing a tactic, things are wired up so that assigning a term to an Elpi variable representing an evar resumes a type checking goal to ensure the term has the expected type. We will explain this in detail in the tutorial about tactics. ---------------------------- Outside the pattern fragment ---------------------------- This encoding of evars is such that the programmer does not need to care much about them: no need to carry around an assignment/typing map like the Evar map, no need to declare new variables there, etc. The programmer can freely call Coq API passing an Elpi term containing holes. There is one limitation, though. The rest of this tutorial describes it and introduces a few APIs and options to deal with it. The limitation is that the automatic declaration and mapping does not work in all situations. In particular it only works for Elpi unification variables which are in the pattern fragment, which mean that they are applied only to distinct names (bound variables). This is the case for all the `{{ _ }}` one writes inside quotations, for example, but it is not hard to craft a term outside this fragment. In particular we can use Elpi's substitution (function application) to put an arbitrary term in place of a bound variable. |*) Fail Elpi Query lp:{{ T = {{ fun x : nat => x + _ }}, % remark the hole sees x T = fun N Ty Bo, % 1 is the offending term we put in place of x Bo1 = Bo {{ 1 }}, % Bo1 is outside the pattern fragment coq.say "Bo1 (not in pattern fragment) =" Bo1, % boom coq.typecheck Bo1 {{ nat }} ok. }}. (* .fails *) (*| This snippet fails hard, with the following message: .. mquote:: .s(Elpi).msg(Flexible term outside) :language: elpi Indeed :e:`Bo1` contains a term outside the pattern fragment, the second argument of `plus`, which is obtained by replacing :e:`c0` with `{{ 1 }}` in :e:`X0 c0`. While programming Coq extensions in Elpi, it may happen that we want to use a Coq term as a syntax tree (with holes) and we need to apply substitutions to it but we don't really care about the scope of holes. We would like these holes to stay `{{ _ }}` (a fresh hole which sees the entire context of bound variables). In some sense, we would like `{{ _ }}` to be a special dummy constant, to be turned into an actual hole on the fly when needed. This use case is perfectly legitimate and is supported by all APIs taking terms in input thanks to the :macro:`@holes!` option. |*) Elpi Query lp:{{ T = {{ fun x : nat => x + _ }}, T = fun N Ty Bo, Bo1 = Bo {{ 1 }}, coq.say "Bo1 before =" Bo1, % by loading this rule in the context, we set % the option for the APIs called under it (@holes! ==> coq.typecheck Bo1 {{ nat }} ok), coq.say "Bo1 after =" Bo1. }}. (*| Note that after the call to :builtin:`coq.typecheck`, :e:`X0` is assigned the term :e:`_\ X1`, that means that the offending argument has been pruned (discarded). .. note:: All APIs taking a term support the :macro:`@holes!` option. In addition to the :macro:`@holes!` option, there is a class of APIs which can deal with terms outside the pattern fragment. These APIs take in input a term *skeleton*. A skeleton is not modified in place, as :builtin:`coq.typecheck` does with its first argument, but is rather elaborated to a term related to it. In some sense APIs taking a skeleton are more powerful, because they can modify the structure of the term, eg. insert a coercions, but are less precise, in the sense that the relation between the input and the output terms is not straightforward (it's not unification). |*)
|
Definition
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_HOAS.v
|
m
| |
nat2bool n := match n with O => false | _ => true end. Open Scope bool_scope. Elpi Query lp:{{ T = {{ fun x : nat => x && _ }}, T = fun N Ty Bo, Bo1 = Bo {{ 1 }}, coq.elaborate-skeleton Bo1 {{ bool }} Bo2 ok }}. (*| Here :e:`Bo2` is obtained by taking :e:`Bo1`, considering all unification variables as holes and all `{{ Type }}` levels as fresh (the are none in this example), and running Coq's elaborator on it. The result is a term with a similar structure (skeleton), but a coercion is inserted to make :e:`x` fit as a boolean value, and a fresh hole :e:`X1` is put in place of the term :e:`X0 (app [global (indc «S»), global (indc «O»)])` which is left untouched. Skeletons and their APIs are described in more details in the tutorial on commands. That is all for this tutorial. You can continue by reading the tutorial about `commands <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_command.html>`_ or the one about `tactics <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_tactic.html>`_. |*)
|
Coercion
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_coq_elpi_HOAS.v
|
nat2bool
| |
tutorial x y : x + 1 = y. elpi show. (* .in .messages *) Abort. (*| In the Elpi code up there :e:`Proof` is the hole for the current goal, :e:`Type` the statement to be proved and :e:`Ctx` the proof context (the list of hypotheses). Since we don't assign :e:`Proof` the tactic makes no progress. Elpi prints somethinglike this: .. mquote:: .s(elpi).msg{Goal:*X0 c0 c1*} :language: text The first line is the proof context: proof variables are bound Elpi variables (here :e:`c0` and :e:`c1`), the context is a list of predicates holding on them (their type in Coq). For example: .. code:: decl c0 `x` (global (indt «nat»)) asserts that :e:`c0` (pretty printed as `x`) has type `nat`. Then we see that the value of :e:`Proof` is :e:`X0 c0 c1`. This means that the proof of the current goal is represented by Elpi's variable :e:`X0` and that the variable has :e:`c0` and :e:`c1` in scope (the proof term can use them). Finally we see the type of the goal `x + 1 = y`. The :e:`_Trigger` component, which we did not print, is a variable that, when assigned, triggers the elaboration of its value against the type of the goal and obtains a value for :e:`Proof` this way. Keeping in mind that the :builtin:`solve` predicate relates one goal to a list of subgoals, we implement our first tactic which blindly tries to solve the goal. |*) Elpi Tactic blind. Elpi Accumulate lp:{{ solve (goal _ Trigger _ _ _) [] :- Trigger = {{0}}. solve (goal _ Trigger _ _ _) [] :- Trigger = {{I}}. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
tutorial
| |
test_blind : True * nat. Proof. (* .in *) split. - elpi blind. - elpi blind. Show Proof. (* .in .messages *) Qed. (*| Since the assignment of a term to :e:`Trigger` triggers its elaboration against the expected type (the goal statement), assigning the wrong proof term results in a failure which in turn results in the other rule being tried. For now, this is all about the low level mechanics of tactics which is developed further in the section `The-proof-engine`_. We now focus on how to better integrate tactics written in Elpi with Ltac. --------------------- Integration with Ltac --------------------- For a simple tactic like `blind` the list of subgoals is easy to write, since it is empty, but in general one should collect all the holes in the value of :e:`Proof` (the checked proof term) and build goals out of them. There is a family of APIs named after :libtac:`refine`, the mother of all tactics, in `elpi-ltac.elpi <https://github.com/LPCIC/coq-elpi/blob/master/elpi/elpi-ltac.elpi>`_ which does this job for you. Usually a tactic builds a (possibly partial) term and calls :libtac:`refine` on it. Let's rewrite the `blind` tactic using this schema. |*) Elpi Tactic blind2. Elpi Accumulate lp:{{ solve G GL :- refine {{0}} G GL. solve G GL :- refine {{I}} G GL. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_blind
| |
test_blind2 : True * nat. Proof. (* .in *) split. - elpi blind2. - elpi blind2. Qed. (*| This schema works even if the term is partial, that is if it contains holes corresponding to missing sub proofs. Let's write a tactic which opens a few subgoals, for example let's implement the `split` tactic. .. important:: Elpi's equality (that is, unification) on Coq terms corresponds to alpha equivalence, we can use that to make our tactic less blind. The head of a rule for the solve predicate is *matched* against the goal. This operation cannot assign unification variables in the goal, only variables in the rule's head. As a consequence the following rule for `solve` is only used when the statement features an explicit conjunction. |*) About conj. (* remark the implicit arguments *) Elpi Tactic split. Elpi Accumulate lp:{{ solve (goal _ _ {{ _ /\ _ }} _ _ as G) GL :- !, % conj has 4 arguments, but two are implicits % (_ are added for them and are inferred from the goal) refine {{ conj _ _ }} G GL. solve _ _ :- % This signals a failure in the Ltac model. A failure % in Elpi, that is no more clauses to try, is a fatal % error that cannot be caught by Ltac combinators like repeat. coq.ltac.fail _ "not a conjunction". }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_blind2
| |
test_split : exists t : Prop, True /\ True /\ t. Proof. (* .in *) eexists. repeat elpi split. (* The failure is caught by Ltac's repeat *) (* Remark that the last goal is left untouched, since it did not match the pattern {{ _ /\ _ }}. *) all: elpi blind. Show Proof. (* .in .messages *) Qed. (*| The tactic `split` succeeds twice, stopping on the two identical goals `True` and the one which is an evar of type `Prop`. We then invoke `blind` on all goals. In the third case the type checking constraint triggered by assigning `{{0}}` to `Trigger` fails because its type `nat` is not of sort `Prop`, so it backtracks and picks `{{I}}`. Another common way to build an Elpi tactic is to synthesize a term and then call some Ltac piece of code finishing the work. The API :libtac:`coq.ltac.call` invokes some Ltac piece of code passing to it the desired arguments. Then it builds the list of subgoals. Here we pass an integer, which in turn is passed to `fail`, and a term, which in turn is passed to `apply`. |*)
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_split
| |
helper_split2 n t := fail n || apply t. Elpi Tactic split2. Elpi Accumulate lp:{{ solve (goal _ _ {{ _ /\ _ }} _ _ as G) GL :- coq.ltac.call "helper_split2" [int 0, trm {{ conj }}] G GL. solve _ _ :- coq.ltac.fail _ "not a conjunction". }}.
|
Ltac
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
helper_split2
| |
test_split2 : exists t : Prop, True /\ True /\ t. Proof. (* .in *) eexists. repeat elpi split2. all: elpi blind. Qed. (*| ============================= Arguments and Tactic Notation ============================= Elpi tactics can receive arguments. Arguments are received as a list, which is the last argument of the goal constructor. This suggests that arguments are attached to the current goal being observed, but we will dive into this detail later on. |*) Elpi Tactic print_args. Elpi Accumulate lp:{{ solve (goal _ _ _ _ Args) _ :- coq.say Args. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_split2
| |
test_print_args : True. (* .in *) elpi print_args 1 x "a b" (1 = 0). (* .in .messages *) Abort. (*| The convention is that numbers like `1` are passed as :e:`int 1`, identifiers or strings are passed as :e:`str "arg"` and terms have to be put between parentheses. .. important:: terms are received in raw format, eg before elaboration Indeed the type argument to `eq` is a variable. One can use APIs like :builtin:`coq.elaborate-skeleton` to infer holes like :e:`X0`. See the :type:`argument` data type for a detailed description of all the arguments a tactic can receive. Now let's write a tactic which behaves pretty much like the :libtac:`refine` one from Coq, but prints what it does using the API :builtin:`coq.term->string`. |*) Elpi Tactic refine. Elpi Accumulate lp:{{ solve (goal _ _ Ty _ [trm S] as G) GL :- % check S elaborates to T of type Ty (the goal) coq.elaborate-skeleton S Ty T ok, coq.say "Using" {coq.term->string T} "of type" {coq.term->string Ty}, % since T is already checked, we don't check it again refine.no_check T G GL. solve (goal _ _ _ _ [trm S]) _ :- Msg is {coq.term->string S} ^ " does not fit", coq.ltac.fail _ Msg. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_print_args
| |
test_refine (P Q : Prop) (H : P -> Q) : Q. Proof. (* .in *) Fail elpi refine (H). (* .fails *) elpi refine (H _). Abort. (*| --------------------------------
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_refine
| |
arguments to Elpi arguments -------------------------------- It is customary to use the Tactic Notation command to attach a nicer syntax to Elpi tactics. In particular `elpi tacname` accepts as arguments the following `bridges for Ltac values <https://coq.inria.fr/doc/master/refman/proof-engine/ltac.html#syntactic-values>`_ : * `ltac_string:(v)` (for `v` of type `string` or `ident`) * `ltac_int:(v)` (for `v` of type `int` or `integer`) * `ltac_term:(v)` (for `v` of type `constr` or `open_constr` or `uconstr` or `hyp`) * `ltac_(string|int|term)_list:(v)` (for `v` of type `list` of ...) Note that the Ltac type associates some semantics to the action of passing the arguments. For example `hyp` will accept an identifier only if it is an hypotheses of the context. While `uconstr` does not type check the term, which is the recommended way to pass terms to an Elpi tactic (since it is likely to be typed anyway by the Elpi tactic). |*) Tactic Notation "use" uconstr(t) := elpi refine ltac_term:(t). Tactic Notation "use" hyp(t) := elpi refine ltac_term:(t).
|
Ltac
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
arguments
| |
test_use (P Q : Prop) (H : P -> Q) (p : P) : Q. Proof. (* .in *) use (H _). Fail use q. (* .fails .in .messages *) use p. Qed. Tactic Notation "print" uconstr_list_sep(l, ",") := elpi print_args ltac_term_list:(l).
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_use
| |
test_print (P Q : Prop) (H : P -> Q) (p : P) : Q. print P, p, (H p). (* .in .messages *) Abort. (*| ======== Failure ======== The :builtin:`coq.error` aborts the execution of both Elpi and any enclosing Ltac context. This failure cannot be caught by Ltac. On the contrary the :builtin:`coq.ltac.fail` builtin can be used to abort the execution of Elpi code in such a way that Ltac can catch it. This API takes an integer akin to Ltac's fail depth together with the error message to be displayed to the user. Library functions of the `assert!` family call, by default, :builtin:`coq.error`. The flag `@ltacfail! N` can be set to alter this behavior and turn errors into calls to `coq.ltac.fail N`. |*) Elpi Tactic abort. Elpi Accumulate lp:{{ solve _ _ :- coq.error "uncatchable". }}. Goal True. Fail elpi abort || idtac. Abort. Elpi Tactic fail. Elpi Accumulate lp:{{ solve (goal _ _ _ _ [int N]) _ :- coq.ltac.fail N "catchable". }}. Goal True. elpi fail 0 || idtac. Fail elpi fail 1 || idtac. Abort. (*| ======== Examples ======== ------------------------------- Let's code `assumption` in Elpi ------------------------------- `assumption` is a very simple tactic: we look up in the proof context for an hypothesis which unifies with the goal. Recall that `Ctx` is made of :builtin:`decl` and :builtin:`def` (here, for simplicity, we ignore the latter case). |*) Elpi Tactic assumption. Elpi Accumulate lp:{{ solve (goal Ctx _ Ty _ _ as G) GL :- % H is the name for hyp, Ty is the goal std.mem Ctx (decl H _ Ty), refine H G GL. solve _ _ :- coq.ltac.fail _ "no such hypothesis". }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_print
| |
test_assumption (P Q : Prop) (p : P) (q : Q) : P /\ id Q. Proof. (* .in *) split. elpi assumption. Fail elpi assumption. (* .fails *) Abort. (*| As we hinted before, Elpi's equality is alpha equivalence. In the second goal the assumption has type `Q` but the goal has type `id Q` which is convertible (unifiable, for Coq's unification) to `Q`. Let's improve our tactic by looking for an assumption which is unifiable with the goal, and not just alpha convertible. The :builtin:`coq.unify-leq` calls Coq's unification for types (on which cumulativity applies, hence the `-leq` suffix). The :stdlib:`std.mem` utility, thanks to backtracking, eventually finds an hypothesis that satisfies the following predicate (ie unifies with the goal). |*) Elpi Tactic assumption2. Elpi Accumulate lp:{{ solve (goal Ctx _ Ty _ _ as G) GL :- % std.mem is backtracking (std.mem! would stop at the first hit) std.mem Ctx (decl H _ Ty'), coq.unify-leq Ty' Ty ok, refine H G GL. solve _ _ :- coq.ltac.fail _ "no such hypothesis". }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_assumption
| |
test_assumption2 (P Q : Prop) (p : P) (q : Q) : P /\ id Q. Proof. (* .in *) split. all: elpi assumption2. Qed. (*| :libtac:`refine` does unify the type of goal with the type of the term, hence we can simplify the code further. We obtain a tactic very similar to our initial `blind` tactic, which picks candidates from the context rather than from the program itself. |*) Elpi Tactic assumption3. Elpi Accumulate lp:{{ solve (goal Ctx _ _ _ _ as G) GL :- std.mem Ctx (decl H _ _), refine H G GL. solve _ _ :- coq.ltac.fail _ "no such hypothesis". }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_assumption2
| |
test_assumption3 (P Q : Prop) (p : P) (q : Q) : P /\ id Q. Proof. (* .in *) split. all: elpi assumption3. Qed. (*| ------------------------ Let's code `set` in Elpi ------------------------ The `set` tactic takes a term, possibly with holes, and makes a let-in out of it. It gives us the occasion to explain the :lib:`copy` utility. |*) Elpi Tactic find. Elpi Accumulate lp:{{ solve (goal _ _ T _ [trm X]) _ :- pi x\ ((copy X x :- !) ==> copy T (Tabs x)), if (occurs x (Tabs x)) (coq.say "found" {coq.term->string X}) (coq.ltac.fail _ "not found"). }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_assumption3
| |
test_find (P Q : Prop) : (P /\ P) \/ (P /\ Q). Proof. (* .in *) elpi find (P). Fail elpi find (Q /\ _). (* .fails .in .messages *) elpi find (P /\ _). Abort. (*| This first approximation only prints the term it found, or better the first instance of the given term. Now lets focus on :lib:`copy`. An excerpt: .. code:: elpi copy X X :- name X. % checks X is a bound variable copy (global _ as C) C. copy (fun N T F) (fun N T1 F1). copy T T1, pi x\ copy (F x) (F1 x). copy (app L) (app L1) :- !, std.map L copy L1. Copy implements the identity: it builds, recursively, a copy of the first term into the second argument. Unless one loads in the context a new rule, which takes precedence over the identity ones. Here we load: .. code:: elpi copy X x which, at run time, looks like .. code:: elpi copy (app [global (indt «andn»), sort prop, sort prop, c0, X0 c0 c1]) c2 and that rule masks the one for :constructor:`app` when the sub-term being copied matches `(P /\ _)`. The first time this rule is used :e:`X0` is assigned, making the rule represent the term `(P /\ P)`. Now let's refine the tactic to build a let-in, and complain if the desired name is already taken. |*) Elpi Tactic set. Elpi Accumulate lp:{{ solve (goal _ _ T _ [str ID, trm X] as G) GL :- pi x\ ((copy X x :- !) ==> copy T (Tabs x)), if (occurs x (Tabs x)) (if (coq.ltac.id-free? ID G) true (coq.warn ID "is already taken, Elpi will make a name up"), coq.id->name ID Name, Hole x = {{ _ : lp:{{ Tabs x }} }}, % a hole with a type refine (let Name _ X x\ Hole x) G GL) (coq.ltac.fail _ "not found"). }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_find
| |
test_set (P Q : Prop) : (P /\ P) \/ (P /\ Q). Proof. (* .in *) elpi set "x" (P). unfold x. Fail elpi set "x" (Q /\ _). (* .fails .in .messages *) elpi set "x" (P /\ _). Abort. (*| For more examples of (basic) tactics written in Elpi see the `eltac app <https://github.com/LPCIC/coq-elpi/tree/master/apps/eltac>`_. .. _The-proof-engine: ================ The proof engine ================ In this section we dive into the details of the proof engine, that is how goals are represented in Elpi and how things are wired up behind the scenes. Let's inspect the proof state a bit deeper: |*) Elpi Tactic show_more. Elpi Accumulate lp:{{ solve (goal Ctx _Trigger Type Proof _) _ :- coq.say "Goal:" Ctx "|-" Proof ":" Type, coq.say "Proof state:", coq.sigma.print. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_set
| |
test_show_more x : x + 1 = 0. elpi show_more. (* .in .messages *) Abort. (*| In addition to the goal we print the Elpi and Coq proof state, plus the link between them. The proof state is the collection of goals together with their types. On the Elpi side this state is represented by constraints for the :e:`evar` predicate. .. mquote:: .s(elpi show_more).msg{*c0*evar (X1 c0)*suspended on X1, X0*} :language: text One can recognize the set of bound variables `{c0}`, the hypothetical context of rules about these variable (that also corresponds to the proof context), and finally the suspended goal :e:`evar (X1 c0) .. (X0 c0)`. The set of constraints on `evar` represents the Coq data structure called sigma (sometimes also called evd or evar_map) that is used to represent the proof state in Coq. It is printed just afterwards: .. mquote:: .s(elpi show_more).msg{EVARS:*[?]X97*x + 1 = 0*} :language: text .. mquote:: .s(elpi show_more).msg{Rocq-Elpi mapping:*RAW:*[?]X97 <-> *X1*ELAB:*[?]X97 <-> *X0*} :language: text Here `?X97` is a Coq evar linked with Elpi's :e:`X0` and :e:`X1`. :e:`X1` represents the goal (the trigger) while :e:`X0` represent the proof. The meaning of the :e:`evar` Elpi predicate linking the two is that the term assigned to the trigger :e:`X1` has to be elaborated to the final proof term :e:`X0`, that should be a well typed term of type `x + 1 = 0`. This means that when an Elpi tactic assigns a value to :e:`X1` some procedure to turn that value into :e:`X0` is triggered. That procedure is called elaboration and it is currently implemented by calling the :builtin:`coq.elaborate-skeleton` API. Given this set up, it is impossible to use a term of the wrong type as a Proof. Let's rewrite the `split` tactic without using :libtac:`refine`. |*) Elpi Tactic split_ll. Elpi Accumulate lp:{{ solve (goal Ctx Trigger {{ lp:A /\ lp:B }} Proof []) GL :- !, Trigger = {{ conj _ _ }}, % triggers elaboration, filling Proof Proof = {{ conj lp:Pa lp:Pb }}, GL = [seal G1, seal G2], G1 = goal Ctx _ A Pa [], G2 = goal Ctx _ B Pb []. solve _ _ :- coq.ltac.fail _ "not a conjunction". }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_show_more
| |
test_split_ll : exists t : Prop, True /\ True /\ t. Proof. (* .in *) eexists. repeat elpi split_ll. all: elpi blind. Qed. (*| Crafting by hand the list of subgoal is not easy. In particular here we did not set up the new trigger for :e:`Pa` and :e:`Pb`, nor seal the goals appropriately (we did not bind proof variables). The :builtin:`coq.ltac.collect-goals` API helps us doing this. |*) Elpi Tactic split_ll_bis. Elpi Accumulate lp:{{ solve (goal Ctx Trigger {{ lp:A /\ lp:B }} Proof []) GL :- !, % this triggers the elaboration Trigger = {{ conj _ _ }}, % we only take main goals coq.ltac.collect-goals Proof GL _ShelvedGL. solve _ _ :- coq.ltac.fail _ "not a conjunction". }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_split_ll
| |
test_split_ll_bis : exists t : Prop, True /\ True /\ t. Proof. (* .in *) eexists. repeat elpi split_ll_bis. all: elpi blind. Qed. (*| At the light of that, :libtac:`refine` is simply: .. code:: elpi refine T (goal _ RawEv _ Ev _) GS :- RawEv = T, coq.ltac.collect-goals Ev GS _. Now that we know the low level plumbing, we can use :libtac:`refine` ;-) The only detail we still have to explain is what exactly a :type:`sealed-goal` is. A sealed goal wraps into a single object all the proof variables and the assumptions about them, making this object easy (or better, sound) to pass around. ------------------ multi-goal tactics ------------------ Since Coq 8.4 tactics can see more than one goal (multi-goal tactics). You can access this feature by using `all:` goal selector: * if the tactic is a regular one, it will be used on each goal independently * if the tactic is a multi-goal one, it will receive all goals In Elpi you can implement a multi-goal tactic by providing a rule for the :builtin:`msolve` predicate. Since such a tactic will need to manipulate multiple goals, potentially living in different proof context, it receives a list of :type:`sealed-goal`, a data type which seals a goal and its proof context. |*) Elpi Tactic ngoals. Elpi Accumulate lp:{{ msolve GL _ :- coq.say "#goals =" {std.length GL}, coq.say GL. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_split_ll_bis
| |
test_undup (P Q : Prop) : P /\ Q. Proof. (* .in *) split. all: elpi ngoals. Abort. (*| This simple tactic prints the number of goals it receives, as well as the list itself. We see something like: .. mquote:: .s(elpi ngoals).msg{*goals =*} :language: text .. mquote:: .s(elpi ngoals).msg{*nabla*} :language: elpi :constructor:`nabla` binds all proof variables, then :constructor:`seal` holds a regular goal, which in turn carries the proof context. In order to operate inside a goal one can use the :libtac:`coq.ltac.open` utility, which postulates all proof variables using :e:`pi x\ ` and loads the proof context using :e:`=>`. Operating on multiple goals at the same time is doable, but not easy. In particular the two proof context have to be related in some way. The following simple multi goal tactic shrinks the list of goals by removing duplicates. As one can see, there is much room for improvement in the :e:`same-ctx` predicate. |*) Elpi Tactic undup. Elpi Accumulate lp:{{ pred same-goal i:sealed-goal, i:sealed-goal. same-goal (nabla G1) (nabla G2) :- % TODO: proof variables could be permuted pi x\ same-goal (G1 x) (G2 x). same-goal (seal (goal Ctx1 _ Ty1 P1 _) as G1) (seal (goal Ctx2 _ Ty2 P2 _) as G2) :- same-ctx Ctx1 Ctx2, % this is an elpi builtin, aka same_term, which does not % unify but rather compare two terms without assigning variables Ty1 == Ty2, P1 = P2. pred same-ctx i:goal-ctx, i:goal-ctx. same-ctx [] []. same-ctx [decl V _ T1|C1] [decl V _ T2|C2] :- % TODO: we could compare up to permutation... % TODO: we could try to relate def and decl T1 == T2, same-ctx C1 C2. pred undup i:sealed-goal, i:list sealed-goal, o:list sealed-goal. undup _ [] []. undup G [G1|GN] GN :- same-goal G G1. undup G [G1|GN] [G1|GL] :- undup G GN GL. msolve [G1|GS] [G1|GL] :- % TODO: we could find all duplicates, not just % copies of the first goal... undup G1 GS GL. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_undup
| |
test_undup (P Q : Prop) (p : P) (q : Q) : P /\ Q /\ P. Proof. (* .in *) repeat split. Show Proof. (* .in .messages *) all: elpi undup. Show Proof. (* .in .messages *) - apply p. - apply q. Qed. (*| The two calls to show proof display, respectively: .. mquote:: .s(Show Proof).msg{*conj [?]Goal (conj [?]Goal0 [?]Goal1)*} :language: text .. mquote:: .s(Show Proof).msg{*conj [?]Goal (conj [?]Goal0 [?]Goal)*} :language: text the proof term is the same but for the fact that after the tactic the first and last missing subterm (incomplete proof tree branch) are represented by the same hole `?Goal`. Indeed by solving one, we can also solve the other. ------------- LCF tacticals ------------- On the notion of sealed-goal it is easy to define the usual LCF combinators, also known as Ltac tacticals. Tacticals usually take in input one or more tactic, here the precise type definition: .. code:: elpi typeabbrev tactic (sealed-goal -> (list sealed-goal -> prop)). A few tacticals can be found in the `elpi-ltac.elpi file <https://github.com/LPCIC/coq-elpi/blob/master/elpi/elpi-ltac.elpi>`_. For example this is the code of :libtac:`try`: .. code:: elpi pred try i:tactic, i:sealed-goal, o:list sealed-goal. try T G GS :- T G GS. try _ G [G]. ------------------------------ Setting arguments for a tactic ------------------------------ As we hinted before, tactic arguments are attached to the goal since they can mention proof variables. So the Ltac code: .. code:: coq intro H; apply H. has to be seen as 3 steps, starting from a goal `G`: * introduction of `H`, obtaining `G1` * setting the argument `H`, obtaining `G2` * calling apply, obtaining `G3` |*) Elpi Tactic argpass. Elpi Accumulate lp:{{ % this directive lets you use short names shorten coq.ltac.{ open, thenl, all }. type intro open-tactic. % goal -> list sealed-goal intro G GL :- refine {{ fun H => _ }} G GL. type set-arg-n-hyp int -> open-tactic. set-arg-n-hyp N (goal Ctx _ _ _ _ as G) [SG1] :- std.nth N Ctx (decl X _ _), coq.ltac.set-goal-arguments [trm X] G (seal G) SG1. type apply open-tactic. apply (goal _ _ _ _ [trm T] as G) GL :- refine T G GL. msolve SG GL :- all (thenl [ open intro, open (set-arg-n-hyp 0), open apply ]) SG GL. }}.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_undup
| |
test_argpass (P : Prop) : P -> P. Proof. (* .in *) elpi argpass. Qed. (*| Of course the tactic playing the role of `intro` could communicate back a datum to be passed to what follows .. code:: elpi thenl [ open (tac1 Datum), open (tac2 Datum) ] but the binder structure of :type:`sealed-goal` would prevent :e:`Datum` to mention proof variables, that would otherwise escape the sealing. The utility :libtac:`set-goal-arguments`: .. code:: elpi coq.ltac.set-goal-arguments Args G G1 G1wArgs tries to move :e:`Args` from the context of :e:`G` to the one of :e:`G1`. Relating the two proof contexts is not obvious: you may need to write your own procedure if the two contexts are very distant. ================ Tactics in terms ================ Elpi tactics can be used inside terms via the usual `ltac:(...)` quotation, but can also be exported to the term grammar. Here we write a simple tactic for default values, which optionally takes a bound to the search depth. |*) Elpi Tactic default. Elpi Accumulate lp:{{ pred default i:term, i:int, o:term. default _ 0 _ :- coq.ltac.fail _ "max search depth reached". default {{ nat }} _ {{ 46 }}. default {{ bool }} _ {{ false }}. default {{ list lp:A }} Max {{ cons lp:D nil }} :- Max' is Max - 1, default A Max' D. solve (goal _ _ T _ [] as G) GL :- default T 9999 P, refine P G GL. }}. Elpi Export default.
|
Lemma
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
test_argpass
| |
foo : nat := default. Print foo.
|
Definition
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
foo
| |
bar : list bool := default. Print bar. (*| The grammar entries for Elpi tactics in terms take an arbitrary number of arguments with the limitation that they are all terms: you can't pass a string or an integer as one would normally do. Here we use Coq's primitive integers to pass the search depth (in a compact way). |*) Elpi Accumulate default lp:{{ solve (goal _ _ T _ [trm (primitive (uint63 Max))] as G) GL :- coq.uint63->int Max MaxI, default T MaxI P, refine P G GL. }}. From Corelib Require Import PrimInt63. Open Scope uint63_scope. Fail Definition baz : list nat := default 1. (* .fails *)
|
Definition
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
bar
| |
baz : list nat := default 2. Print baz. (*| That is all folks! |*)
|
Definition
|
examples
|
[
"From elpi Require Import elpi.",
"From Corelib Require Import PrimInt63."
] |
examples/tutorial_coq_elpi_tactic.v
|
baz
| |
that in the premise the variable :math:`x` is still bound, this time not by a λ-abstraction but by the context :math:`\Gamma, x : A`. In λProlog the context is the set of hypothetical rules and :e:`pi\ ` -quantified variables and is implicitly handled by the runtime of the programming language. A slogan to keep in mind is that: .. important:: There is no such thing as a free variable! Indeed the variable bound by the λ-abstraction (of our data) is replaced by a fresh variable bound by the context (of our program). This is called binder mobility. See also the paper `Mechanized metatheory revisited <https://hal.inria.fr/hal-01884210/>`_ by Dale Miller which is an excellent introduction to these concepts. ========= Debugging ========= The most sophisticated debugging feature can be used via the Visual Studio Code extension ``gares.elpi-lang`` and its ``Elpi Tracer`` tab. --------------- Trace browser --------------- In order to generate a trace one needs to execute the ``Elpi Trace Browser.`` command and then run any Elpi code. |*) (* Elpi Trace Browser. *) Elpi Query stlc lp:{{ % We run the query in the stlc program of (fun (x\ fun y\ x)) Ty, coq.say Ty }}. (*| The trace file is generated in ``/tmp/traced.tmp.json``. If it does not load automatically one can do it manually by clicking on the load icon, in the upper right corner of the Elpi Tracer panel. .. note:: partial display of goals At the time of writing one may need to disable syntax highlighting in the extension settings in order to get a correct display. The trace browser displays, on the left column, a list of cards corresponding to a step performed by the interpreter. The right side of the panel gives more details about the selected step. In the image below one can see the goal, the rule being applied, the assignments performed by the unification of the rule's head with the goal, the subgoals generated. .. image:: tracer.png :width: 800 One can also look at the trace in text format (if VSCode is not an option, for example). |*) Elpi Trace. Elpi Query stlc lp:{{ % We run the query in the stlc program of (fun (x\ fun y\ x)) Ty, coq.say Ty }}. Fail Elpi Query stlc lp:{{ of (fun (x\ app x x)) Ty, coq.say Ty }}. (* .fails *) (*| The trace can be limited to a range of steps. Look at the numbers ``run HERE {{{``. |*) Elpi Trace 6 8. Elpi Query stlc lp:{{ of (fun (x\ fun y\ x)) Ty, coq.say Ty }}. (*| The trace can be limited to a (list of) predicates as follows: |*) Elpi Trace "of". Elpi Query stlc lp:{{ of (fun (x\ fun y\ x)) Ty, coq.say Ty }}. (*| One can combine the range of steps with the predicate: |*) Elpi Trace 6 8 "of". Elpi Query stlc lp:{{ of (fun (x\ fun y\ x)) Ty, coq.say Ty }}. (*| To switch traces off: |*) Elpi Trace Off. (*| --------------- Good old print --------------- A common λProlog idiom is to have a debug rule lying around. The :e:`:if` attribute can be used to make the rule conditionally interpreted (only if the given debug variable is set). |*) Elpi Debug "DEBUG_MYPRED". Elpi Program debug lp:{{ pred mypred i:int. :if "DEBUG_MYPRED" mypred X :- coq.say "calling mypred on " X, fail. mypred 0 :- coq.say "ok". mypred M :- N is M - 1, mypred N. }}. Elpi Query lp:{{ mypred 3 }}. (*| ------------------------ Printing entire programs ------------------------ Given that programs are not written in a single place, but rather obtained by accumulating code, Elpi is able to print a (full) program to an text file as follows. The obtained file provides a facility to filter rules by their predicate. Note that the first component of the path is a Coq Load Path (i.e. coqc options -R and -Q), the text file will be placed in the directory bound to it. |*) Elpi Print stlc "elpi_examples/stlc". (*| ----------------------------- Bounding the number of steps ----------------------------- Finally, one can bound the number of backchaining steps performed by the interpreter: |*) Elpi Query lp:{{ 0 = 0, 1 = 1 }}. Elpi Bound Steps 1. Fail Elpi Query lp:{{ 0 = 0, 1 = 1 }}. (* .fails *) (* it needs 2 steps! *) Elpi Bound Steps 0. (* Go back to no bound *) (*| =================== Pitfalls and tricks =================== Well, no programming language is perfect. --------------------------------------------- Precedence of :e:`,`, :e:`==>` and :e:`=>` --------------------------------------------- In this tutorial we only used :e:`==>` but Elpi also provides the standard λProlog implication :e:`=>`. They have the same meaning but different precedences w.r.t. :e:`,`. The code :e:`a, c ==> d, e` reads :e:`a, (c ==> (d,e))`, that means that the rule :e:`c` is available to both :e:`d` and :e:`e`. On the contrary the code :e:`a, c => d, e` reads :e:`a, (c ==> d), e`, making :e:`c` only available to :e:`d`. So, :e:`=>` binds stronger than :e:`,`, while :e:`==>` binds stronger only on the left. According to our experience the precedence of :e:`=>` is a common source of mistakes for beginners, if only because it is not stable by adding of debug prints, that is :e:`a => b` and :e:`a => print "doing b", b` have very different meaning (:e:`a` becomes only available to `print`!). In this tutorial we only used :e:`==>` that was introduced in Elpi 2.0, but there is code out there using :e:`=>`. Elpi 2.0 raises a warning if the right hand side of :e:`=>` is a conjenction with no parentheses. A concrete example: |*) Fail Elpi Query stlc lp:{{ pi x\ of x A => of x B, of x C }}. (* .fails *) Elpi Query stlc lp:{{ pi x\ of x A => (of x B, of x C) % both goals see of x A }}. Elpi Query stlc lp:{{ pi x\ of x A ==> of x B, of x C }}. (*| ------------------------------------------------- The :e:`=!=>` operator and functional predicates ------------------------------------------------- When an hypothetical rule is added to a functional predicate the determinacy may fail to detect its mutual exclusiveness, especially if the rule is generated dynamically as below: .. code:: elpi X = f P, X ==> q % static error, X could be anything Elpi 3.0 provides the :e:`=!=>` connective that adds a tail cut to the hypothetical rule, be it explicitly given or computed at run time. For example: .. code:: elpi (f P :- !) ==> q % fine, new rule for f cuts all the others, f still a function f P =!=> q % desugars to the above (f P :- h P, !) ==> q % fine as before (f P :- h P) =!=> q % desugars to the above X = f P, X =!=> q % at run time it evaluates as below X = f P, X' = (X :- !), X' ==> q X = (f P :- h P), X =!=> q % at run time it evaluates as below X = f P, X' = (X :- h P, !), X' ==> q -------------------- Taming backtracking -------------------- Backtracking can lead to weird execution traces and bad performances. The main tool to eliminate backtracking is the cut operator, but one may forget to use it. Elpi provides two mechanisms to help with that. The former one is functional predicates: by declaring a predicate as functional one is typically forced to use cut. This is the recommended way of writing code since Elpi 3.0. The latter mechanism is the e :stdlib:`std.do!` predicate that can be used as follows. .. code:: elpi pred not-a-backtracking-one. not-a-backtracking-one :- condition, !, std.do! [ step, (generate, test), step, ]. In the example above once :e:`condition` holds we start a sequence of steps which we will not reconsider. Locally, backtracking is still available, e.g. between :e:`generate` and :e:`test`. See also the :stdlib:`std.spy-do!` predicate which prints each and every step, and the :stdlib:`std.spy` one which can be used to spy on a single one. ----------------------------------------------- Unification variables v.s. Imperative variables ----------------------------------------------- Unification variables sit in between variables in imperative programming and functional programming. In imperative programming a variable can hold a value, and that value can change over time via assignment. In functional languages variables always hold a value, and that value never changes. In logic programming a unification variable can either be unset (no value) or set to a value that never changes. Backtracking goes back in time, it is not visible to the program. As a result of this, code like .. code:: elpi pred bad-example. bad-example :- X is 1 + 2, X is 4 + 5. fails, because :e:`X` cannot be at the same time 3 and 9. Initially :e:`X` is unset, then it is set to 3, and finally the programmer is asserting that 3 (the value hold by :e:`X`) is equal to 9. The second call to :e:`is` does not change the value carried by :e:`X`! Unification, and hence the :e:`=` predicate, plays two roles. When :e:`X` is unset, :e:`X = v` sets the variable. When :e:`X` is set to :e:`u`, :e:`X = v` checks if the value of :e:`X` is equal to :e:`u`: it is equivalent to :e:`u = v`. =============== Further reading =============== The `λProlog website <http://www.lix.polytechnique.fr/~dale/lProlog/>`_ contains useful links to λProlog related material. Papers and other documentation about Elpi can be found at the `Elpi home on github <https://github.com/LPCIC/elpi/>`_. Three more tutorials specific to Elpi as an extension language for Coq can be found in the `examples folder <https://github.com/LPCIC/coq-elpi/blob/master/examples/>`_. You can continue by reading the one about the `HOAS for Coq terms <https://lpcic.github.io/coq-elpi/tutorial_coq_elpi_HOAS.html>`_. |*)
|
Remark
|
examples
|
[
"From elpi Require Import elpi."
] |
examples/tutorial_elpi_lang.v
|
that
| |
map2 : (nat -> nat -> nat) -> list nat -> list nat -> list nat. (* This example make use of the open-trm argument type in order to implement a tactic that takes in input expressions mentioning variables that are bound in the goal (and not in the proof context) *)
|
Axiom
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
map2
| |
easy_example : forall x, x + 1 = 1 + x. Proof. intros x. (* easy: x is bound by the proof context *) replace (x + 1) with (1 + x) by ring. reflexivity. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
easy_example
| |
hard_example : forall l, map (fun x => x + 1) l = map (fun x => 1 + x) l. Proof. intros l. (* hard: x is bound by a lambda in the goal *) Fail replace (x + 1) with (1 + x) by ring. (* fails and prints: The variable x was not found in the current environment.*) (* This example implements a new repl tactic that will instead succeed. *) Abort. (* Elpi provides a type of tactic argument called open-trm for terms with free variables. Since there is no such a thing as free variables in Elpi, a pre-processor closes the term under binders and pairs the closed term with the number of such "technical binders". *) Elpi Tactic show_open_term. Elpi Accumulate lp:{{ solve (goal _ _ _ _ [open-trm N F]) _ :- coq.say "The argument " {coq.term->string F} "was closed under" N "binders". }}. Goal map (fun x => x + x) nil = nil :> list nat. elpi show_open_term `(x + _). (* prints: The argument fun x : ?e => x + ?e1 was closed under 1 binders *) Abort. (* A key step in the implementation of repl is to align the technical binders of the open term with actual binders present in the goal. For this we use the names as written by the user. We call this operation instantiate *) (* We put the code into a file, so that we can reuse it later *) Elpi File instantiate.code lp:{{ % [instantiate-replacement N Ty x L R L1 R1] is called when crossing % a goal binder for the variable x named N and of type Ty. The replacement % L with R is instantiated (if possible) to L1 with R1 pred instantiate-replacement i:name, i:term, i:term, i:argument, i:argument, o:argument, o:argument. instantiate-replacement N Ty C L R L1 R1 :- std.do! [ instantiate N Ty C L L1, instantiate N Ty C R R1, ]. pred instantiate i:name, i:term, i:term, i:argument, o:argument. instantiate _ _ _ (open-trm 0 A) (open-trm 0 A) :- !. instantiate N T C (open-trm I F) (open-trm J F1) :- remove-binder-for N T C F F1, !, J is I - 1. instantiate _ _ _ X X. pred remove-binder-for i:name, i:term, i:term, i:term, o:term. % we found the binder remove-binder-for N _ C (fun N1 _ F) Res :- {coq.name->id N} = {coq.name->id N1}, !, % Remember that in Elpi all names are the same, eg `x` = `y` % coq.name->id gives a string, the string used for printing, and as one expects % not("x" = "y") Res = (F C). % we cross the binder and look deeper remove-binder-for N T C (fun N1 T1 F) (fun N1 T1 F1) :- @pi-decl N1 T1 x \ remove-binder-for N T C (F x) (F1 x). }}. Elpi Tactic test_instantiate. Elpi Accumulate File instantiate.code. Elpi Accumulate lp:{{ solve (goal _ _ {{ map2 lp:F _ _ = _ }} _ [(open-trm _ LF as L), (open-trm _ RF as R)]) _ :- coq.say "old replacement:" {coq.term->string LF} "with" {coq.term->string RF}, F = fun N Ty _, @pi-decl N Ty x\ instantiate-replacement N Ty x L R (open-trm _ (L1 x)) (open-trm _ (R1 x)), coq.say "new replacement:" {coq.term->string (L1 x)} "with" {coq.term->string (R1 x)}. }}. Goal map2 (fun x y => x - y) nil nil = nil. elpi test_instantiate `(x - y) `(y + x). (* prints: old replacement: fun (x : ?e) (y : ?e0) => x - y with fun (y : ?e1) (x : ?e2) => y + x new replacement: fun y : ?e0 => x - y with fun y : ?e1 => y + x
|
Lemma
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
hard_example
| |
that the technical binders are generated following a left-to-right traversal of the term, hence their order varies. This is the reason why we need the second rule for remove-binder-for. Also remark that L1 and R1 need to see the variable we crossed, and that is bound by pi: we are capturing the free variable by it (or better removing the techincal binding and replacing that bound variable by the variable bound by pi). *) Abort. (* We need a few helpers to cross the context *)
|
Remark
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
that
| |
congrP (A : Type) (B : A -> Type) (f g : forall x : A, B x) : f = g -> forall v1 v2 (p : v1 = v2), match p in _ = x return B x with eq_refl => f v1 end = g v2. Proof. now intros fg v1 v2 v1v2; rewrite fg, v1v2. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
congrP
| |
congrA (A B : Type) (f g : A -> B) : f = g -> forall v1 v2 (p : v1 = v2), f v1 = g v2. Proof. now intros fg v1 v2 v1v2; rewrite fg, v1v2. Qed. Elpi File congruence.code lp:{{ % iterates congrA and congrP to prove f x1..xn = f y1..yn from proofs of xi = yi % [congruence F G PFG Ty XS YS PXYS R] starting from a proof PFG that F = G % it consumes X Y and PXY : X = Y to build a proof R : (F X = G Y). It needs to % look at the type of F (and G) in order to decide which congruence lemma to apply pred conguence i:term, i:term, i:term, i:term, i:list term, i:list term, i: list term, o:term. conguence _ _ P _ [] [] [] P :- !. conguence F G PFG {{ _ -> lp:Ty }} [X|XS] [Y|YS] [PXY|PS] Q :- !, PFXGY = {{ congrA _ _ lp:F lp:G lp:PFG lp:X lp:Y lp:PXY }}, conguence {coq.mk-app F [X]} {coq.mk-app G [Y]} PFXGY Ty XS YS PS Q. conguence F G PFG {{ forall x, lp:(Ty x) }} [X|XS] [Y|YS] [PXY|PS] Q :- PFXGY = {{ congrP _ _ lp:F lp:G lp:PFG lp:X lp:Y lp:PXY }}, conguence {coq.mk-app F [X]} {coq.mk-app G [Y]} PFXGY (Ty X) XS YS PS Q. }}. Elpi Tactic test_congruence. Elpi Accumulate File congruence.code. Elpi Accumulate lp:{{ pred mk-refl i:term, o:term. mk-refl T {{ @refl_equal Type lp:T }} :- coq.typecheck-ty T _ ok, !. % we don't like Set mk-refl T {{ refl_equal lp:T }}. solve (goal _ _ {{ lp:A = lp:B }} _ _ as G) GL :- std.do! [ A = app[HD|Args1], B = app[HD|Args2], std.map2 Args1 Args2 (_\ mk-refl) Proofs, coq.typecheck HD Ty ok, conguence HD HD {{ refl_equal lp:HD }} Ty Args1 Args2 Proofs P, refine P G GL, ]. }}. Goal forall l, map (fun x => x) l = map (fun x => x) l :> list nat. intros. elpi test_congruence. Qed. (* We now build the final tactic *) Elpi Tactic replace. Elpi Accumulate File instantiate.code. Elpi Accumulate File congruence.code. Elpi Accumulate lp:{{ % [replace L R X Y P] replaces L by R in X obtaining Y and % a proof P that X = Y. P will contain holes (sub goals) for sub proofs % of L = R. pred replace i:argument, i:argument, i:term, o:term, o:term. % all binders are crossed and we find a term identical to L. % the proof is a hole of type L = R. replace (open-trm 0 L) (open-trm 0 R) L R P :- !, TY = {{ lp:L = lp:R }}, coq.typecheck-ty TY _ ok, coq.typecheck P TY ok. % we cross the binder by functional extensionality replace L R (fun N T F) (fun N T F1) {{ functional_extensionality lp:{{ fun N T F }} lp:{{ fun N T F1 }} lp:{{ fun N T Prf }}}} :- !, @pi-decl N T x\ instantiate-replacement N T x L R (L1 x) (R1 x), replace (L1 x) (R1 x) (F x) (F1 x) (Prf x). replace L R (app [HD|TS]) (app [HD|TS1]) Prf :- replace-list L R TS TS1 PS, coq.typecheck HD Ty ok, conguence HD HD {{ refl_equal lp:HD }} Ty TS TS1 PS Prf. % base cases replace _ _ X X {{ refl_equal lp:X }} :- name X, !. replace _ _ (global _ as C) C {{ @refl_equal Type lp:C }} :- coq.typecheck-ty C _ ok, !. % we don't like Set replace _ _ (global _ as C) C {{ refl_equal lp:C }} :- !. % we omit rules for primitive constants, fixpoints, let, forall, ... pred replace-list i:argument, i:argument, i:list term, o:list term, o:list term. replace-list _ _ [] [] []. replace-list L R [X|XS] [Y|YS] [P|PS] :- replace L R X Y P, replace-list L R XS YS PS. solve (goal _ _ {{ lp:X = lp:Y }} _ [(open-trm _ _ as L), (open-trm _ _ as R)] as G) GL :- !, std.do! [ replace L R X X1 P, refine {{ @eq_trans _ lp:X lp:X1 lp:Y lp:P _ }} G GL, ]. solve (goal _ _ {{ _ = _ }} _ _) _ :- !, coq.error "elpi: replace: the goal is not an equality". solve _ _ :- !, coq.error "elpi: replace: the two arguments must be open terms". }}. Tactic Notation (at level 0) "repl" uconstr(x) "with" uconstr(y) := elpi replace ltac_open_term:(x) ltac_open_term:(y); simpl. Tactic Notation (at level 0) "repl" uconstr(x) "with" uconstr(y) "by" tactic(t) := elpi replace ltac_open_term:(x) ltac_open_term:(y); try (simpl; t).
|
Lemma
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
congrA
| |
hard_example : forall l, map (fun x => x + 1) l = map (fun x => 1 + x) l. Proof. intros l. repl (x + 1) with (1 + x) by ring. reflexivity. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
hard_example
| |
hard_example2 : forall l, map2 (fun x y => x + 0 + y) l l = map2 (fun x y => y + x) l l. Proof. intros l. repl (x + 0 + y) with (y + x) by ring. reflexivity. Qed. (* An extended version of this tactic by Y. Bertot can be found in the tests/ directory under the name test_open_terms.v *)
|
Lemma
|
examples-stdlib
|
[
"From elpi Require Import elpi.",
"Require Import Arith ZArith List FunctionalExtensionality."
] |
examples-stdlib/example_open_terms.v
|
hard_example2
| |
lang := | var (i : nat) (* i-th variable in the context *) | zero : lang (* Neutral element *) | add (x y : lang). (* binary operation *) (* Interpretation to T *)
|
Inductive
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
lang
| |
interp T (e : T) (op : T -> T -> T) (gamma : list T) (t : lang) : T := match t with | var v => nth v gamma e | zero => e | add x y => op (interp T e op gamma x) (interp T e op gamma y) end. (* normalization of parentheses and units *)
|
Fixpoint
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
interp
| |
normAx t1 acc := match t1 with | add t1 t2 => normAx t1 (normAx t2 acc) | _ => add t1 acc end.
|
Fixpoint
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normAx
| |
normA t := match t with | add s1 s2 => normAx s1 (normA s2) | _ => t end.
|
Fixpoint
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normA
| |
norm1 t := match t with | var _ => t | zero => t | add t1 t2 => match norm1 t1 with | zero => norm1 t2 | t1 => match norm1 t2 with | zero => t1 | t2 => add t1 t2 end end end.
|
Fixpoint
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm1
| |
norm t := normA (norm1 t). (* Correctness theorem. This is not the point of this demo, please don't look at the proofs ;-) *)
|
Definition
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm
| |
normAxA t1 t2 : normAx t1 (normA t2) = normA (add t1 t2). Proof. by []. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normAxA
| |
normAx_add {t1 t2 s} : normAx t1 t2 = s -> exists s1 s2, s = add s1 s2. Proof. elim: t1 t2 s => /= [i||w1 H1 w2 H2] t2 s <-; try by do 2 eexists; reflexivity. by case E: (normAx _ _); case/H1: E => s1 [s2 ->]; do 2 eexists; reflexivity. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normAx_add
| |
norm1_zero {l t} : norm1 t = zero -> interp T unit op l t = unit. Proof. by elim: t => [||s1 + s2] //=; case E1: (norm1 s1); case E2: (norm1 s2) => //= -> // ->. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm1_zero
| |
norm_zero {l t} : norm t = zero -> interp T unit op l t = unit. Proof. rewrite /norm; case E: (norm1 t) => [||x y] //; first by rewrite (norm1_zero E). by move/normAx_add=> [] ? []. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm_zero
| |
norm1_var {l t j} : norm1 t = var j -> interp T unit op l t = nth j l unit. Proof. elim: t => [i [->]||s1 + s2] //=; case E1: (norm1 s1); case E2: (norm1 s2) => //=. by rewrite (norm1_zero E2) unit_r => + _ H => ->. by rewrite (norm1_zero E1) unit_l => _ + H => ->. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm1_var
| |
norm_var {l t j} : norm t = var j -> interp T unit op l t = nth j l unit. Proof. rewrite /norm; case E: (norm1 t); rewrite /= ?(norm1_var E) //; first by move=> [->]. by move/normAx_add=> [] ? []. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm_var
| |
norm1_add {l t s1 s2} : norm1 t = add s1 s2 -> interp T unit op l t = op (interp T unit op l s1) (interp T unit op l s2). Proof. elim: t s1 s2 => [||w1 + w2 + s1 s2] //=. by case E1: (norm1 w1); case E2: (norm1 w2) => //= ++ [<- <-] /=; do 2! [ move=> /(_ _ _ (refl_equal _)) -> | move=> _]; rewrite ?(norm1_zero E1) ?(norm1_zero E2) ?(norm1_var E1) ?(norm1_var E2). Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm1_add
| |
normAxP {l t1 t2} : interp T unit op l (normAx t1 t2) = op (interp T unit op l t1) (interp T unit op l t2). Proof. by elim: t1 t2 => [||s1 Hs1 s2 Hs2] t2 //=; rewrite Hs1 Hs2 !op_assoc. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normAxP
| |
normAP {l} t : interp T unit op l (normA t) = interp T unit op l t. Proof. by elim: t => //= x Hx y Hy; rewrite normAxP Hy. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normAP
| |
norm_add {l t s1 s2} : norm t = add s1 s2 -> interp T unit op l t = op (interp T unit op l s1) (interp T unit op l s2). Proof. rewrite /norm; case E: (norm1 t) => [||x y]; rewrite //= (norm1_add E). elim: x y s1 s2 {E} => //= [>[<- <- //=]|>[<- <-]|x + y + w s1 s2]; rewrite ?normAP //= ?unit_l //. by rewrite normAxA -!op_assoc => ++ E => /(_ _ _ _ E) ->. Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
norm_add
| |
normP_ l t1 t2 : norm t1 = norm t2 -> interp T unit op l t1 = interp T unit op l t2. Proof. case E: (norm t2) => [?||??] => [/norm_var|/norm_zero|/norm_add] ->. by rewrite (norm_var E). by rewrite (norm_zero E). by rewrite (norm_add E). Qed.
|
Lemma
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normP_
| |
normP {T e op gamma t1 t2} p1 p2 p3 H := @normP_ T e op p1 p2 p3 gamma t1 t2 H. About normP. Open Scope Z_scope. Goal forall x y z t, (x + y) + (z + 0 + t) = x + (y + z) + t. Proof. intros. change (interp Z Z.zero Z.add (x::y::z::t::nil) (add (add (var 0) (var 1)) (add (add (var 2) zero) (var 3))) = interp Z Z.zero Z.add (x::y::z::t::nil) (add (add (var 0) (add (var 1) (var 2))) (var 3))). apply: normP Z.add_assoc Z.add_0_l Z.add_0_r _. reflexivity. Qed. (** Now, let's implement a tactic that does for us: - the change step (reification) - apply the correctness lemma *) (* This is for later *) Elpi Db monoid.db lp:{{ pred is_monoid i:term, % type o:term, % zero o:term, % op o:term, % assoc o:term, % unit_l o:term. % unit_r }}. Elpi Tactic monoid. Elpi Accumulate Db monoid.db. Elpi Accumulate lp:{{ % [mem L X N] asserts that X is at position N in L. % The list is open-ended, that is it terminates with an Elpi unification % variable, so that the list can be extended with new elements if needed. % e.g. mem (3 :: L) 4 N ---> L = 4 :: L1, N = 1 % Note: we build a Coq list, since we have to generate that anyway. We could % use an Elpi list or any other data structure here, but then we would need % to convert back anyway. pred mem o:term, o:term, o:term. mem {{ lp:X :: _ }} X {{ O }} :- !. mem {{ _ :: lp:XS }} X {{ S lp:N }} :- mem XS X N. % Give that [mem] works with open ended lists we need a way to close it (assign % nil to the tail) at the very end of reification. pred close o:term. close {{ nil }} :- !. close {{ _ :: lp:XS }} :- close XS. % [quote Zero Op T AstT L] recognizes Zero and Op in T and generates the % corresponding AstT using the "context" L for variables standing for % terms that are not Zero nor Op pred quote i:term, i:term, i:term, o:term, o:term. quote Zero Op {{ lp:Op lp:T1 lp:T2 }} {{ add lp:R1 lp:R2 }} L :- !, quote Zero Op T1 R1 L, quote Zero Op T2 R2 L. quote Zero _ Zero {{ zero }} _ :- !. quote _ _ T {{ var lp:R }} L :- mem L T R. % This preliminary version of the tactic takes as arguments the monoid signature % and changes the goal [A = B] into [interp L AstA = interp L AstB] solve (goal _ _ {{ @eq lp:T lp:A lp:B }} _ [trm Zero, trm Op] as G) GS :- quote Zero Op A AstA L, quote Zero Op B AstB L, close L, % We are very low level here, we assign a term directly to the goal handler % while one could use ltac primitives (as we do later) Ty = {{ (interp lp:T lp:Zero lp:Op lp:L lp:AstA) = (interp lp:T lp:Zero lp:Op lp:L lp:AstB) }}, % This implements the "change" tactic refine {{ (_ : lp:Ty) }} G GS. :name "error" solve _ _ :- coq.error "Not an equality / no signature provided". }}. Tactic Notation "monoid" constr(zero) constr(add) := elpi monoid (zero) (add). (** Let's test the tactic *) Goal forall x y z t, (x + y) + (z + 0 + t) = x + (y + z) + t. Proof. intros. monoid 0 Z.add. (* OK, the goal was reified for us, we can use normP now *) apply: normP Z.add_assoc Z.add_0_l Z.add_0_r _. reflexivity. Qed. (** Now let's register in the Db the monoid for Z *) Elpi Accumulate monoid.db lp:{{ is_monoid {{ Z }} {{ 0 }} {{ Z.add }} {{ Z.add_assoc }} {{ Z.add_0_l }} {{ Z.add_0_r }}. }}. (** Now let's improve the tactic. This time we don't expect the signature but rather look it up in the Db. *)
|
Definition
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
normP
| |
my_compute := vm_compute. Elpi Accumulate monoid lp:{{ :before "error" solve (goal _ _ {{ @eq lp:T lp:A lp:B }} _ [] as G) GL :- is_monoid T Zero Op Assoc Ul Ur, quote Zero Op A AstA L, quote Zero Op B AstB L, close L, % This time we use higher level combinators, closer to the standard ltac1 ones refine {{ @normP lp:T lp:Zero lp:Op lp:L lp:AstA lp:AstB lp:Assoc lp:Ul lp:Ur _ }} G [SubG], coq.ltac.thenl [ coq.ltac "my_compute", % https://github.com/coq/coq/issues/10769 coq.ltac "reflexivity", ] SubG GL. }}. Tactic Notation "monoid" := elpi monoid. (** Let's test it once more *) Goal forall x y z t, (x + y) + (z + 0 + t) = x + (y + z) + t. Proof. intros. monoid. Show Proof. Qed. Elpi Accumulate monoid.db lp:{{ is_monoid {{ Z }} {{ 1 }} {{ Z.mul }} {{ Z.mul_assoc }} {{ Z.mul_1_l }} {{ Z.mul_1_r }}. }}. Goal forall x y z t, (x * y) * (1 * (z + t)) = x * y * (z + t). Proof. intros. monoid. Qed.
|
Ltac
|
examples-stdlib
|
[
"From elpi Require elpi."
] |
examples-stdlib/example_reflexive_tactic.v
|
my_compute
| |
myType := Type.
|
Definition
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/bug_748.v
|
myType
| |
indd : myType := Indd : indd.
|
Variant
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/bug_748.v
|
indd
| |
myType_R u v := u -> v -> Type. Elpi Command foo. Elpi Accumulate " main _ :- std.assert-ok! (coq.typecheck-indt-decl (inductive ""indt_R"" tt (arity {{ myType_R indd indd }}) c1 \ [ constructor ""Indd_R"" (arity {{ lp:c1 Indd Indd }}) ])) ""error"". ". Elpi foo.
|
Definition
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/bug_748.v
|
myType_R
| |
x := 3. Elpi Command perf. Elpi Accumulate lp:{{ pred loop i:int, i:gref. loop 0 _. loop M GR :- N is M - 1, (@local! => coq.arguments.set-implicit GR [[]]). loop N GR. main [int N] :- loop N {coq.locate "x"}. }}. Elpi Export perf. Timeout 1 perf 3000.
|
Definition
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/perf_calls.v
|
x
| |
succ x := (S x). Elpi Query lp:{{ std.do! [ coq.locate-all "plus" X1, X1 = [loc-gref (const GR)], coq.locate-all "Nat.add" X2, X2 = [loc-gref (const GR)], coq.locate-all "succ" X3, X3 = [loc-abbreviation A_], coq.locate-all "Init.Datatypes" X4, X4 = [loc-modpath MP_], coq.locate-all "fdsfdsjkfdksljflkdsjlkfdjkls" [], ]. }}. (***** Univs *******************************) Elpi Query lp:{{coq.univ.print}}. Elpi Query lp:{{coq.univ.new X_}}. Elpi Query lp:{{coq.sort.leq X_ Y_}}. Elpi Query lp:{{coq.sort.eq X_ Y_}}. Elpi Query lp:{{coq.sort.pts-triple X_ Y_ Z_}}. Elpi Query lp:{{coq.sort.sup X_ Y_}}. (********* accumulate *************** *) Elpi Db test.db lp:{{type foo string -> prop.}}. Elpi Command test.use.db. Elpi Accumulate Db test.db. #[synterp] Elpi Accumulate lp:{{ main [] :- coq.env.begin-module "test_db_accumulate" none, coq.env.end-module _. }}. Elpi Accumulate lp:{{ main [] :- coq.elpi.accumulate _ "test.db" (clause _ _ (pi x\ foo x :- x = "here")), coq.env.begin-module "test_db_accumulate" _, coq.elpi.accumulate current "test.db" (clause _ _ (pi x\ foo x :- x = "there")), coq.env.end-module _. }}. Fail Elpi Query lp:{{foo _}}. Elpi test.use.db. Elpi Query lp:{{foo "here"}}. Fail Elpi Query lp:{{foo "there"}}. Import test_db_accumulate. Elpi Query lp:{{foo "there"}}.
|
Notation
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/test_API.v
|
succ
| |
x1 := 3.
|
Definition
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
x1
| |
x2 := 3. Strategy opaque [x2].
|
Definition
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
x2
| |
x3 := 3. Strategy expand [x3]. Elpi Command strategy. Elpi Query lp:{{ coq.locate "x1" (const X1), coq.locate "x2" (const X2), coq.locate "x3" (const X3), coq.strategy.get X1 (level 0), coq.strategy.get X2 opaque, coq.strategy.get X3 expand, coq.strategy.set [X3] (level 123), coq.strategy.get X3 (level 123). }}.
|
Definition
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
x3
| |
P : nat -> Prop. Elpi Command mode. Elpi Query lp:{{ coq.hints.add-mode {{:gref P }} "core" [mode-input], coq.hints.add-mode {{:gref P }} "core" [mode-ground], coq.hints.modes {{:gref P }} "core" M, std.assert! (M = [[mode-ground],[mode-input]]) "wrong modes" }}. Elpi Command pv. Elpi Accumulate lp:{{ main [trm (primitive (uint63 P))] :- !, coq.say {coq.uint63->int P}. main [trm (primitive (float64 P))] :- !, coq.say {coq.float64->float P}. main X :- coq.error "not a primitive-value" X. }}. Elpi Command vp. Elpi Accumulate lp:{{ main [int I] :- !, coq.say {coq.int->uint63 I}. main [] :- !, coq.say {coq.float->float64 1.2}. }}. From Corelib Require Import PrimFloat PrimInt63. Open Scope uint63_scope. Elpi pv (1). Fail Elpi pv (4611686018427387904). (* max_int + 1 *) Elpi vp 1. Fail Elpi vp -1. Open Scope float_scope. Elpi pv (1.0). Elpi vp. Elpi Query lp:{{ coq.option.available? ["Primitive", "Projections"] ff }}. Elpi Query lp:{{ coq.option.set ["Primitive", "Projections"] (coq.option.bool tt), coq.option.get ["Primitive", "Projections"] (coq.option.bool tt), coq.option.set ["Primitive", "Projections"] (coq.option.bool ff), coq.option.get ["Primitive", "Projections"] (coq.option.bool ff) }}. Elpi Query lp:{{ coq.option.add ["Primitive", "Projections"] (coq.option.bool tt) _, coq.option.get ["Primitive", "Projections"] (coq.option.bool tt) }}. Elpi Query lp:{{ % done in test_API.v % coq.option.add ["Foo", "Bar"] (coq.option.string (some "x")) tt, coq.option.get ["Foo", "Bar"] (coq.option.string (some "x")) }}. Set Foo Bar "y". Elpi Query lp:{{ coq.option.get ["Foo", "Bar"] (coq.option.string (some "y")) }}. Unset Foo Bar. Elpi Query lp:{{ coq.option.get ["Foo", "Bar"] (coq.option.string none) }}. (* Hints transparent *) #[local] Hint Opaque plus : core.
|
Axiom
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
P
| |
times := plus. #[local] Hint Transparent times : core. Elpi Query lp:{{ {{ plus }} = global (const C1), coq.hints.opaque C1 "core" X1, std.assert!(X1 = @opaque!) "wrong opaque plus", {{ times }} = global (const C2), coq.hints.opaque C2 "core" X2, std.assert!(X2 = @transparent!) "wrong opaque times" }}.
|
Definition
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
times
| |
x := 3. Elpi Query lp:{{ std.do! [ {{ x }} = global (const C1), coq.hints.opaque C1 "core" @opaque!, coq.hints.set-opaque C1 "core" @transparent!, coq.hints.opaque C1 "core" @transparent!, ] }}. #[local] Hint Opaque x : core. Elpi Query lp:{{ std.do! [coq.env.begin-module "xx" none, coq.env.end-module XX, coq.env.import-module XX ] }} lp:{{ std.do! [ {{ x }} = global (const C1), coq.hints.opaque C1 "core" @opaque!, coq.env.begin-module "xx" _, (@local! ==> coq.hints.set-opaque C1 "core" @transparent!), coq.env.end-module M, coq.hints.opaque C1 "core" @opaque!, coq.env.import-module M, coq.hints.opaque C1 "core" @opaque!, ] }}. Elpi Query lp:{{ std.do! [coq.env.begin-module "xx2" none, coq.env.end-module XX, coq.env.import-module XX] }} lp:{{ std.do! [ {{ x }} = global (const C1), coq.hints.opaque C1 "core" @opaque!, coq.env.begin-module "xx2" _, coq.hints.set-opaque C1 "core" @transparent!, coq.env.end-module M, coq.hints.opaque C1 "core" @opaque!, coq.env.import-module M, coq.hints.opaque C1 "core" @transparent!, ] }}. #[local] Hint Opaque x : core. Elpi Query lp:{{ std.do! [coq.env.begin-module "xx3" none, coq.env.end-module _] }} lp:{{ std.do! [ {{ x }} = global (const C1), coq.hints.opaque C1 "core" @opaque!, coq.env.begin-module "xx3" _, (@global! => coq.hints.set-opaque C1 "core" @transparent!), coq.env.end-module M, coq.hints.opaque C1 "core" @transparent!, ] }}. Fail Elpi Query lp:{{ {{ x }} = global (const C1), coq.hints.opaque C1 "corexx" T }}. (* Hints transparent *)
|
Definition
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
x
| |
xeq T x y := x = y :> T.
|
Definition
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
xeq
| |
xxx : xeq _ 0 1. Elpi Query lp:{{ coq.hints.add-resolve {{:gref xxx }} "core" 0 _. }}. Goal 0 = 1. Fail solve [trivial]. Abort. Create HintDb xxx. Elpi Query lp:{{ coq.hints.add-resolve {{:gref xxx }} "xxx" 0 {{ 0 = _ }} }}. Print HintDb xxx. (* I could not test the pattern, but it is printed Goal 0 = 1. solve [debug eauto with xxx]. Abort. *) (* ------------- functor application ---------------- *) (*Module Type T. Axiom Inline(1) T : Type. End T.*) Elpi Query lp:{{ std.do! [ coq.env.begin-module-type "T", coq.env.end-module-type _, ] }} lp:{{ coq.env.begin-module-type "T", @inline-at! 1 ==> coq.env.add-axiom "T" {{ Type }} _, coq.env.end-module-type _ }}. (*Module F(P : T). Definition id (a : P.T) := a. End F.*) Elpi Query lp:{{ std.do! [coq.env.begin-module-functor "F" none [pr "P" {coq.locate-module-type "T"}], coq.env.end-module _] }} lp:{{ coq.env.begin-module-functor "F" _ _, coq.locate "P.T" GR, coq.env.add-const "id" (fun `a` (global GR) a\ a) _ _ _, coq.env.end-module _. }}. (*Module X. Definition T := nat. End X.*) Elpi Query lp:{{ std.do! [coq.env.begin-module "X" none, coq.env.end-module _] }} lp:{{ coq.env.begin-module "X" _, coq.env.add-const "T" {{ nat }} _ _ _, coq.env.end-module _. }}. (*Module G := F X [no inline].*) Elpi Query lp:{{ std.do! [coq.env.apply-module-functor "G" none {coq.locate-module "F"} [{coq.locate-module "X"}] coq.inline.no _] }} lp:{{ coq.env.apply-module-functor "G" _ _ _ _ G, coq.say G }}. Print Module G. (*Module H := F X [inline at leve 2].*) Elpi Query lp:{{ std.do! [coq.env.apply-module-functor "H" none {coq.locate-module "F"} [{coq.locate-module "X"}] (coq.inline.at 2) _] }} lp:{{ coq.env.apply-module-functor "H" _ _ _ _ H, coq.say H }}. Print Module H. Goal G.id 3%nat = 3%nat. Fail match goal with |- @Logic.eq nat _ _ => idtac end. match goal with |- @Logic.eq X.T _ _ => idtac end. Abort. Goal H.id 3%nat = 3%nat. match goal with |- @Logic.eq nat _ _ => idtac end. Fail match goal with |- @Logic.eq X.T _ _ => idtac end. Abort. (* ------------- functor type application ---------------- *) (*Module Type FT (P : T). Axiom idT : P.T -> P.T. End FT.*) Elpi Query lp:{{ std.do! [coq.env.begin-module-type-functor "FT" [pr "P" {coq.locate-module-type "T"}], coq.env.end-module-type _] }} lp:{{ coq.env.begin-module-type-functor "FT" _, coq.locate "P.T" GR, coq.env.add-axiom "idT" (prod _ (global GR) _\ (global GR)) _, coq.env.end-module-type _. }}. Print Module Type FT. (*Module Type GT := FT X [no inline].*) Elpi Query lp:{{ std.do! [coq.env.apply-module-type-functor "GT" {coq.locate-module-type "FT"} [{coq.locate-module "X"}] coq.inline.no _] }} lp:{{ coq.env.apply-module-type-functor "GT" _ _ _ G, coq.say G }}. Print Module Type GT. (*Module Type HT := FT X [inline at leve 2].*) Elpi Query lp:{{ std.do! [coq.env.apply-module-type-functor "HT" {coq.locate-module-type "FT"} [{coq.locate-module "X"}] (coq.inline.at 2) _] }} lp:{{ coq.env.apply-module-type-functor "HT" _ _ _ H, coq.say H }}. Print Module Type HT.
|
Axiom
|
tests
|
[
"From elpi Require Import elpi.",
"From elpi.tests Require test_API.",
"From Corelib Require Import PrimFloat PrimInt63."
] |
tests/test_API2.v
|
xxx
| |
imp : forall T (x:T), x = x -> Prop. Arguments imp {_} [_] _ , [_] _ _ . Elpi Query lp:{{ coq.locate "imp" I, coq.arguments.implicit I [[maximal,implicit,explicit], [implicit,explicit,explicit]], (@global! => coq.arguments.set-implicit I [[]]), coq.arguments.implicit I [[explicit,explicit,explicit]] }}.
|
Axiom
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/test_API_arguments.v
|
imp
| |
foo (T : Type) (x : T) := x. Arguments foo : clear implicits. Fail Check foo 3. Elpi Query lp:{{ @global! => coq.arguments.set-default-implicit {coq.locate "foo"} }}. Check foo 3.
|
Definition
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/test_API_arguments.v
|
foo
| |
f T (x : T) := x = x. Elpi Query lp:{{ coq.arguments.set-name {coq.locate "f"} [some "S"], coq.arguments.name {coq.locate "f"} [some "S"], coq.arguments.set-implicit {coq.locate "f"} [[implicit]], coq.arguments.set-scope {coq.locate "f"} [["type"]], coq.arguments.scope {coq.locate "f"} [["type_scope"]] }}. About f. Check f (S:= bool * bool). Elpi Query lp:{{ coq.arguments.set-simplification {coq.locate "f"} (when [] (some 1)) }}. About f. Check f (S:= bool * bool). Eval simpl in f (S := bool).
|
Definition
|
tests
|
[
"From elpi Require Import elpi."
] |
tests/test_API_arguments.v
|
f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.