Debian Codegraph @

src/rocq_elpi_HOAS.ml

raw symbols SCIP
1 (* rocq-elpi: Coq terms as the object language of elpi *)
2 (* license: GNU Lesser General Public License Version 2.1 or later *)
3 (* ------------------------------------------------------------------------- *)
4
5 module API = Elpi.API
6 module E = API.RawData
7 module CD = API.RawOpaqueData
8 module U = API.Utils
9 module P = API.RawPp
10 module S = API.State
11 module F = API.FlexibleData
12 module A = API.Ast.Term
13
14 module C = Constr
15 module EC = EConstr
16 open Names
17 module G = GlobRef
18 open Rocq_elpi_utils
19
20 (* ************************************************************************ *)
21 (* ****************** HOAS of Coq terms and goals ************************* *)
22 (* See also coq-HOAS.elpi (terms) *)
23 (* ************************************************************************ *)
24
25 (* {{{ CData ************************************************************** *)
26
27 type annot_name = (Name.t,EConstr.ERelevance.t) Context.pbinder_annot
28
29 (* names *)
30 let namein, naminc, isname, nameout, (name : annot_name API.Conversion.t) =
31 let { CD.cin; cino; isc; cout }, name = CD.declare {
32 CD.name = "name";
33 doc = "Name.Name.t: Name hints (in binders), can be input writing a name between backticks, e.g. `x` or `_` for anonymous. Important: these are just printing hints with no meaning, hence in elpi two name are always related: `x` = `y`";
34 pp = (fun fmt (x : annot_name) ->
35 Format.fprintf fmt "`%a:%a`"
36 Pp.pp_with (Name.print @@ Context.binder_name x)
37 Pp.pp_with ((function Sorts.Relevant -> Pp.str"r" | Sorts.Irrelevant -> Pp.str"i" | Sorts.RelevanceVar q -> Pp.str @@ Sorts.QVar.to_string q) @@ Evd.MiniEConstr.ERelevance.unsafe_to_relevance @@ Context.binder_relevance x)
38 );
39 compare = (fun _ _ -> 0);
40 hash = (fun _ -> 0);
41 hconsed = false;
42 constants = [];
43 } in
44 cin, cino, isc, cout, name
45 ;;
46 let in_elpi_name x = namein x
47 let in_elpiast_name ~loc x = A.mkOpaque ~loc @@ naminc x
48 let coq_language = ref API.Quotation.elpi_language
49 let set_coq coq = coq_language := coq
50 let name_of_name ~loc = function
51 | { Context.binder_name = Names.Name.Anonymous } -> None
52 | { Context.binder_name = Names.Name.Name id } -> Some (API.Ast.Name.from_string @@ Names.Id.to_string id, loc, !coq_language)
53
54 let is_coq_name ~depth t =
55 match E.look ~depth t with
56 | E.CData n -> isname n || (CD.is_string n && Id.is_valid (CD.to_string n))
57 | _ -> false
58
59 (* engine prologue, to break ciclicity *)
60
61 type coq_engine = {
62 global_env : Environ.env;
63 sigma : Evd.evar_map; (* includes universe constraints *)
64 }
65 let pre_engine : coq_engine S.component option ref = ref None
66
67 (* universes *)
68
69 module UnivOrd = struct
70 type t = Univ.Universe.t
71 let compare = Univ.Universe.compare
72 let show x = Pp.string_of_ppcmds (Univ.Universe.pr UnivNames.pr_level_with_global_universes x)
73 let pp fmt x = Format.fprintf fmt "%s" (show x)
74 end
75 module UnivSet = U.Set.Make(UnivOrd)
76 module UnivMap = U.Map.Make(UnivOrd)
77 module UnivLevelOrd = struct
78 type t = Univ.Level.t
79 let compare = Univ.Level.compare
80 let show x = Pp.string_of_ppcmds (UnivNames.pr_level_with_global_universes x)
81 let pp fmt x = Format.fprintf fmt "%s" (show x)
82 end
83 module UnivLevelSet = U.Set.Make(UnivLevelOrd)
84 module UnivLevelMap = U.Map.Make(UnivLevelOrd)
85
86 (* map from Elpi evars and Coq's universe levels *)
87 module UM = F.Map(struct
88 type t = Univ.Universe.t
89 let compare = Univ.Universe.compare
90 let show x = Pp.string_of_ppcmds @@ Univ.Universe.pr UnivNames.pr_level_with_global_universes x
91 let pp fmt x = Format.fprintf fmt "%a" Pp.pp_with (Univ.Universe.pr UnivNames.pr_level_with_global_universes x)
92 end)
93
94 let um = S.declare_component ~name:"rocq-elpi:evar-univ-map" ~descriptor:interp_state
95 ~pp:UM.pp ~init:(fun () -> UM.empty) ~start:(fun x -> x) ()
96
97
98 let constraint_leq u1 u2 =
99 let open UnivProblem in
100 ULe (u1, u2)
101
102 let constraint_eq u1 u2 =
103 let open UnivProblem in
104 ULe (u1, u2)
105
106 [%%if coq = "9.0" || coq = "9.1"]
107 let add_constraints state c = S.update (Option.get !pre_engine) state (fun ({ sigma } as x) ->
108 { x with sigma = Evd.add_universe_constraints sigma c })
109 [%%else]
110 let add_constraints state c = S.update (Option.get !pre_engine) state (fun ({ sigma } as x) ->
111 { x with sigma = Evd.add_constraints sigma c })
112 [%%endif]
113
114 [%%if coq = "9.0" || coq = "9.1"]
115 let add_universe_constraint state c =
116 let open UnivProblem in
117 try add_constraints state (Set.singleton c)
118 with
119 | UGraph.UniverseInconsistency p ->
120 let sigma = (S.get (Option.get !pre_engine) state).sigma in
121 Feedback.msg_debug
122 (UGraph.explain_universe_inconsistency
123 (Termops.pr_evd_qvar sigma)
124 (Termops.pr_evd_level sigma)
125 p);
126 raise API.BuiltInPredicate.No_clause
127 | Evd.UniversesDiffer | UState.UniversesDiffer ->
128 Feedback.msg_debug Pp.(str"UniversesDiffer");
129 raise API.BuiltInPredicate.No_clause
130 [%%elif coq = "9.2"]
131 let add_universe_constraint state c =
132 let open UnivProblem in
133 try add_constraints state (Set.singleton c)
134 with
135 | QGraph.(EliminationError (QualityInconsistency (Some printer, (k, q, q', e)))) ->
136 Feedback.msg_debug
137 (QGraph.explain_quality_inconsistency printer e);
138 raise API.BuiltInPredicate.No_clause
139
140 | UGraph.UniverseInconsistency p ->
141 let sigma = (S.get (Option.get !pre_engine) state).sigma in
142 Feedback.msg_debug
143 (UGraph.explain_universe_inconsistency
144 (Termops.pr_evd_qvar sigma)
145 (Termops.pr_evd_level sigma)
146 p);
147 raise API.BuiltInPredicate.No_clause
148 | Evd.UniversesDiffer | UState.UniversesDiffer ->
149 Feedback.msg_debug Pp.(str"UniversesDiffer");
150 raise API.BuiltInPredicate.No_clause
151 [%%else]
152 let add_universe_constraint state c =
153 let open UnivProblem in
154 try add_constraints state (Set.singleton c)
155 with
156 | QGraph.(EliminationError (QualityInconsistency (Some printer, (k, q, q', e)))) ->
157 Feedback.msg_debug
158 (QGraph.explain_quality_inconsistency printer e);
159 raise API.BuiltInPredicate.No_clause
160
161 | UGraph.UniverseInconsistency p ->
162 let sigma = (S.get (Option.get !pre_engine) state).sigma in
163 Feedback.msg_debug
164 (UGraph.explain_universe_inconsistency
165 (Evd.sort_printer sigma)
166 p);
167 raise API.BuiltInPredicate.No_clause
168 | Evd.UniversesDiffer | UState.UniversesDiffer ->
169 Feedback.msg_debug Pp.(str"UniversesDiffer");
170 raise API.BuiltInPredicate.No_clause
171 [%%endif]
172
173 let new_univ_level_variable ?(flexible=false) state =
174 S.update_return (Option.get !pre_engine) state (fun ({ sigma } as e) ->
175 (* ~name: really mean the universe level is a binder as in Definition f@{x} *)
176 let rigidity = if flexible then UState.univ_flexible_alg else UState.univ_rigid in
177 let sigma, v = Evd.new_univ_level_variable ?name:None rigidity sigma in
178 let u = Univ.Universe.make v in
179 (*
180 let sigma = Evd.add_universe_constraints sigma
181 (UnivProblem.Set.singleton (UnivProblem.ULe (Sorts.set,Sorts.sort_of_univ u))) in
182 *)
183 { e with sigma }, (v, u))
184
185
186 (* We patch data_of_cdata by forcing all output universes that
187 * are unification variables to be a Coq universe variable, so that
188 * we can always call Coq's API *)
189 let isuniv, univout, univino, (univ : Univ.Universe.t API.Conversion.t) =
190 let { CD.cin = univin; cino = univino; isc = isuniv; cout = univout }, univ_to_be_patched = CD.declare {
191 CD.name = "univ";
192 doc = "universe level (algebraic: max, +1, univ.variable)";
193 pp = (fun fmt x ->
194 let s = Pp.string_of_ppcmds (Univ.Universe.pr UnivNames.pr_level_with_global_universes x) in
195 Format.fprintf fmt "«%s»" s);
196 compare = Univ.Universe.compare;
197 hash = Univ.Universe.hash;
198 hconsed = false;
199 constants = [];
200 } in
201 (* turn UVars into fresh universes *)
202 isuniv, univout, univino, { univ_to_be_patched with
203 API.Conversion.readback = begin fun ~depth state t ->
204 match E.look ~depth t with
205 | E.UnifVar (b,args) ->
206 let m = S.get um state in
207 begin try
208 let u = UM.host b m in
209 state, u, []
210 with Not_found ->
211 (* flexible makes {{ Type }} = {{ Set }} also true when coq.unify-eq {{ Type }} {{ Set }} *)
212 let state, (_,u) = new_univ_level_variable ~flexible:true state in
213 let state = S.update um state (UM.add b u) in
214 let state, prune_ev = prune_uvar state b args in
215 state, u, [ prune_ev; API.Conversion.Unify(E.mkUnifVar b ~args state,univin u) ]
216 end
217 | _ -> univ_to_be_patched.API.Conversion.readback ~depth state t
218 end
219 }
220
221
222 let universe_level_variable =
223 let { CD.cin = levelin }, universe_level_variable_to_patch = CD.declare {
224 CD.name = "univ.variable";
225 doc = "universe level variable";
226 pp = (fun fmt x ->
227 let s = Pp.string_of_ppcmds (UnivNames.pr_level_with_global_universes x) in
228 Format.fprintf fmt "«%s»" s);
229 compare = Univ.Level.compare;
230 hash = Univ.Level.hash;
231 hconsed = false;
232 constants = [];
233 } in
234 { universe_level_variable_to_patch with
235 API.Conversion.readback = begin fun ~depth state t ->
236 match E.look ~depth t with
237 | E.UnifVar (b,args) ->
238 let m = S.get um state in
239 begin try
240 let u = UM.host b m in
241 state, Option.get @@ Univ.Universe.level u, []
242 with Not_found ->
243 let state, (l,u) = new_univ_level_variable state in
244 let state = S.update um state (UM.add b u) in
245 let state, prune_ev = prune_uvar state b args in
246 state, l, [ prune_ev; API.Conversion.Unify(E.mkUnifVar b ~args state,levelin l) ]
247 end
248 | _ -> universe_level_variable_to_patch.API.Conversion.readback ~depth state t
249 end
250 }
251
252 [%%if coq = "9.0" || coq = "9.1"]
253 type univ_cst = Univ.univ_constraint
254 type univ_csts = Univ.Constraints.t
255
256 let univ_lt = Univ.Lt
257 let univ_le = Univ.Le
258 let univ_eq = Univ.Eq
259 let univ_csts_of_list = Univ.Constraints.of_list
260 let univ_csts_to_list = Univ.Constraints.elements
261 let evd_merge_ctx_set rigid = Evd.merge_sort_context_set rigid
262 let subst_univs_constraints = Univ.subst_univs_level_constraints
263 let univs_of_csts = UVars.UContext.constraints
264 let mk_universe_decl univdecl_extensible_instance univdecl_extensible_constraints univdecl_constraints univdecl_instance =
265 let open UState in
266 { univdecl_qualities = [];
267 univdecl_extensible_instance;
268 univdecl_extensible_qualities = false;
269 univdecl_extensible_constraints;
270 univdecl_constraints;
271 univdecl_instance}
272 let default_univ_decl = UState.default_univ_decl
273 let dest_udecl ({ UState.univdecl_instance ; univdecl_constraints } : UState.universe_decl) =
274 univdecl_instance, univdecl_constraints
275
276 let universe_constraint : univ_cst API.Conversion.t =
277 let open API.Conversion in let open API.AlgebraicData in declare {
278 ty = TyName "univ-constraint";
279 doc = "Constraint between two universes level variables";
280 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
281 constructors = [
282 K("lt","",A(universe_level_variable,A(universe_level_variable,N)),
283 B (fun u1 u2 -> (u1,univ_lt,u2)),
284 M (fun ~ok ~ko -> function (l1,Univ.Lt,l2) -> ok l1 l2 | _ -> ko ()));
285 K("le","",A(universe_level_variable,A(universe_level_variable,N)),
286 B (fun u1 u2 -> (u1,univ_le,u2)),
287 M (fun ~ok ~ko -> function (l1,Univ.Le,l2) -> ok l1 l2 | _ -> ko ()));
288 K("eq","",A(universe_level_variable,A(universe_level_variable,N)),
289 B (fun u1 u2 -> (u1,univ_eq,u2)),
290 M (fun ~ok ~ko -> function (l1,Univ.Eq,l2) -> ok l1 l2 | _ -> ko ()))
291 ]
292 } |> API.ContextualConversion.(!<)
293 [%%else]
294 type univ_cst = Univ.UnivConstraint.t
295 type univ_csts = Univ.UnivConstraints.t
296 let univ_lt = Univ.UnivConstraint.Lt
297 let univ_le = Univ.UnivConstraint.Le
298 let univ_eq = Univ.UnivConstraint.Eq
299 let univ_csts_of_list = Univ.UnivConstraints.of_list
300 let univ_csts_to_list = Univ.UnivConstraints.elements
301 let evd_merge_ctx_set rigid = Evd.merge_sort_context_set rigid
302 let subst_univs_constraints x = UVars.subst_univs_constraints x
303 let univs_of_csts x = PConstraints.univs @@ UVars.UContext.constraints x
304 let mk_universe_decl univdecl_extensible_instance univdecl_extensible_constraints univdecl_univ_constraints univdecl_instance =
305 let open UState in
306 { univdecl_qualities = [];
307 univdecl_extensible_instance;
308 univdecl_elim_constraints = Sorts.ElimConstraints.empty;
309 univdecl_extensible_qualities = false;
310 univdecl_extensible_constraints;
311 univdecl_univ_constraints;
312 univdecl_instance}
313 let default_univ_decl = UState.default_univ_decl
314 let dest_udecl ({ UState.univdecl_instance ; univdecl_univ_constraints } : UState.universe_decl) =
315 univdecl_instance, univdecl_univ_constraints
316
317 let universe_constraint : univ_cst API.Conversion.t =
318 let open API.Conversion in let open API.AlgebraicData in declare {
319 ty = TyName "univ-constraint";
320 doc = "Constraint between two universes level variables";
321 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
322 constructors = [
323 K("lt","",A(universe_level_variable,A(universe_level_variable,N)),
324 B (fun u1 u2 -> (u1,univ_lt,u2)),
325 M (fun ~ok ~ko -> function (l1,Univ.UnivConstraint.Lt,l2) -> ok l1 l2 | _ -> ko ()));
326 K("le","",A(universe_level_variable,A(universe_level_variable,N)),
327 B (fun u1 u2 -> (u1,univ_le,u2)),
328 M (fun ~ok ~ko -> function (l1,Univ.UnivConstraint.Le,l2) -> ok l1 l2 | _ -> ko ()));
329 K("eq","",A(universe_level_variable,A(universe_level_variable,N)),
330 B (fun u1 u2 -> (u1,univ_eq,u2)),
331 M (fun ~ok ~ko -> function (l1,Univ.UnivConstraint.Eq,l2) -> ok l1 l2 | _ -> ko ()))
332 ]
333 } |> API.ContextualConversion.(!<)
334 [%%endif]
335
336
337 let universe_variance : (Univ.Level.t * UVars.Variance.t option) API.Conversion.t =
338 let open API.Conversion in let open API.AlgebraicData in declare {
339 ty = TyName "univ-variance";
340 doc = "Variance of a universe level variable";
341 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
342 constructors = [
343 K("auto","",A(universe_level_variable,N),
344 B (fun u -> u,None),
345 M (fun ~ok ~ko -> function (u,None) -> ok u | _ -> ko ()));
346 K("covariant","",A(universe_level_variable,N),
347 B (fun u -> u,Some UVars.Variance.Covariant),
348 M (fun ~ok ~ko -> function (u,Some UVars.Variance.Covariant) -> ok u | _ -> ko ()));
349 K("invariant","",A(universe_level_variable,N),
350 B (fun u -> u,Some UVars.Variance.Invariant),
351 M (fun ~ok ~ko -> function (u,Some UVars.Variance.Invariant) -> ok u | _ -> ko ()));
352 K("irrelevant","",A(universe_level_variable,N),
353 B (fun u -> u,Some UVars.Variance.Invariant),
354 M (fun ~ok ~ko -> function (u,Some UVars.Variance.Irrelevant) -> ok u | _ -> ko ()));
355 ]
356 } |> API.ContextualConversion.(!<)
357
358 type universe_decl = (Univ.Level.t list * bool) * (univ_csts * bool)
359 type universe_decl_cumul = ((Univ.Level.t * UVars.Variance.t option) list * bool) * (univ_csts * bool)
360
361 type any_universe_decl =
362 | NonCumul of universe_decl
363 | Cumul of universe_decl_cumul
364
365 let universe_decl : any_universe_decl API.Conversion.t =
366 let open API.Conversion in let open API.BuiltInData in let open API.AlgebraicData in let open Elpi.Builtin in declare {
367 ty = TyName "upoly-decl";
368 doc = "Constraints for a non-cumulative declaration. Boolean tt means loose (e.g. the '+' in f@{u v + | u < v +})";
369 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
370 constructors = [
371 K("upoly-decl","",A(list universe_level_variable,A(bool,A(list universe_constraint,A(bool,N)))),
372 B (fun x sx y sy-> NonCumul ((x,sx),(univ_csts_of_list y,sy))),
373 M (fun ~ok ~ko -> function NonCumul ((x,sx),(y,sy)) -> ok x sx (univ_csts_to_list y) sy | Cumul _ -> ko ()));
374 K("upoly-decl-cumul","",A(list universe_variance,A(bool,A(list universe_constraint,A(bool,N)))),
375 B (fun x sx y sy -> Cumul ((x,sx),(univ_csts_of_list y,sy))),
376 M (fun ~ok ~ko -> function Cumul ((x,sx),(y,sy)) -> ok x sx (univ_csts_to_list y) sy | NonCumul _ -> ko ()))
377 ]
378 } |> API.ContextualConversion.(!<)
379
380 (* All in one data structure to represent the Coq context and its link with
381 the elpi one:
382 - section is not part of the elpi context, but Coq's evars are applied
383 also to that part
384 - proof is the named_context with proof variables only (no section part)
385 - local is the rel_context
386 - db2rel stores how many locally bound (rel) variables were there when
387 the binder for the given dbl is crossed: see lp2term
388 - env is a Coq environment corresponding to section + proof + local *)
389 type empty = [ `Options ]
390 type full = [ `Options | `Context ]
391
392 (* Readback of UVars into ... *)
393 type ppoption = All | Most | Normal
394 type hole_mapping =
395 | Verbatim (* 1:1 correspondence between UVar and Evar *)
396 | Heuristic (* new UVar outside Llam is pruned before being linked to Evar *)
397 | Implicit (* No link, UVar is intepreted as a "hole" constant *)
398 type uinstanceoption =
399 | NoInstance
400 (* the elpi command involved has to generate a fresh instance *)
401 | ConcreteInstance of UVars.Instance.t
402 (* a concrete instance was provided, the command will use it *)
403 | VarInstance of (F.Elpi.t * E.term list * inv_rel_key)
404 (* a variable was provided, the command will compute the instance to unify with it *)
405 type universe_decl_option =
406 | NotUniversePolymorphic
407 | Cumulative of universe_decl_cumul
408 | NonCumulative of universe_decl
409 type options = {
410 hoas_holes : hole_mapping option;
411 local : bool option;
412 user_warns : UserWarn.t option;
413 primitive : bool option;
414 failsafe : bool; (* readback is resilient to illformed terms *)
415 ppwidth : int;
416 pp : ppoption;
417 pplevel : Constrexpr.entry_relative_level;
418 using : string option;
419 inline : Declaremods.inline;
420 uinstance : uinstanceoption;
421 universe_decl : universe_decl_option;
422 reversible : bool option;
423 keepunivs : bool option;
424 redflags : RedFlags.reds option;
425 no_tc: bool option;
426 algunivs : bool option;
427 }
428 let default_options () = {
429 hoas_holes = Some Verbatim;
430 local = None;
431 user_warns = None;
432 primitive = None;
433 failsafe = false;
434 ppwidth = Option.default 80 (Topfmt.get_margin ());
435 pp = Normal;
436 pplevel = Constrexpr.LevelSome;
437 using = None;
438 inline = Declaremods.NoInline;
439 uinstance = NoInstance;
440 universe_decl = NotUniversePolymorphic;
441 reversible = None;
442 keepunivs = None;
443 redflags = None;
444 no_tc = None;
445 algunivs = None;
446 }
447 let make_options ~hoas_holes ~local ~warn ~depr ~primitive ~failsafe ~ppwidth
448 ~pp ~pplevel ~using ~inline ~uinstance ~universe_decl ~reversible ~keepunivs
449 ~redflags ~no_tc ~algunivs =
450 let user_warns = Some UserWarn.{ depr; warn } in
451 { hoas_holes; local; user_warns; primitive; failsafe; ppwidth; pp;
452 pplevel; using; inline; uinstance; universe_decl; reversible; keepunivs;
453 redflags; no_tc; algunivs; }
454 let make_warn = UserWarn.make_warn
455
456 type 'a conv_context = {
457 section : Names.Id.t list;
458 section_len : int;
459 proof : EConstr.named_context;
460 proof_len : int;
461 local : (int * EConstr.rel_declaration) list;
462 local_len : int;
463 env : Environ.env;
464 db2name : Names.Id.t Int.Map.t;
465 name2db : int Names.Id.Map.t;
466 db2rel : int Int.Map.t;
467 names : Id.Set.t;
468 options : options;
469 hyps : E.hyp list;
470 }
471 let upcast (x : [> `Options ] conv_context) : full conv_context = (x :> full conv_context)
472
473 let pr_coq_ctx { env; db2name; db2rel } sigma =
474 let open Pp in
475 v 0 (
476 str "Mapping from DBL:"++ cut () ++ str " " ++
477 v 0 (prlist_with_sep cut (fun (i,n) -> str(E.Constants.show i) ++ str " |-> " ++ Id.print n)
478 (Int.Map.bindings db2name)) ++ cut () ++
479 v 0 (prlist_with_sep cut (fun (i,n) -> str(E.Constants.show i) ++ str " |-> " ++ int n)
480 (Int.Map.bindings db2rel)) ++ cut () ++
481 str "Named:" ++ cut () ++ str " " ++
482 v 0 (Printer.pr_named_context_of env sigma) ++ cut () ++
483 str "Rel:" ++ cut () ++ str " " ++
484 v 0 (Printer.pr_rel_context_of env sigma) ++ cut ()
485 )
486
487 let propc = E.Constants.declare_global_symbol "prop"
488 let spropc = E.Constants.declare_global_symbol "sprop"
489 let typc = E.Constants.declare_global_symbol "typ"
490
491 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
492 let ppsort fmt = function
493 | Sorts.Type _ -> Format.fprintf fmt "Type"
494 | Sorts.Set -> Format.fprintf fmt "Set"
495 | Sorts.Prop -> Format.fprintf fmt "Prop"
496 | Sorts.SProp -> Format.fprintf fmt "SProp"
497 | Sorts.QSort _ -> Format.fprintf fmt "QSort"
498 [%%else]
499 let ppsort fmt = function
500 | Sorts.Type _ -> Format.fprintf fmt "Type"
501 | Sorts.Set -> Format.fprintf fmt "Set"
502 | Sorts.Prop -> Format.fprintf fmt "Prop"
503 | Sorts.SProp -> Format.fprintf fmt "SProp"
504 | Sorts.GSort _ -> Format.fprintf fmt "GSort"
505 | Sorts.VSort _ -> Format.fprintf fmt "VSort"
506 [%%endif]
507
508 let sort : (Sorts.t, _ conv_context, API.Data.constraints) API.ContextualConversion.t =
509 let open API.ContextualConversion in
510 {
511 ty = API.Conversion.TyName "sort";
512 pp_doc = (fun fmt () ->
513 Format.fprintf fmt "%% Sorts (kinds of types)\n";
514 Format.fprintf fmt "kind sort type.\n";
515 Format.fprintf fmt "external symbol prop : sort. %% impredicative sort of propositions\n";
516 Format.fprintf fmt "external symbol sprop : sort. %% impredicative sort of propositions with definitional proof irrelevance\n";
517 Format.fprintf fmt "external symbol typ : univ -> sort. %% predicative sort of data (carries a universe level)\n";
518 );
519 pp = ppsort;
520 embed = (fun ~depth { options } _ state s ->
521 match s with
522 | Sorts.Prop -> state, E.mkConst propc, []
523 | Sorts.SProp -> state, E.mkConst spropc, []
524 | Sorts.Set ->
525 let state, u, gls = univ.embed ~depth state Univ.Universe.type0 in
526 state, E.mkApp typc u [], gls
527 | Sorts.Type u ->
528 let state, u, gls = univ.embed ~depth state u in
529 state, E.mkApp typc u [], gls
530 | _ -> nYI "sort polymorphism");
531 readback = (fun ~depth { options } _ state t ->
532 match E.look ~depth t with
533 | E.Const c when c == propc -> state, Sorts.prop, []
534 | E.Const c when c == spropc -> state, Sorts.sprop, []
535 | E.App(c,u,[]) when c == typc ->
536 let state, u, gls = univ.readback ~depth state u in
537 state, Sorts.sort_of_univ u ,gls
538 | E.UnifVar(k,_) -> begin
539 let m = S.get um state in
540 try
541 let u = UM.host k m in
542 state, Sorts.sort_of_univ u, []
543 with Not_found ->
544 let state, (_,u) = new_univ_level_variable state in
545 let state = S.update um state (UM.add k u) in
546 state, Sorts.sort_of_univ u, []
547 end
548 | _ -> raise API.Conversion.(TypeErr(TyName"sort",depth,t)));
549 }
550
551 let ast_sort ~loc = function
552 | Sorts.Prop -> A.mkGlobal ~loc propc
553 | Sorts.SProp -> A.mkGlobal ~loc spropc
554 | Sorts.Set -> A.mkAppGlobal ~loc ~hdloc:loc typc (A.mkOpaque ~loc @@ univino Univ.Universe.type0) []
555 | Sorts.Type u -> A.mkAppGlobal ~loc ~hdloc:loc typc (A.mkOpaque ~loc @@ univino u) []
556 | _ -> assert false
557
558
559 let unspec2opt = function Elpi.Builtin.Given x -> Some x | Elpi.Builtin.Unspec -> None
560 let opt2unspec = function Some x -> Elpi.Builtin.Given x | None -> Elpi.Builtin.Unspec
561
562 (* constants *)
563
564 type global_constant = Variable of Names.Id.t | Constant of Names.Constant.t
565 let hash_global_constant = function
566 | Variable id -> Names.Id.hash id
567 | Constant c -> Names.Constant.CanOrd.hash c
568 let compare_global_constant x y = match x,y with
569 | Variable v1, Variable v2 -> Names.Id.compare v1 v2
570 | Constant c1, Constant c2 -> Names.Constant.CanOrd.compare c1 c2
571 | Variable _, _ -> -1
572 | _ -> 1
573
574 let global_constant_of_globref = function
575 | GlobRef.VarRef x -> Variable x
576 | GlobRef.ConstRef x -> Constant x
577 | x -> CErrors.anomaly Pp.(str"not a global constant: " ++ (Printer.pr_global x))
578
579 let ({ CD.isc = isconstant; cout = constantout; cin = constantin; cino = constantino },constant),
580 ({ CD.isc = isinductive; cout = inductiveout; cin = inductivein; cino = inductiveino },inductive),
581 ({ CD.isc = isconstructor; cout = constructorout; cin = constructorin; cino = constructorino },constructor) =
582 let open API.RawOpaqueData in
583 declare {
584 name = "constant";
585 doc = "Global constant name";
586 pp = (fun fmt x ->
587 let x = match x with
588 | Variable x -> GlobRef.VarRef x
589 | Constant c -> GlobRef.ConstRef c in
590 Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global x));
591 compare = compare_global_constant;
592 hash = hash_global_constant;
593 hconsed = false;
594 constants = [];
595 },
596 declare {
597 name = "inductive";
598 doc = "Inductive type name";
599 pp = (fun fmt x -> Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global (GlobRef.IndRef x)));
600 compare = Names.Ind.CanOrd.compare;
601 hash = Names.Ind.CanOrd.hash;
602 hconsed = false;
603 constants = [];
604 },
605 declare {
606 name = "constructor";
607 doc = "Inductive constructor name";
608 pp = (fun fmt x -> Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global (GlobRef.ConstructRef x)));
609 compare = Names.Construct.CanOrd.compare;
610 hash = Names.Construct.CanOrd.hash;
611 hconsed = false;
612 constants = [];
613 }
614 ;;
615 let inductiveina ~loc x = A.mkOpaque ~loc (inductiveino x)
616 let constantina ~loc x = A.mkOpaque ~loc (constantino x)
617 let constructorina ~loc x = A.mkOpaque ~loc (constructorino x)
618
619 let subst_cdata subst c =
620 if isconstant c then
621 match constantout c with
622 | Variable _ -> c
623 | Constant k ->
624 let k' = Mod_subst.subst_constant subst k in
625 if k == k' then c else constantino (Constant k')
626 else if isinductive c then
627 let i = inductiveout c in
628 let i' = Mod_subst.subst_ind subst i in
629 if i == i' then c else inductiveino i'
630 else if isconstructor c then
631 let k = constructorout c in
632 let k' = Mod_subst.subst_constructor subst k in
633 if k == k' then c else constructorino k'
634 else c
635
636 let compare_instances x y =
637 let qx, ux = UVars.Instance.to_array x
638 and qy, uy = UVars.Instance.to_array y in
639 Util.Compare.(compare [(CArray.compare Sorts.Quality.compare, qx, qy); (CArray.compare Univ.Level.compare, ux, uy)])
640
641 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
642 let ppinst u = UVars.Instance.pr Sorts.QVar.raw_pr UnivNames.pr_level_with_global_universes u
643 [%%else]
644 let ppinst u = UVars.Instance.pr Sorts.raw_printer u
645 [%%endif]
646
647 let uinstancein, uinstanceino, isuinstance, uinstanceout, uinstance =
648 let { CD.cin; cino; isc; cout }, uinstance = CD.declare {
649 CD.name = "univ-instance";
650 doc = "Universes level instance for a universe-polymorphic constant";
651 pp = (fun fmt x ->
652 let s = Pp.string_of_ppcmds (ppinst x) in
653 Format.fprintf fmt "«%s»" s);
654 compare = compare_instances;
655 hash = UVars.Instance.hash;
656 hconsed = false;
657 constants = [];
658 } in
659 cin, cino, isc, cout, uinstance
660 ;;
661
662 let uinstanceina ~loc x = A.mkOpaque ~loc (uinstanceino x)
663
664 let collect_term_variables ~depth t =
665 let rec aux ~depth acc t =
666 match E.look ~depth t with
667 | E.CData c when isconstant c ->
668 begin match constantout c with
669 | Variable id -> id :: acc
670 | _ -> acc
671 end
672 | x -> fold_elpi_term aux acc ~depth x
673 in
674 aux ~depth [] t
675
676 let constc = E.Constants.declare_global_symbol "const"
677 let indcc = E.Constants.declare_global_symbol "indc"
678 let indtc = E.Constants.declare_global_symbol "indt"
679
680 let gref : Names.GlobRef.t API.Conversion.t = {
681 API.Conversion.ty = API.Conversion.TyName "gref";
682 pp_doc = (fun fmt () ->
683 Format.fprintf fmt "%% Global objects: inductive types, inductive constructors, definitions@\n";
684 Format.fprintf fmt "kind gref type.@\n";
685 Format.fprintf fmt "external symbol const : constant -> gref. %% Nat.add, List.append, ...@\n";
686 Format.fprintf fmt "external symbol indt : inductive -> gref. %% nat, list, ...@\n";
687 Format.fprintf fmt "external symbol indc : constructor -> gref. %% O, S, nil, cons, ...@\n";
688 );
689 pp = (fun fmt x ->
690 Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global x));
691 embed = (fun ~depth state -> function
692 | GlobRef.IndRef i -> state, E.mkApp indtc (inductivein i) [], []
693 | GlobRef.ConstructRef c -> state, E.mkApp indcc (constructorin c) [], []
694 | GlobRef.VarRef v -> state, E.mkApp constc (constantin (Variable v)) [], []
695 | GlobRef.ConstRef c -> state, E.mkApp constc (constantin (Constant c)) [], []
696 );
697 readback = (fun ~depth state t ->
698 match E.look ~depth t with
699 | E.App(c,t,[]) when c == indtc ->
700 begin match E.look ~depth t with
701 | E.CData d when isinductive d -> state, GlobRef.IndRef (inductiveout d), []
702 | _ -> raise API.Conversion.(TypeErr(TyName"inductive",depth,t)); end
703 | E.App(c,t,[]) when c == indcc ->
704 begin match E.look ~depth t with
705 | E.CData d when isconstructor d -> state, GlobRef.ConstructRef (constructorout d), []
706 | _ -> raise API.Conversion.(TypeErr(TyName"constructor",depth,t)); end
707 | E.App(c,t,[]) when c == constc ->
708 begin match E.look ~depth t with
709 | E.CData d when isconstant d ->
710 begin match constantout d with
711 | Variable v -> state, GlobRef.VarRef v, []
712 | Constant v -> state, GlobRef.ConstRef v, [] end
713 | _ -> raise API.Conversion.(TypeErr(TyName"constant",depth,t)); end
714 | _ -> raise API.Conversion.(TypeErr(TyName"gref",depth,t));
715 );
716 }
717
718 let abbreviation =
719 let open API.OpaqueData in
720 declare {
721 name = "abbreviation";
722 doc = "Name of an abbreviation";
723 pp = (fun fmt x -> Format.fprintf fmt "«%s»" (KerName.to_string x));
724 compare = KerName.compare;
725 hash = KerName.hash;
726 hconsed = false;
727 constants = [];
728 }
729
730 module GROrd = struct
731 include Names.GlobRef.CanOrd
732 let show x = Pp.string_of_ppcmds (Printer.pr_global x)
733 let pp fmt x = Format.fprintf fmt "%a" Pp.pp_with (Printer.pr_global x)
734 end
735 module GRMap = U.Map.Make(GROrd)
736 module GRSet = U.Set.Make(GROrd)
737
738 let globalc = E.Constants.declare_global_symbol "global"
739 let pglobalc = E.Constants.declare_global_symbol "pglobal"
740
741 module GrefCache = Hashtbl.Make(GlobRef.UserOrd)
742 let cache = GrefCache.create 13
743
744 let assert_in_coq_gref_consistent ~poly gr =
745 match Global.is_polymorphic gr, poly with
746 | true, true -> ()
747 | false, false -> ()
748 | true, false ->
749 U.type_error Printf.(sprintf "Universe polymorphic gref %s used with the 'global' term constructor" (GROrd.show gr))
750 | false, true ->
751 U.type_error Printf.(sprintf "Non universe polymorphic gref %s used with the 'pglobal' term constructor" (GROrd.show gr))
752 ;;
753
754 let assert_in_elpi_gref_consistent ~poly gr =
755 match Global.is_polymorphic gr, poly with
756 | true, true -> ()
757 | false, false -> ()
758 | true, false ->
759 U.anomaly Printf.(sprintf "Universe polymorphic gref %s used with the 'global' term constructor" (GROrd.show gr))
760 | false, true ->
761 U.anomaly Printf.(sprintf "Non universe polymorphic gref %s used with the 'pglobal' term constructor" (GROrd.show gr))
762 ;;
763
764
765 let in_elpi_gr ~depth s r =
766 assert_in_elpi_gref_consistent ~poly:false r;
767 try
768 GrefCache.find cache r
769 with Not_found ->
770 let s, t, gl = gref.API.Conversion.embed ~depth s r in
771 assert (gl = []);
772 let x = E.mkAppGlobal globalc t [] in
773 GrefCache.add cache r x;
774 x
775
776 let in_elpiast_gref ~loc r =
777 match r with
778 | GlobRef.IndRef i -> A.mkAppGlobal ~loc ~hdloc:loc indtc (inductiveina ~loc i) []
779 | GlobRef.ConstructRef c -> A.mkAppGlobal ~loc ~hdloc:loc indcc (constructorina ~loc c) []
780 | GlobRef.VarRef v -> A.mkAppGlobal ~loc ~hdloc:loc constc (constantina ~loc (Variable v)) []
781 | GlobRef.ConstRef c -> A.mkAppGlobal ~loc ~hdloc:loc constc (constantina ~loc (Constant c)) []
782
783 let in_elpiast_gr ~loc r =
784 assert_in_elpi_gref_consistent ~poly:false r;
785 A.mkAppGlobal ~loc ~hdloc:loc globalc (in_elpiast_gref ~loc r) []
786
787 let in_elpi_poly_gr ~depth s r i =
788 assert_in_elpi_gref_consistent ~poly:true r;
789 let open API.Conversion in
790 let s, t, gl = gref.embed ~depth s r in
791 assert (gl = []);
792 E.mkApp pglobalc t [i]
793
794 let in_elpiast_poly_gr ~loc r i =
795 assert_in_elpi_gref_consistent ~poly:true r;
796 let t = in_elpiast_gref ~loc r in
797 A.mkAppGlobal ~loc ~hdloc:loc pglobalc t [i]
798
799 let in_elpi_poly_gr_instance ~depth s r i =
800 assert_in_elpi_gref_consistent ~poly:true r;
801 let open API.Conversion in
802 let s, i, gl = uinstance.embed ~depth s i in
803 assert (gl = []);
804 in_elpi_poly_gr ~depth s r i
805
806 let in_elpiast_poly_gr_instance ~loc r i =
807 assert_in_elpi_gref_consistent ~poly:true r;
808 let i = uinstanceina ~loc i in
809 in_elpiast_poly_gr ~loc r i
810
811 let in_coq_gref ~depth ~origin ~failsafe s t =
812 try
813 let s, t, gls = gref.API.Conversion.readback ~depth s t in
814 assert_in_coq_gref_consistent ~poly:false t;
815 assert(gls = []);
816 s, t
817 with API.Conversion.TypeErr _ ->
818 if failsafe then
819 s, Rocqlib.lib_ref "elpi.unknown_gref"
820 else
821 err Pp.(str "The term " ++ str(pp2string (P.term depth) origin) ++
822 str " cannot be represented in Coq since its gref part is illformed")
823
824 let mpin, ismp, mpout, modpath =
825 let { CD.cin; isc; cout }, x = CD.declare {
826 CD.name = "modpath";
827 doc = "Name of a module /*E*/";
828 pp = (fun fmt x ->
829 Format.fprintf fmt "«%s»" (Names.ModPath.to_string x));
830 compare = Names.ModPath.compare;
831 hash = Names.ModPath.hash;
832 hconsed = false;
833 constants = [];
834 } in
835 cin, isc, cout, x
836 ;;
837 let mptyin, istymp, mptyout, modtypath =
838 let { CD.cin; isc; cout }, x = CD.declare {
839 CD.name = "modtypath";
840 doc = "Name of a module type /*E*/";
841 pp = (fun fmt x ->
842 Format.fprintf fmt "«%s»" (Names.ModPath.to_string x));
843 compare = Names.ModPath.compare;
844 hash = Names.ModPath.hash;
845 hconsed = false;
846 constants =[];
847 } in
848 cin, isc, cout, x
849 ;;
850
851 let in_elpi_modpath ~ty mp = if ty then mptyin mp else mpin mp
852 let is_modpath ~depth t =
853 match E.look ~depth t with E.CData x -> ismp x | _ -> false
854 let is_modtypath ~depth t =
855 match E.look ~depth t with E.CData x -> istymp x | _ -> false
856 let in_coq_modpath ~depth t =
857 match E.look ~depth t with
858 | E.CData x when ismp x -> mpout x
859 | E.CData x when istymp x -> mptyout x
860 | _ -> assert false
861
862 (* ********************************* }}} ********************************** *)
863
864 (* {{{ constants (app, fun, ...) ****************************************** *)
865 (* binders *)
866 let lamc = E.Constants.declare_global_symbol "fun"
867 let in_elpi_lam n s t = E.mkApp lamc (in_elpi_name n) [s;E.mkLam t]
868
869 let in_elpiast_lam ~loc n s t =
870 A.mkAppGlobal ~loc ~hdloc:loc lamc (in_elpiast_name ~loc n) [s;A.mkLam ~loc (name_of_name ~loc n) t]
871
872 let prodc = E.Constants.declare_global_symbol "prod"
873 let in_elpi_prod n s t = E.mkApp prodc (in_elpi_name n) [s;E.mkLam t]
874 let in_elpiast_prod ~loc n s t =
875 A.mkAppGlobal ~loc~hdloc:loc prodc (in_elpiast_name ~loc n) [s;A.mkLam ~loc (name_of_name ~loc n) t]
876
877 let letc = E.Constants.declare_global_symbol "let"
878 let in_elpi_let n b s t = E.mkApp letc (in_elpi_name n) [s;b;E.mkLam t]
879 let in_elpiast_let ~loc n ~ty:s ~bo:b t =
880 A.mkAppGlobal ~loc ~hdloc:loc letc (in_elpiast_name ~loc n) [s;b;A.mkLam ~loc (name_of_name ~loc n) t]
881
882 (* other *)
883 let appc = E.Constants.declare_global_symbol "app"
884
885 let in_elpi_app_Arg ~depth hd args = E.mkAppMoreArgs ~depth hd args
886
887 let flatten_appc ~depth hd (args : E.term list) =
888 if E.isApp ~depth hd then
889 match E.look ~depth hd with
890 | E.App(c,x,[]) when c == appc ->
891 E.mkApp appc (U.list_to_lp_list (U.lp_list_to_list ~depth x @ args)) []
892 | _ ->
893 E.mkApp appc (U.list_to_lp_list (hd :: args)) []
894 else
895 E.mkApp appc (U.list_to_lp_list (hd :: args)) []
896
897 let in_elpi_appl ~depth hd (args : E.term list) =
898 if args = [] then hd
899 else flatten_appc ~depth hd args
900
901 let flatten_appc_ast ~loc hd args =
902 match hd with
903 | { A.it = A.App(g,c,_,x,[]); loc } when API.Ast.Name.is_global c appc ->
904 A.mkAppGlobal ~loc ~hdloc:loc appc (A.ne_list_to_lp_list (A.lp_list_to_list x @ args)) []
905 | { loc } -> A.mkAppGlobal ~loc ~hdloc:loc appc (A.ne_list_to_lp_list (hd :: args)) []
906
907 let in_elpiast_appl ~loc hd args =
908 if args = [] then hd
909 else flatten_appc_ast ~loc hd args
910
911
912 let in_elpi_app ~depth hd (args : E.term array) =
913 in_elpi_appl ~depth hd (Array.to_list args)
914
915 let matchc = E.Constants.declare_global_symbol "match"
916
917 let in_elpi_match (*ci_ind ci_npar ci_cstr_ndecls ci_cstr_nargs*) t rt bs =
918 E.mkApp matchc t [rt; U.list_to_lp_list bs]
919
920 let in_elpiast_match ~loc t rt bs =
921 A.mkAppGlobal ~loc ~hdloc:loc matchc t [rt;A.list_to_lp_list ~loc bs]
922
923 let fixc = E.Constants.declare_global_symbol "fix"
924
925 let in_elpi_fix name rno ty bo =
926 E.mkApp fixc (in_elpi_name name) [CD.of_int rno; ty; E.mkLam bo]
927
928 let in_elpiast_fix ~loc n rno ty bo =
929 A.mkAppGlobal ~loc ~hdloc:loc fixc (in_elpiast_name ~loc n) [A.mkOpaque ~loc @@ CD.int.cino rno; ty; A.mkLam ~loc (name_of_name ~loc n) bo]
930
931 let mfixc = E.Constants.declare_global_symbol "mfix"
932 let mfix_tyc = E.Constants.declare_global_symbol "mfix-ty"
933 let mfix_boc = E.Constants.declare_global_symbol "mfix-bo"
934
935 let in_elpiast_mfix ~loc names_rnos_tys focus_idx bodies =
936 (* assert (List.length names_rnos_tys = List.length bodies); *)
937 let focus_recno = (List.nth names_rnos_tys focus_idx |> fun (_,x,_) -> x) in
938 let inner = A.mkAppGlobal ~loc ~hdloc:loc mfix_boc (A.list_to_lp_list ~loc bodies) [] in
939 let block =
940 List.fold_right (fun (name, rno, ty) acc ->
941 A.mkAppGlobal ~loc ~hdloc:loc mfix_tyc (in_elpiast_name ~loc name)
942 [A.mkOpaque ~loc @@ CD.int.cino rno; ty;
943 A.mkLam ~loc (name_of_name ~loc name) acc])
944 names_rnos_tys inner in
945 A.mkAppGlobal ~loc ~hdloc:loc mfixc
946 (A.mkOpaque ~loc @@ CD.int.cino focus_idx)
947 [A.mkOpaque ~loc @@ CD.int.cino focus_recno;block]
948
949 let in_elpi_mfix names_rnos_tys focus_idx bodies =
950 (* assert (List.length names_rnos_tys = List.length bodies); *)
951 let inner = E.mkApp mfix_boc (U.list_to_lp_list bodies) [] in
952 let focus_recno = List.nth names_rnos_tys focus_idx |> fun (_,x,_) -> x in
953 let block =
954 List.fold_right (fun (name, rno, ty) acc ->
955 E.mkApp mfix_tyc (in_elpi_name name) [CD.of_int rno; ty; E.mkLam acc])
956 names_rnos_tys inner in
957 E.mkApp mfixc (CD.of_int focus_idx) [CD.of_int focus_recno; block]
958
959 let primitivec = E.Constants.declare_global_symbol "primitive"
960
961
962 type pstring = Pstring.t
963 let pp_pstring = Pstring.to_string
964 let eC_mkString = EC.mkString
965
966 type primitive_value =
967 | Uint63 of Uint63.t
968 | Float64 of Float64.t
969 | Pstring of pstring
970 | Projection of Projection.t
971
972 let ui63c = E.Constants.declare_global_symbol "uint63"
973 let fl64c = E.Constants.declare_global_symbol "float64"
974 let pstrc = E.Constants.declare_global_symbol "pstring"
975 let projc = E.Constants.declare_global_symbol "proj"
976
977 let uint63ina ~loc x = A.mkAppGlobal ~loc ~hdloc:loc primitivec (A.mkAppGlobal ~loc ~hdloc:loc ui63c (A.mkOpaque ~loc (uint63c.cino x)) []) []
978 let float64ina ~loc x = A.mkAppGlobal ~loc ~hdloc:loc primitivec (A.mkAppGlobal ~loc ~hdloc:loc fl64c (A.mkOpaque ~loc (float64c.cino x)) []) []
979 let projectionina ~loc p =
980 let n = Names.Projection.(arg p + npars p) in
981 A.mkAppGlobal ~loc ~hdloc:loc primitivec (A.mkAppGlobal ~loc ~hdloc:loc projc
982 (A.mkOpaque ~loc (projectionc.cino p)) [A.mkOpaque ~loc @@ CD.int.cino n]) []
983 let pstringina ~loc x = A.mkAppGlobal ~loc~hdloc:loc primitivec (A.mkAppGlobal ~loc ~hdloc:loc pstrc (A.mkOpaque ~loc (pstringc.cino x)) []) []
984
985 let primitive_value : primitive_value API.Conversion.t =
986 let module B = Rocq_elpi_utils in
987 let open API.AlgebraicData in declare {
988 ty = API.Conversion.TyName "primitive-value";
989 doc = "Primitive values";
990 pp = (fun fmt -> function
991 | Uint63 i -> Format.fprintf fmt "%s" (Uint63.to_string i)
992 | Float64 f -> Format.fprintf fmt "%s" (Float64.to_string f)
993 | Pstring s -> Format.fprintf fmt "%s" (pp_pstring s)
994 | Projection p -> Format.fprintf fmt "%s" (Projection.to_string p));
995 constructors = [
996 K("uint63","unsigned integers over 63 bits",A(B.uint63,N),
997 B (fun x -> Uint63 x),
998 M (fun ~ok ~ko -> function Uint63 x -> ok x | _ -> ko ()));
999 K("float64","double precision foalting points",A(B.float64,N),
1000 B (fun x -> Float64 x),
1001 M (fun ~ok ~ko -> function Float64 x -> ok x | _ -> ko ()));
1002 K("pstring","primitive string",A(B.pstring,N),
1003 B (fun x -> Pstring x),
1004 M (fun ~ok ~ko -> function Pstring x -> ok x | _ -> ko ()));
1005 K("proj","primitive projection",A(B.projection,A(API.BuiltInData.int,N)),
1006 B (fun p n -> Projection p),
1007 M (fun ~ok ~ko -> function Projection p -> ok p Names.Projection.(arg p + npars p) | _ -> ko ()));
1008 ]
1009 } |> API.ContextualConversion.(!<)
1010
1011 let in_elpi_primitive ~depth state i =
1012 let state, i, _ = primitive_value.API.Conversion.embed ~depth state i in
1013 state, E.mkApp primitivec i []
1014
1015 let in_elpiast_primitive ~loc = function
1016 | Uint63 i -> uint63ina ~loc i
1017 | Float64 f -> float64ina ~loc f
1018 | Pstring s -> pstringina ~loc s
1019 | Projection p -> projectionina ~loc p
1020
1021 let in_elpi_primitive_value ~depth state = function
1022 | C.Int i -> in_elpi_primitive ~depth state (Uint63 i)
1023 | C.Float f -> in_elpi_primitive ~depth state (Float64 f)
1024 | C.String s -> in_elpi_primitive ~depth state (Pstring s)
1025 | C.Array _ -> nYI "HOAS for persistent arrays"
1026 | (C.Fix _ | C.CoFix _ | C.Lambda _ | C.App _ | C.Prod _ | C.Case _ | C.Cast _ | C.Construct _ | C.LetIn _ | C.Ind _ | C.Meta _ | C.Rel _ | C.Var _ | C.Proj _ | C.Evar _ | C.Sort _ | C.Const _) -> assert false
1027
1028 (* ********************************* }}} ********************************** *)
1029
1030 (* {{{ HOAS : Evd.evar_map -> elpi *************************************** *)
1031
1032 module CoqEngine_HOAS : sig
1033
1034 val show_coq_engine : ?with_univs:bool -> coq_engine -> string
1035
1036 val engine : coq_engine S.component
1037
1038 val from_env_sigma : Environ.env -> Evd.evar_map -> coq_engine
1039
1040 (* when the env changes under the hood, we can adapt sigma or drop it but keep
1041 its constraints *)
1042 val from_env_keep_univ_of_sigma : uctx:Univ.ContextSet.t -> env0:Environ.env -> env:Environ.env -> Evd.evar_map -> coq_engine
1043 val from_env_keep_univ_and_sigma : uctx:Univ.ContextSet.t -> env0:Environ.env -> env:Environ.env -> Evd.evar_map -> coq_engine
1044
1045 end = struct
1046
1047 let pp_coq_engine ?with_univs fmt { sigma } =
1048 Format.fprintf fmt "%a" Pp.pp_with (Termops.pr_evar_map ?with_univs None (Global.env()) sigma)
1049
1050 let show_coq_engine ?with_univs e = Format.asprintf "%a" (pp_coq_engine ?with_univs) e
1051
1052 let from_env_sigma global_env sigma =
1053 {
1054 global_env;
1055 sigma;
1056 }
1057
1058 let from_env env = from_env_sigma env (Evd.from_env env)
1059
1060
1061 let demote uctx sigma0 env =
1062 UState.demote_global_univs uctx (Evd.ustate sigma0)
1063
1064 let from_env_keep_univ_and_sigma ~uctx ~env0 ~env sigma0 =
1065 assert(env0 != env);
1066 let uctx = demote uctx sigma0 env in
1067 from_env_sigma env (Evd.set_universe_context sigma0 uctx)
1068
1069 let from_env_keep_univ_of_sigma ~uctx ~env0 ~env sigma0 =
1070 assert(env0 != env);
1071 let uctx = demote uctx sigma0 env in
1072 from_env_sigma env (Evd.from_ctx uctx)
1073
1074 let init () =
1075 from_env (Global.env ())
1076
1077 let engine : coq_engine S.component =
1078 S.declare_component ~name:"rocq-elpi:evmap-constraint-type" ~descriptor:interp_state
1079 ~pp:pp_coq_engine ~init ~start:(fun _ -> init()) ()
1080
1081 end
1082 let () = pre_engine := Some CoqEngine_HOAS.engine
1083 open CoqEngine_HOAS
1084
1085 (* Bidirectional mapping between Elpi's UVars and Coq's Evars.
1086
1087 Coq evar E is represented by a constraint
1088
1089 evar X1 ty X2
1090
1091 and eventually a goal
1092
1093 goal ctx X1 ty attrs
1094
1095 and the bidirectional mapping
1096
1097 E <-> X2 \in UVElabMap
1098 E <-> X1 \in UVRawMap
1099 *)
1100 module CoqEvarKey = struct
1101 type t = Evar.t
1102 let compare = Evar.compare
1103 let pp fmt t = Format.fprintf fmt "%a" Pp.pp_with (Evar.print t)
1104 let show t = Format.asprintf "%a" pp t
1105 end
1106 module UVElabMap = F.Map(CoqEvarKey)
1107 module UVRawMap = F.Map(CoqEvarKey)
1108
1109 module UVMap = struct
1110 let elpi k s =
1111 UVRawMap.elpi k (S.get UVRawMap.uvmap s),
1112 UVElabMap.elpi k (S.get UVElabMap.uvmap s)
1113
1114 let add k raw elab s =
1115 let s = S.update UVRawMap.uvmap s (UVRawMap.add raw k) in
1116 let s = S.update UVElabMap.uvmap s (UVElabMap.add elab k) in
1117 s
1118
1119 (* should we remove this "unsafe" API? *)
1120 let host elab s =
1121 try
1122 UVElabMap.host elab (S.get UVElabMap.uvmap s)
1123 with Not_found ->
1124 UVRawMap.host elab (S.get UVRawMap.uvmap s)
1125
1126 let mem_elpi x s =
1127 try
1128 let _ = UVElabMap.host x (S.get UVElabMap.uvmap s) in true
1129 with Not_found -> try
1130 let _ = UVRawMap.host x (S.get UVRawMap.uvmap s) in true
1131 with Not_found ->
1132 false
1133 [@@ocaml.warning "-32"]
1134
1135 let mem_host x s =
1136 try
1137 let _ = UVElabMap.elpi x (S.get UVElabMap.uvmap s) in true
1138 with Not_found -> try
1139 let _ = UVRawMap.elpi x (S.get UVRawMap.uvmap s) in true
1140 with Not_found ->
1141 false
1142
1143 let show s =
1144 "RAW:\n" ^ UVRawMap.show (S.get UVRawMap.uvmap s) ^
1145 "ELAB:\n" ^ UVElabMap.show (S.get UVElabMap.uvmap s)
1146
1147 let empty s =
1148 let s = S.set UVRawMap.uvmap s UVRawMap.empty in
1149 let s = S.set UVElabMap.uvmap s UVElabMap.empty in
1150 s
1151
1152 let fold f s acc =
1153 UVElabMap.fold (fun ev uv sol acc ->
1154 let ruv = UVRawMap.elpi ev (S.get UVRawMap.uvmap s) in
1155 f ev ruv uv sol acc)
1156 (S.get UVElabMap.uvmap s) acc
1157
1158 exception Return of Evar.t
1159
1160 let rec morally_same_uvar ~depth uv bo =
1161 match E.look ~depth bo with
1162 | E.Lam x -> morally_same_uvar ~depth:(depth+1) uv x
1163 | E.UnifVar(ev,_) -> F.Elpi.equal ev uv
1164 | _ -> false
1165
1166 let host_upto_assignment f s =
1167 try
1168 UVElabMap.fold (fun ev _ sol _ ->
1169 match sol with
1170 | None -> () (* the fast lookup can only fail if the uvar was instantiated (as is expanded or pruned)*)
1171 | Some sol ->
1172 if f ev sol then raise (Return ev) else ())
1173 (S.get UVElabMap.uvmap s) ();
1174 raise Not_found
1175 with Return a -> a
1176
1177 let host_failsafe elab s =
1178 try
1179 UVElabMap.host elab (S.get UVElabMap.uvmap s)
1180 with Not_found ->
1181 try
1182 UVRawMap.host elab (S.get UVRawMap.uvmap s)
1183 with Not_found ->
1184 host_upto_assignment (fun evar bo -> morally_same_uvar ~depth:0 elab bo) s
1185
1186 let remove_host evar s =
1187 let s = S.update UVRawMap.uvmap s (UVRawMap.remove_host evar) in
1188 let s = S.update UVElabMap.uvmap s (UVElabMap.remove_host evar) in
1189 s
1190
1191 let filter_host f s =
1192 let s = S.update UVRawMap.uvmap s (UVRawMap.filter (fun evar _ -> f evar)) in
1193 let s = S.update UVElabMap.uvmap s (UVElabMap.filter (fun evar _ -> f evar)) in
1194 s
1195
1196 end
1197
1198 let fresh_relevance_variable state =
1199 S.update_return engine state (fun e ->
1200 let sigma, qv = Evd.new_quality_variable e.sigma in
1201 let rv = Sorts.RelevanceVar qv in
1202 let rv = EConstr.ERelevance.make rv in
1203 { e with sigma }, rv)
1204
1205 let mk_coq_name state id =
1206 let state, rv = fresh_relevance_variable state in
1207 state, Context.make_annot (Name.Name id) rv
1208
1209 let mk_coq_annot state id =
1210 let state, rv = fresh_relevance_variable state in
1211 state, Context.make_annot id rv
1212
1213 let in_coq_name ~depth state t =
1214 match E.look ~depth t with
1215 | E.CData n when isname n ->
1216 let name = nameout n in
1217 let { sigma } = S.get engine state in
1218 let name = Context.map_annot_relevance (fun x -> EConstr.ERelevance.(make (kind sigma x))) name in
1219 state, name,[]
1220 | E.CData n when CD.is_string n ->
1221 let state, rv = fresh_relevance_variable state in
1222 let s = CD.to_string n in
1223 if s = "_" then
1224 state, Context.make_annot Name.Anonymous rv,[]
1225 else
1226 state, Context.make_annot (Name.Name (Id.of_string s)) rv,[]
1227 | E.UnifVar (ev,args) ->
1228 let state, rv = fresh_relevance_variable state in
1229 let annot = Context.make_annot Name.Anonymous rv in
1230 let state, prune_ev = prune_uvar state ev args in
1231 state, annot,[prune_ev;API.Conversion.Unify(t,in_elpi_name annot)]
1232 | _ -> err Pp.(str"Not a name: " ++ str (API.RawPp.Debug.show_term t))
1233
1234 let in_coq_fresh ~id_only =
1235 let mk_fresh dbl =
1236 Id.of_string_soft
1237 (Printf.sprintf "elpi_ctx_entry_%d_" dbl) in
1238 fun ~depth dbl name ~names state ->
1239 let state, binder, gls = in_coq_name ~depth state name in
1240 let binder = match binder.Context.binder_name with
1241 | Name.Anonymous when id_only -> { binder with Context.binder_name = Name.Name (mk_fresh dbl) }
1242 | Name.Anonymous -> binder
1243 | Name.Name id when Id.Set.mem id names -> { binder with Context.binder_name = Name.Name (mk_fresh dbl) }
1244 | Name.Name _ -> binder in
1245 state, binder, gls
1246
1247 let in_coq_annot ~depth state t = in_coq_name ~depth state t
1248
1249 let in_coq_fresh_annot_name ~depth ~coq_ctx dbl state t =
1250 in_coq_fresh ~id_only:false ~depth ~names:coq_ctx.names dbl state t
1251
1252 let in_coq_fresh_annot_id ~depth ~names dbl state t =
1253 let get_name (st,n,gl) = st, Context.map_annot (function Name.Name x -> x | Name.Anonymous -> assert false) n, gl in
1254 in_coq_fresh ~id_only:true ~depth ~names dbl t state |> get_name
1255
1256
1257 let section_ids env =
1258 let named_ctx = Environ.named_context env in
1259 Context.Named.fold_inside
1260 (fun acc x -> Context.Named.Declaration.get_id x :: acc)
1261 ~init:[] named_ctx
1262
1263 let sortc = E.Constants.declare_global_symbol "sort"
1264
1265 let force_level_of_universe state u =
1266 match Univ.Universe.level u with
1267 | Some lvl -> state, lvl, u, Sorts.sort_of_univ u
1268 | None ->
1269 let state, (l,v) = new_univ_level_variable state in
1270 let w = Sorts.sort_of_univ v in
1271 add_universe_constraint state (constraint_eq (Sorts.sort_of_univ u) w), l, v, w
1272
1273 [%%if coq = "9.0"]
1274 let univ_of_sort = let open Sorts in function
1275 | SProp | Prop | Set -> Univ.Universe.type0
1276 | Type u | QSort (_, u) -> u
1277 [%%else]
1278 let univ_of_sort = Sorts.univ_of_sort
1279 [%%endif]
1280
1281 let purge_algebraic_univs_sort state s =
1282 let sigma = (S.get engine state).sigma in
1283 match EConstr.ESorts.kind sigma s with
1284 | Set | Prop | SProp as x -> state, x
1285 | s ->
1286 let state, _, _, s = force_level_of_universe state (univ_of_sort s) in
1287 state, s
1288
1289 let in_elpi_flex_sort t = E.mkApp sortc (E.mkApp typc t []) []
1290 let in_elpiast_flex_sort ~loc t =
1291 A.mkAppGlobal ~loc ~hdloc:loc sortc (A.mkAppGlobal ~loc ~hdloc:loc typc t []) []
1292
1293 let sort = { sort with API.ContextualConversion.embed = (fun ~depth ctx csts state s ->
1294 let state, s =
1295 if ctx.options.algunivs = None || ctx.options.algunivs = Some false then
1296 purge_algebraic_univs_sort state (EConstr.ESorts.make s)
1297 else
1298 state, s in
1299 sort.API.ContextualConversion.embed ~depth ctx csts state s) }
1300
1301 let in_elpi_sort ~depth ctx csts state s =
1302 let state, s, gl = sort.API.ContextualConversion.embed ~depth ctx csts state s in
1303 assert(gl=[]);
1304 state, E.mkApp sortc s [], gl
1305
1306 let in_elpiast_sort ~loc state s =
1307 A.mkAppGlobal ~loc ~hdloc:loc sortc (ast_sort ~loc s) []
1308
1309
1310 (* ********************************* }}} ********************************** *)
1311
1312 (* {{{ HOAS : EConstr.t -> elpi ******************************************* *)
1313
1314 let get_sigma s = (S.get engine s).sigma
1315 let update_sigma s f = (S.update engine s (fun e -> { e with sigma = f e.sigma }))
1316 let get_global_env s = (S.get engine s).global_env
1317
1318 let declare_evc = E.Constants.declare_global_symbol "declare-evar"
1319 let rm_evarc = E.Constants.declare_global_symbol "rm-evar"
1320
1321 (* We extend extra_goal with two /delayed/ actions: declaring a new evear to
1322 elpi and removing a previously declared one. When the actions happen in
1323 the same FFI call, we cancel them out, see set_extra_goals_postprocessing *)
1324 type API.Conversion.extra_goal +=
1325 | DeclareEvar of Evar.t * int * F.Elpi.t * F.Elpi.t
1326 | RmEvar of Evar.t * E.term * E.term
1327
1328 let rec cancel_opposites acc removals = function
1329 | [] -> []
1330 | DeclareEvar(e,_,_,_) :: rest when Evar.Set.mem e removals ->
1331 debug Pp.(fun () -> str "cancelling extra_goal for " ++ Evar.print e);
1332 cancel_opposites (Evar.Set.add e acc) removals rest
1333 | RmEvar(e,_,_) :: rest when Evar.Set.mem e acc -> cancel_opposites acc removals rest
1334 | x :: rest -> x :: cancel_opposites acc removals rest
1335
1336 let rec removals_of acc = function
1337 | [] -> acc
1338 | RmEvar(e,_,_) :: rest -> removals_of (Evar.Set.add e acc) rest
1339 | _ :: rest -> removals_of acc rest
1340
1341 let pp_coq_ctx { env } state =
1342 try
1343 Printer.pr_named_context_of env (get_sigma state)
1344 with e when CErrors.noncritical e ->
1345 Pp.(str "error in printing: " ++ str (Printexc.to_string e))
1346
1347 let module_inline_core = let open API.AlgebraicData in let open Declaremods in declare {
1348 ty = API.Conversion.TyName "coq.inline";
1349 doc = "Coq Module inline directive";
1350 pp = (fun fmt -> function
1351 | NoInline -> Format.fprintf fmt "NoInline"
1352 | DefaultInline -> Format.fprintf fmt "DefaultInline"
1353 | InlineAt x -> Format.fprintf fmt "InlineAt %d" x);
1354 constructors = [
1355 K("coq.inline.no", "Coq's [no inline] (aka !)",N,
1356 B NoInline,
1357 M (fun ~ok ~ko -> function NoInline -> ok | _ -> ko ()));
1358 K("coq.inline.default","The default, can be omitted",N,
1359 B DefaultInline,
1360 M (fun ~ok ~ko -> function DefaultInline -> ok | _ -> ko ()));
1361 K("coq.inline.at","Coq's [inline at <num>]",A(API.BuiltInData.int,N),
1362 B (fun x -> InlineAt x),
1363 M (fun ~ok ~ko -> function InlineAt x -> ok x | _ -> ko ()));
1364 ]
1365 } |> API.ContextualConversion.(!<)
1366 let module_inline_unspec = Elpi.Builtin.unspec module_inline_core
1367 let module_inline_default = { module_inline_unspec with
1368 API.Conversion.pp = (fun fmt x ->
1369 module_inline_unspec.API.Conversion.pp fmt (Elpi.Builtin.Given x));
1370 API.Conversion.embed = (fun ~depth state x ->
1371 module_inline_unspec.API.Conversion.embed ~depth state (Elpi.Builtin.Given x));
1372 API.Conversion.readback = (fun ~depth state x ->
1373 match module_inline_unspec.API.Conversion.readback ~depth state x with
1374 | state, Elpi.Builtin.Given x, gls -> state,x,gls
1375 | state, Elpi.Builtin.Unspec, gls -> state,Declaremods.DefaultInline,gls)
1376 }
1377
1378 let reduction_flags = let open API.OpaqueData in let open RedFlags in declare {
1379 name = "coq.redflags";
1380 doc = "Set of flags for lazy, cbv, ... reductions";
1381 pp = (fun fmt (x : RedFlags.reds) -> Format.fprintf fmt "TODO");
1382 compare = Stdlib.compare;
1383 hash = Hashtbl.hash;
1384 hconsed = false;
1385 constants = [
1386 "coq.redflags.all", all ;
1387 "coq.redflags.allnolet", allnolet ;
1388 "coq.redflags.beta", beta ;
1389 "coq.redflags.betadeltazeta", betadeltazeta;
1390 "coq.redflags.betaiota", betaiota ;
1391 "coq.redflags.betaiotazeta", betaiotazeta ;
1392 "coq.redflags.betazeta", betazeta ;
1393 "coq.redflags.delta", delta ;
1394 "coq.redflags.zeta", zeta ;
1395 "coq.redflags.nored", nored ;
1396 ];
1397 }
1398
1399 let get_optionc = E.Constants.declare_global_symbol "get-option"
1400
1401 let get_options ~depth hyps state =
1402 let is_string ~depth t =
1403 match E.look ~depth t with
1404 | E.CData d -> CD.is_string d
1405 | _ -> false in
1406 let get_string ~depth t =
1407 match E.look ~depth t with
1408 | E.CData d -> CD.to_string d
1409 | _ -> assert false in
1410 let options =
1411 hyps |> CList.map_filter (fun { E.hdepth = depth; E.hsrc = t } ->
1412 match E.look ~depth t with
1413 | E.App(c,name,[p]) when c == get_optionc && is_string ~depth name ->
1414 Some (get_string ~depth name, (p,depth))
1415 | _ -> None) in
1416 let map = List.fold_right (fun (k,v) m -> API.Data.StrMap.add k v m) options API.Data.StrMap.empty in
1417 let get_bool_option name =
1418 try
1419 let t, depth = API.Data.StrMap.find name map in
1420 let _, b, _ = Elpi.Builtin.bool.API.Conversion.readback ~depth state t in
1421 Some b
1422 with Not_found -> None in
1423 let get_string_option name =
1424 try
1425 let t, depth = API.Data.StrMap.find name map in
1426 let _, b, _ = API.BuiltInData.string.API.Conversion.readback ~depth state t in
1427 Some b
1428 with Not_found -> None in
1429 let get_int_option name =
1430 try
1431 let t, depth = API.Data.StrMap.find name map in
1432 let _, b, _ = API.BuiltInData.int.API.Conversion.readback ~depth state t in
1433 Some b
1434 with Not_found -> None in
1435 let locality s =
1436 if s = Some "default" then None
1437 else if s = Some "local" then Some true
1438 else if s = Some "global" then Some false
1439 else if s = None then None
1440 else err Pp.(str"Unknown locality attribute: " ++ str (Option.get s)) in
1441 let pp s =
1442 if s = Some "all" then All
1443 else if s = Some "most" then Most
1444 else Normal in
1445 let ppwidth = function Some i -> i | None -> 80 in
1446 let pplevel = function None -> Constrexpr.LevelSome | Some i -> Constrexpr.LevelLe i in
1447 let get_module_inline_option name =
1448 try
1449 let t, depth = API.Data.StrMap.find name map in
1450 let _, b, _ = module_inline_core.API.Conversion.readback ~depth state t in
1451 b
1452 with Not_found -> Declaremods.NoInline in
1453 let get_pair_option fst snd name =
1454 try
1455 let t, depth = API.Data.StrMap.find name map in
1456 let _, b, _ = Elpi.Builtin.(pair (unspec fst) (unspec snd)).API.Conversion.readback ~depth state t in
1457 Some b
1458 with Not_found -> None in
1459 let get_uinstance_option name =
1460 match API.Data.StrMap.find_opt name map with
1461 | Some (t, depth) when t <> E.mkDiscard -> begin
1462 match E.look ~depth t with
1463 | E.UnifVar (head, args) -> VarInstance (head, args, depth)
1464 | _ ->
1465 let _, i, gl = uinstance.Elpi.API.Conversion.readback ~depth state t in
1466 assert (gl = []);
1467 ConcreteInstance i
1468 end
1469 | _ -> NoInstance in
1470 let empty2none = function Some "" -> None | x -> x in
1471 let deprecation = function
1472 | None -> None
1473 | Some(since,note) ->
1474 let since = unspec2opt since |> empty2none in
1475 let note = unspec2opt note |> empty2none in
1476 Some { Deprecation.since; note } in
1477 let warn = function
1478 | None -> []
1479 | Some(cats,note) ->
1480 let cats = unspec2opt cats |> empty2none in
1481 let note = unspec2opt note |> empty2none in
1482 Option.cata (fun note -> [make_warn ~note ?cats ()]) [] note in
1483 let get_universe_decl () =
1484 match API.Data.StrMap.find_opt "coq:udecl-cumul" map, API.Data.StrMap.find_opt "coq:udecl" map with
1485 | None, None -> NotUniversePolymorphic
1486 | Some _, Some _ -> err Pp.(str"Conflicting attributes: @udecl! and @udecl-cumul! (or @univpoly! and @univpoly-cumul!)")
1487 | Some (t,depth), None ->
1488 let _, ud, gl = universe_decl.Elpi.API.Conversion.readback ~depth state t in
1489 assert (gl = []);
1490 begin match ud with
1491 | Cumul ud -> Cumulative ud
1492 | NonCumul _ -> U.type_error "@udecl-cumul! containing a non-cumulative declaration"
1493 end
1494 | None, Some (t,depth) ->
1495 let _, ud, gl = universe_decl.Elpi.API.Conversion.readback ~depth state t in
1496 assert (gl = []);
1497 begin match ud with
1498 | NonCumul ud -> NonCumulative ud
1499 | Cumul _ -> U.type_error "@udecl! containing a cumulative declaration"
1500 end
1501 in
1502 let get_redflags_option () =
1503 match API.Data.StrMap.find_opt "coq:redflags" map with
1504 | None -> None
1505 | Some (t,depth) ->
1506 let _, rd, gl = reduction_flags.Elpi.API.Conversion.readback ~depth state t in
1507 assert (gl = []);
1508 Some rd in
1509 let depr = deprecation @@ get_pair_option API.BuiltInData.string API.BuiltInData.string "coq:deprecation" in
1510 let warn = warn @@ get_pair_option API.BuiltInData.string API.BuiltInData.string "coq:warn" in
1511 let hoas_holes =
1512 begin match get_bool_option "HOAS:holes" with
1513 | None -> None
1514 | Some true -> Some Heuristic
1515 | Some false -> Some Verbatim end in
1516 let local = locality @@ get_string_option "coq:locality" in
1517 let primitive = get_bool_option "coq:primitive" in
1518 let failsafe = false in
1519 let ppwidth = ppwidth @@ get_int_option "coq:ppwidth" in
1520 let pp = pp @@ get_string_option "coq:pp" in
1521 let pplevel = pplevel @@ get_int_option "coq:pplevel" in
1522 let using = get_string_option "coq:using" in
1523 let inline = get_module_inline_option "coq:inline" in
1524 let uinstance = get_uinstance_option "coq:uinstance" in
1525 let universe_decl = get_universe_decl () in
1526 let reversible = get_bool_option "coq:reversible" in
1527 let no_tc = get_bool_option "coq:no_tc" in
1528 let keepunivs = get_bool_option "coq:keepunivs" in
1529 let redflags = get_redflags_option () in
1530 let algunivs = get_bool_option "coq:keepalgunivs" in
1531 make_options ~hoas_holes ~local ~warn ~depr ~primitive ~failsafe ~ppwidth
1532 ~pp ~pplevel ~using ~inline ~uinstance ~universe_decl ~reversible ~keepunivs
1533 ~redflags ~no_tc ~algunivs
1534 let empty_conv_context ~options state =
1535 let env = get_global_env state in
1536 let section = section_ids env in
1537 {
1538 section;
1539 section_len = List.length section;
1540 proof = [];
1541 proof_len = 0;
1542 local = [];
1543 local_len = 0;
1544 db2name = Int.Map.empty;
1545 name2db = Names.Id.Map.empty;
1546 db2rel = Int.Map.empty;
1547 names = Environ.named_context env |> Context.Named.to_vars;
1548 env;
1549 options;
1550 hyps = [];
1551 }
1552
1553 let push_coq_ctx_proof i (e,h) coq_ctx =
1554 assert(coq_ctx.local = []);
1555 let id = Context.Named.Declaration.get_id e in
1556 {
1557 coq_ctx with
1558 proof = e :: coq_ctx.proof;
1559 proof_len = 1 + coq_ctx.proof_len;
1560 env = push_named (EConstr.Unsafe.to_named_decl e) coq_ctx.env;
1561 db2name = Int.Map.add i id coq_ctx.db2name;
1562 name2db = Names.Id.Map.add id i coq_ctx.name2db;
1563 names = Id.Set.add id coq_ctx.names;
1564 hyps = h :: coq_ctx.hyps;
1565 }
1566
1567 let push_coq_ctx_local i e coq_ctx =
1568 let rel = 1 + coq_ctx.local_len in
1569 {
1570 coq_ctx with
1571 local = (i,e) :: coq_ctx.local;
1572 local_len = rel;
1573 db2rel = Int.Map.add i rel coq_ctx.db2rel;
1574 env = EConstr.push_rel e coq_ctx.env;
1575 }
1576
1577 (* Not sure this is sufficient, eg we don't restrict evars, but elpi shuld... *)
1578 let restrict_conv_context live_db state { proof; proof_len; local; name2db; env; options; hyps } =
1579 let named_ctx =
1580 empty_conv_context ~options state |> List.fold_right2 (fun e h ctx ->
1581 let id = Context.Named.Declaration.get_id e in
1582 let db = Names.Id.Map.find id name2db in
1583 if List.mem db live_db
1584 then
1585 push_coq_ctx_proof db (e,h) ctx
1586 else ctx) proof hyps in
1587
1588 debug Pp.(fun () ->
1589 str "restrict_conv_context: named: " ++
1590 Printer.pr_named_context_of named_ctx.env (get_sigma state));
1591
1592 let subst_rel_decl env k s = function
1593 | Context.Rel.Declaration.LocalAssum(n,t) ->
1594
1595 debug Pp.(fun () ->
1596 Printer.pr_econstr_env env (get_sigma state) t
1597 ++str "--"++ int k ++ str"->" ++
1598 Printer.pr_econstr_env env (get_sigma state) (EConstr.Vars.substnl s k t));
1599
1600 Context.Rel.Declaration.LocalAssum(n,EConstr.Vars.substnl s k t)
1601 | Context.Rel.Declaration.LocalDef(n,t,b) ->
1602 Context.Rel.Declaration.LocalDef(n,EConstr.Vars.substnl s k t,EConstr.Vars.substnl s k b) in
1603
1604 (named_ctx,[]) |> List.fold_right (fun (db,e) (ctx,s) ->
1605
1606 debug Pp.(fun () ->
1607 str"restrict_conv_context: cur rel ctx: " ++
1608 Printer.pr_rel_context_of ctx.env (get_sigma state) ++ fnl() ++
1609 str"restrict_conv_context: cur subst: " ++
1610 prlist_with_sep spc (Printer.pr_econstr_env ctx.env (get_sigma state)) s ++ fnl() ++
1611 str"restrict_conv_context: looking at " ++
1612 Names.Name.print (Context.Rel.Declaration.get_name e)
1613 ++ str"(dbl " ++ int db ++ str")");
1614
1615 if List.mem db live_db
1616 then push_coq_ctx_local db (subst_rel_decl ctx.env 0 s e) ctx, (EConstr.mkRel 1) :: List.map (EConstr.Vars.lift 1) s
1617 else ctx, EConstr.mkProp :: s) local |>
1618 fun (x,_) -> x
1619
1620 let info_of_undefined_evar ~env ~sigma ~section k =
1621 let open Context.Named in
1622 let evi = Evd.find_undefined sigma k in
1623 let info = Evarutil.nf_evar_info sigma evi in
1624 let filtered_hyps = Evd.evar_filtered_hyps info in
1625 let ctx = EC.named_context_of_val filtered_hyps in
1626 let ctx = ctx |> CList.filter (fun x ->
1627 not(CList.mem_f Id.equal (Declaration.get_id x) section)) in
1628 Evd.evar_concl info, ctx, Environ.reset_with_named_context filtered_hyps env
1629
1630 let info_of_defined_evar ~env ~sigma ~section k =
1631 let open Context.Named in
1632 let evi = Evd.find_defined sigma k in
1633 assert(Option.has_some evi);
1634 let info = Evarutil.nf_evar_info sigma (Option.get evi) in
1635 let filtered_hyps = Evd.evar_filtered_hyps info in
1636 let env = Environ.reset_with_named_context filtered_hyps env in
1637 let Evd.Evar_defined bo = Evd.evar_body info in
1638 let ty = Retyping.get_type_of env sigma bo in
1639 let ctx = EC.named_context_of_val filtered_hyps in
1640 let ctx = ctx |> CList.filter (fun x ->
1641 not(CList.mem_f Id.equal (Declaration.get_id x) section)) in
1642 bo, ty, ctx, env
1643
1644
1645 (* ******************************************* *)
1646 (* <---- depth ----> *)
1647 (* proof_ctx |- pis \ t *)
1648 (* ******************************************* *)
1649
1650 let declc = E.Constants.declare_global_symbol "decl"
1651 let defc = E.Constants.declare_global_symbol "def"
1652 let evarc = E.Constants.declare_global_symbol "evar"
1653
1654 let mk_pi rest =
1655 E.mkBuiltin E.Pi [E.mkLam rest]
1656
1657 let mk_pi_arrow hyp rest =
1658 mk_pi (E.mkBuiltin E.Impl [hyp;rest])
1659
1660 let mk_decl ~depth name ~ty =
1661 E.mkApp declc E.(mkConst depth) [in_elpi_name name; ty]
1662
1663 let in_elpiast_decl ~loc ~v name ~ty =
1664 A.mkAppGlobal ~loc ~hdloc:loc declc v [in_elpiast_name ~loc name;ty]
1665
1666 let mk_def ~depth name ~bo ~ty =
1667 E.mkApp defc E.(mkConst depth) [in_elpi_name name; ty; bo]
1668
1669 let in_elpiast_def ~loc ~v name ~ty ~bo =
1670 A.mkAppGlobal ~loc ~hdloc:loc defc v [in_elpiast_name ~loc name;ty;bo]
1671
1672 let rec constr2lp coq_ctx ~calldepth ~depth state t =
1673 assert(depth >= coq_ctx.proof_len);
1674 let { sigma } = S.get engine state in
1675 let gls = ref [] in
1676 let rec aux ~depth env state t = match EC.kind sigma t with
1677 | C.Rel n -> state, E.mkConst (depth - n)
1678 | C.Var n ->
1679 begin
1680 try state, E.mkConst @@ Names.Id.Map.find n coq_ctx.name2db
1681 with Not_found ->
1682 assert(List.mem n coq_ctx.section);
1683 state, in_elpi_gr ~depth state (G.VarRef n)
1684 end
1685 | C.Meta _ -> nYI "constr2lp: Meta"
1686 | C.Evar (k,args) ->
1687 (* the evar is created at the depth the conversion is called, not at
1688 the depth at which it is found *)
1689 let state, elpi_uvk, _, gsl_t = in_elpi_evar ~calldepth k state in
1690 gls := gsl_t @ !gls;
1691 let args = Evd.expand_existential sigma (k, args) in
1692 let argno = List.length args - coq_ctx.section_len in
1693 if (argno < 0) then
1694 nYI "constr2lp: cleared section variables";
1695 let args = CList.firstn argno args in
1696 let state, args = CList.fold_left_map (aux ~depth env) state args in
1697 state, E.mkUnifVar elpi_uvk ~args:(List.rev args) state
1698 | C.Sort s ->
1699 let state, s, gl = in_elpi_sort ~depth coq_ctx API.RawData.no_constraints state (EC.ESorts.kind sigma s) in
1700 gls := gl @ !gls;
1701 state, s
1702 | C.Cast (t,_,ty0) ->
1703 let state, t = aux ~depth env state t in
1704 let state, ty = aux ~depth env state ty0 in
1705 let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(EConstr.anonR,ty0)) env in
1706 let state, self = aux ~depth:(depth+1) env state (EC.mkRel 1) in
1707 state, in_elpi_let EConstr.anonR t ty self
1708 | C.Prod(n,s0,t) ->
1709 let state, s = aux ~depth env state s0 in
1710 let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(n,s0)) env in
1711 let state, t = aux ~depth:(depth+1) env state t in
1712 state, in_elpi_prod n s t
1713 | C.Lambda(n,s0,t) ->
1714 let state, s = aux ~depth env state s0 in
1715 let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(n,s0)) env in
1716 let state, t = aux ~depth:(depth+1) env state t in
1717 state, in_elpi_lam n s t
1718 | C.LetIn(n,b0,s0,t) ->
1719 let state, b = aux ~depth env state b0 in
1720 let state, s = aux ~depth env state s0 in
1721 let env = EConstr.push_rel Context.Rel.Declaration.(LocalDef(n,b0,s0)) env in
1722 let state, t = aux ~depth:(depth+1) env state t in
1723 state, in_elpi_let n b s t
1724 | C.App(hd,args) ->
1725 let state, hd = aux ~depth env state hd in
1726 let state, args = CArray.fold_left_map (aux ~depth env) state args in
1727 state, in_elpi_app ~depth hd args
1728 | C.Const(c,i) when Global.is_polymorphic (G.ConstRef c) ->
1729 state, in_elpi_poly_gr_instance ~depth state (G.ConstRef c) (EC.EInstance.kind sigma i)
1730 | C.Const(c,i) ->
1731 state, in_elpi_gr ~depth state (G.ConstRef c)
1732 | C.Ind (ind, i) when Global.is_polymorphic (G.IndRef ind) ->
1733 state, in_elpi_poly_gr_instance ~depth state (G.IndRef ind) (EC.EInstance.kind sigma i)
1734 | C.Ind (ind, i) ->
1735 state, in_elpi_gr ~depth state (G.IndRef ind)
1736 | C.Construct (construct, i) when Global.is_polymorphic (G.ConstructRef construct) ->
1737 let gref = G.ConstructRef construct in
1738 state, in_elpi_poly_gr_instance ~depth state gref (EC.EInstance.kind sigma i)
1739 | C.Construct (construct, i) ->
1740 state, in_elpi_gr ~depth state (G.ConstructRef construct)
1741 | C.Case(ci, u, pms, rt, iv, t, bs) ->
1742 let (_, (rt,_), _, t, bs) = EConstr.expand_case env sigma (ci, u, pms, rt, iv, t, bs) in
1743 let state, t = aux ~depth env state t in
1744 let state, rt = aux ~depth env state rt in
1745 let state, bs = CArray.fold_left_map (aux ~depth env) state bs in
1746 state,
1747 in_elpi_match (*ci_ind ci_npar ci_cstr_ndecls ci_cstr_nargs*) t rt
1748 (Array.to_list bs)
1749 | C.Fix(([| rarg |],_),([| name |],[| typ0 |], [| bo |])) ->
1750 let state, typ = aux ~depth env state typ0 in
1751 let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(name,typ0)) env in
1752 let state, bo = aux ~depth:(depth+1) env state bo in
1753 state, in_elpi_fix name rarg typ bo
1754 | C.Fix((rargs, focus_idx),(names, tys, bos)) ->
1755 let names = Array.to_list names in
1756 let tys = Array.to_list tys in
1757 let rargs = Array.to_list rargs in
1758 let (n,state,env), names_rnos_tys =
1759 CList.fold_left_map (fun (n,state,env) ((name,rno),typ0) ->
1760 let state,typ = aux ~depth env state typ0 in
1761 let typ = U.move ~from:depth ~to_:(depth+n) typ in
1762 let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(name,typ0)) env in
1763 (n+1,state,env), (name, rno, typ))
1764 (0,state,env) (List.combine (List.combine names rargs) tys) in
1765 let state, bos = CArray.fold_left_map (aux ~depth:(depth+n) env) state bos in
1766 state, in_elpi_mfix names_rnos_tys focus_idx (Array.to_list bos)
1767 | C.Proj(p,_,t) ->
1768 let state, t = aux ~depth env state t in
1769 let state, p = in_elpi_primitive ~depth state (Projection p) in
1770 state, in_elpi_app ~depth p [|t|]
1771 | C.CoFix _ -> nYI "HOAS for cofix"
1772 | x -> in_elpi_primitive_value ~depth state x
1773 in
1774 debug Pp.(fun () ->
1775 str"term2lp: depth=" ++ int depth ++
1776 str " ctx=" ++ pp_coq_ctx coq_ctx state ++
1777 str " term=" ++Printer.pr_econstr_env (get_global_env state) (get_sigma state) t);
1778 let state, t = aux ~depth coq_ctx.env state t in
1779 debug Pp.(fun () -> str"term2lp (out): " ++ str (pp2string (P.term depth) t));
1780 state, t, !gls
1781
1782 and under_coq2elpi_ctx ~calldepth state ctx ?(mk_ctx_item=fun decl -> mk_pi_arrow decl) kont =
1783 let open Context.Named.Declaration in
1784 let gls = ref [] in
1785 let rec aux i ~depth coq_ctx state = function
1786 | [] -> state, coq_ctx
1787 | LocalAssum (name, ty) as e :: rest ->
1788 let name = Context.map_annot (fun x -> Name x) name in
1789 let state, ty, gls_ty = constr2lp coq_ctx ~calldepth ~depth:(depth+1) state ty in
1790 gls := gls_ty @ !gls;
1791 let hsrc = mk_decl ~depth name ~ty in
1792 let hyp = { E.hsrc ; hdepth = depth + 1 } in
1793 let coq_ctx = push_coq_ctx_proof depth (e,hyp) coq_ctx in
1794 aux (succ i) ~depth:(depth+1) coq_ctx state rest
1795 | LocalDef (name,bo,ty) as e :: rest ->
1796 let name = Context.map_annot (fun x -> Name x) name in
1797 let state, ty, gls_ty = constr2lp coq_ctx ~calldepth ~depth:(depth+1) state ty in
1798 let state, bo, gls_bo = constr2lp coq_ctx ~calldepth ~depth:(depth+1) state bo in
1799 gls := gls_ty @ gls_bo @ !gls;
1800 let hsrc = mk_def ~depth name ~bo ~ty in
1801 let hyp = { E.hsrc ; hdepth = depth + 1 } in
1802 let coq_ctx = push_coq_ctx_proof depth (e,hyp) coq_ctx in
1803 aux (succ i) ~depth:(depth+1) coq_ctx state rest
1804 in
1805 let state, coq_ctx =
1806 aux 0 ~depth:calldepth (empty_conv_context ~options:(default_options ()) state) state (List.rev ctx) in
1807 let state, t, gls_t = kont coq_ctx ~depth:(calldepth + List.length coq_ctx.hyps) state in
1808 gls := gls_t @ !gls;
1809 let t = List.fold_left (fun rest hyp -> mk_ctx_item hyp.E.hsrc rest) t coq_ctx.hyps in
1810 state, t, !gls
1811
1812 and in_elpi_evar_concl evar_concl ~raw_uvar elpi_evk coq_ctx ~calldepth ~depth state =
1813 let state, evar_concl, gls_evar_concl = constr2lp coq_ctx ~calldepth ~depth state evar_concl in
1814 let args = CList.init coq_ctx.proof_len (fun i -> E.mkConst @@ i + calldepth) in
1815 debug Pp.(fun () -> str"in_elpi_evar_concl: moving Ctx down to" ++ int depth);
1816 let hyps = List.map (fun { E.hsrc = ctx_entry; hdepth = from } ->
1817 U.move ~from ~to_:depth ctx_entry) coq_ctx.hyps
1818 |> U.list_to_lp_list in
1819 state, hyps,
1820 (E.mkUnifVar raw_uvar ~args state),
1821 (E.mkUnifVar elpi_evk ~args state),
1822 evar_concl, gls_evar_concl
1823
1824 and in_elpi_solved_evar evar_body evar_concl coq_ctx ~calldepth ~depth state =
1825 let state, evar_body, gls_evar_body = constr2lp coq_ctx ~calldepth ~depth state evar_body in
1826 let state, evar_concl, gls_evar_concl = constr2lp coq_ctx ~calldepth ~depth state evar_concl in
1827 debug Pp.(fun () -> str"in_elpi_solved_evar: moving Ctx down to" ++ int depth);
1828 let hyps = List.map (fun { E.hsrc = ctx_entry; hdepth = from } ->
1829 U.move ~from ~to_:depth ctx_entry) coq_ctx.hyps
1830 |> U.list_to_lp_list in
1831 state, hyps, evar_body, evar_concl, gls_evar_body @ gls_evar_concl
1832
1833 and in_elpi_evar_info ~calldepth ~env ~sigma ctx ~raw_ev:elpi_revk elpi_evk evar_concl state =
1834 under_coq2elpi_ctx ~mk_ctx_item:(fun _ -> mk_pi) ~calldepth state ctx (fun coq_ctx ~depth state ->
1835 let state, hyps, raw_ev, ev, ty, gls =
1836 in_elpi_evar_concl evar_concl ~raw_uvar:elpi_revk elpi_evk coq_ctx
1837 ~calldepth ~depth state in
1838 state, E.mkApp declare_evc hyps [raw_ev; ty; ev], gls)
1839
1840 and in_elpi_evar ~calldepth k state =
1841 debug Pp.(fun () -> str"in_elpi_evar:" ++ Evar.print k);
1842 try
1843 let elpi_raw_evk, elpi_evk = UVMap.elpi k state in
1844 debug Pp.(fun () ->
1845 str"in_elpi_evar: known " ++
1846 Evar.print k ++ str" as " ++ str(F.Elpi.show elpi_evk));
1847 state, elpi_evk, elpi_raw_evk, []
1848 with Not_found ->
1849 let state, elpi_evk = F.Elpi.make state in
1850 let state, elpi_raw_evk = F.Elpi.make state in
1851 let state, gls = in_elpi_fresh_evar ~calldepth k ~raw_ev:elpi_raw_evk elpi_evk state in
1852 state, elpi_evk, elpi_raw_evk, gls
1853
1854 and in_elpi_fresh_evar ~calldepth k ~raw_ev elpi_evk state =
1855 let state = UVMap.add k raw_ev elpi_evk state in
1856 state, [DeclareEvar(k,calldepth,raw_ev,elpi_evk)]
1857 ;;
1858
1859 let rec postprocess_DeclareEvar calldepth k raw_ev elpi_evk state =
1860 let { sigma; global_env } as e = S.get engine state in
1861 debug Pp.(fun () -> str"in_elpi_fresh_evar: unknown " ++ Evar.print k ++ str " <-> " ++ str(pp2string (P.term calldepth) (E.mkUnifVar raw_ev ~args:[] state)) ++ cut () ++
1862 str (UVMap.show state));
1863 let evar_concl, ctx, _ = info_of_undefined_evar ~env:global_env ~sigma ~section:(section_ids global_env) k in
1864 let state, evar_decl, gls = in_elpi_evar_info ~calldepth ~env:global_env ~sigma ctx ~raw_ev elpi_evk evar_concl state in
1865 debug Pp.(fun () -> str"in_elpi_fresh_evar: new decl at depth:" ++ int calldepth ++ str" for " ++ Evar.print k ++ str " <-> " ++ str(pp2string (P.term calldepth) (E.mkUnifVar raw_ev ~args:[] state)) ++ cut () ++
1866 str(pp2string (P.term calldepth) evar_decl));
1867 let state, gls = generate_actual_goals state gls in
1868 state, gls @ [API.RawData.RawGoal evar_decl]
1869
1870 and generate_actual_goals state = function
1871 | [] -> state, []
1872 (* We reset the UVmap when we change Coq's global state *)
1873 | DeclareEvar (k,_,_,_) :: rest when not (UVMap.mem_host k state) -> generate_actual_goals state rest
1874
1875 | DeclareEvar(k,calldepth,raw_ev,elpi_evk) :: rest ->
1876 let state, gls1 = postprocess_DeclareEvar calldepth k raw_ev elpi_evk state in
1877 let state, rest = generate_actual_goals state rest in
1878 state, gls1 @ rest
1879 | RmEvar (k,raw_ev,ev) :: rest ->
1880 let state, rest = generate_actual_goals state rest in
1881 (*let state = UVMap.remove_host k state in*)
1882 state, API.RawData.RawGoal (E.mkAppGlobalL rm_evarc [raw_ev; ev]) :: rest
1883 | (API.Conversion.Unify _ | API.RawData.RawGoal _) as x :: xs ->
1884 let state, xs = generate_actual_goals state xs in
1885 state, x :: xs
1886 | _ -> assert false
1887
1888 let prepend_removals l =
1889 let removals, rest = List.partition (function RmEvar _ -> true | _ -> false) l in
1890 removals @ rest
1891
1892 let () = E.set_extra_goals_postprocessing ~descriptor:interp_hoas (fun l state ->
1893 generate_actual_goals state
1894 (prepend_removals
1895 (cancel_opposites Evar.Set.empty (removals_of Evar.Set.empty l) l)))
1896
1897 (* ********************************* }}} ********************************** *)
1898
1899 (* {{{ HOAS : elpi -> Constr.t * Evd.evar_map ***************************** *)
1900
1901 let poly_ctx_size_of_gref env gr =
1902 let open Names.GlobRef in
1903 match gr with
1904 | VarRef _ -> 0, 0
1905 | ConstRef c ->
1906 let cb = Environ.lookup_constant c env in
1907 let univs = Declareops.constant_polymorphic_context cb in
1908 UVars.AbstractContext.size univs
1909 | IndRef ind ->
1910 let (mib,_ as specif) = Inductive.lookup_mind_specif env ind in
1911 let univs = Declareops.inductive_polymorphic_context mib in
1912 UVars.AbstractContext.size univs
1913 | ConstructRef cstr ->
1914 let (mib,_ as specif) =
1915 Inductive.lookup_mind_specif env (inductive_of_constructor cstr) in
1916 let univs = Declareops.inductive_polymorphic_context mib in
1917 UVars.AbstractContext.size univs
1918
1919 let mk_global state gr inst_opt = S.update_return engine state (fun x ->
1920 match inst_opt with
1921 | None ->
1922 let sigma, t = EConstr.fresh_global x.global_env x.sigma gr in
1923 let _, i = EConstr.destRef sigma t in
1924 { x with sigma }, (t, Some (EConstr.EInstance.kind sigma i))
1925 | Some ui ->
1926 let expected = poly_ctx_size_of_gref x.global_env gr in
1927 let actual = UVars.Instance.length ui in
1928 if not (UVars.eq_sizes expected actual) then begin
1929 let plen (qlen,ulen) = Pp.(prlist_with_sep (fun () -> str ", ") int [qlen;ulen]) in
1930 U.type_error Pp.(string_of_ppcmds
1931 (str"Global reference " ++ Printer.pr_global gr ++
1932 str " takes a univ-instance of size " ++ plen expected ++
1933 str " but was given an instance of size " ++ plen actual))
1934 end;
1935 let i = EConstr.EInstance.make ui in
1936 x, (EConstr.mkRef (gr,i), None)
1937 ) |> (fun (x,(y,z)) -> x,y,z)
1938
1939 [%%if coq = "9.0" || coq = "9.1"]
1940 let merge_universe_context_set rigid sigma uctx =
1941 Evd.merge_context_set rigid sigma uctx
1942 [%%else]
1943 let merge_universe_context_set rigid sigma uctx =
1944 Evd.merge_universe_context_set rigid sigma uctx
1945 [%%endif]
1946
1947 let body_of_constant state c inst_opt = S.update_return engine state (fun x ->
1948 match
1949 Global.body_of_constant_body (Library.indirect_accessor[@alert "-deprecated"]) (Environ.lookup_constant c x.global_env)
1950 with
1951 | Some (bo, priv, ctx) ->
1952 let c, ctx = UnivGen.fresh_global_instance x.global_env (ConstRef c) ?names:inst_opt in
1953 let c, inst = Constr.destConst c in
1954 let bo = Vars.subst_instance_constr inst bo in
1955 let sigma = evd_merge_ctx_set Evd.univ_rigid x.sigma ctx in
1956 let sigma = match priv with
1957 | Opaqueproof.PrivateMonomorphic () -> sigma
1958 | Opaqueproof.PrivatePolymorphic ctx ->
1959 let ctx = Util.on_snd (subst_univs_constraints (snd (UVars.make_instance_subst inst))) ctx in
1960 merge_universe_context_set Evd.univ_rigid sigma ctx
1961 in
1962 { x with sigma }, (Some (EConstr.of_constr bo), Some inst)
1963 | None -> x, (None, None)) |> (fun (x,(y,z)) -> x,y,z)
1964
1965 let evar_arity k state =
1966 let EvarInfo info = Evd.find (S.get engine state).sigma k in
1967 let filtered_hyps = Evd.evar_filtered_hyps info in
1968 List.length (Environ.named_context_of_val filtered_hyps)
1969
1970 (* This is random: u < v /\ u <= FOO.123 /\ FOO.123 <= u ===>
1971 u < FOO.123
1972 even if u is a binder, and FOO.123 is not.
1973 Hence this is disabled. *)
1974 let minimize_universes state = state (*
1975 S.update engine state (fun ({ sigma } as x) ->
1976 { x with sigma = Evd.minimize_universes sigma })
1977 *)
1978
1979 let is_sort ~depth x =
1980 match E.look ~depth x with
1981 | E.App(s,_,[]) -> sortc == s
1982 | _ -> false
1983
1984 let is_prod ~depth x =
1985 match E.look ~depth x with
1986 | E.App(s,_,[ty;bo]) when prodc == s ->
1987 begin match E.look ~depth bo with
1988 | E.Lam bo -> Some(ty,bo)
1989 | _ -> None end
1990 | _ -> None
1991
1992 let is_let ~depth x =
1993 match E.look ~depth x with
1994 | E.App(s,_,[ty;d;bo]) when letc == s ->
1995 begin match E.look ~depth bo with
1996 | E.Lam bo -> Some(ty,d,bo)
1997 | _ -> None end
1998 | _ -> None
1999
2000
2001 let is_lam ~depth x =
2002 match E.look ~depth x with
2003 | E.App(s,_,[ty;bo]) when lamc == s ->
2004 begin match E.look ~depth bo with
2005 | E.Lam bo -> Some(ty,bo)
2006 | _ -> None end
2007 | _ -> None
2008
2009 let pp_cst fmt { E.goal = (depth,concl); context } =
2010 Format.fprintf fmt "%d |> %a |- %a" depth
2011 (P.list (fun fmt { E.hdepth; E.hsrc } ->
2012 Format.fprintf fmt "%d:%a" hdepth (P.term hdepth) hsrc) ", ")
2013 context
2014 (P.term depth) concl
2015
2016 let find_evar var csts =
2017 csts |> CList.find_map_exn (fun ({ E.goal = (depth,concl); context } as cst) ->
2018 match E.look ~depth concl with
2019 | E.App(c,x,[ty;rx]) when c == evarc ->
2020 begin match E.look ~depth x, E.look ~depth rx with
2021 | E.UnifVar(raw,args), E.UnifVar(r,_) when F.Elpi.(equal raw var || equal r var) ->
2022 debug Pp.(fun () ->
2023 str"lp2term: evar: found relevant constraint: " ++
2024 str(pp2string pp_cst cst));
2025 Some r
2026 | _ -> None end
2027 | _ -> None)
2028
2029 let preprocess_context visible context =
2030 let select_ctx_entries visible ({ E.hdepth = depth; E.hsrc = t } as h) =
2031 let isVisibleConst t = match E.look ~depth t with E.Const i -> visible i | _ -> false in
2032 let destConst t = match E.look ~depth t with E.Const x -> x | _ -> assert false in
2033 match E.look ~depth t with
2034 | E.App(c,v,[name;ty]) when c == declc && isVisibleConst v ->
2035 Some (destConst v, depth, h, `Decl(name,ty))
2036 | E.App(c,v,[name;ty;bo]) when c == defc && isVisibleConst v ->
2037 Some (destConst v, depth, h, `Def (name,ty,bo))
2038 | _ ->
2039 debug Pp.(fun () ->
2040 str "skip entry" ++
2041 str(pp2string (P.term depth) t));
2042 None
2043 in
2044 let ctx_hyps = CList.map_filter (select_ctx_entries visible) context in
2045 let dbl2ctx =
2046 List.fold_right (fun (i,d,t,e) m ->
2047 if Int.Map.mem i m
2048 then err Pp.(str "Duplicate context entry for " ++
2049 str(pp2string (P.term d) (E.mkConst i)))
2050 else Int.Map.add i (d,t,e) m)
2051 ctx_hyps Int.Map.empty in
2052 dbl2ctx
2053
2054 let rec dblset_of_canonical_ctx ~depth acc = function
2055 | [] -> acc
2056 | x :: xs ->
2057 match E.look ~depth x with
2058 | E.Const i -> dblset_of_canonical_ctx ~depth (Int.Set.add i acc) xs
2059 | _ -> err Pp.(str"HOAS: non canonical constraint, the evar is applied to:" ++
2060 str(pp2string (P.term depth) x))
2061
2062 let find_evar_decl var csts =
2063 csts |> CList.find_map_exn (fun ({ E.goal = (depth,concl); context } as cst) ->
2064 match E.look ~depth concl with
2065 | E.App(c,x,[ty;rx]) when c == evarc ->
2066 begin match E.look ~depth x, E.look ~depth rx with
2067 | E.UnifVar(raw,args_raw), E.UnifVar(r,args) when F.Elpi.(equal raw var || equal r var) ->
2068 debug Pp.(fun () ->
2069 str"lp2term: evar: found relevant constraint: " ++
2070 str(pp2string pp_cst cst));
2071 let args = if F.Elpi.(equal raw var) then args_raw else args in
2072 let visible_set = dblset_of_canonical_ctx ~depth Int.Set.empty args in
2073 let dbl2ctx = preprocess_context (fun x -> Int.Set.mem x visible_set) context in
2074 Some (dbl2ctx, raw, r, (depth,ty), cst)
2075 | _ -> None end
2076 | _ -> None)
2077
2078 let analyze_scope ~depth coq_ctx args =
2079 let is_in_coq i =
2080 Int.Map.mem i coq_ctx.db2name || Int.Map.mem i coq_ctx.db2rel in
2081 let rec aux seen mask args needs_restriction deterministic = function
2082 | [] ->
2083 if needs_restriction then `NeedsRestriction (deterministic, List.rev mask)
2084 else `GoodToGo (List.rev args)
2085 | x :: xs ->
2086 match E.look ~depth x with
2087 | E.Const i ->
2088 let is_duplicate = E.Constants.Set.mem i seen in
2089 let keep = not is_duplicate && is_in_coq i in
2090 aux (E.Constants.Set.add i seen) (keep :: mask) (i::args)
2091 (needs_restriction || not keep) (deterministic && not is_duplicate) xs
2092 | _ -> aux seen (false :: mask) args true false xs
2093 in
2094 aux E.Constants.Set.empty [] [] false true args
2095
2096 module UIM = F.Map(struct
2097 type t = UVars.Instance.t
2098 let compare = compare_instances
2099
2100 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
2101 let ppinst u = UVars.Instance.pr Sorts.QVar.raw_pr UnivNames.pr_level_with_global_universes u
2102 [%%else]
2103 let ppinst u = UVars.Instance.pr UnivNames.(sort_printer empty_binders) u
2104 [%%endif]
2105
2106 let show x = Pp.string_of_ppcmds @@ ppinst x
2107 let pp fmt x = Format.fprintf fmt "%a" Pp.pp_with (ppinst x)
2108 end)
2109
2110 let uim = S.declare_component ~name:"rocq-elpi:evar-univ-instance-map" ~descriptor:interp_state
2111 ~pp:UIM.pp ~init:(fun () -> UIM.empty) ~start:(fun x -> x) ()
2112
2113 let in_coq_poly_gref ~depth ~origin ~failsafe s t i =
2114 let open API.Conversion in
2115 let uinstance_readback s i t =
2116 match E.look ~depth i with
2117 | E.UnifVar (b, args) ->
2118 let m = S.get uim s in
2119 begin try
2120 let u = UIM.host b m in
2121 s, u, []
2122 with Not_found ->
2123 let u, ctx = UnivGen.fresh_global_instance (get_global_env s) t in
2124 let s = update_sigma s (fun sigma -> evd_merge_ctx_set UState.univ_flexible_alg sigma ctx) in
2125 let u =
2126 match C.kind u with
2127 | C.Const (_, u) -> u
2128 | C.Ind (_, u) -> u
2129 | C.Construct (_, u) -> u
2130 | _ -> assert false
2131 in
2132 let s = S.update uim s (UIM.add b u) in
2133 let s, prune_ev = prune_uvar s b args in
2134 s, u, [prune_ev; API.Conversion.Unify (E.mkUnifVar b ~args s,uinstancein u)]
2135 end
2136 | _ -> uinstance.readback ~depth s i
2137 in
2138 try
2139 let s, t, gls1 = gref.readback ~depth s t in
2140 assert_in_coq_gref_consistent ~poly:true t;
2141 let s, i, gls2 = uinstance_readback s i t in
2142 assert (gls1 = []);
2143 s, t, i, gls2
2144 with API.Conversion.TypeErr _ ->
2145 if failsafe then
2146 s, Rocqlib.lib_ref "elpi.unknown_gref", UVars.Instance.empty, []
2147 else
2148 let open Pp in
2149 err ?loc:None @@
2150 str "The term " ++ str (pp2string (P.term depth) origin) ++
2151 str " cannot be represented in Coq since its gref or univ-instance part is illformed"
2152
2153
2154 type global_or_pglobal =
2155 | Global of E.term option
2156 | PGlobal of E.term option * UVars.Instance.t option
2157 | NotGlobal
2158 | Var
2159
2160 let is_global_or_pglobal ~depth t =
2161 let do_gr x =
2162 match E.look ~depth x with
2163 | E.UnifVar _ -> None
2164 | _ -> Some x in
2165 let do_ui x =
2166 match E.look ~depth x with
2167 | E.CData c when isuinstance c -> Some (uinstanceout c)
2168 | _ -> None in
2169 match E.look ~depth t with
2170 | E.App(c,gr,[]) when c == globalc -> (Global(do_gr gr))
2171 | E.App(c,gr,[]) when c == pglobalc -> (PGlobal(do_gr gr, None))
2172 | E.App(c,gr,[ui]) when c == pglobalc -> (PGlobal(do_gr gr, do_ui ui))
2173 | E.UnifVar _ -> Var
2174 | _ -> NotGlobal
2175
2176
2177 let rec of_elpi_ctx ~calldepth syntactic_constraints depth dbl2ctx state initial_coq_ctx =
2178
2179 let aux coq_ctx depth state t =
2180 lp2constr ~calldepth syntactic_constraints coq_ctx ~depth state t
2181 in
2182 let of_elpi_ctx_entry id dbl coq_ctx ~depth e state =
2183 match e with
2184 | `Decl(name_hint,ty) ->
2185 debug Pp.(fun () -> str "decl name (hint/actual): " ++ str(pp2string (P.term depth) name_hint) ++ spc () ++ Id.print (Context.binder_name id));
2186 debug Pp.(fun () -> str "decl ty: " ++ str(pp2string (P.term depth) ty));
2187 let state, ty, gls = aux coq_ctx depth state ty in
2188 state, Context.Named.Declaration.LocalAssum(id,ty), gls
2189 | `Def(name_hint,ty,bo) ->
2190 debug Pp.(fun () -> str "def name (hint/actual): " ++ str(pp2string (P.term depth) name_hint) ++ spc () ++ Id.print (Context.binder_name id));
2191 debug Pp.(fun () -> str "def ty: " ++ str(pp2string (P.term depth) ty));
2192 debug Pp.(fun () -> str "def bo: " ++ str(pp2string (P.term depth) bo));
2193 let state, ty, gl1 = aux coq_ctx depth state ty in
2194 let state, bo, gl2 = aux coq_ctx depth state bo in
2195 state, Context.Named.Declaration.LocalDef(id,bo,ty), gl1 @ gl2
2196 in
2197 let of_elpi_ctx_entry_name dbl names ~depth state e =
2198 match e with
2199 | `Decl(name_hint,_) -> in_coq_fresh_annot_id ~depth ~names dbl state name_hint
2200 | `Def(name_hint,_,_) -> in_coq_fresh_annot_id ~depth ~names dbl state name_hint
2201 in
2202 let rec build_ctx_entry coq_ctx state gls = function
2203 | [] -> state, coq_ctx, List.(concat (rev gls))
2204 | (i,id,d,h,e) :: rest ->
2205 debug Pp.(fun () -> str "<<< context entry for DBL "++ int i ++ str" at depth" ++ int d);
2206 let state, e, gl1 = of_elpi_ctx_entry id i coq_ctx ~depth:d e state in
2207 debug Pp.(fun () -> str "<<< context entry for DBL "++ int i ++ str" at depth" ++ int d);
2208 let coq_ctx = push_coq_ctx_proof i (e,h) coq_ctx in
2209 build_ctx_entry coq_ctx state (gl1 :: gls) rest
2210 in
2211 (* we go from the bottom (most recent addition) to the top in order to
2212 give precedence to the name recently introduced *)
2213 let rec ctx_entries_names names i state =
2214 if i < 0 then state, [], []
2215 else (* context entry for the i-th variable *)
2216 if not (Int.Map.mem i dbl2ctx)
2217 then ctx_entries_names names (i - 1) state
2218 else
2219 let d, t, e = Int.Map.find i dbl2ctx in
2220 let state, id, gl = of_elpi_ctx_entry_name i names ~depth:d state e in
2221 let names = Id.Set.add (Context.binder_name id) names in
2222 let state, res, gls = ctx_entries_names names (i - 1) state in
2223 state, (i,id,d,t,e) :: res, gl :: gls
2224 in
2225 let state, names, gls = ctx_entries_names initial_coq_ctx.names(depth-1) state in
2226 List.rev names |> (* we need to readback the context from top to bottom *)
2227 build_ctx_entry initial_coq_ctx state []
2228
2229 (* ***************************************************************** *)
2230 (* <-- depth --> *)
2231 (* names |- pis |- t *)
2232 (* | \- lp fresh constans *)
2233 (* \- proof_ctx *)
2234 (* ***************************************************************** *)
2235
2236 and lp2constr ~calldepth syntactic_constraints coq_ctx ~depth state ?(on_ty=false) t =
2237 let aux = lp2constr ~calldepth syntactic_constraints coq_ctx in
2238 let aux_lam coq_ctx ~depth s t = match E.look ~depth t with
2239 | E.Lam t -> lp2constr ~calldepth syntactic_constraints coq_ctx ~depth:(depth+1) s t
2240 | E.UnifVar(r,args) ->
2241 lp2constr ~calldepth syntactic_constraints coq_ctx ~depth:(depth+1) s
2242 (E.mkUnifVar r ~args:(List.map (U.move ~from:depth ~to_:(depth+1)) args @ [E.mkConst depth]) state)
2243 | _ -> err Pp.(str"HOAS: expecting a lambda, got: " ++ str(pp2string (P.term depth) t))
2244 in
2245 debug Pp.(fun () -> str"lp2term@" ++ int depth ++ str":" ++ str(pp2string (P.term depth) t));
2246 match E.look ~depth t with
2247 | E.App(s,p,[]) when sortc == s ->
2248 let state, u, gsl = sort.API.ContextualConversion.readback ~depth coq_ctx syntactic_constraints state p in
2249 state, EC.mkSort (EC.ESorts.make u), gsl
2250 (* constants *)
2251 | E.App(c,d,[]) when globalc == c ->
2252 let state, gr = in_coq_gref ~depth ~origin:t ~failsafe:coq_ctx.options.failsafe state d in
2253 begin match gr with
2254 | G.VarRef x -> state, EC.mkVar x, []
2255 | G.ConstRef x -> state, EC.UnsafeMonomorphic.mkConst x, []
2256 | G.ConstructRef x -> state, EC.UnsafeMonomorphic.mkConstruct x, []
2257 | G.IndRef x -> state, EC.UnsafeMonomorphic.mkInd x, []
2258 end
2259 | E.App(c,d,[i]) when pglobalc == c ->
2260 let state, gr, i, gls =
2261 in_coq_poly_gref ~depth ~origin:t ~failsafe:coq_ctx.options.failsafe state d i in
2262 begin match gr with
2263 | G.VarRef x -> assert false
2264 | G.ConstRef x -> state, EC.mkConstU (x, EC.EInstance.make i), gls
2265 | G.ConstructRef x -> state, EC.mkConstructU (x, EC.EInstance.make i), gls
2266 | G.IndRef x -> state, EC.mkIndU (x, EC.EInstance.make i), gls
2267 end
2268 (* binders *)
2269 | E.App(c,name,[s;t]) when lamc == c || prodc == c ->
2270 let state, name, gl0 = in_coq_fresh_annot_name ~depth ~coq_ctx depth name state in
2271 let state, s, gl1 = aux ~depth state ~on_ty:true s in
2272 let coq_ctx = push_coq_ctx_local depth (Context.Rel.Declaration.LocalAssum(name,s)) coq_ctx in
2273 let state, t, gl2 = aux_lam coq_ctx ~depth state t in
2274 if lamc == c then state, EC.mkLambda (name,s,t), gl0 @ gl1 @ gl2
2275 else state, EC.mkProd (name,s,t), gl0 @ gl1 @ gl2
2276 | E.App(c,name,[s;b;t]) when letc == c ->
2277 let state, name, gl0 = in_coq_fresh_annot_name ~depth ~coq_ctx depth name state in
2278 let state, s, gl1 = aux ~depth state ~on_ty:true s in
2279 let state, b, gl2 = aux ~depth state b in
2280 let coq_ctx = push_coq_ctx_local depth (Context.Rel.Declaration.LocalDef(name,b,s)) coq_ctx in
2281 let state, t, gl3 = aux_lam coq_ctx ~depth state t in
2282 if EC.eq_constr (get_sigma state) t (EC.mkRel 1) then
2283 state, EC.mkCast (b,Constr.DEFAULTcast,s), gl0 @ gl1 @ gl2 @ gl3
2284 else
2285 state, EC.mkLetIn (name,b,s,t), gl0 @ gl1 @ gl2 @ gl3
2286
2287 | E.Const n ->
2288
2289 if n >= 0 then
2290 try state, EC.mkVar(Int.Map.find n coq_ctx.db2name), []
2291 with Not_found ->
2292 try state, EC.mkRel(coq_ctx.local_len - Int.Map.find n coq_ctx.db2rel + 1), []
2293 with Not_found ->
2294 if coq_ctx.options.failsafe then
2295 let hole = EConstr.of_constr (UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "elpi.unknown_gref")) in
2296 state, hole, []
2297 else
2298 err Pp.(hov 0 (str"Bound variable " ++ str (E.Constants.show n) ++
2299 str" not found in the Coq context:" ++ cut () ++
2300 pr_coq_ctx coq_ctx (get_sigma state) ++ cut () ++
2301 str"Did you forget to load some hypotheses with => ?"))
2302 else
2303 err Pp.(str"lp2constr: wrong constant: " ++ int n ++ str " " ++ str (E.Constants.show n))
2304
2305 (* app *)
2306 | E.App(c,x,[]) when appc == c -> begin
2307 match U.lp_list_to_list ~depth x with
2308 | x :: xs -> begin
2309 match E.look ~depth x, xs with
2310 | E.App(c,p,[]), i :: xs when primitivec == c ->
2311 let state, p, gls = primitive_value.API.Conversion.readback ~depth state p in
2312 begin match p with
2313 | Projection p ->
2314 let state, i, gl1 = aux ~depth state i in
2315 let state, xs, gl2 = API.Utils.map_acc (aux ~depth ~on_ty:false) state xs in
2316 (* let state, rv = fresh_relevance_variable state in *)
2317 let rv = EC.ERelevance.relevant in
2318 state, EC.mkApp (EC.mkProj (p,rv,i),Array.of_list xs), gls @ gl1 @ gl2
2319 | _ -> err Pp.(str"not a primitive projection:" ++ str (E.Constants.show c))
2320 end
2321 | x, _ ->
2322 let state, x, gl1 = aux ~depth state (E.kool x) in
2323 let state, xs, gl2 = API.Utils.map_acc (aux ~depth ~on_ty:false) state xs in
2324 state, EC.mkApp (x, Array.of_list xs), gl1 @ gl2
2325 end
2326 | _ -> U.type_error "the app term constructor expects a non empty list"
2327 end
2328
2329 (* match *)
2330 | E.App(c,t,[rt;bs]) when matchc == c ->
2331 let state, t, gl1 = aux ~depth state t in
2332 let state, rt, gl2 = aux ~depth state rt in
2333 let state, bt, gl3 =
2334 API.Utils.map_acc (aux ~depth ~on_ty:false) state (U.lp_list_to_list ~depth bs) in
2335 let ind =
2336 (* XXX fixme reduction *)
2337 let { sigma } = S.get engine state in
2338 let rec aux t o = match EC.kind sigma t with
2339 | C.Lambda(n,s,t) -> aux t (`SomeTerm (n,s))
2340 | _ -> match o with
2341 | `None ->
2342 if List.length bt = 1 then `None
2343 else CErrors.anomaly Pp.(str "match on unknown, non singleton, inductive")
2344 | `SomeTerm (n,t) as x ->
2345 match safe_destApp sigma t with
2346 | C.Ind i, _ -> `SomeInd (fst i)
2347 | _ ->
2348 if List.length bt = 1 then x
2349 else CErrors.anomaly Pp.(str "match on unknown, non singleton, inductive")
2350 in
2351 aux rt `None in
2352 let default_case_info () =
2353 let unknown_ind_cinfo = Inductiveops.make_case_info (get_global_env state)
2354 begin match Rocqlib.lib_ref "elpi.unknown_inductive" with
2355 | GlobRef.IndRef i -> i
2356 | _ -> assert false end
2357 C.LetStyle in
2358 let ci_pp_info = unknown_ind_cinfo.Constr.ci_pp_info in
2359 { unknown_ind_cinfo with Constr.ci_pp_info} in
2360 let { sigma } = S.get engine state in
2361 begin match ind with
2362 | `SomeInd ind ->
2363 let ci = Inductiveops.make_case_info (get_global_env state) ind C.MatchStyle in
2364 let state, rv = fresh_relevance_variable state in
2365 state, EC.mkCase (EConstr.contract_case (get_global_env state) sigma (ci,(rt,rv),C.NoInvert,t,Array.of_list bt)), gl1 @ gl2 @ gl3
2366 | `None -> CErrors.anomaly Pp.(str "non dependent match on unknown, non singleton, inductive")
2367 | `SomeTerm (n,rt) ->
2368 let ci = default_case_info () in
2369 let b =
2370 match bt with
2371 | [t] -> [||], t
2372 | _ -> assert false in
2373 let state, rv = fresh_relevance_variable state in
2374 state, EConstr.mkCase (ci,EConstr.EInstance.empty,[||],(([|n|],rt),rv),Constr.NoInvert,t,[|b|]), gl1 @ gl2 @ gl3
2375 end
2376
2377 (* fix *)
2378 | E.App(c,name,[rno;ty;bo]) when fixc == c ->
2379 let state, name, gl0 = in_coq_fresh_annot_name ~depth ~coq_ctx depth name state in
2380 let state, ty, gl1 = aux ~depth state ~on_ty:true ty in
2381 let coq_ctx = push_coq_ctx_local depth (Context.Rel.Declaration.LocalAssum(name,ty)) coq_ctx in
2382 let state, bo, gl2 = aux_lam coq_ctx ~depth state bo in
2383 let rno = lp2int ~depth ~ctx:"fix" rno in
2384 state, EC.mkFix (([|rno|],0),([|name|],[|ty|],[|bo|])), gl0 @ gl1 @ gl2
2385
2386 (* mfix *)
2387 | E.App(c,focus_lp,[rno;block_lp]) when mfixc == c ->
2388 (* mkFix's types live in outer_ctx (no self-refs); bodies use extended ctx. *)
2389 let outer_ctx = coq_ctx in
2390 let focus_idx = lp2int ~depth ~ctx:"mfix focus" focus_lp in
2391 let top_rno = lp2int ~depth ~ctx:"mfix rno" rno in
2392 let rec collect_ty ~depth state coq_ctx node defs gls_acc =
2393 match E.look ~depth node with
2394 | E.App(c2,name_lp,[rno_lp; ty_lp; rest_lam]) when mfix_tyc == c2 ->
2395 let state, name, gl0 = in_coq_fresh_annot_name ~depth ~coq_ctx depth name_lp state in
2396 let rno = lp2int ~depth ~ctx:"mfix-ty rno" rno_lp in
2397 let state, ty, gl =
2398 lp2constr ~calldepth syntactic_constraints outer_ctx
2399 ~depth state ~on_ty:true ty_lp in
2400 let coq_ctx = push_coq_ctx_local depth
2401 (Context.Rel.Declaration.LocalAssum(name,ty)) coq_ctx in
2402 let defs = (name, rno, ty) :: defs in
2403 let gls_acc = gl0 @ gl @ gls_acc in
2404 (match E.look ~depth rest_lam with
2405 | E.Lam body ->
2406 collect_ty ~depth:(depth+1) state coq_ctx body defs gls_acc
2407 | _ -> err Pp.(str"mfix: expected lambda in mfix-ty body"))
2408 | E.App(c2,bodies_lp,[]) when mfix_boc == c2 ->
2409 finish_mfix ~depth state coq_ctx (List.rev defs) bodies_lp gls_acc
2410 | _ -> err Pp.(str"mfix: expected mfix-ty or mfix-bo, got: " ++
2411 str (P.Debug.show_term node))
2412 and finish_mfix ~depth state coq_ctx defs bodies_lp gls_acc =
2413 let n = List.length defs in
2414 if focus_idx < 0 || focus_idx >= n then
2415 err Pp.(str"mfix: focus index out of range: " ++ int focus_idx);
2416 let _, focus_rno, _ = List.nth defs focus_idx in
2417 if top_rno <> focus_rno then
2418 err Pp.(str"mfix: top-level rno " ++ int top_rno ++
2419 str" does not match focused component rno " ++ int focus_rno);
2420 let body_list = U.lp_list_to_list ~depth bodies_lp in
2421 if List.length body_list <> n then
2422 err Pp.(str"mfix: expected " ++ int n ++ str" bodies, got " ++
2423 int (List.length body_list));
2424 let state, coq_bodies, gls_bos =
2425 List.fold_left (fun (state, bos, gls) bo_lp ->
2426 let state, bo, gl =
2427 lp2constr ~calldepth syntactic_constraints coq_ctx
2428 ~depth state bo_lp in
2429 (state, bo :: bos, gl @ gls)
2430 ) (state, [], []) body_list
2431 in
2432 let coq_bodies = List.rev coq_bodies in
2433 let names = Array.of_list (List.map (fun (n,_,_) -> n) defs) in
2434 let rnos = Array.of_list (List.map (fun (_,r,_) -> r) defs) in
2435 let typs = Array.of_list (List.map (fun (_,_,t) -> t) defs) in
2436 state,
2437 EC.mkFix ((rnos, focus_idx),(names, typs, Array.of_list coq_bodies)),
2438 gls_acc @ gls_bos
2439 in
2440 collect_ty ~depth state coq_ctx block_lp [] []
2441
2442 | E.App(c,v,[]) when primitivec == c ->
2443 let state, v, gls = primitive_value.API.Conversion.readback ~depth state v in
2444 begin match v with
2445 | Uint63 i -> state, EC.mkInt i, gls
2446 | Float64 f -> state, EC.mkFloat f, gls
2447 | Pstring s -> state, eC_mkString s, gls
2448 | Projection p -> state, EC.UnsafeMonomorphic.mkConst (get_projection_constant (get_global_env state) (Projection.repr p)), gls
2449 end
2450
2451 (* evar *)
2452 | E.UnifVar (elpi_evk,args) as x ->
2453 debug Pp.(fun () ->
2454 str"lp2term: evar: calldepth:" ++ int calldepth ++ str" " ++
2455 str (pp2string (P.term depth) (E.kool x)) ++ spc () ++ str (UVMap.show state));
2456 if coq_ctx.options.hoas_holes = Some Implicit then
2457 (* If we don't apply the hole to the whole context Detyping will prune
2458 (in the binder name) variables that don't occur, and then Pretyping
2459 does not put the variables back in scope *)
2460 let hole = EConstr.of_constr (UnivGen.constr_of_monomorphic_global (Global.env ()) (Rocqlib.lib_ref "elpi.hole")) in
2461 let all_ctx = CArray.init coq_ctx.local_len (fun x -> EConstr.mkRel (x+1)) in
2462 (* We put another hole at the end to know how many arguments we added here *)
2463 let all_ctx = Array.append all_ctx [|hole|] in
2464 state, EConstr.mkApp(hole, all_ctx), []
2465 else
2466 begin try
2467 let ext_key = UVMap.host elpi_evk state in
2468
2469 debug Pp.(fun () -> str"lp2term: evar: already in Coq: " ++ Evar.print ext_key);
2470
2471 let state, args, gl1 = API.Utils.map_acc (aux ~depth ~on_ty:false) state args in
2472 let args = List.rev args in
2473 let section_args =
2474 CList.rev_map EC.mkVar (section_ids (get_global_env state)) in
2475 let arity = evar_arity ext_key state in
2476 let ev =
2477 let { sigma } = S.get engine state in
2478 let all_args = args @ section_args in
2479 let nargs = List.length all_args in
2480 if nargs > arity then
2481 let args1, args2 = CList.chop (nargs - arity) all_args in
2482 EC.mkApp(EC.mkLEvar sigma (ext_key, args2),
2483 CArray.rev_of_list args1)
2484 else
2485 EC.mkLEvar sigma (ext_key, all_args) in
2486
2487 state, ev, gl1
2488 with Not_found -> try
2489 let canonical_context, elpi_revkc, elpi_evkc, ty, relevant_constraint =
2490 find_evar_decl elpi_evk (E.constraints syntactic_constraints) in
2491 let state, k, gl1 =
2492 declare_evar_of_constraint ~calldepth elpi_revkc elpi_evkc syntactic_constraints canonical_context ty state coq_ctx.options in
2493
2494 debug Pp.(fun () -> str"lp2term: evar: declared new: " ++
2495 Evar.print k ++ str" = " ++ str(F.Elpi.show elpi_evk));
2496
2497 if List.length args <> Int.Map.cardinal canonical_context then
2498 CErrors.anomaly Pp.(str"Mismatch between canonical context and instance." ++ fnl () ++
2499 str"Instance:" ++ fnl () ++
2500 str (pp2string (P.term depth) t) ++ fnl () ++
2501 str"Canonical context:" ++ fnl () ++
2502 str(pp2string pp_cst relevant_constraint));
2503 let state, x, gls = aux ~depth state t in
2504 state, x, gl1 @ gls
2505 with Not_found ->
2506
2507 debug Pp.(fun () -> str"lp2term: evar: unknown: calldepth:" ++ int calldepth ++ str " " ++ str(F.Elpi.show elpi_evk));
2508
2509 match analyze_scope ~depth coq_ctx args with
2510 | `GoodToGo args_in_coq_ctx ->
2511 create_evar_unknown ~calldepth syntactic_constraints
2512 coq_ctx ~args_in_coq_ctx ~depth state elpi_evk ~on_ty (E.kool x)
2513 | `NeedsRestriction (is_deterministic, keep_mask)
2514 when is_deterministic || coq_ctx.options.hoas_holes = Some Heuristic ->
2515
2516 debug Pp.(fun () -> str"evar: unknown: needs restriction ");
2517
2518 let state, new_uv = F.Elpi.make state in
2519 let ass =
2520 let rec mk_restriction d acc = function
2521 | [] -> E.mkUnifVar new_uv ~args:(List.rev acc) state
2522 | true :: mask -> E.mkLam (mk_restriction (d+1) (E.mkBound d :: acc) mask)
2523 | false :: mask -> E.mkLam (mk_restriction (d+1) acc mask) in
2524 mk_restriction calldepth [] keep_mask in
2525 let restriction_assignment =
2526 let u = E.mkUnifVar elpi_evk ~args:[] state in
2527 debug Pp.(fun () ->
2528 str"evar: unknown: restriction assignment: "
2529 ++ str (pp2string (P.term calldepth) u)
2530 ++ str " = "
2531 ++ str (pp2string (P.term calldepth) ass));
2532 API.Conversion.Unify(u ,ass) in
2533 let args =
2534 CList.map_filter (fun (b,a) -> if b then Some a else None) (List.combine keep_mask args) in
2535 let state, t, gls = aux ~depth state (E.mkUnifVar new_uv ~args state) in
2536 state, t, restriction_assignment :: gls
2537
2538 | `NeedsRestriction _ ->
2539 err Pp.(str "Flexible term outside pattern fragment:"++cut ()++str (pp2string (P.term depth) @@ E.kool x))
2540 end
2541
2542 (* errors *)
2543 | E.Lam _ ->
2544 err Pp.(str "out of place lambda: "++
2545 str (pp2string P.(term depth) t))
2546 | _ -> err Pp.(str"Not a HOAS term:" ++ str (P.Debug.show_term t))
2547
2548 and lp2int ~depth ~ctx lp =
2549 match E.look ~depth lp with
2550 | E.CData n when CD.is_int n -> CD.to_int n
2551 | _ -> err Pp.(str"lp2constr: " ++ str ctx ++ str" not an int: " ++
2552 str (P.Debug.show_term lp))
2553
2554 (* Evar info out of thin air: the user wrote an X that was never encountered by
2555 type checking (of) hence we craft a tower ?1 : ?2 : Type and link X with ?1 *)
2556 and create_evar_unknown ~calldepth syntactic_constraints (coq_ctx : 'a conv_context) ~args_in_coq_ctx ~depth ~on_ty state elpi_evk orig =
2557 debug Pp.(fun () ->
2558 str"lp2term: evar: create_unknown: whole ctx:" ++
2559 Printer.pr_named_context_of coq_ctx.env (get_sigma state) ++ str" ; "++
2560 Printer.pr_rel_context_of coq_ctx.env (get_sigma state) );
2561 debug Pp.(fun () ->
2562 str"lp2term: evar: create_unknown: visible ctx:" ++
2563 str (pp2string (P.list (P.term depth) " ") (List.map E.mkBound args_in_coq_ctx)));
2564
2565 let env = (restrict_conv_context args_in_coq_ctx state coq_ctx).env in
2566
2567 debug Pp.(fun () ->
2568 str"lp2term: evar: create_unknown: restricted ctx:" ++
2569 Printer.pr_named_context_of coq_ctx.env (get_sigma state) ++
2570 Printer.pr_rel_context_of env (get_sigma state));
2571
2572 let state, (k, kty) = S.update_return engine state (fun ({ sigma } as e) ->
2573 let sigma, (ty, _) = Evarutil.new_type_evar ~naming:(Namegen.IntroFresh (Names.Id.of_string "e")) env sigma Evd.univ_rigid in
2574 let ty_key, _ = EConstr.destEvar sigma ty in
2575 if on_ty then
2576 { e with sigma }, (ty_key, None)
2577 else
2578 let sigma, t = Evarutil.new_evar ~typeclass_candidate:false ~naming:(Namegen.IntroFresh (Names.Id.of_string "e")) env sigma ty in
2579 let t_key, _ = EConstr.destEvar sigma t in
2580 { e with sigma }, (t_key, Some ty_key)) in
2581 (*let state = S.update UVMap.uvmap state (UVMap.add elpi_evk k) in*)
2582 let state, gls_kty =
2583 match kty with
2584 | None -> state, []
2585 | Some k ->
2586 let state, _,_, gls = in_elpi_evar ~calldepth k state in
2587 state, gls in
2588 let state, gls_k = in_elpi_fresh_evar ~calldepth k ~raw_ev:elpi_evk elpi_evk state in
2589 debug Pp.(fun () ->
2590 str"lp2term: evar: create_unknown: new link: ? |> " ++
2591 Printer.pr_named_context_of env (get_sigma state) ++ str" |- ? = " ++ Evar.print k ++ cut() ++
2592 str(show_coq_engine @@ S.get engine state));
2593 let state, x, gls_orig = lp2constr ~calldepth syntactic_constraints coq_ctx ~depth state ~on_ty orig in
2594 state, x, gls_kty @ gls_k @ gls_orig
2595
2596 (* Evar info read back from a constraint (contains the context and the type) *)
2597 and declare_evar_of_constraint ~calldepth elpi_revkc elpi_evkc syntactic_constraints ctx (depth_concl,concl) state options =
2598 let state, coq_ctx, gl1 =
2599 of_elpi_ctx ~calldepth syntactic_constraints depth_concl ctx state
2600 (empty_conv_context ~options state) in
2601 let state, ty, gl2 = lp2constr ~calldepth syntactic_constraints coq_ctx ~depth:depth_concl state concl in
2602 let state, k = S.update_return engine state (fun ({ sigma } as e) ->
2603 let sigma, t = Evarutil.new_evar~typeclass_candidate:false ~naming:(Namegen.IntroFresh (Names.Id.of_string "elpi_evar")) coq_ctx.env sigma ty in
2604 { e with sigma }, fst (EConstr.destEvar sigma t)) in
2605 let state = UVMap.add k elpi_revkc elpi_evkc state in
2606 debug Pp.(fun () ->
2607 str"lp2term: evar: new from constraint: " ++ int depth_concl ++ str" |> " ++
2608 pp_coq_ctx coq_ctx state ++ str" |- " ++
2609 str(pp2string (P.term depth_concl) concl) ++
2610 str " = " ++ Evar.print k ++ spc () ++ str (UVMap.show state));
2611 state, k, gl1 @ gl2
2612 ;;
2613
2614 let lp2constr syntactic_constraints coq_ctx ~depth state t =
2615 debug Pp.(fun () ->
2616 str"lp2term: depth=" ++ int depth ++
2617 str " ctx=[" ++ pp_coq_ctx coq_ctx state ++ str"]" ++
2618 str " term=" ++ str (pp2string (P.term depth) t));
2619 let state, t, gls = lp2constr ~calldepth:depth syntactic_constraints coq_ctx ~depth state t in
2620 debug Pp.(fun () ->
2621 str"lp2term: out=" ++
2622 (Printer.pr_econstr_env (get_global_env state) (get_sigma state) t) ++
2623 spc () ++ str "elpi2coq:" ++ cut () ++ str(UVMap.show state) ++ Termops.pr_evar_map None (Global.env()) (get_sigma state));
2624 state, t, gls
2625
2626 (* ********************************* }}} ********************************** *)
2627
2628 let set_sigma state sigma = S.update engine state (fun x -> { x with sigma })
2629 let set_initial_sigma state sigma = S.update engine state (fun x -> assert(Evd.is_empty x.sigma); { x with sigma })
2630
2631 (* We reset the evar map since it depends on the env in which it was created *)
2632 let grab_global_env ~uctx state =
2633 let env0 = get_global_env state in
2634 let env = Global.env () in
2635 if env == env0 then state
2636 else
2637 if Environ.universes env0 == Environ.universes env then
2638 let state = S.set engine state (CoqEngine_HOAS.from_env_sigma env (get_sigma state)) in
2639 state
2640 else
2641 let state = S.set engine state (CoqEngine_HOAS.from_env_keep_univ_and_sigma ~uctx ~env0 ~env (get_sigma state)) in
2642 state
2643 let grab_global_env_drop_univs_and_sigma state =
2644 let env0 = get_global_env state in
2645 let env = Global.env () in
2646 if env == env0 then state
2647 else
2648 let state = S.set engine state (CoqEngine_HOAS.from_env_sigma env (Evd.from_env env)) in
2649 let state = UVMap.empty state in
2650 state
2651
2652 let grab_global_env_drop_sigma state =
2653 let env0 = get_global_env state in
2654 let env = Global.env () in
2655 if env == env0 then state
2656 else begin
2657 let sigma = get_sigma state in
2658 let ustate = Evd.ustate sigma in
2659 let state = S.set engine state (CoqEngine_HOAS.from_env_sigma env (Evd.from_ctx ustate)) in
2660 let state = UVMap.empty state in
2661 state
2662 end
2663
2664 let grab_global_env_drop_sigma_keep_univs ~uctx state =
2665 let env0 = get_global_env state in
2666 let env = Global.env () in
2667 if env == env0 then state
2668 else begin
2669 let sigma = get_sigma state in
2670 let state = S.set engine state (CoqEngine_HOAS.from_env_keep_univ_of_sigma ~uctx ~env0 ~env sigma) in
2671 let state = UVMap.empty state in
2672 state
2673 end
2674
2675 let solvec = E.Constants.declare_global_symbol "solve"
2676 let msolvec = E.Constants.declare_global_symbol "msolve"
2677 let goalc = E.Constants.declare_global_symbol "goal"
2678 let nablac = E.Constants.declare_global_symbol "nabla"
2679 let sealc = E.Constants.declare_global_symbol "seal"
2680 let openc = E.Constants.declare_global_symbol "coq.ltac.open"
2681 let allc = E.Constants.declare_global_symbol "coq.ltac.all"
2682
2683 let mk_goal hyps rev ty ev args =
2684 E.mkApp goalc hyps [rev ;ty; ev; U.list_to_lp_list args]
2685
2686 let in_elpi_goal state ~args ~hyps ~raw_ev ~ty ~ev =
2687 mk_goal hyps raw_ev ty ev args
2688
2689 let show_coq_engine ?with_univs state =
2690 show_coq_engine ?with_univs (S.get engine state)
2691
2692 let show_coq_elpi_engine_mapping state =
2693 "Rocq-Elpi mapping:\n" ^ UVMap.show state
2694
2695 let show_all_engine state = show_coq_engine ~with_univs:true state ^ "\n" ^ show_coq_elpi_engine_mapping state
2696
2697 let sealed_goal2lp ~depth ~args ~in_elpi_tac_arg ~base state k =
2698 let calldepth = depth in
2699 let env = get_global_env state in
2700 let sigma = get_sigma state in
2701 let state, elpi_goal_evar, elpi_raw_goal_evar, evar_decls = in_elpi_evar ~calldepth k state in
2702 let evar_concl, goal_ctx, _goal_env =
2703 info_of_undefined_evar ~env ~sigma ~section:(section_ids env) k in
2704 let state, g, gls =
2705 under_coq2elpi_ctx ~calldepth state goal_ctx
2706 ~mk_ctx_item:(fun _ t -> E.mkApp nablac (E.mkLam t) [])
2707 (fun coq_ctx ~depth state ->
2708 let state, args, gls_args = API.Utils.map_acc (in_elpi_tac_arg ~base ~depth ?calldepth:(Some calldepth) coq_ctx [] sigma) state args in
2709 let args = List.flatten args in
2710 let state, hyps, raw_ev, ev, goal_ty, gls =
2711 in_elpi_evar_concl evar_concl ~raw_uvar:elpi_raw_goal_evar elpi_goal_evar
2712 coq_ctx ~calldepth ~depth state in
2713 state, E.mkApp sealc (in_elpi_goal state ~args ~hyps ~raw_ev ~ty:goal_ty ~ev) [], gls_args @ gls) in
2714 state, g, evar_decls @ gls
2715
2716 let sealed_solved_goal2lp ~depth state k =
2717 let calldepth = depth in
2718 let env = get_global_env state in
2719 let sigma = get_sigma state in
2720 let evar_body, evar_concl, goal_ctx, _goal_env =
2721 info_of_defined_evar ~env ~sigma ~section:(section_ids env) k in
2722 let state, g, gls =
2723 under_coq2elpi_ctx ~calldepth state goal_ctx
2724 ~mk_ctx_item:(fun _ t -> E.mkApp nablac (E.mkLam t) [])
2725 (fun coq_ctx ~depth state ->
2726 let tate, hyps, evar_body, evar_concl, gls = in_elpi_solved_evar evar_body evar_concl coq_ctx ~calldepth ~depth state in
2727 state, E.mkApp sealc (in_elpi_goal state ~args:[] ~hyps ~raw_ev:evar_body ~ty:evar_concl ~ev:evar_body) [], gls) in
2728 state, g, gls
2729
2730 let solvegoal2query sigma goals loc args ~in_elpi_tac_arg ~depth:calldepth ~base state =
2731
2732 let state = S.set engine state (from_env_sigma (get_global_env state) sigma) in
2733
2734 debug Pp.(fun () -> str"initial coq sigma:\n" ++ str (show_all_engine state));
2735 debug Pp.(fun () -> str"initial coq goals:\n" ++ prlist_with_sep spc Evar.print goals);
2736
2737 let state, gl, gls =
2738 API.Utils.map_acc (fun state goal ->
2739 if not (Evd.is_undefined sigma goal) then
2740 err Pp.(str (Printf.sprintf "Evar %d is not a goal" (Evar.repr goal)));
2741
2742 sealed_goal2lp ~depth:calldepth ~in_elpi_tac_arg ~args ~base state goal) state goals in
2743
2744 let state, ek = F.Elpi.make ~name:"NewGoals" state in
2745 let newgls = E.mkUnifVar ek ~args:[] state in
2746
2747 let query =
2748 E.mkApp API.RawData.Constants.orc
2749 (E.mkApp msolvec (U.list_to_lp_list gl) [newgls])
2750 [E.mkApp allc (E.mkApp openc (E.mkConst solvec) []) [U.list_to_lp_list gl;newgls]] in
2751
2752 state, query, gls
2753 ;;
2754
2755 let sealed_goal2lp ~depth state goal =
2756 sealed_goal2lp ~depth ~args:[] ~base:() ~in_elpi_tac_arg:(fun ~base ~depth ?calldepth _ _ _ _ _ -> assert false) state goal
2757
2758 let sealed_maybe_solved_goal2lp ~depth state k =
2759 let sigma = get_sigma state in
2760 if Evd.is_defined sigma k then sealed_solved_goal2lp ~depth state k
2761 else sealed_goal2lp ~depth state k
2762
2763
2764 let customtac2query sigma goals loc text ~depth:calldepth ~base state =
2765 match goals with
2766 | [] | _ :: _ :: _ ->
2767 CErrors.user_err Pp.(str "elpi query can only be used on one goal")
2768 | [goal] ->
2769 let EvarInfo info = Evd.find sigma goal in
2770 let env = get_global_env state in
2771 let env = Environ.reset_with_named_context (Evd.evar_filtered_hyps info) env in
2772 if not (Evd.is_undefined sigma goal) then
2773 err Pp.(str (Printf.sprintf "Evar %d is not a goal" (Evar.repr goal)));
2774 let state = S.set engine state (from_env_sigma env sigma) in
2775 let state, elpi_goal_evar, elpi_raw_goal_evar, evar_decls = in_elpi_evar ~calldepth goal state in
2776 let evar_concl, goal_ctx, goal_env =
2777 info_of_undefined_evar ~env ~sigma ~section:(section_ids env) goal in
2778 let state, query, gls =
2779 under_coq2elpi_ctx ~calldepth state goal_ctx
2780 (fun coq_ctx ~depth state ->
2781 let q = API.Quotation.elpi ~language:API.Quotation.elpi_language state loc text in
2782 let _amap, q = API.RawQuery.term_to_raw_term state base ~depth q in
2783 state, q, []) in
2784 debug Pp.(fun () -> str"engine: " ++ str (show_coq_engine state));
2785 state, query, evar_decls @ gls
2786 ;;
2787
2788 (* type 'arg tactic_main = Solve of 'arg list | Custom of string *)
2789
2790 let solvegoals2query sigma goals loc ~main:args ~in_elpi_tac_arg ~depth ~base state =
2791 solvegoal2query sigma goals loc args ~in_elpi_tac_arg ~depth ~base state
2792
2793 let txtgoals2query sigma goals loc ~main:text ~depth ~base state =
2794 customtac2query sigma goals loc text ~depth ~base state
2795
2796 let eat_n_lambdas ~depth t upto state =
2797 let open E in
2798 let rec aux n t =
2799 if n = upto then t
2800 else match look ~depth:n t with
2801 | Lam t -> aux (n+1) t
2802 | UnifVar(r,a) -> aux (n+1) (mkUnifVar r ~args:(a@[mkConst n]) state)
2803 | Const c -> aux (n+1) (mkApp c (mkConst n) [])
2804 | App (c, x, xs) -> aux (n+1) (mkApp c x (xs@[mkConst n]))
2805 | _ -> CErrors.anomaly Pp.(str "rocq-elpi eat_n_lambdas : " ++
2806 str(pp2string (P.term depth) t))
2807 in
2808
2809 aux depth t
2810
2811 type declared_goal =
2812 | Open of { evar:Evar.t; scope: E.term list; ctx: E.term; args: E.term list}
2813 | Closed_by_side_effect
2814 | Not_a_goal
2815
2816 let get_goal_ref ~depth syntactic_constraints state t =
2817 match E.look ~depth t with
2818 | E.App(c,ctx,[_;_;g;i]) when c == goalc ->
2819 begin match E.look ~depth g with
2820 | E.UnifVar(ev,scope) ->
2821 begin try
2822 let uv = find_evar ev syntactic_constraints in
2823 let evar = UVMap.host_failsafe uv state in
2824 Open {ctx; evar; scope; args = U.lp_list_to_list ~depth i}
2825 with Not_found ->
2826 Not_a_goal
2827 end
2828 | _ -> Closed_by_side_effect
2829 end
2830 | _ -> Not_a_goal
2831
2832 let rec get_sealed_goal_ref ~depth syntactic_constraints state t =
2833 match E.look ~depth t with
2834 | E.App(c,g,[]) when c == nablac ->
2835 begin match E.look ~depth g with
2836 | E.Lam g -> get_sealed_goal_ref ~depth:(depth+1) syntactic_constraints state g
2837 | _ -> err Pp.(str"Not a lambda after nabla: " ++ str(pp2string (P.term depth) g))
2838 end
2839 | E.App(c,g,[]) when c == sealc ->
2840 get_goal_ref ~depth syntactic_constraints state g
2841 | _ -> Not_a_goal
2842
2843 let no_list_given = function
2844 | E.UnifVar _ -> true
2845 | _ -> false
2846
2847 let rec skip_lams ~depth d t = match E.look ~depth t with
2848 | E.Lam t -> skip_lams ~depth:(depth+1) (d+1) t
2849 | x -> x, d
2850
2851 let is_uvar ~depth t =
2852 match E.look ~depth t with
2853 | E.UnifVar(e,_) -> Some e
2854 | _ -> None
2855
2856 let elpi_solution_to_coq_solution ~eta_contract_solution ~calldepth syntactic_constraints state =
2857 let { sigma; global_env } as e = S.get engine state in
2858
2859 debug Pp.(fun () -> str"elpi sigma -> coq sigma: before:\n" ++ str (show_all_engine state));
2860
2861 (* if ?X <-> Y = Z, we have two cases:
2862 - Z unknown ---> we update the link, i.e. ?X <-> Z (no update, the code below does it)
2863 - ?B <-> Z ---> we propagate the unif to Coq, i.e. ?X = ?B
2864 *)
2865 let updates =
2866 UVMap.fold (fun k er e elpi_solution updates ->
2867 match elpi_solution with
2868 | None -> updates
2869 | Some t ->
2870 match is_uvar ~depth:0 t with
2871 | None -> updates
2872 | Some e' when UVMap.mem_elpi e' state && not @@ Evar.equal k (UVMap.host_failsafe e' state) -> updates
2873 | Some e' -> (k,er,e') :: updates
2874 ) state [] in
2875 let state = List.fold_left (fun state (k,r,e) ->
2876 let state = UVMap.remove_host k state in
2877 UVMap.add k r e state
2878 ) state updates in
2879
2880 debug Pp.(fun () -> str"elpi sigma -> coq sigma: synchronized:\n" ++ str (show_all_engine state));
2881
2882 let state, assigned, changed, extra_gls =
2883 UVMap.fold (fun k _ _ elpi_solution (state, assigned, changed, extra) ->
2884 match elpi_solution with
2885 | None -> (state, assigned, changed, extra)
2886 | Some t ->
2887
2888 (* The canonical context in which have to port the solution found by elpi *)
2889 let _, ctx, _ = info_of_undefined_evar ~env:global_env ~sigma ~section:(section_ids global_env) k in
2890
2891 (* under_coq_ctx is tied to elpi terms, while here I need the coq_ctx to
2892 convert the term back, hence this spill hack *)
2893 let spilled_solution = ref (EConstr.mkProp) in
2894 let eta_reduced = ref false in
2895 let state, _, gls = under_coq2elpi_ctx ~calldepth:0 state ctx ~mk_ctx_item:(fun _ x -> x)
2896 (fun coq_ctx ~depth state ->
2897 debug Pp.(fun () ->
2898 str"solution for "++ Evar.print k ++ str" in ctx=" ++ cut () ++
2899 Printer.pr_named_context_of coq_ctx.env (get_sigma state) ++ cut () ++
2900 str" at depth=" ++ int depth ++ str" id term=" ++ str(pp2string (P.term 0) t));
2901
2902 (* These meta-level-lambdas are elpi specific, they don't exist in Coq *)
2903 debug Pp.(fun () -> str "before:" ++ str(pp2string (P.term 0) t));
2904 let t = eat_n_lambdas ~depth:0 t coq_ctx.proof_len state in
2905 debug Pp.(fun () -> str "after:" ++ str(pp2string (P.term coq_ctx.proof_len) t));
2906
2907 let state, solution, gls = lp2constr
2908 syntactic_constraints coq_ctx ~depth state t in
2909
2910 let solution =
2911 if eta_contract_solution then
2912 let sol' = eta_contract coq_ctx.env (get_sigma state) solution in
2913 eta_reduced := sol' != solution;
2914 sol'
2915 else solution in
2916
2917 let gls = gls |> List.map (function
2918 | DeclareEvar(k,d,r,s) -> DeclareEvar(k,calldepth,r,s)
2919 | x -> x
2920 ) in
2921
2922 spilled_solution := solution;
2923 state, E.mkNil (* dummy *), gls)
2924 in
2925 let coq_solution = !spilled_solution in
2926
2927 let state = S.update engine state (fun ({ sigma } as e) ->
2928 let sigma =
2929 if !eta_reduced then
2930 let info = Evd.find_undefined sigma k in
2931 let ty = Evd.evar_concl info in
2932 Typing.check (Evd.evar_env global_env info) sigma coq_solution ty
2933 else sigma in
2934 let sigma = Evd.define k coq_solution sigma in
2935 { e with sigma }) in
2936
2937 (* since the order in which we add is not topological*)
2938 let assigned = Evar.Set.add k assigned in
2939
2940 state, assigned, true, gls :: extra) state
2941 (state, Evar.Set.empty, false, [])
2942 in
2943
2944 (* Drop from the mapping the evars that were assigned *)
2945 let state = UVMap.filter_host (fun k -> not (Evar.Set.mem k assigned)) state in
2946
2947 debug Pp.(fun () -> str"elpi sigma -> coq sigma: after:\n" ++ str (show_all_engine state));
2948
2949 state, assigned, changed, List.(concat (rev extra_gls))
2950
2951
2952 let sealed_goals2ev ~depth constraints state pp_ctx r =
2953 let syntactic_constraints = E.constraints constraints in
2954 let l, depth = skip_lams ~depth 0 (r) in
2955 if no_list_given l then None
2956 else
2957 let l = U.lp_list_to_list ~depth (E.kool l) in
2958 let declared = CList.filter_map (fun x ->
2959 match get_sealed_goal_ref ~depth syntactic_constraints state x with
2960 | Open {evar; _} -> Some evar
2961 | Closed_by_side_effect -> None
2962 | Not_a_goal ->
2963 err Pp.(str"Not a goal " ++ str(pp2string (P.term depth) x) ++ str " in " ++ cut () ++
2964 str(pp2string (API.Pp.constraints pp_ctx) constraints))) l in
2965 Some declared
2966
2967 let rec reachable1 sigma root acc =
2968 let EvarInfo info = Evd.find sigma root in
2969 let res =
2970 match Evd.evar_body info with
2971 | Evd.Evar_empty -> Evar.Set.add root acc
2972 | Evd.Evar_defined d -> acc in
2973 let res = Evar.Set.union res @@ Evarutil.filtered_undefined_evars_of_evar_info sigma info in
2974 if Evar.Set.equal res acc then acc else reachable sigma res res
2975 and reachable sigma roots acc =
2976 Evar.Set.fold (reachable1 sigma) roots acc
2977
2978 let reachable sigma roots acc =
2979 let res = reachable sigma roots acc in
2980 debug Pp.(fun () ->
2981 str"reachable from:" ++
2982 prlist_with_sep spc Evar.print (Evar.Set.elements roots) ++
2983 str" = " ++
2984 prlist_with_sep spc Evar.print (Evar.Set.elements res));
2985 res
2986
2987 let sealed_goals2coqgoals all_goals constraints state assignments pp_ctx =
2988 match API.Data.StrMap.find "NewGoals" assignments with
2989 | exception Not_found -> Evar.Set.elements all_goals , []
2990 | r ->
2991 match sealed_goals2ev ~depth:0 constraints state pp_ctx r with
2992 | None -> Evar.Set.elements all_goals, []
2993 | Some declared -> declared, Evar.Set.elements @@ Evar.Set.diff all_goals (List.fold_right Evar.Set.add declared Evar.Set.empty)
2994
2995 let solution2evd ~eta_contract_solution sigma0 { API.Data.constraints; assignments; state; pp_ctx } roots =
2996 let state, solved_goals, _, _gls = elpi_solution_to_coq_solution ~eta_contract_solution ~calldepth:0 constraints state in
2997 let sigma = get_sigma state in
2998 let reachable_undefined_evars = reachable sigma roots Evar.Set.empty in
2999 let declared_goals, shelved_goals =
3000 sealed_goals2coqgoals (Evar.Set.diff reachable_undefined_evars solved_goals) constraints state assignments pp_ctx in
3001 let reachable_undefined_evars =
3002 List.fold_left (fun e x -> Evar.Set.add x e) reachable_undefined_evars (declared_goals @ shelved_goals) in
3003 debug Pp.(fun () -> str "Goals: " ++ prlist_with_sep spc Evar.print declared_goals);
3004 debug Pp.(fun () -> str "Shelved Goals: " ++ prlist_with_sep spc Evar.print shelved_goals);
3005 Evd.fold_undefined (fun k _ sigma ->
3006 if Evar.Set.mem k reachable_undefined_evars || Evd.mem sigma0 k then sigma
3007 else Evd.remove sigma k
3008 ) sigma sigma,
3009 declared_goals,
3010 shelved_goals
3011
3012 let tclSOLUTION2EVD ~eta_contract_solution sigma0 solution gls =
3013 let open Proofview.Unsafe in
3014 let open Tacticals in
3015 let open Proofview.Notations in
3016 tclGETSHELF >>= fun sh ->
3017 let roots = List.fold_right Evar.Set.add gls Evar.Set.empty in
3018 let sigma, declared_goals, shelved_goals = solution2evd ~eta_contract_solution sigma0 solution roots in
3019
3020 let future_goals, sigma = Evd.pop_future_goals sigma in
3021 let future_goals = Evd.FutureGoals.map_filter (Proofview.Unsafe.advance sigma) future_goals in
3022 let future_goals = Evd.FutureGoals.filter (fun ev -> not @@ List.mem ev (Evd.shelf sigma) && not @@ List.mem ev shelved_goals) future_goals in
3023 let sigma = Proofview.Unsafe.mark_as_goals sigma (Evd.FutureGoals.comb future_goals @ declared_goals) in
3024 let comb = CList.map (fun x -> Proofview.with_empty_state x) (Evd.FutureGoals.comb future_goals @ declared_goals) in
3025
3026 tclTHENLIST [
3027 tclEVARS sigma;
3028 tclSETGOALS @@ comb;
3029 tclNEWSHELVED shelved_goals
3030 ]
3031
3032
3033 let set_current_sigma ~depth state sigma =
3034
3035 debug Pp.(fun () -> str"bringing updated sigma back to lp");
3036
3037 let state = set_sigma state sigma in
3038 let state, assignments, decls, to_remove_coq, to_remove_elpi =
3039 UVMap.fold (fun k elpi_raw_evk elpi_evk solution (state, assignments, decls, to_remove_coq, to_remove_elpi as acc) ->
3040 let EvarInfo info = Evd.find sigma k in
3041 match Evd.evar_body info with
3042 | Evd.Evar_empty -> acc
3043 | Evd.Evar_defined c ->
3044 let ctx = Evd.evar_filtered_context info in
3045 let env = get_global_env state in
3046 let section_ids = section_ids env in
3047 let ctx = ctx |> CList.filter (fun e -> let id = Context.Named.Declaration.get_id e in not(List.mem id section_ids)) in
3048 let assigned = E.mkUnifVar elpi_evk ~args:[] state in
3049 debug Pp.(fun () ->
3050 str"set_current_sigma: preparing assignment for " ++ str (pp2string (P.term depth) assigned) ++
3051 str" under context " ++ Printer.pr_named_context env sigma (EConstr.Unsafe.to_named_context ctx));
3052 let state, t, dec = under_coq2elpi_ctx ~mk_ctx_item:(fun _ -> E.mkLam) ~calldepth:depth state ctx (fun coq_ctx ~depth:new_ctx_depth state ->
3053 constr2lp coq_ctx ~calldepth:depth ~depth:new_ctx_depth state c) in
3054 let assignment = API.Conversion.Unify(assigned, t) in
3055 debug Pp.(fun () ->
3056 str"set_current_sigma: assignment at depth" ++ int depth ++
3057 str" is: " ++ str (pp2string (P.term depth) assigned) ++
3058 str" = " ++ str (pp2string (P.term depth) t));
3059 state, assignment :: assignments, dec :: decls, k :: to_remove_coq, (elpi_raw_evk, elpi_evk, List.length ctx) :: to_remove_elpi
3060 ) state (state,[],[],[],[]) in
3061 let state = List.fold_right UVMap.remove_host to_remove_coq state in
3062 let removals = List.map2 (fun (rk,k,ano) e ->
3063 let args = CList.init ano (fun x -> E.mkConst (x+depth)) in
3064 let raw_ev = E.mkUnifVar rk ~args state in
3065 let ev = E.mkUnifVar k ~args state in
3066 RmEvar (e,raw_ev, ev)) to_remove_elpi to_remove_coq in
3067 state, removals @ List.concat decls @ assignments
3068
3069 (* elpi -> Entries.mutual_inductive_entry **************************** *)
3070
3071 (* documentation of the Coq API
3072
3073 Coq < Inductive foo (A : Type) (a : A) : A -> Prop := K : foo A a a.
3074
3075 {Entries.mind_entry_record = None; mind_entry_finite = Finite;
3076 mind_entry_params =
3077 [(a, Entries.LocalAssumEntry _UNBOUND_REL_1);
3078 (A, Entries.LocalAssumEntry Type@{Top.1})];
3079 mind_entry_inds =
3080 [{Entries.mind_entry_typename = foo;
3081 mind_entry_arity = _UNBOUND_REL_2 -> Prop; mind_entry_template = false;
3082 mind_entry_consnames = [K];
3083 mind_entry_lc =
3084 [_UNBOUND_REL_3 _UNBOUND_REL_2 _UNBOUND_REL_1 _UNBOUND_REL_1]}];
3085 mind_entry_universes = Entries.Monomorphic_ind_entry Top.1 |= ;
3086 mind_entry_private = None}
3087
3088 Coq < Inductive bar (n m : nat) : Prop := K (_ : bar n (S m)).
3089
3090 {Entries.mind_entry_record = None; mind_entry_finite = Finite;
3091 mind_entry_params =
3092 [(m, Entries.LocalAssumEntry nat); (n, Entries.LocalAssumEntry nat)];
3093 mind_entry_inds =
3094 [{Entries.mind_entry_typename = bar; mind_entry_arity = Prop;
3095 mind_entry_template = false; mind_entry_consnames = [K];
3096 mind_entry_lc =
3097 [_UNBOUND_REL_3 _UNBOUND_REL_2 (S _UNBOUND_REL_1) ->
3098 _UNBOUND_REL_4 _UNBOUND_REL_3 _UNBOUND_REL_2]}];
3099 mind_entry_universes = Entries.Monomorphic_ind_entry ;
3100 mind_entry_private = None}
3101 *)
3102
3103 type coercion_status = Regular | Off | Reversible
3104 type record_field_att =
3105 | Coercion of coercion_status
3106 | Canonical of bool
3107
3108 let coercion_status = let open API.Conversion in let open API.AlgebraicData in declare {
3109 ty = TyName "coercion-status";
3110 doc = "Status of a record field w.r.t. coercions";
3111 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
3112 constructors = [
3113 K("regular","",N,
3114 B Regular,
3115 M (fun ~ok ~ko -> function Regular -> ok | _ -> ko ()));
3116 K("reversible","",N,
3117 B Reversible,
3118 M (fun ~ok ~ko -> function Reversible -> ok | _ -> ko ()));
3119 K("off","",N,
3120 B Off,
3121 M (fun ~ok ~ko -> function Off -> ok | _ -> ko ()));
3122 ]
3123 } |> API.ContextualConversion.(!<)
3124
3125 let record_field_att = let open API.Conversion in let open API.AlgebraicData in let open Elpi.Builtin in declare {
3126 ty = TyName "field-attribute";
3127 doc = "Attributes for a record field. Can be left unspecified, see defaults below.";
3128 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
3129 constructors = [
3130 K("coercion","default off",A(coercion_status,N),
3131 B (fun x -> Coercion (x)),
3132 M (fun ~ok ~ko -> function Coercion x -> ok (x) | _ -> ko ()));
3133 K("canonical","default true, if field is named",A(bool,N),
3134 B (fun x -> Canonical(x)),
3135 M (fun ~ok ~ko -> function Canonical x -> ok (x) | _ -> ko ()));
3136 ]
3137 } |> API.ContextualConversion.(!<)
3138
3139 let record_field_attributes = Elpi.Builtin.unspec (API.BuiltInData.list record_field_att)
3140
3141 let is_coercion_att = function
3142 | Elpi.Builtin.Unspec -> Off
3143 | Elpi.Builtin.Given l ->
3144 let rec aux = function
3145 | [] -> Off
3146 | Coercion x :: _ -> x
3147 | _ :: l -> aux l
3148 in
3149 aux l
3150 let is_canonical_att = function
3151 | Elpi.Builtin.Unspec -> true
3152 | Elpi.Builtin.Given l ->
3153 let rec aux = function
3154 | [] -> true
3155 | Canonical x :: _ -> x
3156 | _ :: l -> aux l
3157 in
3158 aux l
3159
3160 let implicit_kind : Glob_term.binding_kind API.Conversion.t = let open API.Conversion in let open API.AlgebraicData in let open Glob_term in declare {
3161 ty = TyName "implicit_kind";
3162 doc = "Implicit status of an argument";
3163 pp = (fun fmt -> function
3164 | NonMaxImplicit -> Format.fprintf fmt "implicit"
3165 | Explicit -> Format.fprintf fmt "explicit"
3166 | MaxImplicit -> Format.fprintf fmt "maximal");
3167 constructors = [
3168 K("implicit","regular implicit argument, eg Arguments foo [x]",N,
3169 B NonMaxImplicit,
3170 M (fun ~ok ~ko -> function NonMaxImplicit -> ok | _ -> ko ()));
3171 K("maximal","maximally inserted implicit argument, eg Arguments foo {x}",N,
3172 B MaxImplicit,
3173 M (fun ~ok ~ko -> function MaxImplicit -> ok | _ -> ko ()));
3174 K("explicit","explicit argument, eg Arguments foo x",N,
3175 B Explicit,
3176 M (fun ~ok ~ko -> function Explicit -> ok | _ -> ko ()));
3177 ]
3178 } |> API.ContextualConversion.(!<)
3179
3180 let in_coq_imp ~depth st x =
3181 let open Elpi.Builtin in
3182 match (unspec implicit_kind).API.Conversion.readback ~depth st x with
3183 | st, Unspec, gl -> assert(gl = []); st, Glob_term.Explicit
3184 | st, Given x, gl -> assert(gl = []); st, x
3185
3186 let in_elpi_imp ~depth st x =
3187 let st, x, gl = implicit_kind.API.Conversion.embed ~depth st x in
3188 assert (gl = []);
3189 st, x
3190
3191 let arity_parameterc = E.Constants.declare_global_symbol ~variant:1 "parameter"
3192 let inductive_parameterc = E.Constants.declare_global_symbol ~variant:2 "parameter"
3193 let arityc = E.Constants.declare_global_symbol "arity"
3194 let constructorc = E.Constants.declare_global_symbol "constructor"
3195 let inductivec = E.Constants.declare_global_symbol "inductive"
3196 let minductivec = E.Constants.declare_global_symbol "minductive"
3197 let mblockc = E.Constants.declare_global_symbol "mblock"
3198 let recordc = E.Constants.declare_global_symbol "record"
3199 let fieldc = E.Constants.declare_global_symbol "field"
3200 let end_recordc = E.Constants.declare_global_symbol "end-record"
3201
3202 let in_elpi_id = function
3203 | Names.Name.Name id -> CD.of_string (Names.Id.to_string id)
3204 | Names.Name.Anonymous -> CD.of_string "_"
3205
3206 let in_elpi_bool state b =
3207 let _, b, _ = Elpi.Builtin.bool.API.Conversion.embed ~depth:0 state b in
3208 b
3209 let in_coq_bool ~depth state ~default b =
3210 let _, b, _ = Elpi.Builtin.(unspec bool).API.Conversion.readback ~depth state b in
3211 match b with
3212 | Elpi.Builtin.Given b -> b
3213 | Elpi.Builtin.Unspec -> default
3214
3215 let in_elpi_arity_parameter id ~imp ty rest =
3216 E.mkApp arity_parameterc (in_elpi_id @@ Context.binder_name id) [imp;ty;E.mkLam rest]
3217 let in_elpi_inductive_parameter id ~imp ty rest =
3218 E.mkApp inductive_parameterc (in_elpi_id @@ Context.binder_name id) [imp;ty;E.mkLam rest]
3219
3220 let in_elpi_arity t =
3221 E.mkApp arityc t []
3222
3223 let in_elpi_indtdecl_record rid arity kid rest =
3224 E.mkApp recordc (in_elpi_id rid) [arity;in_elpi_id kid;rest]
3225 let in_elpi_indtdecl_endrecord () =
3226 E.mkConst end_recordc
3227
3228 let in_elpi_field atts n ty fields =
3229 E.mkApp fieldc atts [in_elpi_id n; ty; E.mkLam fields]
3230
3231 let in_elpi_indtdecl_inductive state find id arity constructors =
3232 let coind = not (Declarations.CoFinite = find) in
3233 E.mkApp inductivec (in_elpi_id id) [in_elpi_bool state coind; arity;E.mkLam @@ U.list_to_lp_list constructors]
3234
3235 let in_elpi_indtdecl_minductive state find id arity rest =
3236 let coind = not (Declarations.CoFinite = find) in
3237 E.mkApp minductivec (in_elpi_id id) [in_elpi_bool state coind; arity;E.mkLam rest]
3238
3239 let in_elpi_indtdecl_mblock constructor_blocks =
3240 let constructor_blocks = List.map U.list_to_lp_list constructor_blocks in
3241 E.mkApp mblockc (U.list_to_lp_list constructor_blocks) []
3242
3243 let in_elpi_indtdecl_constructor id ty =
3244 E.mkApp constructorc (in_elpi_id id) [ty]
3245
3246 type record_field_spec = { name : Name.t; is_coercion : coercion_status; is_canonical : bool }
3247 let in_elpi_indtdecl_field ~depth s { name; is_coercion; is_canonical } ty rest =
3248 let open API.Conversion in
3249 let s, att, gl = record_field_attributes.embed ~depth s (Elpi.Builtin.Given [Coercion is_coercion; Canonical is_canonical]) in
3250 assert(gl = []);
3251 s, E.mkApp fieldc att [in_elpi_id name;ty;E.mkLam rest]
3252
3253 let force_name =
3254 let n = ref 0 in
3255 function
3256 | Name.Name x -> x
3257 | _ ->
3258 incr n; Id.of_string (Printf.sprintf "_missing_parameter_name_%d_" !n)
3259
3260 let force_name_ctx =
3261 let open Context in
3262 let open Rel.Declaration in
3263 List.map (function
3264 | LocalAssum(n,t) -> LocalAssum (map_annot (fun n -> Name (force_name n)) n, t)
3265 | LocalDef(n,b,ty) -> LocalDef(map_annot (fun n -> Name (force_name n)) n, b, ty))
3266 ;;
3267
3268
3269 let readback_arity ~depth coq_ctx constraints state t =
3270 let lp2constr coq_ctx ~depth state t =
3271 lp2constr constraints coq_ctx ~depth state t in
3272 let rec aux_arity coq_ctx ~depth params impls state extra t =
3273 match E.look ~depth t with
3274 | E.App(c,name,[imp;ty;decl]) when is_coq_name ~depth name && c == arity_parameterc ->
3275 let state, name, gl0 = in_coq_annot ~depth state name in
3276 let state, imp = in_coq_imp ~depth state imp in
3277 let state, ty, gls = lp2constr coq_ctx ~depth state ty in
3278 let e = Context.Rel.Declaration.LocalAssum(name,ty) in
3279 aux_lam e coq_ctx ~depth (e :: params) (manual_implicit_of_binding_kind (Context.binder_name name) imp :: impls) state (gl0 :: gls :: extra) decl
3280 | E.App(c,ty,[]) when c == arityc ->
3281 let state, ty, gls = lp2constr coq_ctx ~depth state ty in
3282 state, params, impls, ty, List.flatten @@ gls :: extra
3283 | _ -> err Pp.(str"arity expected, got: "++ str (pp2string P.(term depth) t))
3284 and aux_lam e coq_ctx ~depth params impls state extra t =
3285 match E.look ~depth t with
3286 | E.Lam t -> aux_arity (push_coq_ctx_local depth e coq_ctx) ~depth:(depth+1) params impls state extra t
3287 | _ -> err Pp.(str"lambda expected: " ++
3288 str (pp2string P.(term depth) t))
3289 in
3290 aux_arity coq_ctx ~depth [] [] state [] t
3291 ;;
3292
3293
3294 let inference_nonuniform_params_off =
3295 CWarnings.create
3296 ~name:"elpi.unsupported-nonuniform-parameters-inference"
3297 ~category:Rocq_elpi_utils.elpi_cat Pp.(fun () ->
3298 strbrk"Inference of non-uniform parameters is not available in Elpi, please use the explicit | mark in the inductive declaration or Set Uniform Inductive Parameters")
3299 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
3300 let collapse = UState.collapse_sort_variables
3301 [%%else]
3302 let collapse = UState.collapse_sort_variables ~only_above_prop:false
3303 [%%endif]
3304 let restricted_sigma_of s state =
3305 let sigma = get_sigma state in
3306 let ustate = Evd.ustate sigma in
3307 let ustate = UState.restrict_even_binders ustate s in
3308 let ustate = UState.fix_undefined_variables ustate in
3309 let ustate = collapse ustate in
3310 let sigma = Evd.set_universe_context sigma ustate in
3311 sigma
3312
3313 let universes_of_term state t =
3314 let sigma = get_sigma state in
3315 snd (EConstr.universes_of_constr sigma t)
3316
3317 let universes_of_udecl state udecl =
3318 let used1, csts = dest_udecl udecl in
3319 let used2 = List.map (fun (x,_,y) -> [x;y]) (univ_csts_to_list csts) in
3320 let used = List.fold_right Univ.Level.Set.add used1 Univ.Level.Set.empty in
3321 let used = List.fold_right Univ.Level.Set.add (List.flatten used2) used in
3322 used
3323
3324 let name_universe_level = ref 0
3325
3326 let name_universe_level state l =
3327 S.update_return engine state (fun e ->
3328 let ustate = Evd.ustate e.sigma in
3329 match UState.id_of_level ustate l with
3330 | Some id -> e, id
3331 | None ->
3332 incr name_universe_level;
3333 let id = Id.of_string Printf.(sprintf "eu%d" !name_universe_level) in
3334 let ustate = UState.name_level l id ustate in
3335 let sigma = Evd.set_universe_context e.sigma ustate in
3336 { e with sigma }, id
3337 )
3338
3339
3340 let poly_cumul_udecl_variance_of_options state options =
3341 match options.universe_decl with
3342 | NotUniversePolymorphic -> state, false, false, default_univ_decl, [| |]
3343 | Cumulative ((univ_lvlt_var,univdecl_extensible_instance),(univdecl_constraints,univdecl_extensible_constraints)) ->
3344 let univdecl_instance, variance = List.split univ_lvlt_var in
3345 state, true, true,
3346 mk_universe_decl univdecl_extensible_instance univdecl_extensible_constraints univdecl_constraints univdecl_instance,
3347 Array.of_list variance
3348 | NonCumulative((univ_lvlt,univdecl_extensible_instance),(univdecl_constraints,univdecl_extensible_constraints)) ->
3349 let univdecl_instance = univ_lvlt in
3350 let variance = List.init (List.length univdecl_instance) (fun _ -> None) in
3351 state, true, false,
3352 mk_universe_decl univdecl_extensible_instance univdecl_extensible_constraints univdecl_constraints univdecl_instance,
3353 Array.of_list variance
3354
3355 [%%if coq = "9.0"]
3356 let comInductive_interp_mutual_inductive_constr ~cumulative ~poly ~template ~finite ~indnames =
3357 let flags = {
3358 ComInductive.poly;
3359 cumulative;
3360 template = Some false;
3361 finite;
3362 mode = None;
3363 }
3364 in
3365 let arities_explicit = List.map (fun _ -> true) indnames in
3366 let template_syntax = List.map (fun _ -> ComInductive.SyntaxAllowsTemplatePoly) indnames in
3367 ComInductive.interp_mutual_inductive_constr ~indnames ~arities_explicit ~template_syntax ~flags
3368 [%%elif coq = "9.1"]
3369 let comInductive_interp_mutual_inductive_constr ~cumulative ~poly ~template ~finite ~ctx_params ~env_ar_params ~indnames =
3370 let flags = {
3371 ComInductive.poly;
3372 cumulative;
3373 template = Some false;
3374 finite;
3375 mode = None;
3376 }
3377 in
3378 let arities_explicit = List.map (fun _ -> true) indnames in
3379 let template_syntax = List.map (fun _ -> ComInductive.SyntaxAllowsTemplatePoly) indnames in
3380 let env_ar = Environ.pop_rel_context (List.length ctx_params) env_ar_params in
3381 ComInductive.interp_mutual_inductive_constr ~indnames ~arities_explicit ~template_syntax ~flags ~env_ar ~ctx_params
3382 [%%else]
3383 let comInductive_interp_mutual_inductive_constr ~cumulative ~poly ~template ~finite ~ctx_params ~env_ar_params ~indnames =
3384 let flags = {
3385 ComInductive.poly = PolyFlags.make ~univ_poly:poly ~cumulative ~collapse_sort_variables:true;
3386 template = Some false;
3387 finite;
3388 mode = None;
3389 schemes = Default;
3390 }
3391 in
3392 let arities_explicit = List.map (fun _ -> true) indnames in
3393 let template_syntax = List.map (fun _ -> ComInductive.SyntaxAllowsTemplatePoly) indnames in
3394 let env_ar = Environ.pop_rel_context (List.length ctx_params) env_ar_params in
3395 ComInductive.interp_mutual_inductive_constr ~indnames ~arities_explicit ~template_syntax ~flags ~env_ar ~ctx_params
3396 [%%endif]
3397
3398
3399 let comInductive_interp_mutual_inductive_constr_post x = x
3400
3401 let lp2inductive_entry ~depth coq_ctx constraints state t =
3402
3403 let lp2constr coq_ctx ~depth state t =
3404 lp2constr constraints coq_ctx ~depth state t in
3405
3406 let check_consistency_and_drop_nuparams sigma nuparams name params arity =
3407 let eq_param ind_index x y =
3408 Name.equal
3409 (Context.Rel.Declaration.get_name x)
3410 (Context.Rel.Declaration.get_name y) &&
3411 EConstr.eq_constr_nounivs sigma
3412 (EConstr.Vars.liftn 1 ind_index (Context.Rel.Declaration.get_type x))
3413 (Context.Rel.Declaration.get_type y) in
3414 let rec aux n nuparams params =
3415 match nuparams, params with
3416 | [], params -> EC.it_mkProd_or_LetIn arity (List.rev params)
3417 | x :: nuparams, y :: params when eq_param n x y ->
3418 aux (succ n) nuparams params
3419 | x :: _, p -> err Pp.(pr_nth n ++ str" non uniform parameter, named " ++
3420 Name.print (Context.Rel.Declaration.get_name x) ++
3421 str ", not found in constructor "++Id.print name)
3422 in aux 1 (List.rev nuparams) (List.rev params) in
3423
3424 let aux_construtors coq_ctx ~depth (params,impls) (nuparams,nuimpls) arity itname finiteness state ks =
3425
3426 let params = force_name_ctx params in
3427 let paramno = List.length params in
3428
3429 (* decode constructors' types *)
3430 let (state, gls_rev), names_ktypes =
3431 CList.fold_left_map (fun (state, extra) t ->
3432
3433 match E.look ~depth t with
3434 | E.App(c,name,[ty]) when c == constructorc ->
3435 begin match E.look ~depth name with
3436 | E.CData name when CD.is_string name ->
3437 let name = Id.of_string (CD.to_string name) in
3438 let state, params, impls, ty, gls = readback_arity ~depth coq_ctx constraints state ty in
3439 (state, gls :: extra), (name, ty, params, List.rev impls)
3440 | _ -> err Pp.(str"@gref expected: " ++
3441 str (pp2string P.(term depth) name))
3442 end
3443 | _ -> err Pp.(str"constructor expected: " ++
3444 str (pp2string P.(term depth) t)))
3445 (state,[]) ks in
3446 let knames, ktypes, kparams, kimpls = CList.split4 names_ktypes in
3447
3448 let sigma = get_sigma state in
3449
3450 (* Handling of non-uniform parameters *)
3451 let nupno = List.length nuparams in
3452 let ktypes = CList.map3 (check_consistency_and_drop_nuparams sigma nuparams) knames kparams ktypes in
3453 let kimpls = List.map (fun x -> impls @ x) kimpls in
3454
3455 (* Relocation to match Coq's API.
3456 * From
3457 * Params, Ind, NuParams |- ktys
3458 * To
3459 * Ind, Params, NuParams |- ktys
3460 * This latter context is called, later, env_ar_params
3461 *)
3462 let ktypes = ktypes |> List.map (fun t ->
3463 let subst = CList.init (nupno + paramno + 1) (fun i ->
3464 if i < nupno then EC.mkRel (i+1)
3465 else if i = nupno then
3466 let ind = EC.mkRel (nupno + paramno + 1) in
3467 if paramno = 0 then ind
3468 else
3469 let ps =
3470 CArray.init paramno (fun i -> EC.mkRel (nupno + paramno - i)) in
3471 EC.mkApp (ind,ps)
3472 else EC.mkRel i) in
3473 EC.Vars.substl subst t
3474 ) in
3475
3476 let state, (melims, mind, ubinders, uctx) =
3477 let private_ind = false in
3478 let state, poly, cumulative, udecl, variances =
3479 poly_cumul_udecl_variance_of_options state coq_ctx.options in
3480 let state, name = mk_coq_name state itname in
3481 let the_type =
3482 let open Context.Rel.Declaration in
3483 LocalAssum(name, EConstr.it_mkProd_or_LetIn arity (nuparams @ params)) in
3484 let env_ar_params = (Global.env ()) |> EC.push_rel the_type |> EC.push_rel_context (nuparams @ params) in
3485
3486 (* restruction to used universes *)
3487 let state = minimize_universes state in
3488 let used =
3489 List.fold_left (fun acc t ->
3490 Univ.Level.Set.union acc
3491 (universes_of_term state t))
3492 (universes_of_term state arity) ktypes in
3493 let used =
3494 let open Context.Rel.Declaration in
3495 List.fold_left (fun acc -> function
3496 | (LocalDef(_,t,b)) ->
3497 Univ.Level.Set.union acc
3498 (Univ.Level.Set.union
3499 (universes_of_term state t)
3500 (universes_of_term state b))
3501 | (LocalAssum(_,t)) ->
3502 Univ.Level.Set.union acc
3503 (universes_of_term state t))
3504 used (nuparams @ params) in
3505 let sigma = restricted_sigma_of used state in
3506
3507 state, comInductive_interp_mutual_inductive_constr
3508 ~sigma
3509 ~template:(Some false)
3510 ~udecl
3511 ~variances
3512 ~ctx_params:(nuparams @ params)
3513 ~arities:[arity]
3514 ~constructors:[knames, ktypes]
3515 ~env_ar_params
3516 ~cumulative
3517 ~poly
3518 ~private_ind
3519 ~finite:finiteness
3520 ~indnames:[itname] |> comInductive_interp_mutual_inductive_constr_post
3521 in
3522 let mind = { mind with
3523 Entries.mind_entry_record =
3524 if finiteness = Declarations.BiFinite then
3525 if coq_ctx.options.primitive = Some true then Some (Some [|Names.Id.of_string "record"|]) (* primitive record *)
3526 else Some None (* regular record *)
3527 else None } (* not a record *) in
3528 let i_impls = impls @ nuimpls in
3529
3530 state, melims, mind, uctx, ubinders, i_impls, kimpls, List.(concat (rev gls_rev))
3531 in
3532
3533 let rec aux_fields depth state ind fields =
3534 match E.look ~depth fields with
3535 | E.App(c,atts,[n; ty; fields]) when c == fieldc ->
3536 begin match E.look ~depth fields with
3537 | E.Lam fields ->
3538 let state, fs, tf, gl = aux_fields (depth+1) state ind fields in
3539 let state, name, gl0 = in_coq_name ~depth state n in
3540 let state, atts, gl1 = record_field_attributes.API.Conversion.readback ~depth state atts in
3541 state, { name = name.Context.binder_name; is_coercion = is_coercion_att atts; is_canonical = is_canonical_att atts } :: fs,
3542 in_elpi_prod name ty tf, gl0 :: gl1 :: gl
3543 | _ -> err Pp.(str"field/end-record expected: "++
3544 str (pp2string P.(term depth) fields))
3545 end
3546 | E.Const c when c == end_recordc -> state, [], ind, []
3547 | _ -> err Pp.(str"field/end-record expected: "++
3548 str (pp2string P.(term depth) fields))
3549 in
3550
3551 let constructor_blocks_of_lp ~depth blocks =
3552 U.lp_list_to_list ~depth blocks |>
3553 List.map (fun block -> U.lp_list_to_list ~depth block)
3554 in
3555
3556 let relocate_mutual_constructor_type ~paramsno ~ninds t =
3557 let subst = CList.init (paramsno + ninds) (fun i ->
3558 let rel = i + 1 in
3559 if rel <= ninds then
3560 let ind = EC.mkRel (paramsno + rel) in
3561 if paramsno = 0 then ind
3562 else
3563 let ps = CArray.init paramsno (fun i -> EC.mkRel (paramsno - i)) in
3564 EC.mkApp (ind, ps)
3565 else EC.mkRel (rel - ninds)) in
3566 EC.Vars.substl subst t
3567 in
3568
3569 let aux_mutual_constructors coq_ctx ~depth (params,impls) inds state constructor_blocks =
3570 let params = force_name_ctx params in
3571 let paramsno = List.length params in
3572 let ninds = List.length inds in
3573 if List.length constructor_blocks <> ninds then
3574 err Pp.(str"mblock: expected " ++ int ninds ++ str" constructor blocks, got " ++
3575 int (List.length constructor_blocks));
3576 let state, constructor_infos, gls_rev =
3577 List.fold_left2 (fun (state, infos, gls_acc) (name, nuparams, nuimpls, arity, _kind) ks ->
3578 if nuparams <> [] then nYI "non-uniform parameters in mutual inductives";
3579 let (state, gls_rev), names_ktypes_impls =
3580 CList.fold_left_map (fun (state, extra) t ->
3581 match E.look ~depth t with
3582 | E.App(c,kname,[ty]) when c == constructorc ->
3583 begin match E.look ~depth kname with
3584 | E.CData kname when CD.is_string kname ->
3585 let kname = Id.of_string (CD.to_string kname) in
3586 let state, kparams, kimpls, ty, gls = readback_arity ~depth coq_ctx constraints state ty in
3587 let ty = check_consistency_and_drop_nuparams (get_sigma state) nuparams kname kparams ty in
3588 let ty = relocate_mutual_constructor_type ~paramsno ~ninds ty in
3589 (state, gls :: extra), (kname, ty, impls @ (List.rev nuimpls) @ kimpls)
3590 | _ -> err Pp.(str"@gref expected: " ++ str (pp2string P.(term depth) kname))
3591 end
3592 | _ -> err Pp.(str"constructor expected: " ++ str (pp2string P.(term depth) t)))
3593 (state,[]) ks in
3594 let knames, ktypes, kimpls = CList.split3 names_ktypes_impls in
3595 state, (name, arity, knames, ktypes, impls @ List.rev nuimpls, kimpls) :: infos, gls_rev @ gls_acc)
3596 (state, [], []) inds constructor_blocks in
3597 let constructor_infos = List.rev constructor_infos in
3598 let indnames = List.map (fun (name, _, _, _, _, _) -> name) constructor_infos in
3599 let arities = List.map (fun (_, arity, _, _, _, _) -> arity) constructor_infos in
3600 let constructors = List.map (fun (_, _, knames, ktypes, _, _) -> knames, ktypes) constructor_infos in
3601 let ind_impls = List.map (fun (_, _, _, _, i_impls, k_impls) -> i_impls, k_impls) constructor_infos in
3602 let finiteness =
3603 match inds with
3604 | [] -> err Pp.(str"mblock: empty mutual inductive block")
3605 | (_, _, _, _, kind) :: rest ->
3606 if List.for_all (fun (_, _, _, _, kind') -> kind = kind') rest then kind
3607 else err Pp.(str"mblock: cannot mix inductive and coinductive declarations") in
3608 let state, (melims, mind, ubinders, uctx) =
3609 let private_ind = false in
3610 let state, poly, cumulative, udecl, variances =
3611 poly_cumul_udecl_variance_of_options state coq_ctx.options in
3612 let ind_types =
3613 List.mapi (fun i (name, arity) ->
3614 let ty = EConstr.it_mkProd_or_LetIn arity params in
3615 Context.Rel.Declaration.LocalAssum(EConstr.nameR name, EConstr.Vars.lift i ty))
3616 (List.combine indnames arities) in
3617 let env_ar_params =
3618 let env_ar = List.fold_left (fun env ind_type -> EC.push_rel ind_type env) (Global.env ()) ind_types in
3619 EC.push_rel_context params env_ar in
3620 let state = minimize_universes state in
3621 let used =
3622 List.fold_left (fun acc t ->
3623 Univ.Level.Set.union acc (universes_of_term state t))
3624 Univ.Level.Set.empty arities in
3625 let used =
3626 List.fold_left (fun acc (_, ktypes) ->
3627 List.fold_left (fun acc t -> Univ.Level.Set.union acc (universes_of_term state t)) acc ktypes)
3628 used constructors in
3629 let used =
3630 let open Context.Rel.Declaration in
3631 List.fold_left (fun acc -> function
3632 | LocalDef(_,t,b) ->
3633 Univ.Level.Set.union acc
3634 (Univ.Level.Set.union (universes_of_term state t) (universes_of_term state b))
3635 | LocalAssum(_,t) -> Univ.Level.Set.union acc (universes_of_term state t))
3636 used params in
3637 let sigma = restricted_sigma_of used state in
3638 state, comInductive_interp_mutual_inductive_constr
3639 ~sigma
3640 ~template:(Some false)
3641 ~udecl
3642 ~variances
3643 ~ctx_params:params
3644 ~arities
3645 ~constructors
3646 ~env_ar_params
3647 ~cumulative
3648 ~poly
3649 ~private_ind
3650 ~finite:finiteness
3651 ~indnames |> comInductive_interp_mutual_inductive_constr_post
3652 in
3653 state, (melims, mind, uctx, ubinders, None, ind_impls), List.concat (List.rev gls_rev)
3654 in
3655
3656
3657 let rec aux_decl coq_ctx ~depth params impls state extra t =
3658
3659 match E.look ~depth t with
3660 | E.App(c,name,[imp;ty;decl]) when is_coq_name ~depth name && c == inductive_parameterc ->
3661 let state, name, gl0 = in_coq_annot ~depth state name in
3662 let state, imp = in_coq_imp ~depth state imp in
3663 let state, ty, gls = lp2constr coq_ctx ~depth state ty in
3664 let e = Context.Rel.Declaration.LocalAssum(name,ty) in
3665 aux_lam e coq_ctx ~depth (e :: params) (manual_implicit_of_binding_kind (Context.binder_name name) imp :: impls) state (gls :: extra) decl
3666 | E.App(c,id,[fin;arity;rest])
3667 when c == minductivec ->
3668 let state, e, fin, iname, nuparams, nuimpls, arity, gl1 =
3669 aux_inductive ~depth id fin arity coq_ctx state in
3670 aux_mind_lam e coq_ctx ~depth params impls [(iname, nuparams, List.rev nuimpls, arity, fin)] state (gl1 :: extra) rest
3671 | E.App(c,id,[fin;arity;ks])
3672 when c == inductivec ->
3673 let state, e, fin, iname, nuparams, nuimpls, arity, gl1 =
3674 aux_inductive ~depth id fin arity coq_ctx state in
3675 aux_ind_lam e coq_ctx ~depth params impls state ks nuparams nuimpls arity iname fin (gl1 :: extra)
3676 | E.App(c,id,[arity;kn;fields]) when c == recordc ->
3677 begin match E.look ~depth kn with
3678 | E.CData kname when CD.is_string kname ->
3679
3680 let state, arity, gl1 = lp2constr coq_ctx ~depth state arity in
3681
3682 let state, name, gl2 = in_coq_annot ~depth state id in
3683 if Name.is_anonymous (Context.binder_name name) then
3684 err Pp.(str"id expected, got: "++ str (pp2string P.(term depth) id));
3685 let e = Context.Rel.Declaration.LocalAssum(name,arity) in
3686 let iname =
3687 match Context.binder_name name with Name x -> x | _ -> assert false in
3688 let fields = U.move ~from:depth ~to_:(depth+1) fields in
3689 (* We simulate the missing binders for the inductive *)
3690 let ind = E.mkConst depth in
3691 let state, fields_names_coercions, kty, gl3 = aux_fields (depth+1) state ind fields in
3692 let k = [E.mkApp constructorc kn [in_elpi_arity kty]] in
3693 let state, melims, idecl, uctx, ubinders, i_impls, ks_impls, gl4 =
3694 aux_construtors (push_coq_ctx_local depth e coq_ctx) ~depth:(depth+1) (params,List.rev impls) ([],[]) arity iname Declarations.BiFinite
3695 state k in
3696 let primitive = coq_ctx.options.primitive = Some true in
3697 state, (melims, idecl, uctx, ubinders, Some (primitive,fields_names_coercions), [i_impls, ks_impls]), List.(concat (rev (gl2 :: gl1 :: extra)))
3698 | _ -> err Pp.(str"id expected, got: "++
3699 str (pp2string P.(term depth) kn))
3700 end
3701 | _ -> err Pp.(str"(co)inductive/record expected: "++
3702 str (pp2string P.(term depth) t))
3703 and aux_lam e coq_ctx ~depth params impls state extra t =
3704 match E.look ~depth t with
3705 | E.Lam t -> aux_decl (push_coq_ctx_local depth e coq_ctx) ~depth:(depth+1) params impls state extra t
3706 | _ -> err Pp.(str"lambda expected: " ++
3707 str (pp2string P.(term depth) t))
3708 and aux_inductive ~depth id fin arity coq_ctx state =
3709 let state, name, gl0 = in_coq_annot ~depth state id in
3710 if Name.is_anonymous (Context.binder_name name) then
3711 err Pp.(str"id expected, got: "++ str (pp2string P.(term depth) id));
3712 let fin = if in_coq_bool ~depth state ~default:true fin then Declarations.Finite else Declarations.CoFinite in
3713 let state, nuparams, nuimpls, arity, gl1 = readback_arity ~depth coq_ctx constraints state arity in
3714 let e = Context.Rel.Declaration.LocalAssum(name,arity) in
3715 let iname =
3716 match Context.binder_name name with Name x -> x | _ -> assert false in
3717 state, e, fin, iname, nuparams, nuimpls, arity, gl0 @ gl1
3718
3719 and aux_mind_decl coq_ctx ~depth params impls inds state extra t =
3720 match E.look ~depth t with
3721 | E.App(c,id,[fin;arity;rest]) when c == minductivec ->
3722 let state, e, fin, iname, nuparams, nuimpls, arity, gl1 =
3723 aux_inductive ~depth id fin arity coq_ctx state in
3724 aux_mind_lam e coq_ctx ~depth params impls ((iname, nuparams, List.rev nuimpls, arity, fin) :: inds) state (gl1 :: extra) rest
3725 | E.App(c,blocks,[]) when c == mblockc ->
3726 let inds = List.rev inds in
3727 let constructor_blocks = constructor_blocks_of_lp ~depth blocks in
3728 let state, res, gl2 = aux_mutual_constructors coq_ctx ~depth (params,List.rev impls) inds state constructor_blocks in
3729 state, res, List.(concat (rev (gl2 :: extra)))
3730 | _ -> err Pp.(str"minductive/mblock expected: " ++ str (pp2string P.(term depth) t))
3731 and aux_ind_lam e coq_ctx ~depth params impls state ks nuparams nuimpls arity iname fin extra =
3732 match E.look ~depth ks with
3733 | E.Lam t ->
3734 let ks = U.lp_list_to_list ~depth:(depth+1) t in
3735 let state, melims, idecl, uctx, ubinders, i_impls, ks_impls, gl2 =
3736 aux_construtors (push_coq_ctx_local depth e coq_ctx) ~depth:(depth+1) (params,List.rev impls) (nuparams, List.rev nuimpls) arity iname fin
3737 state ks in
3738 state, (melims, idecl, uctx, ubinders, None, [i_impls, ks_impls]), List.(concat (rev (gl2 :: extra)))
3739 | _ -> err Pp.(str"lambda expected: " ++
3740 str (pp2string P.(term depth) ks))
3741
3742 and aux_mind_lam e coq_ctx ~depth params impls inds state extra t =
3743 match E.look ~depth t with
3744 | E.Lam t -> aux_mind_decl (push_coq_ctx_local depth e coq_ctx) ~depth:(depth+1) params impls inds state extra t
3745 | _ -> err Pp.(str"lambda expected: " ++ str (pp2string P.(term depth) t))
3746 in
3747 aux_decl coq_ctx ~depth [] [] state [] t
3748 ;;
3749
3750 let rec safe_combine3 l1 l2 l3 ~default3 =
3751 match l1, l2, l3 with
3752 | [], [], [] -> []
3753 | x::xs, y::ys, z::zs -> (x,y,z) :: safe_combine3 xs ys zs ~default3
3754 | x::xs, y::ys, [] -> (x,y,default3) :: safe_combine3 xs ys [] ~default3
3755 | _ -> raise (Invalid_argument "safe_combine3")
3756
3757 let rec safe_combine2_impls l1 l2 ~default2 =
3758 match l1, l2 with
3759 | [], _ -> []
3760 | x::xs, y::ys -> (x,y) :: safe_combine2_impls xs ys ~default2
3761 | x::xs, [] -> (x,default2) :: safe_combine2_impls xs [] ~default2
3762 let safe_combine2_impls l1 l2 ~default2 =
3763 let l = safe_combine2_impls (List.rev l1) l2 ~default2 in
3764 List.rev l
3765
3766
3767 (* convention: nuparams are also in each constructor *)
3768 type 'a ctx_entry = { id : Id.t; typ : EConstr.t; extra : 'a }
3769 type constructor = { id : Id.t; arity : Glob_term.binding_kind ctx_entry list; typ : EConstr.t }
3770 type inductive_decl = {
3771 id : Id.t;
3772 nuparams : Glob_term.binding_kind ctx_entry list;
3773 typ : EConstr.t;
3774 constructors : constructor list;
3775 kind : Declarations.recursivity_kind;
3776 }
3777 type record_decl = {
3778 id : Id.t;
3779 kid : Id.t;
3780 typ : EConstr.t;
3781 fields : record_field_att list ctx_entry list;
3782 }
3783 type ind_decl =
3784 | Inductive of inductive_decl
3785 | Record of record_decl
3786 | Mutual of inductive_decl list
3787 type hoas_ind = {
3788 params : Glob_term.binding_kind ctx_entry list;
3789 decl : ind_decl;
3790 }
3791
3792 let mk_inductive_parameter2 ~depth name impl ty rest state =
3793 let state, imp = in_elpi_imp ~depth state impl in
3794 state, in_elpi_inductive_parameter ~imp name ty rest
3795 let mk_arity_parameter2 ~depth name impl ty rest state =
3796 let state, imp = in_elpi_imp ~depth state impl in
3797 state, in_elpi_arity_parameter ~imp name ty rest
3798
3799 let mk_ctx_item_record_field ~depth name atts ty rest state =
3800 let state, atts, gls = record_field_attributes.API.Conversion.embed ~depth state (Elpi.Builtin.Given atts) in
3801 state, in_elpi_field atts (Context.binder_name name) ty rest
3802
3803 let under_coq2elpi_relctx ~calldepth state (ctx : 'a ctx_entry list) ~coq_ctx ~mk_ctx_item kont =
3804 let gls = ref [] in
3805 let rec aux ~depth coq_ctx hyps state = function
3806 | [] ->
3807 let state, t, gls_t = kont coq_ctx hyps ~depth state in
3808 gls := gls_t @ !gls;
3809 state, t
3810 | { id; typ; extra } :: rest ->
3811 let state, name = mk_coq_name state id in
3812 let state, ty, gls_ty = constr2lp coq_ctx ~calldepth ~depth state typ in
3813 gls := gls_ty @ !gls;
3814 let hyp = mk_decl ~depth name ~ty in
3815 let hyps = { E.hsrc = hyp ; hdepth = depth } :: hyps in
3816 let e = Context.Rel.Declaration.LocalAssum (name, typ) in
3817 let coq_ctx = push_coq_ctx_local depth e coq_ctx in
3818 let state, rest = aux ~depth:(depth+1) coq_ctx hyps state rest in
3819 mk_ctx_item ~depth name extra ty rest state
3820 in
3821 let state, t = aux ~depth:calldepth coq_ctx [] state (List.rev ctx) in
3822 state, t, !gls
3823 ;;
3824
3825 [%%if coq = "9.0" || coq = "9.1"]
3826 let inst_opt_names inst_opt = inst_opt
3827 [%%else]
3828 let inst_opt_names inst_opt = Option.map EConstr.EInstance.make inst_opt
3829 [%%endif]
3830
3831 let type_of_global state r inst_opt = API.State.update_return engine state (fun x ->
3832 let names = inst_opt_names inst_opt in
3833 let sigma, c = Evd.fresh_global x.global_env x.sigma r ?names in
3834 let ty = Retyping.get_type_of x.global_env sigma c in
3835 { x with sigma }, (ty, EConstr.Unsafe.to_instance @@ snd @@ EConstr.destRef sigma c))
3836
3837
3838 let compute_with_uinstance ~depth options state f x inst_opt =
3839 match options.uinstance with
3840 | NoInstance ->
3841 let state, r, i = f state x inst_opt in
3842 state, r, i, []
3843 | ConcreteInstance i ->
3844 let state, r, i = f state x (Option.append inst_opt (Some i)) in
3845 state, r, i, []
3846 | VarInstance (v_head, v_args, v_depth) ->
3847 let state, r, i = f state x inst_opt in
3848 match i with
3849 | None -> state, r, None, []
3850 | Some uinst ->
3851 let v' = U.move ~from:v_depth ~to_:depth (E.mkUnifVar v_head ~args:v_args state) in
3852 let state, lp_uinst, extra_goals = uinstance.API.Conversion.embed ~depth state uinst in
3853 state, r, Some uinst, API.Conversion.Unify (v', lp_uinst) :: extra_goals
3854
3855
3856 let embed_arity ~depth coq_ctx state (relctx,ty) =
3857 let calldepth = depth in
3858 under_coq2elpi_relctx ~calldepth ~coq_ctx state relctx
3859 ~mk_ctx_item:mk_arity_parameter2
3860 (fun coq_ctx hyps ~depth state ->
3861 let state, ty, gl = constr2lp coq_ctx ~calldepth ~depth state ty in
3862 state, in_elpi_arity ty, gl)
3863 ;;
3864
3865
3866 let hoas_ind2lp ~depth coq_ctx state { params; decl } =
3867 let calldepth = depth in
3868 under_coq2elpi_relctx ~calldepth ~coq_ctx state params
3869 ~mk_ctx_item:mk_inductive_parameter2
3870 (fun coq_ctx hyps ~depth state -> match decl with
3871 | Inductive _
3872 | Mutual _ ->
3873 let inds =
3874 match decl with
3875 | Mutual l -> l | Inductive x -> [x] | Record _ -> assert false in
3876 let ninds = List.length inds in
3877 let sigma = get_sigma state in
3878 let paramsno = List.length params in
3879 (* Relocation to match Coq's API.
3880 * From
3881 * Ind, Params, NuParams |- ktys
3882 * To
3883 * Params, Ind, NuParams |- ktys
3884 *)
3885 let rec iter n acc f =
3886 if n = 0 then acc
3887 else iter (n-1) (f acc) f in
3888 let subst arityno = CList.init (arityno + paramsno + ninds) (fun i ->
3889 let i = i + 1 in
3890 if i <= arityno then EC.mkRel i
3891 else if i <= arityno + paramsno then EC.mkRel (i + ninds)
3892 else
3893 let indno = i - arityno - paramsno in
3894 let ind = EC.mkRel (arityno + indno) in
3895 iter paramsno ind (fun x -> EConstr.mkLambda (EConstr.anonR,EConstr.mkProp,EConstr.Vars.lift 1 x))) in
3896 let reloc ctx_len t =
3897 let t = EC.Vars.substl (subst ctx_len) t in
3898 Reductionops.nf_beta (Global.env()) sigma t in
3899 let rec embed_arities coq_ctx depth state = function
3900 | [] -> state, [], coq_ctx, depth, []
3901 | { id; nuparams; typ; _ } :: rest ->
3902 let state, arity, gls = embed_arity ~depth coq_ctx state (nuparams,typ) in
3903 let coq_ctx = push_coq_ctx_local depth (Context.Rel.Declaration.LocalAssum(EConstr.anonR,EConstr.mkProp)) coq_ctx in
3904 let state, arities, coq_ctx, depth, gls_rest = embed_arities coq_ctx (depth+1) state rest in
3905 state, arity :: arities, coq_ctx, depth, gls @ gls_rest in
3906 let state, arities, coq_ctx, depth, gls1 = embed_arities coq_ctx depth state inds in
3907 let embed_constructor state { id; arity; typ } =
3908 let alen = List.length arity in
3909 let kctx = List.mapi (fun i ({ extra; typ } as x) -> { x with typ = reloc (alen - i -1) typ }) arity in
3910 let state, karity, gl = embed_arity ~depth coq_ctx state (kctx,reloc alen typ) in
3911 state, in_elpi_indtdecl_constructor (Name id) karity, gl in
3912 begin match decl with
3913 | Record _ -> assert false
3914 | Mutual _ ->
3915 let embed_constructor_block state { constructors; _ } =
3916 API.Utils.map_acc embed_constructor state constructors in
3917 let state, constructor_blocks, gls2 =
3918 API.Utils.map_acc embed_constructor_block state inds in
3919 let body = in_elpi_indtdecl_mblock constructor_blocks in
3920 let body =
3921 List.fold_right2 (fun { id; kind; _ } arity body ->
3922 in_elpi_indtdecl_minductive state kind (Name id) arity body)
3923 inds arities body in
3924 state, body, List.flatten [gls1; gls2]
3925 | Inductive { constructors; id; kind } ->
3926 let state, ks, gls2 =
3927 API.Utils.map_acc embed_constructor state constructors in
3928 state, in_elpi_indtdecl_inductive state kind (Name id) (List.hd arities) ks, List.flatten [gls1 ; gls2]
3929 end
3930 | Record { id; kid; typ; fields } ->
3931 let embed_record_constructor state fields =
3932 under_coq2elpi_relctx ~calldepth:depth state fields
3933 ~coq_ctx
3934 ~mk_ctx_item:mk_ctx_item_record_field
3935 (fun coq_ctx hyps ~depth state -> state, in_elpi_indtdecl_endrecord (), [])
3936 in
3937 let state, sort, gls1 = constr2lp coq_ctx ~calldepth ~depth state typ in
3938 let state, rd, gls2 = embed_record_constructor state fields in
3939 state, in_elpi_indtdecl_record (Name id) sort (Name kid) rd, gls1 @ gls2
3940 )
3941 ;;
3942
3943 let param2ctx l =
3944 let open Context.Rel.Declaration in
3945 List.map (function
3946 | LocalAssum( { Context.binder_name = Anonymous },typ), (Glob_term.Explicit as bk) -> { id = Id.of_string "_"; typ; extra = bk }
3947 | LocalAssum( { Context.binder_name = Name id },typ), bk -> { id; typ; extra = bk }
3948 | LocalDef _, _ -> nYI "let-in in inductive parameters"
3949 | _ -> assert false) l
3950
3951 let nonexpimpls impls =
3952 let rec aux = function
3953 | [] -> []
3954 | Glob_term.Explicit :: l -> aux l
3955 | l -> l in
3956 aux (List.rev impls)
3957
3958 let drop_nparams_from_ctx n ctx =
3959 let ctx, _ = CList.chop (List.length ctx - n) ctx in
3960 ctx
3961
3962 let ideclc = E.Constants.declare_global_symbol "indt-decl"
3963 let uideclc = E.Constants.declare_global_symbol "upoly-indt-decl"
3964
3965
3966 [%%if coq = "9.0" || coq = "9.1"]
3967 let mind_record (mib,_) = mib.Declarations.mind_record
3968 [%%else]
3969 let mind_record (_,mip) = mip.Declarations.mind_record
3970 [%%endif]
3971
3972 [%%if coq = "9.0" || coq = "9.1"]
3973 let find_structure env ind = Structures.Structure.find ind
3974 [%%else]
3975 let find_structure env ind = Structures.Structure.find env ind
3976 [%%endif]
3977
3978
3979 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
3980 let get_template_instance mind uinst = uinst
3981 [%%else]
3982 let get_template_instance mind uinst = match mind.Declarations.mind_template with
3983 | None -> uinst
3984 | Some templ -> templ.template_defaults
3985 [%%endif]
3986
3987 let inductive_decl2lp ~depth coq_ctx constraints state (mutind,uinst,mind,(i_impls,k_impls)) =
3988 let { Declarations.mind_params_ctxt;
3989 mind_finite = kind;
3990 mind_nparams = allparamsno;
3991 mind_nparams_rec = paramsno;
3992 } = mind in
3993 let t_uinst = get_template_instance mind uinst in
3994 let ntyps = Array.length mind.mind_packets in
3995 let mind_params_ctxt = Vars.subst_instance_context t_uinst mind_params_ctxt in
3996 let allparams = List.map EConstr.of_rel_decl mind_params_ctxt in
3997 let i_impls0 = match i_impls with [] -> [] | x :: _ -> x in
3998 let allparams = safe_combine2_impls allparams i_impls0 ~default2:Glob_term.Explicit |> param2ctx in
3999 let nuparamsno = allparamsno - paramsno in
4000 let nuparams, params = CList.chop nuparamsno allparams in
4001
4002 let sigma = get_sigma state in
4003 let drop_nparams_from_term n x =
4004 let x = EConstr.of_constr x in
4005 let ctx, sort = EConstr.decompose_prod_decls sigma x in
4006 let ctx = drop_nparams_from_ctx n ctx in
4007 EConstr.it_mkProd_or_LetIn sort ctx in
4008 let one_inductive_decl ind_index ind _i_impls k_impls =
4009 let { Declarations.mind_consnames = constructor_names;
4010 mind_typename = id;
4011 mind_nf_lc = constructor_types;
4012 } = ind in
4013 let mind_record = mind_record (mind,ind) in
4014 let constructor_types =
4015 constructor_types |> Array.map (fun (ctx,ty) ->
4016 Vars.subst_instance_context t_uinst ctx, Vars.subst_instance_constr t_uinst ty) in
4017 let arity_w_params = Inductive.type_of_inductive ((mind,ind),uinst) in
4018 if mind_record = Declarations.NotRecord then
4019 let typ = drop_nparams_from_term allparamsno arity_w_params in
4020 let constructor_names = Array.to_list constructor_names in
4021 let constructor_types = Array.to_list constructor_types in
4022 if List.length constructor_names <> List.length constructor_types ||
4023 List.length k_impls > List.length constructor_names then
4024 err Pp.(str"ill-shaped mutual inductive constructor metadata for " ++ Id.print id ++
4025 str": names=" ++ int (List.length constructor_names) ++
4026 str" types=" ++ int (List.length constructor_types) ++
4027 str" implicits=" ++ int (List.length k_impls));
4028 let constructors =
4029 safe_combine3 constructor_names constructor_types k_impls ~default3:[] |>
4030 List.map (fun (id,(ctx,x),impls) ->
4031 let x =
4032 Term.it_mkProd_or_LetIn x ctx |>
4033 Inductive.abstract_constructor_type_relatively_to_inductive_types_context ntyps mutind in
4034 let nonexpimplsno = List.length (nonexpimpls impls) in
4035 let ctx, typ = Term.decompose_prod_n_decls (max allparamsno nonexpimplsno) x in
4036 let ctx = EConstr.of_rel_context ctx in
4037 let typ = EConstr.of_constr typ in
4038 let ctx = safe_combine2_impls ctx impls ~default2:Glob_term.Explicit in
4039 let arity = drop_nparams_from_ctx paramsno ctx |> param2ctx in
4040 { id; arity; typ }) in
4041 Inductive { nuparams; id; typ; kind; constructors }
4042 else begin
4043 if ntyps <> 1 then nYI "mutual records";
4044 let kid = constructor_names.(0) in
4045 if (nuparamsno != 0) then nYI "record with non uniform paramters";
4046 let env = get_global_env state in
4047 let projections = (find_structure env (mutind,ind_index)).Structures.Structure.projections in
4048 let fieldsno = List.length projections in
4049 let kctx, _ = constructor_types.(0) in
4050 let kctx = EConstr.of_rel_context kctx in
4051 let kctx = drop_nparams_from_ctx paramsno kctx in
4052 if (List.length kctx != fieldsno) then CErrors.anomaly Pp.(str"record fields number != projections");
4053 let typ = drop_nparams_from_term allparamsno arity_w_params in
4054 let open Structures.Structure in
4055 let fields_atts = List.map (fun { proj_name; proj_body; proj_canonical; } ->
4056 proj_name,
4057 (match proj_body with
4058 | None -> Coercion Off
4059 | Some c ->
4060 try
4061 let { Coercionops.coe_reversible } = Coercionops.coercion_info (Names.GlobRef.ConstRef c) in
4062 Coercion (if coe_reversible then Reversible else Regular)
4063 with Not_found -> Coercion Off) ::
4064 (Canonical proj_canonical) :: [])
4065 (List.rev projections) in
4066 let param2field l =
4067 let open Context.Rel.Declaration in
4068 List.map (function
4069 | LocalAssum( { Context.binder_name = Anonymous },typ), (Anonymous,atts) -> { id = Id.of_string "_"; typ; extra = atts }
4070 | LocalAssum( { Context.binder_name = Name id },typ), (Name id1,atts) when Id.equal id id1 -> { id; typ; extra = atts }
4071 | LocalAssum _, _ -> CErrors.anomaly Pp.(str"record fields names != projections");
4072 | LocalDef _, _ -> nYI "let-in in record fields parameters") l in
4073 let fields = List.combine kctx fields_atts |> param2field in
4074 Record { id; kid; typ; fields }
4075 end
4076 in
4077 let packets = Array.to_list mind.mind_packets in
4078 let rec pad_impls xs ys default =
4079 match xs, ys with
4080 | [], _ -> []
4081 | _ :: xs, y :: ys -> y :: pad_impls xs ys default
4082 | _ :: xs, [] -> default :: pad_impls xs [] default in
4083 let i_impls = pad_impls packets i_impls [] in
4084 let k_impls = pad_impls packets k_impls [] in
4085 let decls = List.mapi (fun i ind ->
4086 let i_impls_i = List.nth i_impls i in
4087 let k_impls_i = List.nth k_impls i in
4088 one_inductive_decl i ind i_impls_i k_impls_i) packets in
4089 let decl = match decls with
4090 | [decl] -> decl
4091 | decls ->
4092 Mutual (List.map (function Inductive d -> d | Record _ -> nYI "mutual records" | Mutual _ -> assert false) decls) in
4093 let ind = { params; decl } in
4094 hoas_ind2lp ~depth coq_ctx state ind
4095 ;;
4096 let upoly_decl_of ~depth state ~loose_udecl mie =
4097 let open Entries in
4098 match mie.mind_entry_universes with
4099 | Template_ind_entry _ -> nYI "template polymorphic inductives"
4100 | Polymorphic_ind_entry uc ->
4101 let qvars, vars = UVars.Instance.to_array @@ UVars.UContext.instance uc in
4102 if not (CArray.is_empty qvars) then nYI "sort poly inductives"
4103 else
4104 let state, vars = CArray.fold_left_map (fun s l -> fst (name_universe_level s l), l) state vars in
4105 let csts = univs_of_csts uc in
4106 begin match mie.mind_entry_variance with
4107 | None ->
4108 let state, up, gls = universe_decl.API.Conversion.embed ~depth state (NonCumul ((Array.to_list vars,loose_udecl),(csts,loose_udecl))) in
4109 state, (fun i -> E.mkApp uideclc i [up]), gls
4110 | Some variance ->
4111 assert(Array.length variance = Array.length vars);
4112 let uv = Array.map2 (fun x y -> (x,y)) vars variance |> Array.to_list in
4113 let state, up, gls = universe_decl.API.Conversion.embed ~depth state (Cumul((uv,loose_udecl),(csts,loose_udecl))) in
4114 state, (fun i -> E.mkApp uideclc i [up]), gls
4115 end
4116 | Monomorphic_ind_entry -> state, (fun i -> E.mkApp ideclc i []), []
4117
4118 [%%if coq = "9.0" || coq = "9.1"]
4119 let merge_ucontext sigma cs =
4120 Evd.merge_context_set UState.univ_flexible sigma (snd (UVars.UContext.to_context_set cs))
4121 [%%else]
4122 let merge_ucontext sigma cs =
4123 let (qs, us), (qcst, ucst) = UVars.UContext.to_context_set cs in
4124 Evd.merge_sort_context_set UState.univ_flexible sigma ((qs, qcst), (us, ucst))
4125 [%%endif]
4126
4127 let inductive_entry2lp ~depth coq_ctx constraints state ~loose_udecl e =
4128 let open ComInductive.Mind_decl in
4129 let open Entries in
4130 let { mie; nuparams; univ_binders; implicits; uctx } = e in
4131 let i_impls, k_impls =
4132 List.map (fun (i,k) ->
4133 List.map binding_kind_of_manual_implicit i,
4134 List.map (List.map binding_kind_of_manual_implicit) k) implicits
4135 |> List.split in
4136 let indno = List.length mie.mind_entry_inds in
4137 let state =
4138 S.update engine state (fun e ->
4139 { e with sigma = merge_universe_context_set UState.univ_flexible e.sigma uctx}) in
4140 let state = match mie.mind_entry_universes with
4141 | Template_ind_entry _ -> nYI "template polymorphic inductives"
4142 | Monomorphic_ind_entry -> state
4143 | Polymorphic_ind_entry cs -> S.update engine state (fun e ->
4144 { e with sigma = merge_ucontext e.sigma cs }) (* ???? *) in
4145 let state, upoly_decl_of, upoly_decl_gls = upoly_decl_of ~depth state ~loose_udecl mie in
4146 let allparams = mie.mind_entry_params in
4147 let allparams = Vars.lift_rel_context indno allparams in
4148 let kind = mie.mind_entry_finite in
4149 let nuparamsno =
4150 match nuparams with
4151 | Some x -> x
4152 | None ->
4153 let open Declarations in
4154 match kind with
4155 | BiFinite -> 0
4156 | Finite | CoFinite ->
4157 if (allparams <> []) then inference_nonuniform_params_off ();
4158 0 in
4159 let i_impls0 = match i_impls with [] -> [] | x :: _ -> x in
4160 let allparams = EConstr.of_rel_context allparams in
4161 let allparams = safe_combine2_impls allparams i_impls0 ~default2:Glob_term.Explicit |> param2ctx in
4162 let nuparams, params = CList.chop nuparamsno allparams in
4163 let one_ind ind k_impls =
4164 let id = ind.mind_entry_typename in
4165 let typ = EConstr.of_constr ind.mind_entry_arity in
4166 let constructors = List.combine ind.mind_entry_consnames ind.mind_entry_lc in
4167 let constructors = safe_combine2_impls constructors k_impls ~default2:[] |>
4168 List.map (fun ((id,typ),_impls) ->
4169 (* FIXME, arity could be longer *)
4170 { id; arity = nuparams; typ = EConstr.of_constr typ }) in
4171 { nuparams; id; typ; kind; constructors } in
4172 let rec pad_impls xs ys default =
4173 match xs, ys with
4174 | [], _ -> []
4175 | _ :: xs, y :: ys -> y :: pad_impls xs ys default
4176 | _ :: xs, [] -> default :: pad_impls xs [] default in
4177 let k_impls = pad_impls mie.mind_entry_inds k_impls [] in
4178 let decls = List.map2 one_ind mie.mind_entry_inds k_impls in
4179 let decl = match decls with
4180 | [decl] -> Inductive decl
4181 | decls -> Mutual decls in
4182 let ind = { params; decl } in
4183 let state, i, gls = hoas_ind2lp ~depth coq_ctx state ind in
4184 state, upoly_decl_of i, gls @ upoly_decl_gls
4185 ;;
4186
4187 [%%if coq = "9.0"]
4188 let record_entry2lp ~depth coq_ctx constraints state ~loose_udecl e =
4189 let open Record.Record_decl in
4190 let open Record.Data in
4191 let open Entries in
4192 let { mie; impls; ubinders; globnames; global_univ_decls; records; _ } = e in
4193 let i_impls, k_impls = match impls with
4194 | [i,k] ->
4195 List.map binding_kind_of_manual_implicit i,
4196 List.map (List.map binding_kind_of_manual_implicit) k
4197 | _ -> nYI "mutual record" in
4198 let ind = match mie.mind_entry_inds with
4199 | [ x ] -> x
4200 | _ -> nYI "mutual record" in
4201 let record = match records with
4202 | [ x ] -> x
4203 | _ -> nYI "mutual record" in
4204 let indno = 1 in
4205
4206 let state = global_univ_decls |> Option.cata (fun ctx ->
4207 S.update engine state (fun e ->
4208 { e with sigma = Evd.merge_context_set UState.univ_flexible e.sigma ctx})) state in
4209
4210 let state = match mie.mind_entry_universes with
4211 | Template_ind_entry _ -> nYI "template polymorphic inductives"
4212 | Monomorphic_ind_entry -> state
4213 | Polymorphic_ind_entry cs -> S.update engine state (fun e ->
4214 { e with sigma = merge_ucontext e.sigma cs }) (* ???? *) in
4215
4216 let state, upoly_decl_of, upoly_decl_gls = upoly_decl_of ~depth state ~loose_udecl mie in
4217
4218 let params = mie.mind_entry_params in
4219 let params = Vars.lift_rel_context indno params in
4220
4221 let params = EConstr.of_rel_context params in
4222 let params = safe_combine2_impls params i_impls ~default2:Glob_term.Explicit |> param2ctx in
4223 let _paramsno = List.length params in
4224
4225 let id = ind.mind_entry_typename in
4226 let typ = EConstr.of_constr ind.mind_entry_arity in
4227 let kid = List.hd ind.mind_entry_consnames in
4228
4229 let fieldsno = List.length record.proj_flags in
4230 let kctx, _ = Term.decompose_prod_decls @@ List.hd ind.mind_entry_lc in
4231 let kctx = EConstr.of_rel_context kctx in
4232 if (List.length kctx != fieldsno) then CErrors.anomaly Pp.(str"record fields number != projections");
4233
4234 let fields = List.map2 (fun { pf_coercion; pf_reversible; pf_canonical } ->
4235 let open Context.Rel.Declaration in
4236 let coe_status = if pf_coercion then if pf_reversible then Reversible else Regular else Off in
4237 function
4238 | LocalAssum( { Context.binder_name = Anonymous },typ) ->
4239 { id = Id.of_string "_"; typ; extra = [Coercion coe_status; Canonical pf_canonical] }
4240 | LocalAssum( { Context.binder_name = Name id },typ) ->
4241 { id; typ; extra = [Coercion coe_status; Canonical pf_canonical] }
4242 | _ -> nYI "let-in in record fields"
4243 ) (List.rev record.proj_flags) kctx in
4244
4245 let ind = { params; decl = Record { id; kid; typ; fields } } in
4246 let state, i, gls = hoas_ind2lp ~depth coq_ctx state ind in
4247 state, upoly_decl_of i, gls @ upoly_decl_gls
4248
4249 let lp2record_field_spec { name; is_coercion; is_canonical } =
4250 name,
4251 { Record.Internal.pf_coercion = is_coercion <> Off ;
4252 pf_reversible = is_coercion = Reversible ;
4253 pf_canonical = is_canonical;
4254 pf_instance = false;
4255 pf_priority = None;
4256 pf_locality = OptDefault }
4257 [%%else]
4258 let record_entry2lp ~depth coq_ctx constraints state ~loose_udecl (decl:Record.Record_decl.t) =
4259 let open Record.Record_decl in
4260 let open Record.Data in
4261 let open Entries in
4262 let i_impls = List.map binding_kind_of_manual_implicit decl.entry.param_impls in
4263
4264 let mie = decl.entry.mie in
4265 let ind = match mie.mind_entry_inds with
4266 | [ x ] -> x
4267 | _ -> nYI "mutual record"
4268 in
4269 let record = match decl.records with
4270 | [ x ] -> x
4271 | _ -> nYI "mutual record" in
4272 let indno = 1 in
4273
4274 let state =
4275 S.update engine state (fun e ->
4276 { e with sigma = merge_universe_context_set UState.univ_flexible e.sigma decl.entry.global_univs})
4277 in
4278
4279 let state = match mie.mind_entry_universes with
4280 | Template_ind_entry _ -> nYI "template polymorphic inductives"
4281 | Monomorphic_ind_entry -> state
4282 | Polymorphic_ind_entry cs -> S.update engine state (fun e ->
4283 { e with sigma = merge_ucontext e.sigma cs }) (* ???? *) in
4284
4285 let state, upoly_decl_of, upoly_decl_gls = upoly_decl_of ~depth state ~loose_udecl mie in
4286
4287 let params = mie.mind_entry_params in
4288 let params = Vars.lift_rel_context indno params in
4289
4290 let params = EConstr.of_rel_context params in
4291 let params = safe_combine2_impls params i_impls ~default2:Glob_term.Explicit |> param2ctx in
4292
4293 let id = ind.mind_entry_typename in
4294 let typ = EConstr.of_constr ind.mind_entry_arity in
4295 let kid = List.hd ind.mind_entry_consnames in
4296
4297 let fieldsno = List.length record.proj_flags in
4298 let kctx, _ = Term.decompose_prod_decls @@ List.hd ind.mind_entry_lc in
4299 let kctx = EConstr.of_rel_context kctx in
4300 if (List.length kctx != fieldsno) then CErrors.anomaly Pp.(str"record fields number != projections");
4301
4302 let fields = List.map2 (fun { pf_coercion; pf_canonical } ->
4303 let open Context.Rel.Declaration in
4304 let coe_status = match pf_coercion with
4305 | None -> Off
4306 | Some { coe_reversible } -> if coe_reversible then Reversible else Regular
4307 in
4308 function
4309 | LocalAssum( { Context.binder_name = Anonymous },typ) ->
4310 { id = Id.of_string "_"; typ; extra = [Coercion coe_status; Canonical pf_canonical] }
4311 | LocalAssum( { Context.binder_name = Name id },typ) ->
4312 { id; typ; extra = [Coercion coe_status; Canonical pf_canonical] }
4313 | _ -> nYI "let-in in record fields"
4314 ) (List.rev record.proj_flags) kctx in
4315
4316 let ind = { params; decl = Record { id; kid; typ; fields } } in
4317 let state, i, gls = hoas_ind2lp ~depth coq_ctx state ind in
4318 state, upoly_decl_of i, gls @ upoly_decl_gls
4319
4320 let lp2record_field_spec { name; is_coercion; is_canonical } =
4321 let pf_coercion = match is_coercion with
4322 | Off -> None
4323 | Reversible -> Some { Record.Data.coe_reversible = true; coe_local = false }
4324 | _ -> Some { coe_reversible= false; coe_local = false }
4325 in
4326 name,
4327 { Record.Data.pf_coercion;
4328 pf_canonical = is_canonical;
4329 pf_instance = None;
4330 }
4331 [%%endif]
4332
4333 let merge_universe_context state uctx =
4334 S.update engine state (fun e -> { e with sigma = Evd.merge_universe_context e.sigma uctx })
4335
4336 (* ********************************* }}} ********************************** *)
4337 (* ****************************** API ********************************** *)
4338
4339 module CtxReadbackCache = Ephemeron.K1.Make(struct
4340 type t = E.hyps
4341 let equal = (==)
4342 let hash = Hashtbl.hash
4343 end)
4344 let ctx_cache_lp2c = CtxReadbackCache.create 1
4345
4346 let get_current_env_sigma ~depth hyps constraints state =
4347 let hyps = E.of_hyps hyps in
4348 let state, _, changed, gl1 = elpi_solution_to_coq_solution ~eta_contract_solution:true ~calldepth:depth constraints state in
4349 if changed then CtxReadbackCache.reset ctx_cache_lp2c;
4350 let state, coq_ctx, gl2 =
4351 match CtxReadbackCache.find ctx_cache_lp2c hyps with
4352 | (c,e,d) when d == depth && e == Global.env () -> state, c, []
4353 | _ ->
4354 of_elpi_ctx ~calldepth:depth constraints depth
4355 (preprocess_context (fun _ -> true) hyps)
4356 state (empty_conv_context ~options:(get_options ~depth hyps state) state)
4357 | exception Not_found ->
4358 of_elpi_ctx ~calldepth:depth constraints depth
4359 (preprocess_context (fun _ -> true) hyps)
4360 state (empty_conv_context ~options:(get_options ~depth hyps state) state)
4361 in
4362 CtxReadbackCache.reset ctx_cache_lp2c;
4363 CtxReadbackCache.add ctx_cache_lp2c hyps (coq_ctx,Global.env (),depth);
4364 state, coq_ctx, get_sigma state, gl1 @ gl2
4365 ;;
4366
4367 let get_global_env_current_sigma ~depth hyps constraints state =
4368 let hyps = E.of_hyps hyps in
4369 let state, _, changed, gls = elpi_solution_to_coq_solution ~eta_contract_solution:true ~calldepth:depth constraints state in
4370 let coq_ctx = empty_conv_context ~options:(get_options ~depth hyps state) state in
4371 let coq_ctx = { coq_ctx with env = Environ.set_universes (Evd.universes (get_sigma state)) coq_ctx.env } in
4372 state, coq_ctx, get_sigma state, gls
4373 ;;
4374
4375 let rec lp2goal ~depth hyps syntactic_constraints state t =
4376 match get_goal_ref ~depth (E.constraints syntactic_constraints) state t with
4377 | Closed_by_side_effect -> assert false
4378 | Not_a_goal -> assert false
4379 | Open {ctx; evar = k; scope; args} ->
4380 let state, _, changed, gl1 =
4381 elpi_solution_to_coq_solution ~eta_contract_solution:true ~calldepth:depth syntactic_constraints state in
4382 if changed then lp2goal ~depth hyps syntactic_constraints state t
4383 else
4384 let visible_set = dblset_of_canonical_ctx ~depth Int.Set.empty scope in
4385 let state, coq_ctx, gl2 =
4386 of_elpi_ctx ~calldepth:depth syntactic_constraints depth
4387 (preprocess_context (fun x -> Int.Set.mem x visible_set)
4388 (U.lp_list_to_list ~depth ctx |>
4389 List.map (fun hsrc -> { E.hdepth = depth; E.hsrc })))
4390 state
4391 (empty_conv_context ~options:(get_options ~depth hyps state) state) in
4392 state, (coq_ctx, k, args), gl1@gl2
4393
4394 let goal2lp ~depth syntactic_constraints state coq_ctx k =
4395 let calldepth = depth in
4396 let env = get_global_env state in
4397 let sigma = get_sigma state in
4398 let state, elpi_goal_evar, elpi_raw_goal_evar, evar_decls =
4399 in_elpi_evar ~calldepth k state in
4400 let evar_concl, goal_ctx, _goal_env =
4401 info_of_undefined_evar ~env ~sigma ~section:(section_ids env) k in
4402
4403 let same_ctx sigma c1 c2 =
4404 let eq_named_declaration =
4405 Context.Named.Declaration.equal (EConstr.ERelevance.equal sigma) (EConstr.eq_constr sigma) in
4406 CList.equal eq_named_declaration c1 c2 in
4407
4408 if same_ctx sigma coq_ctx.proof goal_ctx then
4409 let state, hyps, raw_ev, ev, goal_ty, gls =
4410 in_elpi_evar_concl evar_concl ~raw_uvar:elpi_raw_goal_evar elpi_goal_evar
4411 coq_ctx ~calldepth ~depth state in
4412 Result.Ok (state, in_elpi_goal state ~args:[] ~hyps ~raw_ev ~ty:goal_ty ~ev, evar_decls@gls)
4413 else
4414 Result.Error goal_ctx
4415
4416 let constr2lp ~depth ?(calldepth=depth) coq_ctx _constraints state t =
4417 constr2lp coq_ctx ~calldepth ~depth state t
4418
4419 let lp2constr ~depth coq_ctx constraints state t =
4420 lp2constr constraints coq_ctx ~depth state t
4421
4422 let lp2constr_closed = lp2constr
4423
4424 let constr2lp_closed = constr2lp
4425
4426 let lp2constr_closed_ground ~depth ctx csts state t =
4427 let state, t1, _ as res = lp2constr ~depth ctx csts state t in
4428 if not (Evarutil.is_ground_term (get_sigma state) t1) then
4429 raise API.Conversion.(TypeErr(TyName"closed_term",depth,t));
4430 res
4431
4432 let constr2lp_closed_ground ~depth ?calldepth ctx csts state t =
4433 assert (Evarutil.is_ground_term (get_sigma state) t);
4434 constr2lp ~depth ?calldepth ctx csts state t
4435
4436 let lp2skeleton ~depth coq_ctx constraints state t =
4437 let coq_ctx = { coq_ctx with options = { coq_ctx.options with hoas_holes = Some Implicit }} in
4438 let state, t, gls = lp2constr coq_ctx constraints ~depth state t in
4439 let sigma = get_sigma state in
4440 let gt = Rocq_elpi_utils.detype ?keepunivs:coq_ctx.options.keepunivs coq_ctx.env sigma t in
4441 let gt =
4442 let is_GRef_hole x =
4443 match DAst.get x with
4444 | Glob_term.GRef(r,None) -> Environ.QGlobRef.equal coq_ctx.env r (Rocqlib.lib_ref "elpi.hole")
4445 | _ -> false in
4446 let rec map x = match DAst.get x with
4447 | Glob_term.GEvar _ -> mkGHole
4448 | Glob_term.GApp(hd,args) when is_GRef_hole hd ->
4449 let _, marker_real_args = CList.split_when is_GRef_hole args in
4450 let real_args = List.tl marker_real_args in
4451 if real_args = [] then mkGHole
4452 else DAst.make @@ Glob_term.GApp(mkGHole,List.map (Glob_ops.map_glob_constr map) real_args)
4453 | _ when is_GRef_hole x -> mkGHole
4454 | _ -> Glob_ops.map_glob_constr map x in
4455 map gt in
4456 state, gt, gls
4457
4458 (* {{{ Declarations.module_body -> elpi ********************************** *)
4459
4460 type module_item =
4461 | Module of Names.ModPath.t * module_item list
4462 | ModuleType of Names.ModPath.t
4463 | Gref of Names.GlobRef.t
4464 | Functor of Names.ModPath.t * Names.ModPath.t list
4465 | FunctorType of Names.ModPath.t * Names.ModPath.t list
4466
4467 [%%if coq = "9.0"]
4468 type 'a generic_module_body = 'a Declarations.generic_module_body
4469 let module_view m = m.Declarations.mod_type
4470 let mod_type m = m.Declarations.mod_type
4471
4472 let rec functor_params x =
4473 let open Declarations in
4474 match x with
4475 | MoreFunctor(_,{ mod_type_alg = Some (MENoFunctor (MEident mod_mp)) },rest) -> mod_mp :: functor_params rest
4476 | _ -> [] (* XXX non trivial functors, eg P : X with type a = nat, are badly described (no params) *)
4477 [%%else]
4478 type 'a generic_module_body = 'a Mod_declarations.generic_module_body
4479 let module_view m = Mod_declarations.mod_type m
4480 let mod_type = Mod_declarations.mod_type
4481
4482 let rec functor_params x =
4483 let open Declarations in
4484 match x with
4485 | MoreFunctor (_, mtb, rest) ->
4486 begin match Mod_declarations.mod_type_alg mtb with
4487 | Some (MENoFunctor (MEident mod_mp)) -> mod_mp :: functor_params rest
4488 | _ -> [] (* XXX *)
4489 end
4490 | _ -> [] (* XXX non trivial functors, eg P : X with type a = nat, are badly described (no params) *)
4491 [%%endif]
4492
4493 let rec in_elpi_module_item ~depth path state (name, item) =
4494 let open Declarations in
4495 match item with
4496 | SFBconst _ ->
4497 [Gref (GlobRef.ConstRef (Constant.make2 path name))]
4498 | SFBmind { mind_packets } ->
4499 CList.init (Array.length mind_packets) (fun i -> Gref (GlobRef.IndRef (MutInd.make2 path name,i)))
4500 | SFBrules _ -> nYI "rewrite rules"
4501 | SFBmodule b ->
4502 let mod_mp = MPdot (path, name) in
4503 begin match module_view b with
4504 | NoFunctor _ -> [Module (mod_mp,in_elpi_module ~depth state mod_mp b) ]
4505 | (MoreFunctor _ as l) -> [Functor(mod_mp,functor_params l)]
4506 end
4507 | SFBmodtype m ->
4508 let mod_mp = MPdot (path, name) in
4509 begin match module_view m with
4510 | NoFunctor _ -> [ModuleType mod_mp]
4511 | (MoreFunctor _ as l) -> [FunctorType (mod_mp,functor_params l)]
4512 end
4513
4514 and in_elpi_module : 'a. depth:int -> API.Data.state -> ModPath.t -> 'a generic_module_body -> module_item list =
4515 fun ~depth state mp mb ->
4516 match mod_type mb with
4517 | Declarations.MoreFunctor _ -> nYI "functors"
4518 | Declarations.NoFunctor contents ->
4519 let l =
4520 CList.map (in_elpi_module_item ~depth mp state) contents in
4521 CList.flatten l
4522
4523 let rec in_elpi_modty_item (name, item) = match item with
4524 | Declarations.SFBconst _ ->
4525 [ Label.to_string name ]
4526 | Declarations.SFBmind _ ->
4527 [ Label.to_string name ]
4528 | SFBrules _ -> nYI "rewrite rules"
4529 | Declarations.SFBmodule mb -> in_elpi_modty mb
4530 | Declarations.SFBmodtype _ -> []
4531
4532 and in_elpi_modty : 'a.'a generic_module_body -> string list =
4533 fun mb ->
4534 match mod_type mb with
4535 | Declarations.MoreFunctor _ -> nYI "functors"
4536 | Declarations.NoFunctor contents ->
4537 CList.flatten (CList.map in_elpi_modty_item contents)
4538
4539 let in_elpi_module ~depth s mp x = in_elpi_module ~depth s mp x
4540
4541 let in_elpi_module_type x = in_elpi_modty x
4542
4543 (* ********************************* }}} ********************************** *)
4544
4545 (* vim:set foldmethod=marker: *)