Debian Codegraph @

apps/derive/elpi/param2.elpi

raw
1 /* Binary parametricity translation */
2 /* license: GNU Lesser General Public License Version 2.1 or later */
3 /* ------------------------------------------------------------------------- */
4
5 % Author: Cyril Cohen
6
7 shorten std.{forall, forall2, do!, rev, map2, map}.
8
9 :before "subst-fun:fail"
10 coq.subst-fun XS T TXS :- !, coq.mk-app T XS TXS.
11
12 % this is outside the namespace since the predicate is also the db-one
13 param (sort prop as P) P (fun `s` P x\ fun `s` P y\ prod `s1` x _\ prod `s2` y _\ P) :- !.
14 param (sort _ as P) P
15 (fun `u` (sort (typ U)) x\ fun `v` (sort (typ V)) y\ prod `s1` x _\ prod `s2` y _\ P) :- !,
16 coq.univ.new U, coq.univ.new V.
17
18 param (fun N T B) (fun N T1 B1)
19 (fun N1 T x\ fun N2 T1 x1\ fun NR (TRsubst x x1) xR\ BR x x1 xR) :- !, do! [
20 derive.param2.names12R N N1 N2 NR,
21 param T T1 TR,
22 (@pi-decl N T x\ @pi-decl N1 T1 x1\ @pi-decl NR TR xR\ param x x1 xR =>
23 param (B x) (B1 x1) (BR x x1 xR)),
24 (TRsubst = x\ x1\ {coq.subst-fun [x,x1] TR})
25 ].
26
27 param (prod N T P as Prod) Prod1 ProdR :- !, do! [
28 param T T1 TR,
29 (@pi-decl N T x\ @pi-decl N T1 x1\ @pi-decl N TR xR\ param x x1 xR =>
30 param (P x) (P1 x1) (PR x x1 xR)),
31 Prod1 = prod N T1 P1,
32 derive.param2.names12R N N1 N2 NR,
33 ProdR = fun `f` Prod f\ fun `g` Prod1 g\
34 prod N1 T x\ prod N2 T1 x1\ prod NR {coq.subst-fun [x,x1] TR} xR\
35 {coq.subst-fun [{coq.mk-app f [x]}, {coq.mk-app g [x1]}] (PR x x1 xR)}
36 ].
37
38 % Primitive projections are applied directly to the record instance,
39 % without mentioning the record's parameters. The application node can
40 % have more arguments if the record field is a function, in which case
41 % the first argument should be treated specially, but then the rest
42 % should be processed like a regular application
43 param (app [primitive (proj Proj NoArgs), X | Xs]) (app [PP1, X1 | Xs1])
44 (app [PPR, XR | XsR]) :- !,
45 % Can't use `as PP` to bind `PP` in the clause head, since param is declared
46 % :index(3) and `PP` occurs at depth exactly 3, see
47 % https://github.com/LPCIC/elpi/issues/410
48 % This is fixed in elpi >3.7, as of yet unreleased
49 PP = primitive (proj Proj NoArgs),
50 param PP PP1 PPR,
51 param X X1 XR,
52 derive.param2.param-args Xs Xs1 XsR.
53
54 param (app [A|Bs]) (app [A1|Bs1]) ARBsR :- !, do! [
55 param A A1 AR,
56 derive.param2.param-args Bs Bs1 BsR,
57 coq.mk-app AR BsR ARBsR
58 ].
59
60 param (let N T V B) Let1 LetR :- !, do! [
61 param T T1 TR,
62 param V V1 VR,
63 (@pi-decl N T x\ @pi-decl N T1 x1\ @pi-decl N TR xR\ param x x1 xR =>
64 param (B x) (B1 x1) (BR x x1 xR)),
65 Let1 = let N T1 V1 B1,
66 derive.param2.names12R N N1 N2 NR,
67 LetR = let N1 T V x\ let N2 T1 V1 x1\ let NR {coq.mk-app TR [x,x1]} VR xR\ BR x x1 xR
68 ].
69
70 param (match T P Bs) M1 MR :- !, do! [
71 param T T1 TR,
72 derive.param2.param-match P P1 PRM,
73 param T T1 TR => derive.param2.map-param Bs Bs1 BsR,
74 M1 = match T1 P1 Bs1,
75 MR = match TR (PRM (x\ match x P Bs) (x\ match x P1 Bs1)) BsR
76 ].
77
78 param (fix N Rno T F as Fix) Fix1 FixR :- !, do! [
79 RnoR is 3 * Rno + 2, RnoR1 is RnoR + 1,
80 param T T1 TR,
81 (@pi-decl N T x\ @pi-decl N1 T1 x1\ @pi-decl N TR xR\ param x x1 xR =>
82 param (F x) (F1 x1) (FR x x1 xR)),
83 Fix1 = fix N Rno T1 F1,
84 (TRsubst = f\ f1\ {coq.subst-fun [f, f1] TR}),
85 (pi f f1 xR\ FixBody f f1 xR =
86 let N (TRsubst (F f) (F1 f1)) (FR f f1 xR) fr\
87 {paramX.mk-trivial-match RnoR (TRsubst f f1) [] fr}),
88 (pi f f1 xR\ coq.mk-eta RnoR1 (TRsubst f f1) (FixBody f f1 xR)
89 (EtaFixBody f f1 xR)),
90 derive.param2.names12R N N1 N2 NR,
91 FixR = (let N1 T Fix f\ let N2 T1 Fix1 f1\
92 fix NR RnoR (TRsubst f f1) xR\ EtaFixBody f f1 xR)
93 ].
94
95 namespace derive.param2 {
96
97 func names12R name -> name, name, name.
98 names12R N N1 N2 NR :- !,
99 coq.name-suffix N 1 N1, coq.name-suffix N 2 N2, coq.name-suffix N "_R" NR.
100
101
102 func id12R id -> id, id, id.
103 id12R N N1 N2 NR :- !,
104 N1 is N ^ "1", N2 is N ^ "2", NR is N ^ "_R".
105
106 func param-args -> list term, list term, list term.
107 param-args [] [] [] :- !.
108 param-args [X|Xs] [X1|Xs1] [X,X1,XR|XsR] :- !,
109 param X X1 XR, !, param-args Xs Xs1 XsR, !.
110
111 func map-param -> list term, list term, list term.
112 map-param [] [] [] :- !.
113 map-param [X|Xs] [X1|Xs1] [XR|XsR]:- !,
114 param X X1 XR, !, map-param Xs Xs1 XsR, !.
115
116
117 % helpers for match return type
118 func param-match term -> term, ((term -> term) -> (term -> term) -> term).
119 param-match (fun N T B) P1 PRM :- pi x\ not (B x = fun _ _ _), !,
120 param T T1 TR, !,
121 (pi x x1 xR\ (param x x1 xR :- !) => param (B x) (B1 x1) (BR x x1 xR)), !,
122 P1 = fun N T1 B1,
123 derive.param2.names12R N N1 N2 NR,
124 (pi z z1\ PRM z z1 = fun N1 T x\ fun N2 T1 x1\
125 fun NR {coq.subst-fun [x,x1] TR} xR\
126 {coq.mk-app (BR x x1 xR) [z x, z1 x1]}).
127
128 param-match (fun N T B) P1 PRM :-
129 param T T1 TR, !,
130 (pi x x1 xR\ (param x x1 xR :- !) => param-match (B x) (B1 x1) (BR x x1 xR)), !,
131 P1 = fun N T1 B1,
132 derive.param2.names12R N N1 N2 NR,
133 (pi z z1\ PRM z z1 = fun N1 T x\ fun N2 T1 x1\
134 fun NR {coq.subst-fun [x,x1] TR} xR\
135 BR x x1 xR z z1).
136
137 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
138 % translation of inductive declarations %
139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
140
141 % helper to improve name hints
142 func rename term, list (option id) -> term.
143 rename (prod _ T P) [some Ni|LN] (prod Nn T P') :- !,
144 pi x\ rename (P x) LN (P' x), coq.id->name Ni Nn.
145 rename (prod N T P) [none|LN] (prod N T P') :- !,
146 pi x\ rename (P x) LN (P' x).
147 rename T _ T :- !.
148
149 % Renames only the non-relevant names in the final sort,
150 % while ignoring the new names for the relevant parameter names.
151 func rename-arity-sort arity, list (option id) -> arity.
152 rename-arity-sort (parameter N Expl T P) [_|LN] (parameter N Expl T P') :- !,
153 pi x\ rename-arity-sort (P x) LN (P' x).
154 rename-arity-sort (arity T) LN (arity T') :- !,
155 rename T LN T'.
156 rename-arity-sort A _ A :- !.
157
158 % [param-arity A T1 T2 AR] returns in AR the translation of A applied to the terms
159 % T1 and T2, which are expected to have the types P and P', respectively, P and P'
160 % being the arities A and A' turned into types.
161 func param-arity
162 arity, % Arity (a : A).. | P a..
163 term, % Term T1 : forall (a : A).., P a..
164 term -> % Term T2 : forall (a' : A').., P' a'..
165 arity. % Arity [[ (a : A).. ]] | [[ P a.. ]] (T1 a..) (T2 a'..)
166 param-arity A1 Hd1 Hd2 AR :- param-arity.aux A1 Hd1 Hd2 [] [] AR.
167
168 func param-arity.aux arity, term, term, list term, list term -> arity.
169 param-arity.aux (parameter N _ Ty1 Rest1) Hd1 Hd2 RevParams1 RevParams2
170 % Ignore the explicitness set in the untranslated arity. Reusing it leads
171 % to inference failures, so let the user pick their preferred explicitness with
172 % either Arguments or Set Implicit Arguments.
173 (parameter N1 explicit Ty1 x1\
174 parameter N2 explicit Ty2 x2\
175 parameter NR explicit (TyRsubst x1 x2) xR\ RestR x1 x2 xR) :-
176 id12R N N1 N2 NR,
177 param Ty1 Ty2 TyR,
178 (pi x x'\ coq.subst-fun [x, x'] TyR (TyRsubst x x')), do! [
179 @pi-parameter N1 Ty1 x1\ @pi-parameter N2 Ty2 x2\
180 @pi-parameter NR (TyRsubst x1 x2) xR\
181 param x1 x2 xR =>
182 param-arity.aux (Rest1 x1)
183 Hd1 Hd2 [x1|RevParams1] [x2|RevParams2]
184 (RestR x1 x2 xR)
185 ].
186
187 param-arity.aux (arity T1) Hd1 Hd2 RevParams1 RevParams2 (arity TRSubst) :-
188 param T1 _ TR,
189 coq.mk-app Hd1 {rev RevParams1} Ty1,
190 coq.mk-app Hd2 {rev RevParams2} Ty2,
191 coq.subst-fun [Ty1, Ty2] TR TRSubst.
192
193 % [param-indt-decl I S NR DeclR] accepts a name of an inductive I and a
194 % string S, and returns the representation of the translated inductive DeclR and
195 % its name NR.
196 % The name of the inductive and constructors is generated by appending
197 % S and ensuring freshness in the current context.
198 func param-indt-decl
199 inductive, % Name of the inductive
200 string -> % Suffix to add to the name
201 string, % Name of the translated inductive
202 indt-decl. % Description of the translated inductive
203 param-indt-decl I Suffix NR DeclR :-
204 coq.env.indt-decl I Decl,
205 % Issue: consider the humble Inductive Foo (A : Type) := foo : Foo A -> Foo A.
206 % The arity of foo we get is (f\ "f -> f"), which we can choose to
207 % instantiate either with "Foo", or separately with "Foo A" and "Foo A'".
208 % If we do the translation for Foo, we try to translate (foo : Foo -> Foo),
209 % which produces
210 % (foo_R : ∀ (f : Foo) (f' : Foo), Foo_R f f' -> Foo_R (foo f) (foo f'))
211 % and that's ill-typed, because Foo takes a type parameter, so it should be
212 % (foo_R : ∀ (f : Foo A) (f' : Foo A'), ...).
213 % On the other hand, if we do the translation for Hd1 and Hd2 and we translate
214 % (foo : Foo A -> Foo A), we get
215 % (foo_R : ∀ (f : Foo A) (f' : Foo A'),
216 % Foo_R A A' A_R f f' -> Foo_R A A' A_R (foo f) (foo' f')).
217 % Unfortunately, this is rejected as well, since A A' A_R are
218 % uniform parameters, so the rocq-elpi encoding enforces that the user
219 % treat Foo_R as already being pre-applied. What rocq-elpi expects is
220 % something in the middle, namely
221 % (foo_R : ∀ (f : Foo A) (f' : Foo A'),
222 % Foo_R f f' -> Foo_R (foo f) (foo' f')).
223 % We can avoid the issue by first converting all parameters to non-uniform
224 % ones, since then passing the unapplied inductives everywhere still produces
225 % well-typed arities.
226 % In principle records don't have this problem, since their declarations only
227 % specify the types of fields, and records can't be recursive, so the types
228 % of fields don't ever need to refer to the record type itself. We do, however,
229 % want to still "clean up" records without primitive projections, since those
230 % are expected to be translated as if they were inductives, and this conversion
231 % happens inside the translation to non-uniformly parameterized inductives.
232 if (coq.env.record? I tt)
233 (CleanDecl = Decl)
234 (coq.indt-unif->indt-nonunif Decl CleanDecl),
235 param-indt-decl.aux I Suffix [] [] CleanDecl NR DeclR.
236
237 func param-indt-decl.aux inductive, string,
238 list term, % Reversed list of "unprimed" parameters accumulated so far
239 list term, % Reversed list of "primed" parameters accumulated so far
240 indt-decl -> string, indt-decl.
241 param-indt-decl.aux I Suffix RevParams1 RevParams2
242 % Ignore the explicitness set in the untranslated inductive. Reusing them leads
243 % to inference failures, so let the user pick their preferred explicitness with
244 % either Arguments or Set Implicit Arguments.
245 (parameter N _ Ty Rest) NewName
246 (parameter N1 explicit Ty x\
247 parameter N2 explicit Ty' x'\
248 parameter NR explicit (TyRsubst x x') xR\ RestR x x' xR) :-
249 id12R N N1 N2 NR,
250 param Ty Ty' TyR,
251 (pi x x'\ coq.subst-fun [x,x'] TyR (TyRsubst x x')), do! [
252 @pi-parameter N1 Ty x\ @pi-parameter N2 Ty' x'\ @pi-parameter NR TyR xR\
253 param x x' xR =>
254 param-indt-decl.aux I Suffix
255 [x|RevParams1] [x'|RevParams2]
256 (Rest x) NewName (RestR x x' xR)
257 ].
258
259 param-indt-decl.aux I Suffix RevParams1 RevParams2
260 (inductive N Ind IndexA Ks) NewName
261 (inductive NewName Ind IndexAR (KRs HdTy)) :-
262 coq.ensure-fresh-global-id {calc (N ^ Suffix)} NewName,
263 coq.env.global (indt I) HdTy,
264 rev RevParams1 Params1,
265 rev RevParams2 Params2,
266 param-arity IndexA {coq.mk-app HdTy Params1} {coq.mk-app HdTy Params2} IndexAR,
267 % The indt-decl we get on the input doesn't give us the constructor names
268 % we can actually use to form terms, so we need to fetch those separately
269 coq.env.indt I _ _ _ _ Cs _,
270 % Create a fresh variable for both the untranslated and translated inductives.
271 % The constructors Ks already treat the untranslated inductive as an opaque
272 % term. The alternative is to use HdTy directly instead of ty, but then the
273 % local param rule would technically conflict with the default rule for (p)global,
274 % so the "proper" local assumption would be on the param.gref predicate,
275 % but we don't have a gref for the translated inductive yet.
276 pi ty tyR\
277 param ty ty tyR =!=>
278 map2 Cs (Ks ty) (param-indc-decl Suffix Params1 Params2) (KRs ty tyR).
279
280 param-indt-decl.aux I Suffix RevParams1 RevParams2
281 (record Name Ty Kname Fields) FNameR
282 (parameter C1 explicit Ty1 x \
283 parameter C2 explicit Ty2 x'\
284 record FNameR Ty FKnameR (FieldsR x x')) :-
285 coq.env.global (indt I) HdTy,
286 id12R Name C1 C2 _,
287 coq.ensure-fresh-global-id {calc (Name ^ Suffix)} FNameR,
288 coq.ensure-fresh-global-id {calc (Kname ^ Suffix)} FKnameR,
289 coq.mk-app HdTy {rev RevParams1} Ty1,
290 coq.mk-app HdTy {rev RevParams2} Ty2,
291 % The input declaration does not carry the projection names which we need
292 % to construct terms out of them. We know this record has primitive projections,
293 % since records without primitive projections are treated as inductives.
294 coq.env.primitive-projections I Projs,
295 @pi-parameter C1 Ty1 x\ @pi-parameter C2 Ty2 x'\
296 param-prim-record-decl Fields Suffix Projs x x' (FieldsR x x').
297
298 func param-indc-decl
299 string, % Suffix to add to the name
300 list term, % "Unprimed" parameter instantiation of the inductive
301 list term, % "Primed" parameter instantiation of the inductive
302 constructor, % Name of the constructor being translated
303 indc-decl -> % Declaration of the constructor being translated
304 indc-decl. % Translated constructor
305 param-indc-decl Suffix Params1 Params2 CHd
306 (constructor N A)
307 (constructor NR AR) :-
308 coq.env.global (indc CHd) CT,
309 % If the user changed argument names of the untranslated constructor,
310 % we want to use those for pretty-printing hints in the translation.
311 % We need to be careful, however, because when adding the inductive,
312 % the names of non-uniform parameters in the inductive aritiy and in the
313 % constructor arity need to match. We deal with this by ignoring the name
314 % hints for the relevant names in rename-arity-sort.
315 coq.arguments.name (indc CHd) Names,
316 coq.ensure-fresh-global-id {calc (N ^ Suffix)} NR,
317 param-arity {rename-arity-sort A Names} {coq.mk-app CT Params1} {coq.mk-app CT Params2} AR.
318
319 func param-prim-record-decl
320 record-decl, % Untranslated record declaration
321 string, % Suffix to add to the record, constructor, and projections' names
322 list % List of projection names of the untranslated record
323 (option (pair projection int)),
324 % Records with unnameable projections are not supported
325 term, % "Unprimed" instance of the untranslated record
326 term -> % "Primed" instance of the untranslated record
327 record-decl.
328 param-prim-record-decl end-record _ _ _ _ end-record.
329 param-prim-record-decl (field Attrs Id Ty Rest) Suffix [OProj|Projs]
330 X X' (field Attrs IdR TyRsubst (RestR Proj1 Proj2)) :-
331 (OProj = some (pr Proj NoParams) ;
332 std.fatal-error-w-data "Cannot translate records with unnameable projections" Id), !,
333 coq.env.fresh-global-id {calc (Id ^ Suffix)} IdR,
334 param Ty _Ty' TyR,
335 Proj1 = app [primitive (proj Proj NoParams), X],
336 Proj2 = app [primitive (proj Proj NoParams), X'],
337 coq.subst-fun [Proj1, Proj2] TyR TyRsubst,
338 % Similarly to the inductive case, instantiate the field continutations
339 % with fresh elpi variables, since we prefer to avoid locally assuming
340 % a translation of a complex term like a fully applied projection.
341 pi proj1 proj2 projR\
342 param proj1 proj2 projR =!=>
343 param-prim-record-decl (Rest proj1) Suffix Projs X X'
344 (RestR proj1 proj2 projR).
345
346 % [param-record-constr C N Ty CR Bo TyB] takes the constructor names of
347 % a record and its translation, the number of parameters of the untranslated
348 % record type, and the type of the untranslated constructor, and returns
349 % a parametricity shim for the constructor, and its type.
350 %
351 % Generating a shim is necessary because the type of the constructor of
352 % the translated record type does not have the type of a parametricity
353 % translation of the original constructor: the type of mkFoo in
354 % Record Foo (A : TyA) := mkFoo { fld : TyF }
355 % is (forall A : TyA, TyF -> Foo A). The translation of Foo, however, is
356 % Record Foo_R (A A' A_R) (f : Foo A) (f' : Foo A') :=
357 % mkFoo_R { fld_R : TyF_R f.(fld) f'.(fld) }
358 % where mkFoo_R has the type
359 % (forall A A' A_R f f', TyF_R f.(fld) f'.(fld) -> Foo_R A A' A_R f f').
360 % Meanwhile the expected type is a function type which has a triplet of arguments
361 % for every field in the original record, and whose codomain ends in the translated
362 % record type instantiated at instances constructed from the arguments, here
363 % (forall A A' A_R fld fld',
364 % TyF_R fld fld' -> Foo_R A A' A_R (mkFoo A fld) (mkFoo A' fld')).
365 % The shim generated by this predicate does this transformation by wrapping
366 % the appropriate arguments in constructor calls before forwarding them to
367 % the translated constructor.
368 func param-record-constr
369 constructor, % Name of the untranslated constructor
370 int, % Number of parameters
371 term, % Type of the original constructor
372 constructor -> % Name of the constructor of the translation
373 term, % Body of the new compatibility constant
374 term. % And its type
375 param-record-constr C NParams Ty CR Bo TyR :-
376 % Eta-expand the parameters of the constructor first;
377 % This allows us to treat (ctor A0 ... AN) as a single unit to be
378 % translated. It needs special treatment, because the arguments
379 % which come after correspond to the record fields, which need to be
380 % collected separately and wrapped in a constructor call when forwarding
381 % to the translated constructor.
382 % The expansion is entirely type-driven, and we abstract over the concrete
383 % constructor term to enforce that.
384 (pi ctor\ coq.mk-eta NParams Ty ctor (Exp ctor)),
385
386 % Note: this still doesn't feel great, since we don't control mk-eta from here
387 % and then we're matching on a non-atomic term (app [ctor | xs]). Maybe
388 % we can locally assume a new term constructor similar to app and make our own
389 % mk-eta which uses that instead of app? With that we could also remove the
390 % second local assumption below.
391
392 % Register the translation of (ctor A0 .. AN) to be a function taking
393 % fld1 -> fld1' -> fld1R .. 's to the constructor call
394 % ctorR A0 A0' A0R .. AN AN' ANR
395 % (ctor A0 .. AN fld1 ..)
396 % (ctor A0' .. AN' fld1' ..)
397 % fld1R ..
398 (pi ctor ctorR\
399 [(pi xs C x1s C1 OutR xRs Tele AppliedCR\
400 param (app [ctor | xs]) (app [ctor | x1s]) OutR :- !, do! [
401 param-args xs x1s xRs,
402 % Substitute parameters to the constructor type, leaving just
403 % the arguments corresponding to fields
404 coq.subst-prod xs Ty Tele,
405 % Pre-apply the translation of parameters
406 coq.mk-app ctorR xRs AppliedCR,
407 % Construct the output term by wrapping the rest of the arguments
408 % in (ctor ..xs) and (ctor x1s..) calls
409 param-record-constr.aux Tele
410 (app [ctor | xs]) (app [ctor | x1s]) AppliedCR
411 [] [] []
412 OutR
413 ]),
414 % If the record didn't have any parameters, then there was no eta
415 % expansion, and the constructors are just ctor instead of (ctor)
416 (pi OutR\
417 param ctor ctor OutR :- !,
418 param-record-constr.aux Ty ctor ctor ctorR [] [] [] OutR)] =>
419 % Apply the above translation, together with the usual mechanism
420 % for translating functions when translating parameters
421 param (Exp ctor) _ (BoSubst ctor ctorR)),
422
423 % Instantiate the body of the compatibility constant with concrete constructor terms
424 coq.env.global (indc C) T,
425 coq.env.global (indc CR) TR,
426 Bo = BoSubst T TR,
427
428 param Ty _ TyRUnsubst,
429 coq.subst-fun [T, T] TyRUnsubst TyR,
430
431 % Sanity check that the type of the shim has the type expected of a translation
432 std.assert-ok! (coq.typecheck Bo TyR)
433 "param-record-constr: Ill-typed translated constructor shim".
434
435 func param-record-constr.aux
436 term, % Rest of the constructor telescope
437 term, % Untranslated constructor applied to "unprimed" parameters
438 term, % Untranslated constructor applied to "primed" parameters
439 term, % Constructor of the translated record applied to parameters
440 list term, % Reverse "unprimed" arguments corresponding to
441 % fields of the untranslated record
442 list term, % Reverse "primed" arguments
443 list term -> % Reverse arguments corresponding to fields of the translated record
444 term. % Call to the translated constructor
445 param-record-constr.aux (prod N T1 B) C1 C2 CR RevArgs1 RevArgs2 RevArgsR
446 (fun N1 T1 x1\ fun N2 T2 x2\ fun NR (TRsubst x1 x2) (E x1 x2)) :- !,
447 names12R N N1 N2 NR,
448 param T1 T2 TR,
449 (pi x1 x2\ coq.subst-fun [x1, x2] TR (TRsubst x1 x2)),
450 (@pi-decl N1 T1 x1\ @pi-decl N2 T2 x2\ @pi-decl NR (TRsubst x1 x2) xR\
451 param x1 x2 xR =!=>
452 param-record-constr.aux (B x1) C1 C2 CR
453 [x1 | RevArgs1] [x2 | RevArgs2] [xR | RevArgsR]
454 (E x1 x2 xR)).
455 param-record-constr.aux _ C1 C2 CR RevArgs1 RevArgs2 RevArgsR Call :-
456 rev RevArgs1 Args1,
457 rev RevArgs2 Args2,
458 rev RevArgsR ArgsR,
459 coq.mk-app C1 Args1 CCall1,
460 coq.mk-app C2 Args2 CCall2,
461 coq.mk-app CR [CCall1, CCall2 | ArgsR] Call.
462
463
464 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
465 % Class storage functions: %
466 %%%%%%%%%%%%%%%%%%%%%%%%%%%%
467
468 func store-param string, term, term, term.
469 store-param N X X1 XR :- !,
470 Nparam is "param_" ^ N,
471 Args = [_, _, _, X, X1, XR],
472 T1 = app [{{ lib:@param2.store_param }}|Args],
473 std.assert-ok! (coq.typecheck T1 T2) "store-param: T1 illtyped",
474 coq.ensure-fresh-global-id Nparam FNparam,
475 coq.env.add-const FNparam T1 T2 _ C,
476 @global! => coq.TC.declare-instance (const C) 0.
477
478 func store-param-indc string, constructor, constructor.
479 store-param-indc Suffix K KR :-
480 store-param {calc ({coq.gref->id (indc K)} ^ Suffix)}
481 {coq.env.global (indc K)} {coq.env.global (indc K)}
482 {coq.env.global (indc KR)}.
483
484 %%%%%%%%%%%%%%%%%%%%%%%
485 % toplevel predicates %
486 %%%%%%%%%%%%%%%%%%%%%%%
487
488 :index (1)
489 func dispatch gref, string -> list prop.
490
491 dispatch ((const GR) as C) Suffix Clauses :- do! [
492 % We need to check both projection and primitive-projection: a non-primitive
493 % projection is still a projection, and a manual wrapper of a primitive projection
494 % is succesfully checked as a compatibility constant. We want both of these cases
495 % to be successfully translated, so we want to only rule out manual translations
496 % of generated compatibility constants, which already have registered translations.
497 (not (coq.env.projection? GR _, coq.env.primitive-projection? _ GR _) ;
498 coq.error "derive.param2: cannot translate a projection"),
499 coq.env.global C Term,
500 NameR is {coq.gref->id C} ^ Suffix,
501 coq.env.const GR OBo Ty,
502 (OBo = (some X) ;
503 std.fatal-error-w-data "Cannot translate local constant without body" GR),
504
505 param Ty _ TyR,
506 coq.mk-app TyR [Term, Term] TyRTermTerm,
507 % coq.typecheck is needed to add universe constraints
508 std.assert-ok! (coq.typecheck TyRTermTerm _) "param2: illtyped param type",
509 param X _ XR,
510 % apparently calling the type checker with the expected type is weaker in this case
511 std.assert-ok! (coq.typecheck XR XRTy) "param2: illtyped constant",
512 std.assert-ok! (coq.unify-leq XRTy TyRTermTerm) "param2: constant does not have the right type",
513
514 coq.ensure-fresh-global-id NameR FNameR,
515 coq.env.add-const FNameR XR TyRTermTerm _ TermR,
516
517 store-param NameR Term Term {coq.env.global (const TermR)},
518
519 C1 = (param.gref C C (const TermR) :- !),
520 coq.elpi.accumulate _ "derive.param2.db" (clause _ (before "param:fail") C1),
521 coq.elpi.accumulate _ "derive.param2.db" (clause _ _ (param-done C)),
522 Clauses = [param-done C, C1]
523 ].
524
525 dispatch (indt I as GR) Suffix Clauses :-
526 % Records with primitive projections get translated into records,
527 % as opposed to records without primitive projections, which are
528 % just glorified single-constructor inductives
529 coq.env.record? I tt, !, do! [
530 param-indt-decl I Suffix NameR RecordDeclR,
531
532 std.assert-ok! (coq.typecheck-indt-decl RecordDeclR)
533 "derive.param2 generates illtyped record type",
534
535 (@primitive! => coq.env.add-indt RecordDeclR IR),
536
537 GRR = indt IR,
538 coq.env.global GR Ind,
539 coq.env.global GRR IndR,
540 store-param NameR Ind Ind IndR,
541
542 TypeClause = (param.gref GR GR GRR :- !),
543
544 % All projections are guaranteed to be nameable, otherwise
545 % generating the record declaration would have failed by now
546 coq.env.projections I OProjs,
547 map OProjs (p\ r\ (some r) = p) Projs,
548 coq.env.projections IR OProjsR,
549 map OProjsR (p\ r\ (some r) = p) ProjsR,
550
551 % Primitive projections are different terms,
552 % so we need to register their translations separately
553 coq.env.primitive-projections I OPProjs,
554 coq.env.primitive-projections IR OPProjsR,
555 map OPProjs
556 (p\ r\ sigma pproj args\
557 (some (pr pproj args)) = p,
558 r = proj pproj args)
559 PProjs,
560 map OPProjsR
561 (p\ r\ sigma pproj args\
562 (some (pr pproj args)) = p,
563 r = proj pproj args)
564 PProjsR,
565
566 % store projection translations as witnesses
567 forall2 Projs ProjsR
568 (p\ pR\
569 sigma n fulln gp gpR \
570 coq.gref->id (const p) n,
571 coq.gref->id (const pR) fulln,
572 coq.env.global (const p) gp,
573 coq.env.global (const pR) gpR,
574 store-param fulln gp gp gpR),
575
576 % projection translation clauses
577 map2 Projs ProjsR
578 (p\ pR\ r\ r = (param.gref (const p) (const p) (const pR) :- !))
579 ProjectionClauses,
580 map2 PProjs PProjsR
581 (p\ pR\ r\ r = (param (primitive p) (primitive p) (primitive pR) :- !))
582 PProjectionClauses,
583
584 MostClauses = [TypeClause | {std.append PProjectionClauses ProjectionClauses}],
585
586 coq.env.indt I _ NParams _ _ [C] [CTy],
587 coq.env.indt IR _ _ _ _ [CR] _,
588
589 % Generating the constructor shim needs to know about registered
590 % translations
591 (MostClauses =!=> param-record-constr C NParams CTy CR ShimCR ShimCRTy),
592
593 coq.env.add-const
594 {coq.env.fresh-global-id {calc ("shim_" ^ {coq.gref->id (indc CR)})}}
595 ShimCR ShimCRTy @transparent! Shim,
596
597 store-param {coq.gref->id (indc CR)}
598 {coq.env.global (indc C)} {coq.env.global (indc C)} {coq.env.global (const Shim)},
599
600 ConstrClause = (param.gref (indc C) (indc C) (const Shim) :- !),
601
602 Clauses = [param-done GR, ConstrClause | MostClauses],
603
604 forall Clauses (c\
605 coq.elpi.accumulate _ "derive.param2.db" (clause _ (before "param:fail") c)),
606 ].
607
608 dispatch (indt I as GR) Suffix Clauses :- !,
609 param-indt-decl I Suffix NameR DeclR,
610
611 std.assert-ok! (coq.typecheck-indt-decl DeclR)
612 "derive.param2 generates illtyped inductive type",
613
614 coq.env.add-indt DeclR IR,
615
616 coq.env.global GR Ind,
617 store-param NameR Ind Ind {coq.env.global (indt IR)},
618
619 coq.env.indt I _ _ _ _ Knames _,
620 coq.env.indt IR _ _ _ _ KnamesR _,
621
622 forall2 Knames KnamesR (store-param-indc Suffix),
623
624 C1 = (param.gref GR GR (indt IR) :- !),
625 coq.elpi.accumulate _ "derive.param2.db" (clause _ (before "param:fail") C1),
626 map2 Knames KnamesR (a\ b\ r\ r = (param.gref (indc a) (indc a) (indc b) :- !)) CK,
627 forall CK (c\
628 coq.elpi.accumulate _ "derive.param2.db" (clause _ (before "param:fail") c)),
629 CD = (param-done GR :- !),
630 coq.elpi.accumulate _ "derive.param2.db" (clause _ _ CD),
631
632 Clauses = [CD, C1|CK].
633
634 dispatch (indc _) _ _ :-
635 coq.error "derive.param2: cannot translate a constructor".
636
637 func main gref, string -> list prop.
638 main T _ Clauses :-
639 dispatch T "_R" Clauses.
640
641 func main_register gref, gref.
642 main_register I R :-
643 C1 = (param.gref I I R :- !),
644 coq.elpi.accumulate _ "derive.param2.db" (clause _ (before "param:fail") C1),
645 coq.elpi.accumulate _ "derive.param2.db" (clause _ _ (param-done I)).
646
647 }
648
649 /*
650
651 %%%%%%%%%%%%%%%%%%%%%
652 % Tactic entrypoint %
653 %%%%%%%%%%%%%%%%%%%%%
654
655 % We disable coq-refiner
656 :before "refiner-assign-evar"
657 evar _ _ _ :- !.
658
659 pred ctx->TC i:(list prop), o:(list (pair term term)).
660 ctx->TC [] [] :- !.
661 ctx->TC [decl X _ Ty |Xs] [pr X Ty|Is] :- !, ctx->TC Xs Is.
662 ctx->TC [def X _ _ _ Ty |Xs] [pr X Ty|Is] :- !, ctx->TC Xs Is.
663
664 solve _ [goal Ctx Ev (app[{{@param}}, T, TR, X, XR]) _] _ :- !,
665 coq.sigma.print,
666 coq.say "goal->TC" {ctx->TC Ctx},
667 coq.say "searching param for" X,
668 (param T _ TR),
669 (param X _ XR),
670 Ev = app [{{@Param}}, T, TR, X, XR],
671 coq.typecheck Ev Ty ok,
672 coq.say "Ty=" Ty.
673
674 */