Debian Codegraph @

examples/example_record_expansion.v

raw
1 From elpi Require Import elpi.
2
3 (**
4 This file sketches a procedure to translate a term abstracted over
5 a specific record to a term abstracted over the components of that record.
6
7 Example:
8
9 Record r := mk { proj1 : T1; proj2 : T2 }.
10 Definition f (x : r) := Body(proj1 x,proj2 x).
11
12 Is expanded to:
13
14 Definition f1 v1 v2 := Body(v1,v2).
15
16 And recursively, if g uses f, then g1 must use f1...
17
18 The idea is to take "f", replace "(x : r)" with as many abstractions as
19 needed in order to write "mk v1 v2", then replace "x" with "mk v1 v2", finally
20 fire iota reductions such as "proj1 (mk v1 v2) = v1" to obtain "f1".
21
22 Then record a global replacement "f x = f1 v2 v2" whenever "x = mk v1 v2".
23
24 *)
25
26 Elpi Db record.expand.db lp:{{
27 % This data base will contain all the expansions performed previously.
28 % For example, if f was expandded to f1 we would have this clause:
29
30 % expand (app[f, R | L]) (app[f1, V1, V2 | L1]) :-
31 % expand R (app[k, V1, V2]), std.map L expand L1.
32
33 % [expand A B] can be used to perform a replacement, eg
34 % (expand (const "foo") (const "bar") :- !) ==> expand A B
35 pred expand i:term, o:term.
36
37 }}.
38 Elpi Accumulate record.expand.db lp:{{
39 shorten std.{ map }.
40
41 :name "expand:start"
42 expand (global _ as C) C :- !.
43 expand (pglobal _ _ as C) C :- !.
44 expand (sort _ as C) C :- !.
45 expand (fun N T F) (fun N T1 F1) :- !,
46 expand T T1, pi x\ expand x x ==> expand (F x) (F1 x).
47 expand (let N T B F) (let N T1 B1 F1) :- !,
48 expand T T1, expand B B1, pi x\ expand x x ==> expand (F x) (F1 x).
49 expand (prod N T F) (prod N T1 F1) :- !,
50 expand T T1, (pi x\ expand x x ==> expand (F x) (F1 x)).
51 expand (app L) (app L1) :- !, map L expand L1.
52 expand (fix N Rno Ty F) (fix N Rno Ty1 F1) :- !,
53 expand Ty Ty1, pi x\ expand x x ==> expand (F x) (F1 x).
54 expand (match T Rty B) (match T1 Rty1 B1) :- !,
55 expand T T1, expand Rty Rty1, map B expand B1.
56 expand (primitive _ as C) C :- !.
57
58 }}.
59
60 Elpi Command record.expand.
61 Elpi Accumulate Db record.expand.db.
62 Elpi Accumulate lp:{{
63
64 % This builds a clause to replace "proji (k y1..yn)" by "yi"
65 pred build-iotared-clause i:term, i:(pair constant term), o:prop.
66 build-iotared-clause T (pr Proj Var) C :-
67 coq.env.global (const Proj) HD, % HD is the global term for Proj
68 C = (pi L AppVar\ expand(app [HD,T|L]) AppVar :- coq.mk-app Var L AppVar).
69
70 % The core algorithm ----------------------------------------------------------
71
72 % It is idiomatic in λProlog to perform a single recursion over the data and
73 % perform multiple tasks while going. Here we both obtain the expanded term
74 % and the clause that records that expansion. Indeed the binders introduced
75 % in the new term (standing for the record fialds) and the quantifications
76 % introduced in the clause are very similar.
77
78 % missing in std
79 pred cons_assoc_opt i:option A, i:B, i:list (pair A B), o:list (pair A B).
80 cons_assoc_opt none _ X X.
81 cons_assoc_opt (some A) B X [pr A B|X].
82
83 % a package of data that we need to carry but rarely fully access
84 kind info type.
85 type info
86 inductive % the record to expand
87 -> gref % the term being expanded
88 -> gref % the term being expanded and its expanded name
89 -> list (option constant) % canonical projections
90 -> constructor % record constructor
91 -> term % record constructor type
92 -> info.
93
94 % This predicate turns the OldBo in "fun x : r => OldBo" into
95 % "fun v1 v2 => NewBo". It is fueled by "KTY" (corresponding to the type
96 % of the record constructor). In parallel it consumes the list of projections,
97 % so that it can record that the i-th projection should be replaced by
98 % the variable standing for the i-th record field (accumulator called Iota)
99 pred expand-abstraction
100 i:info,
101 i:term, % the varibale binding the record in the input term
102
103 % fuel
104 i:term, % the type of the record constructor
105 i:list (option constant), % projections
106
107 i:term, o:term, % the Old and New body
108
109 i:term, % constructor applied to all arguments treated so far
110 i:list (pair constant term), % iota rules for reductions so far
111
112 % used by expand-spine, accumulated here
113 i:list term, i:list term, % variables for the head of the clause (LHS and RHS)
114 i:list prop, o:prop. % accumulator for the premises of the clause, and the clause
115
116 expand-abstraction Info Rec (prod N S F) [P|PS] OldBo (fun N S Bo) KArgs Iota AccL AccR Premises (pi x\ Clause x) :- !,
117 pi x\ expand x x ==>
118 expand-abstraction Info Rec
119 (F x) PS OldBo (Bo x) {coq.mk-app KArgs [x]} {cons_assoc_opt P x Iota} AccL [x|AccR] Premises (Clause x).
120
121 expand-abstraction Info Rec (let N S B F) [P|PS] OldBo (let N S B Bo) KArgs Iota AccL AccR Premises Clause :- !,
122 pi x\ expand x x ==>
123 % a let in is not a real argument to KArgs, but may need a "iota" redex, since the projection could exist
124 expand-abstraction Info Rec
125 (F x) PS OldBo (Bo x) KArgs {cons_assoc_opt P x Iota} AccL AccR Premises Clause.
126
127 expand-abstraction Info Rec _ [] OldBo Result ExpandedRecord Iota AccL AccR Premises Clause :-
128 % generate all substitutions
129 std.map Iota (build-iotared-clause ExpandedRecord) IotaClauses,
130 ExpansionClause = expand Rec ExpandedRecord,
131 % eta expand the record to obtain a new body (that typechecks)
132 (ExpansionClause ==> expand OldBo NewBo), !,
133 % continue, but schedule iota reductions (pre-existing projections became iota redexes)
134 IotaClauses ==>
135 expand-spine Info NewBo Result AccL AccR [ExpansionClause|Premises] Clause.
136
137 % This predicate travrses the spine of lambdas. When it finds an abstraction
138 % on the record R is calls expand-abstraction. Finally it copies the term,
139 % applying all substitutions accumulated while descending the spine.
140 pred expand-spine
141 i:info,
142 i:term, o:term, % input and output term
143 i:list term, i:list term, % variables for the LHS and RHS of the clause head
144 i:list prop, o:prop. % premises and final clause
145
146 % if we find a lambda over the record R we expand
147 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, !,
148 pi r\ expand-abstraction Info r KTY Projs (Bo r) Result {coq.env.global (indc K)} [] [r|AccL] AccR Premises (Clause r).
149
150 % otherwise we traverse the spine
151 expand-spine Info (fun Name Ty Bo) (fun Name Ty1 Bo1) AccL AccR Premises (pi x y\ Clause x y) :- !,
152 expand Ty Ty1, !,
153 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).
154 expand-spine Info (let Name Ty V Bo) (let Name Ty1 V1 Bo1) AccL AccR Premises (pi x y\ Clause x y) :- !,
155 expand Ty Ty1, !,
156 expand V V1, !,
157 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).
158
159 % at the end of the spine we fire the iota redexes and complete the clause
160 expand-spine (info _ GR NGR _ _ _) X Y AccL AccR Premises Clause :-
161 expand X Y, !,
162 % we build "app[f,x1..xn|rest]"
163 (pi rest1\ coq.mk-app (global GR) {std.append {std.rev AccL} rest1} (L rest1)),
164 (pi rest2\ coq.mk-app (global NGR) {std.append {std.rev AccR} rest2} (R rest2)),
165 % we can now build the clause "expand (app[f,L1..Ln|Rest1]) (app[f1,R1..Rn|Rest2])"
166 % here we quantify only the tails, the other variables were quantified during
167 % expand-*
168 Clause = (pi rest1 rest2\ expand (L rest1) (R rest2) :- [!, std.map rest1 expand rest2 | Premises]).
169
170 % The entry point of the main algorithm, just fetchs some data and passes initial
171 % values for the accumulators.
172 pred expand-record i:inductive, i:gref, i:gref, i:term, o:term, o:prop.
173 expand-record R GR NGR X Y Clause :-
174 std.assert! (coq.env.indt R tt 0 0 _ [K] [KTY]) "record is too complex for this example",
175 coq.env.projections R Projs,
176 expand-spine (info R GR NGR Projs K KTY) X Y [] [] [] Clause.
177
178 % This simply dispatches between global references ----------------------------
179
180 % The only cleverness is that "expand" also builds the clause to be added to
181 % the data base, and that clause has to mention the name of the constant to be
182 % generated. Since we don't know it yet (Coq tells us in response to coq.env.add-const)
183 % we postulate a name for that constant "nc" and later replace it with the real one "NC"
184 pred expand-gref i:inductive, i:gref, i:string, o:prop.
185 expand-gref Record (const C) Name Clause :- !, std.do! [
186 std.assert! (coq.env.const C (some Bo) _) "only transparent constants can be expanded",
187 (pi nc\ expand-record Record (const C) nc Bo NewBo (NClause nc)),
188 std.assert-ok! (coq.typecheck NewBo _) "illtyped",
189 coq.env.add-const Name NewBo _ _ NC,
190 Clause = NClause (const NC),
191 ].
192
193 expand-gref _ (indt _) _ _ :- coq.error "Not implemented yet".
194
195 expand-gref _ (indc _) _ _ :- coq.error "It makes no sense to expand a constructor alone, expand the inductive instead".
196
197 % Entry point -----------------------------------------------------------------
198 main [str R, str In, str Prefix] :- !,
199 std.assert! (coq.locate R (indt Record)) "The first argument must be a record name",
200 std.assert! (coq.locate In GR) "The second argument must be a global term",
201 NewName is Prefix ^ {coq.gref->id GR},
202
203 expand-gref Record GR NewName Clause,
204
205 % We want our clauses to take precensence over the structural ones of "expand"
206 coq.elpi.accumulate _ "record.expand.db" (clause _ (before "expand:start") Clause).
207
208 main _ :- coq.error "usage: Elpi record.expand record_name global_term prefix".
209 }}.
210
211
212 Record r := { T :> Type; X := T; op : T -> X -> bool }.
213
214 Definition f b (t : r) (q := negb b) := fix rec (l1 l2 : list t) :=
215 match l1, l2 with
216 | nil, nil => b
217 | cons x xs, cons y ys => andb (op _ x y) (rec xs ys)
218 | _, _ => q
219 end.
220
221 Elpi record.expand r f "expanded_".
222 Print f.
223 Print expanded_f.
224
225 (* so that we can see the new "expand" clause *)
226 Elpi Print record.expand "elpi_examples/record.expand".
227
228 Definition g t l s h := (forall x y, op t x y = false) /\ f true t l s = h.
229
230 Elpi record.expand r g "expanded_".
231 Print expanded_g.