Debian Codegraph @

src/rocq_elpi_utils.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
7 let synterp_quotations = API.Quotation.new_quotations_descriptor ()
8 let synterp_hoas = API.RawData.new_hoas_descriptor ()
9 let synterp_state = API.State.new_state_descriptor ()
10 let interp_quotations = API.Quotation.new_quotations_descriptor ()
11 let interp_hoas = API.RawData.new_hoas_descriptor ()
12 let interp_state = API.State.new_state_descriptor ()
13
14 let source_name_of_fname = function
15 | Loc.InFile { file } -> Format.asprintf "%s" file
16 | Loc.ToplevelInput -> "(stdin)"
17
18 let fname_of_source_name ~dirpath s =
19 if s = "(stdin)" then Loc.ToplevelInput
20 else Loc.InFile { dirpath; file = s }
21
22 let of_coq_loc l =
23 let client_payload =
24 match l.Loc.fname with
25 | ToplevelInput -> None
26 | InFile { dirpath } -> Option.map Obj.repr dirpath in
27 {
28 API.Ast.Loc.client_payload;
29 source_name = source_name_of_fname l.Loc.fname;
30 source_start = l.Loc.bp;
31 source_stop = l.Loc.ep;
32 line = l.Loc.line_nb;
33 line_starts_at = l.Loc.bol_pos;
34 }
35
36 let to_coq_loc { API.Ast.Loc.source_name; client_payload; line; line_starts_at; source_start; source_stop } =
37 let dirpath = Option.map Obj.obj client_payload in
38 Loc.create (fname_of_source_name ~dirpath source_name) line line_starts_at source_start source_stop
39
40 let err ?loc msg =
41 let loc = Option.map to_coq_loc loc in
42 CErrors.user_err ?loc msg
43
44 let pp_oloc = function
45 | None -> Pp.mt ()
46 | Some loc -> Pp.str @@ Format.asprintf "%a " API.Ast.Loc.pp loc
47
48 (* If the error comes from another file (see Loc.mergeable) Coq drops the precise loc
49 and reports it on the whole execution site. If so, we print the
50 more precise loc as part of the error message.
51
52 We also copy here Loc.merge since it may anyway discard the better loc,
53 in that case we feedback it
54 *)
55 let coq_would_drop_loc2 loc1 loc2 =
56 let open Loc in
57 if loc1.bp < loc2.bp then
58 if loc1.ep < loc2.ep then false
59 else true
60 else if loc2.ep < loc1.ep then false
61 else false
62
63 let feedback_error loc m = Feedback.(feedback (Message(Error,loc,[],m)))
64
65 let patch_loc_source execution_loc error_loc msg =
66 match execution_loc, error_loc with
67 | _, None -> msg, execution_loc
68 | _, Some elpiloc when Loc.finer (Some elpiloc) (Some execution_loc) -> msg, elpiloc
69 | { Loc.fname },Some ({ Loc.fname = elpiname } as elpiloc) when fname = elpiname ->
70 (* same file, far location, we complementwith a feedback *)
71 feedback_error (Some elpiloc) msg;
72 Pp.(hv 0 (Loc.pr elpiloc ++ spc () ++ Loc.pr execution_loc ++ spc () ++ msg)), execution_loc
73 | _, Some elpiloc ->
74 (* external file *)
75 Pp.(hv 0 (Loc.pr elpiloc ++ spc () ++ msg)), execution_loc
76
77 [%%if coq = "9.0" || coq = "9.1"]
78 exception ParseError = Gramlib.Grammar.Error
79 [%%else]
80 exception ParseError = Gramlib.Grammar.ParseError
81 [%%endif]
82
83 let handle_elpi_compiler_errors ~loc ?error_header f =
84 let w_header m =
85 match error_header with
86 | None -> m
87 | Some x -> Pp.(v 0 (str x ++ str":" ++ spc() ++ m)) in
88 try f ()
89 with
90 | Sys_error msg ->
91 CErrors.user_err ~loc (w_header (Pp.str msg))
92 | Elpi.API.Compile.CompileError(oloc, msg) as e ->
93 let _,info = Exninfo.capture e in
94 let msg, loc = patch_loc_source loc (Option.map to_coq_loc oloc) (Pp.str msg) in
95 CErrors.user_err ~info ~loc (w_header msg)
96 | Elpi.API.Parse.ParseError(oloc, msg) as e ->
97 let _,info = Exninfo.capture e in
98 let msg, loc = patch_loc_source loc (Some (to_coq_loc oloc)) (Pp.str msg) in
99 CErrors.user_err ~info ~loc (w_header msg)
100 | ParseError _ as e ->
101 let _,info = Exninfo.capture e in
102 let cloc = Loc.get_loc info in
103 let msg = CErrors.print_no_report e in
104 let msg, loc = patch_loc_source loc cloc msg in
105 CErrors.user_err ~info ~loc (w_header msg)
106
107
108 exception LtacFail of int * Pp.t
109
110 let ltac_fail_err ?loc n msg =
111 let loc = Option.map to_coq_loc loc in
112 Loc.raise ?loc (LtacFail (n, msg))
113
114 let feedback_fmt_write, feedback_fmt_flush =
115 let b = Buffer.create 2014 in
116 ( Buffer.add_substring b,
117 fun () ->
118 let s = Buffer.to_bytes b in
119 let s =
120 let len = Bytes.length s in
121 if len > 0 && Bytes.get s (len - 1) = '\n' then Bytes.sub_string s 0 (len - 1) else Bytes.to_string s
122 in
123 Feedback.msg_debug Pp.(str s);
124 Buffer.clear b )
125
126 let elpi_cat = CWarnings.create_category ~name:"elpi" ()
127
128 let elpi_depr_cat =
129 CWarnings.create_category ~from:[ elpi_cat; CWarnings.CoreCategories.deprecated ] ~name:"elpi.deprecated" ()
130 let elpi_tc_cat =
131 CWarnings.create_category ~from:[ elpi_cat ] ~name:"elpi.typecheck" ()
132
133 let () = API.Setup.set_error (fun ?loc s -> err ?loc Pp.(str s))
134 let () = API.Setup.set_anomaly (fun ?loc s -> err ?loc Pp.(str s))
135 let () = API.Setup.set_type_error (fun ?loc s -> err ?loc Pp.(str s))
136 let warn = CWarnings.create ~name:"elpi.runtime" ~category:elpi_cat (fun x -> x)
137 let warn_impl = CWarnings.create ~name:"elpi.implication-precedence" ~category:elpi_cat (fun x -> x)
138 let warn_linear = CWarnings.create ~name:"elpi.linear-variable" ~category:elpi_tc_cat (fun x -> x)
139 let warn_missing_types = CWarnings.create ~name:"elpi.missing-types" ~category:elpi_tc_cat (fun x -> x)
140 let warn_flex_clause = CWarnings.create ~name:"elpi.flex-clause" ~category:elpi_tc_cat (fun x -> x)
141 let warn_nested_accumulate = CWarnings.create ~default:CWarnings.AsError ~name:"elpi.nested-accumulate" ~category:elpi_depr_cat (fun x -> x)
142
143 let () = API.Setup.set_warn (fun ?loc ~id x ->
144 let loc = Option.map to_coq_loc loc in
145 let msg = Pp.(hv 0 (Option.cata (fun loc -> Loc.pr loc ++ spc ()) (mt()) loc ++ str x)) in
146 match id with
147 | API.Setup.ImplicationPrecedence -> warn_impl ?loc msg
148 | LinearVariable -> warn_linear ?loc msg
149 | UndeclaredGlobal -> warn_missing_types ?loc msg
150 | FlexClause -> warn_flex_clause ?loc msg
151 | NestedAccumulate -> warn_nested_accumulate ?loc msg)
152 let () = API.Setup.set_std_formatter (Format.make_formatter feedback_fmt_write feedback_fmt_flush)
153 let () = API.Setup.set_err_formatter (Format.make_formatter feedback_fmt_write feedback_fmt_flush)
154 let nYI s = err Pp.(str "Not Yet Implemented: " ++ str s)
155
156 let pp2string pp x =
157 let b = Buffer.create 80 in
158 let fmt = Format.formatter_of_buffer b in
159 Format.pp_set_margin fmt (Option.default 80 (Topfmt.get_margin ()));
160 Format.fprintf fmt "%a%!" pp x;
161 Buffer.contents b
162
163 module C = Constr
164 module EC = EConstr
165
166 let safe_destApp sigma t = match EC.kind sigma t with C.App (hd, args) -> (EC.kind sigma hd, args) | x -> (x, [||])
167 let mkGHole = DAst.make Glob_term.(GHole GInternalHole)
168
169 let mkApp ~depth t l =
170 match l with
171 | [] -> t
172 | x :: xs -> (
173 match API.RawData.look ~depth t with API.RawData.Const c -> API.RawData.mkApp c x xs | _ -> assert false)
174
175 let string_split_on_char c s =
176 let len = String.length s in
177 let rec aux n x =
178 if x = len then [ String.sub s n (x - n) ]
179 else if s.[x] = c then String.sub s n (x - n) :: aux (x + 1) (x + 1)
180 else aux n (x + 1)
181 in
182 aux 0 0
183
184 let rec mk_gforall ty = function
185 | (name, r, bk, None, t) :: ps -> DAst.make @@ Glob_term.GProd (name, r, bk, t, mk_gforall ty ps)
186 | (name, r, _, Some bo, t) :: ps -> DAst.make @@ Glob_term.GLetIn (name, r, bo, Some t, mk_gforall ty ps)
187 | [] -> ty
188
189 let rec mk_gfun ty = function
190 | (name, r, bk, None, t) :: ps -> DAst.make @@ Glob_term.GLambda (name, r, bk, t, mk_gfun ty ps)
191 | (name, r, _, Some bo, t) :: ps -> DAst.make @@ Glob_term.GLetIn (name, r, bo, Some t, mk_gfun ty ps)
192 | [] -> ty
193
194 let manual_implicit_of_binding_kind name = function
195 | Glob_term.NonMaxImplicit -> CAst.make (Some (name, false))
196 | Glob_term.MaxImplicit -> CAst.make (Some (name, true))
197 | Glob_term.Explicit -> CAst.make None
198
199 let binding_kind_of_manual_implicit x =
200 match x.CAst.v with
201 | Some (_, false) -> Glob_term.NonMaxImplicit
202 | Some (_, true) -> Glob_term.MaxImplicit
203 | None -> Glob_term.Explicit
204
205 let manual_implicit_of_gdecl (name, _, bk, _, _) = manual_implicit_of_binding_kind name bk
206
207 let lookup_inductive env i =
208 Inductive.lookup_mind_specif env i
209
210 [%%if coq = "9.0" || coq = "9.1"]
211 let abbreviation_find_interp = Abbreviation.search_abbreviation
212 [%%else]
213 let abbreviation_find_interp = Abbreviation.find_interp
214 [%%endif]
215
216 let locate_qualid qualid =
217 try
218 match Nametab.locate_extended qualid with
219 | Globnames.TrueGlobal gr -> Some (`Gref gr)
220 | Globnames.Abbrev sd -> (
221 match abbreviation_find_interp sd with
222 | _, Notation_term.NRef (gr, _) -> Some (`Gref gr)
223 | _ -> Some (`Abbrev sd))
224 with Not_found -> None
225
226 let locate_simple_qualid qualid =
227 match locate_qualid qualid with
228 | Some (`Gref x) -> x
229 | Some (`Abbrev _) -> nYI ("complex call to Locate: " ^ Libnames.string_of_qualid qualid)
230 | None -> err Pp.(str "Global reference not found: " ++ Libnames.pr_qualid qualid)
231
232 let locate_gref s =
233 let s = String.trim s in
234 try
235 let i = String.index s ':' in
236 let id = String.sub s (i + 1) (String.length s - (i + 1)) in
237 let ref = Rocqlib.lib_ref id in
238 let path = Nametab.path_of_global ref in
239 let qualid = Libnames.qualid_of_path path in
240 locate_simple_qualid qualid
241 with Not_found ->
242 (* String.index *)
243 let qualid = Libnames.qualid_of_string s in
244 locate_simple_qualid qualid
245
246 let (uint63c, uint63) : Uint63.t Elpi.API.RawOpaqueData.cdata * Uint63.t Elpi.API.Conversion.t =
247 let open Elpi.API.RawOpaqueData in
248 declare
249 {
250 name = "uint63";
251 doc = "";
252 pp = (fun fmt i -> Format.fprintf fmt "%s" (Uint63.to_string i));
253 compare = Uint63.compare;
254 hash = Uint63.hash;
255 hconsed = false;
256 constants = [];
257 }
258
259 let (float64c, float64) : Float64.t Elpi.API.RawOpaqueData.cdata * Float64.t Elpi.API.Conversion.t =
260 let open Elpi.API.RawOpaqueData in
261 declare
262 {
263 name = "float64";
264 doc = "";
265 pp = (fun fmt i -> Format.fprintf fmt "%s" (Float64.to_string i));
266 compare = Float64.total_compare;
267 hash = Float64.hash;
268 hconsed = false;
269 constants = [];
270 }
271
272 let (pstringc, pstring) : Pstring.t Elpi.API.RawOpaqueData.cdata * Pstring.t Elpi.API.Conversion.t =
273 let open Elpi.API.RawOpaqueData in
274 declare {
275 name = "pstring";
276 doc = "";
277 pp = (fun fmt s -> Format.fprintf fmt "%S" (Pstring.to_string s));
278 compare = Pstring.compare;
279 hash = Pstring.hash;
280 hconsed = false;
281 constants = [];
282 }
283 let pstring_of_string = Pstring.of_string
284 let string_of_pstring = Pstring.to_string
285
286 let debug = CDebug.create ~name:"elpi" ()
287
288 let elpitime_flag, elpitime = CDebug.create_full ~name:"elpitime" ()
289
290 let (projectionc, projection) : Names.Projection.t Elpi.API.RawOpaqueData.cdata * Names.Projection.t Elpi.API.Conversion.t =
291 let open Elpi.API.RawOpaqueData in
292 declare
293 {
294 name = "projection";
295 doc = "";
296 pp = (fun fmt i -> Format.fprintf fmt "%s" (Names.Projection.to_string i));
297 compare =
298 (let open Names.Projection in
299 fun x y -> Repr.CanOrd.compare (repr x) (repr y));
300 hash =
301 (let open Names.Projection in
302 fun x -> Repr.CanOrd.hash (repr x));
303 hconsed = false;
304 constants = [];
305 }
306
307 let fold_elpi_term f acc ~depth t =
308 let module E = Elpi.API.RawData in
309 match t with
310 | E.Const _ | E.Nil | E.CData _ -> acc
311 | E.App (_, x, xs) -> List.fold_left (f ~depth) (f ~depth acc x) xs
312 | E.Cons (x, xs) -> f ~depth (f ~depth acc x) xs
313 | E.Builtin (_, xs) -> List.fold_left (f ~depth) acc xs
314 | E.Lam x -> f ~depth:(depth + 1) acc x
315 | E.UnifVar (_, xs) -> List.fold_left (f ~depth) acc xs
316
317 type clause_scope = Local | Regular | Global | SuperGlobal
318
319 let pp_scope fmt = function
320 | Local -> Format.fprintf fmt "local"
321 | Regular -> Format.fprintf fmt "regular"
322 | Global -> Format.fprintf fmt "global"
323 | SuperGlobal -> Format.fprintf fmt "superglobal"
324
325 let rec list_map_acc f acc = function
326 | [] -> (acc, [])
327 | x :: xs ->
328 let acc, x = f acc x in
329 let acc, xs = list_map_acc f acc xs in
330 (acc, x :: xs)
331
332 let rec fix_detype x = match DAst.get x with Glob_term.GEvar _ -> mkGHole | _ -> Glob_ops.map_glob_constr fix_detype x
333
334 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
335 let gqvar q = Glob_term.GQVar q
336 [%%else]
337 let gqvar q = Glob_term.GQuality (QVar q)
338 [%%endif]
339
340 let detype_qvar sigma q =
341 let open Glob_term in
342 match UState.id_of_qvar (Evd.ustate sigma) q with
343 | Some id -> GLocalQVar (CAst.make (Names.Name.Name id))
344 | None -> gqvar q
345
346 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
347 let detype_quality sigma q =
348 let open Glob_term in
349 let open Sorts.Quality in
350 match q with QConstant q -> GQConstant q | QVar q -> GQualVar (detype_qvar sigma q)
351 [%%else]
352 let detype_quality sigma q =
353 let open Glob_term in
354 let open Sorts.Quality in
355 match q with QConstant _ | QGlobal _ -> GQuality q | QVar q -> (detype_qvar sigma q)
356 [%%endif]
357
358 let detype_level_name sigma l =
359 let open Glob_term in
360 if Univ.Level.is_set l then GSet
361 else
362 match UState.id_of_level (Evd.ustate sigma) l with
363 | Some id -> GLocalUniv (CAst.make id)
364 | None -> GUniv l
365
366 let detype_level sigma l =
367 let open Glob_term in
368 UNamed (detype_level_name sigma l)
369
370 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
371 let detype_universe sigma u =
372 Glob_term.UNamed (List.map (Util.on_fst (detype_level_name sigma)) (Univ.Universe.repr u))
373 let detype_sort ku sigma x =
374 let open Sorts in
375 let open Glob_ops in
376 match x with
377 | SProp -> glob_SProp_sort
378 | Prop -> glob_Prop_sort
379 | Set -> glob_Set_sort
380 | Type u when ku -> None, detype_universe sigma u
381 | QSort (q, u) when ku -> Some (detype_qvar sigma q), detype_universe sigma u
382 | _ -> glob_Type_sort
383 [%%else]
384 let detype_universe sigma u =
385 Glob_term.UNamed (List.map (Util.on_fst (detype_level_name sigma)) (Univ.Universe.repr u))
386 let detype_sort ku sigma x =
387 let open Sorts in
388 let open Glob_ops in
389 match x with
390 | SProp -> glob_SProp_sort
391 | Prop -> glob_Prop_sort
392 | Set -> glob_Set_sort
393 | Type u when ku -> None, detype_universe sigma u
394 | VSort (q, u) when ku -> Some (detype_qvar sigma q), detype_universe sigma u
395 | GSort (q, u) -> Some (detype_quality sigma (QGlobal q)), if ku then detype_universe sigma u else glob_rigid_univ
396 | _ -> glob_Type_sort
397 [%%endif]
398
399 (*
400 let detype_relevance_info sigma na =
401 match Evarutil.nf_relevance sigma na with
402 | Relevant -> Some Glob_term.GRelevant
403 | Irrelevant -> Some Glob_term.GIrrelevant
404 | RelevanceVar q -> Some (Glob_term.GRelevanceVar (detype_qvar sigma q))
405 *)
406
407 let detype_instance ku sigma l =
408 if not ku then None
409 else
410 let open EConstr in
411 let l = EInstance.kind sigma l in
412 if UVars.Instance.is_empty l then None
413 else
414 let qs, us = UVars.Instance.to_array l in
415 let qs = List.map (detype_quality sigma) (Array.to_list qs) in
416 let us = List.map (detype_level sigma) (Array.to_list us) in
417 Some (qs, us)
418
419 let it_destRLambda_or_LetIn_names l c =
420 let open Glob_term in
421 let rec aux l nal c =
422 match (DAst.get c, l) with
423 | _, [] -> (List.rev nal, c)
424 | GLambda (na, _, _, _, c), false :: l -> aux l (na :: nal) c
425 | GLetIn (na, _, _, _, c), true :: l -> aux l (na :: nal) c
426 | _ -> nYI "detype eta"
427 in
428 aux l [] c
429 let rec decompose accu c = match DAst.get c with
430 | Glob_term.GLambda (na, _, _, _, c) -> decompose (na :: accu) c
431 | _ -> List.rev accu, c
432
433 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
434 let get_projection_constant _env p =
435 Names.Projection.Repr.constant p
436 [%%else]
437 let get_projection_constant env p =
438 Environ.projection_repr_constant env p
439 [%%endif]
440
441 module RobustExpand :
442 sig
443 open Names
444 open EConstr
445 val return_clause : Environ.env -> Evd.evar_map -> Ind.t ->
446 EInstance.t -> EConstr.t array -> EConstr.case_return -> rel_context * EConstr.t
447 val branch : Environ.env -> Evd.evar_map -> Construct.t ->
448 EInstance.t -> EConstr.t array -> EConstr.case_branch -> rel_context * EConstr.t
449 end =
450 struct
451 open Vars
452 open Names
453 open Declarations
454 open UVars
455 open Constr
456 open Context.Rel.Declaration
457
458 let instantiate_context u subst nas ctx =
459 let rec instantiate i ctx = match ctx with
460 | [] -> []
461 | LocalAssum (_, ty) :: ctx ->
462 let ctx = instantiate (pred i) ctx in
463 let ty = substnl subst i (subst_instance_constr u ty) in
464 LocalAssum (nas.(i), ty) :: ctx
465 | LocalDef (_, ty, bdy) :: ctx ->
466 let ctx = instantiate (pred i) ctx in
467 let ty = substnl subst i (subst_instance_constr u ty) in
468 let bdy = substnl subst i (subst_instance_constr u bdy) in
469 LocalDef (nas.(i), ty, bdy) :: ctx
470 in
471 let () = if not (Int.equal (Array.length nas) (List.length ctx)) then raise_notrace Exit in
472 instantiate (Array.length nas - 1) ctx
473
474 let return_clause env sigma ind u params ((nas, p),_) =
475 let nas : Name.t EConstr.binder_annot array = nas in
476 try
477 let u = EConstr.Unsafe.to_instance u in
478 let params = EConstr.Unsafe.to_constr_array params in
479 let nas : Name.t Constr.binder_annot array =
480 match EConstr.Unsafe.relevance_eq with Refl -> nas
481 in
482 let () = if not @@ Environ.mem_mind (fst ind) env then raise_notrace Exit in
483 let mib = Environ.lookup_mind (fst ind) env in
484 let mip = mib.mind_packets.(snd ind) in
485 let paramdecl = subst_instance_context u mib.mind_params_ctxt in
486 let paramsubst = subst_of_rel_context_instance paramdecl params in
487 let realdecls, _ = CList.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
488 let self =
489 let args = Context.Rel.instance mkRel 0 mip.mind_arity_ctxt in
490 let inst = Instance.(abstract_instance (length u)) in
491 mkApp (mkIndU (ind, inst), args)
492 in
493 let realdecls = LocalAssum (Context.anonR, self) :: realdecls in
494 let realdecls = instantiate_context u paramsubst nas realdecls in
495 List.map EConstr.of_rel_decl realdecls, p
496 with e when CErrors.noncritical e ->
497 let dummy na = LocalAssum (na, EConstr.mkProp) in
498 List.rev (CArray.map_to_list dummy nas), p
499
500 let branch env sigma (ind, i) u params (nas, br) =
501 let nas : Name.t EConstr.binder_annot array = nas in
502 try
503 let u = EConstr.Unsafe.to_instance u in
504 let params = EConstr.Unsafe.to_constr_array params in
505 let nas : Name.t Constr.binder_annot array =
506 match EConstr.Unsafe.relevance_eq with Refl -> nas
507 in
508 let () = if not @@ Environ.mem_mind (fst ind) env then raise_notrace Exit in
509 let mib = Environ.lookup_mind (fst ind) env in
510 let mip = mib.mind_packets.(snd ind) in
511 let paramdecl = subst_instance_context u mib.mind_params_ctxt in
512 let paramsubst = subst_of_rel_context_instance paramdecl params in
513 let (ctx, _) = mip.mind_nf_lc.(i - 1) in
514 let ctx, _ = CList.chop mip.mind_consnrealdecls.(i - 1) ctx in
515 let ctx = instantiate_context u paramsubst nas ctx in
516 List.map EConstr.of_rel_decl ctx, br
517 with e when CErrors.noncritical e ->
518 let dummy na = LocalAssum (na, EConstr.mkProp) in
519 List.rev (CArray.map_to_list dummy nas), br
520
521 end
522
523 let detype_relevance_info sigma na =
524 match EConstr.ERelevance.kind sigma na with
525 | Relevant -> Some Glob_term.GRelevant
526 | Irrelevant -> Some Glob_term.GIrrelevant
527 | RelevanceVar q -> Some (GRelevanceVar (detype_qvar sigma q))
528 let mk_glob_decl_g sigma na x y z = Context.binder_name na, detype_relevance_info sigma @@ Context.binder_relevance na, x, y, z
529 let mkGProd sigma na x y z = Glob_term.GProd(Context.binder_name na, detype_relevance_info sigma @@ Context.binder_relevance na, x, y, z)
530 let mkGLambda sigma na x y z = Glob_term.GLambda(Context.binder_name na, detype_relevance_info sigma @@ Context.binder_relevance na, x, y, z)
531 let mkGLetIn sigma na x y z = Glob_term.GLetIn(Context.binder_name na, detype_relevance_info sigma @@ Context.binder_relevance na, x, y, z)
532 let get_ind_tags env ci p =
533 let ind = ci.Constr.ci_ind in
534 if Environ.mem_mind (fst ind) env then
535 let (mib, mip) = Inductive.lookup_mind_specif env ind in
536 Context.Rel.to_tags (CList.firstn mip.mind_nrealdecls mip.mind_arity_ctxt)
537 else
538 let (nas, _), _ = p in
539 CArray.map_to_list (fun _ -> false) nas
540
541 let get_cstr_tags env ci bl =
542 let ind = ci.Constr.ci_ind in
543 if Environ.mem_mind (fst ind) env then
544 let (mib, mip) = Inductive.lookup_mind_specif env ind in
545 Array.map2 (fun (d, _) n -> Context.Rel.to_tags (CList.firstn n d))
546 mip.mind_nf_lc mip.mind_consnrealdecls
547 else
548 let map (nas, _) = CArray.map_to_list (fun _ -> false) nas in
549 Array.map map bl
550
551 let get_GLambda_name_tgt typ =
552 match DAst.get typ with
553 | Glob_term.GLambda (x, _, _, t, c) -> (x, c)
554 | _ -> (Anonymous, typ)
555
556 let detype_primitive_string = function
557 | Constr.String s -> DAst.make @@ Glob_term.GString s
558 | _ -> assert false
559
560 let fresh (names, e) sigma name ty =
561 let open EConstr in
562 let open Names.Name in
563 let mk_fresh was =
564 let id, names = Namegen.Generator.next_name_away Namegen.Generator.fresh was names in
565 (Name id, (names, e))
566 in
567 match name with
568 | Anonymous ->
569 let noccurs sigma i = function None -> true | Some t -> Vars.noccurn sigma i t in
570 let name, names = Namegen.compute_displayed_name_in_gen Namegen.Generator.fresh noccurs e sigma names name ty in
571 (name, (names, e))
572 | Name id when Nameops.Fresh.mem id names -> mk_fresh name
573 | Name id as x -> (x, (Nameops.Fresh.add id names, e))
574
575 let names_of_env env =
576 let namesr = Environ.rel_context env |> Context.Rel.to_vars in
577 let namesv = Environ.named_context env |> Context.Named.to_vars in
578 Names.Id.Set.fold (fun id accu -> Nameops.Fresh.add id accu) namesr (Nameops.Fresh.of_set namesv)
579
580 let detype ?(keepunivs = false) env sigma t =
581 let open Glob_term in
582 let open EConstr in
583 let open Context.Rel.Declaration in
584 debug Pp.(fun () -> str "detype: " ++ Printer.pr_econstr_env env sigma t);
585
586 let fresh (names, e) name ty = fresh (names, e) sigma name ty in
587 let push_rel d env c =
588 let name = Context.Rel.Declaration.get_name d in
589 let r = Context.Rel.Declaration.get_relevance d in
590 let name, (names, env) = fresh env name (Some c) in
591 let namer = Context.make_annot name r in
592 ((names, EConstr.push_rel (Context.Rel.Declaration.set_name name d) env), namer)
593 in
594 let push_occurring_rel d env =
595 let name = Context.Rel.Declaration.get_name d in
596 let r = Context.Rel.Declaration.get_relevance d in
597 let name, (names, env) = fresh env name None in
598 let namer = Context.make_annot name r in
599 ((names, EConstr.push_rel (Context.Rel.Declaration.set_name name d) env), namer)
600 in
601
602 let lookup_rel i (_, env) = Environ.lookup_rel i env in
603
604 let unknown_inductive = Rocqlib.lib_ref "elpi.unknown_inductive" in
605
606 let rec detype_binder env name bo ty t =
607 let gty = aux env ty in
608 let gbo = Option.map (aux env) bo in
609 (*let rinfo = detype_relevance_info sigma binder_relevance in*)
610 let env, name = push_rel (LocalAssum (name, ty)) env t in
611 let gt = aux env t in
612 (name, gbo, gty, gt)
613 and aux env t =
614 match kind sigma t with
615 | Rel i -> (
616 match lookup_rel i env |> get_name with
617 | Names.Name.Anonymous -> assert false
618 | Names.Name.Name x -> DAst.make @@ GVar x
619 | exception Not_found -> assert false)
620 | Var x ->
621 (* Discriminate between section variable and non-section variable *)
622 DAst.make
623 (try
624 let _ = Environ.lookup_named x (snd env) in
625 GRef (Names.GlobRef.VarRef x, None)
626 with Not_found -> GVar x)
627 | Meta _ -> assert false
628 | Evar _ -> mkGHole
629 | Sort s -> DAst.make @@ GSort (detype_sort keepunivs sigma (ESorts.kind sigma s))
630 | Cast (t, k, ty) -> DAst.make @@ GCast (aux env t, Some k, aux env ty)
631 | Prod (name, ty, t) ->
632 let name, _, gty, gt = detype_binder env name None ty t in
633 DAst.make @@ mkGProd sigma name Explicit gty gt
634 | Lambda (name, ty, t) ->
635 let name, _, gty, gt = detype_binder env name None ty t in
636 DAst.make @@ mkGLambda sigma name Explicit gty gt
637 | LetIn (name, bo, ty, t) ->
638 let name, gbo, gty, gt = detype_binder env name (Some bo) ty t in
639 DAst.make @@ mkGLetIn sigma name Option.(get gbo) (Some gty) gt
640 | App (hd, args) -> DAst.make @@ GApp (aux env hd, CArray.map_to_list (aux env) args)
641 | Int i -> DAst.make @@ GInt i
642 | Float i -> DAst.make @@ GFloat i
643 | Array (u, a, d, ty) ->
644 DAst.make @@ GArray (detype_instance keepunivs sigma u, CArray.map (aux env) a, aux env d, aux env ty)
645 | Const (c, u) -> DAst.make @@ GRef (Names.GlobRef.ConstRef c, detype_instance keepunivs sigma u)
646 | Ind (c, u) -> DAst.make @@ GRef (Names.GlobRef.IndRef c, detype_instance keepunivs sigma u)
647 | Construct (c, u) -> DAst.make @@ GRef (Names.GlobRef.ConstructRef c, detype_instance keepunivs sigma u)
648 | Proj (p, r, c) ->
649 if Names.Projection.unfolded p then
650 let open Names in
651 let c = aux env c in
652 let id = Label.to_id @@ Constant.label @@ get_projection_constant (snd env) (Projection.repr p) in
653 let nargs, parg =
654 try
655 let _, mip = Global.lookup_inductive (Projection.inductive p) in
656 (mip.mind_consnrealargs.(0), Projection.arg p)
657 with e when !Flags.in_debugger ->
658 (* kinda weird printing but the name should be enough to
659 indicate which projection it is *)
660 (1, 0)
661 in
662 let pathole = DAst.make @@ PatVar Anonymous in
663 let patargs =
664 List.init nargs (fun i -> if Int.equal i parg then DAst.make @@ PatVar (Name id) else pathole)
665 in
666 let pat = DAst.make @@ PatCstr ((Projection.inductive p, 1), patargs, Anonymous) in
667 let br = ([ id ], [ pat ], DAst.make @@ GVar id) in
668 (* MatchStyle looks relatively heavy *)
669 DAst.make @@ GCases (LetPatternStyle, None, [ (c, (Anonymous, None)) ], [ CAst.make br ])
670 else
671 let pars = Names.Projection.npars p in
672 let hole = DAst.make @@ GHole GInternalHole in
673 let args = CList.make pars hole in
674 DAst.make
675 @@ GApp (DAst.make @@ GRef (Names.GlobRef.ConstRef (get_projection_constant (snd env) (Names.Projection.repr p)), None), args @ [ aux env c ])
676 | Fix (((vn, _) as nvn), (names, tys, bodies)) ->
677 let env, names =
678 list_map_acc
679 (fun env (n, ty) -> push_occurring_rel (LocalAssum (n, ty)) env)
680 env
681 (CList.combine (names|> CArray.to_list) (tys |> CArray.to_list))
682 in
683 let n = Array.length tys in
684 let v = CArray.map3 (fun c t i -> share_names (i + 1) [] env c (Vars.lift n t)) bodies tys vn in
685 DAst.make
686 @@ GRec
687 ( GFix (Array.map (fun i -> Some i) (fst nvn), snd nvn),
688 CArray.map_of_list (function Names.Name.Name x -> x | _ -> assert false) (List.map Context.binder_name names),
689 Array.map (fun (bl, _, _) -> bl) v,
690 Array.map (fun (_, _, ty) -> ty) v,
691 Array.map (fun (_, bd, _) -> bd) v )
692 | CoFix _ -> nYI "cofix"
693 | Case (ci, u, pms, p, iv, c, [| bl |]) when unknown_inductive = Names.GlobRef.IndRef ci.ci_ind ->
694 let tomatch = aux env c in
695 let map i br =
696 let ctx, body = RobustExpand.branch (snd env) sigma (ci.ci_ind, i + 1) u pms br in
697 EConstr.it_mkLambda_or_LetIn body ctx
698 in
699 let bl = map 0 bl in
700 let bl' = aux env bl in
701 let (nal, d) = decompose [] bl' in
702
703 DAst.make @@ GLetTuple (nal, ((*Anonymous,None*) Name (Names.Id.of_string "xxx"), Some mkGHole), tomatch, d)
704 | Case (ci, u, pms, p, iv, c, bl) -> detype_case env (ci, u, pms, p, iv, c, bl)
705 | s -> detype_primitive_string s
706 and share_names n l env bo ty =
707 if n = 0 then (List.rev l, aux env bo, aux env ty)
708 else
709 match (EConstr.kind sigma bo, EConstr.kind sigma ty) with
710 | LetIn (_, b, _, x), _ -> share_names n l env (Vars.subst1 b x) ty
711 | _, LetIn (_, b, _, x) -> share_names n l env bo (Vars.subst1 b x)
712 | Lambda (na, lty, bo), Prod (na', _, ty) ->
713 let na = Nameops.Name.pick_annot na na' in
714 let decl = LocalAssum (na, lty) in
715 let lty = aux env lty in
716 let env, na = push_rel decl env bo in
717 share_names (n - 1) (mk_glob_decl_g sigma na Explicit None lty :: l) env bo ty
718 | _, Prod (na, lty, ty) ->
719 let decl = LocalAssum (na, lty) in
720 let lty = aux env lty in
721 let env, na = push_occurring_rel decl env in
722 let bo = mkApp (Vars.lift 1 bo, [| mkRel 1 |]) in
723 share_names (n - 1) (mk_glob_decl_g sigma na Explicit None lty :: l) env bo ty
724 | _ -> assert false
725 and detype_case env (ci, univs, params, p, iv, c, bl) =
726 let open Constr in
727 let tomatch = aux env c in
728 let tomatch =
729 let _, mip = Global.lookup_inductive ci.ci_ind in
730 let hole = DAst.make @@ GHole GInternalHole in
731 let indices = CList.make mip.mind_nrealargs hole in
732 let t = EConstr.mkApp (EConstr.mkIndU (ci.ci_ind, univs), params) in
733 DAst.make @@ GCast (tomatch, None, Glob_ops.mkGApp (aux env t) indices)
734 in
735
736 let alias, aliastyp, pred =
737 let tags = get_ind_tags (snd env) ci p in
738 let ctx, p = RobustExpand.return_clause (snd env) sigma ci.ci_ind univs params p in
739 let p = EConstr.it_mkLambda_or_LetIn p ctx in
740 let p = aux env p in
741 let nl, typ = it_destRLambda_or_LetIn_names tags p in
742 let n, typ = get_GLambda_name_tgt typ in
743 let aliastyp = if List.for_all (Names.Name.equal Anonymous) nl then None else Some (CAst.make (ci.ci_ind, nl)) in
744 (n, aliastyp, Some typ)
745 in
746 let constructs = Array.init (Array.length bl) (fun i -> (ci.ci_ind, i + 1)) in
747 let constagsl = get_cstr_tags (snd env) ci bl in
748 let eqnl = detype_eqns env constructs constagsl (ci, univs, params, bl) in
749 DAst.make @@ GCases (MatchStyle, pred, [ (tomatch, (alias, aliastyp)) ], eqnl)
750 and detype_eqns env constructs consnargsl bl =
751 let ci, u, pms, bl = bl in
752 CArray.to_list (CArray.map3 (detype_eqn env u pms) constructs consnargsl bl)
753 and detype_eqn env u pms constr construct_nargs br =
754 let ctx, body = RobustExpand.branch (snd env) sigma constr u pms br in
755 let branch = EConstr.it_mkLambda_or_LetIn body ctx in
756 let make_pat decl env b ids =
757 let env, na = push_rel decl env b in
758 let ids = match Context.binder_name na with Names.Name.Name x -> Names.Id.Set.add x ids | _ -> ids in
759 (DAst.make (PatVar (Context.binder_name na)), env, ids)
760 in
761 let rec buildrec ids patlist env n b =
762 if Int.equal n 0 then
763 CAst.make
764 @@ (Names.Id.Set.elements ids, [ DAst.make @@ PatCstr (constr, List.rev patlist, Anonymous) ], aux env b)
765 else
766 match EConstr.kind sigma b with
767 | Lambda (x, t, b) ->
768 let pat, env, new_ids = make_pat (LocalAssum (x, t)) env b ids in
769 buildrec new_ids (pat :: patlist) env (pred n) b
770 | LetIn (x, b, t, b') ->
771 let pat, env, new_ids = make_pat (LocalDef (x, b, t)) env b' ids in
772 buildrec new_ids (pat :: patlist) env (pred n) b'
773 | _ -> assert false
774 in
775 buildrec Names.Id.Set.empty [] env (List.length ctx) branch
776 in
777
778 let x = aux (names_of_env env, env) t in
779 x
780
781 [%%if coq = "9.0" || coq = "9.1"]
782 let pr_constr_expr = Ppconstr.pr_constr_expr
783 let detype_closed_glob = Detyping.detype_closed_glob
784 [%%else]
785 let pr_constr_expr env sigma c = Ppconstr.pr_constr_expr ~flags:(Ppconstr.current_flags()) env sigma c
786 let detype_closed_glob env sigma c = Detyping.detype_closed_glob ~flags:(PrintingFlags.Detype.current()) env sigma c
787 [%%endif]
788
789 let detype_closed_glob env sigma closure =
790 let gbody = detype_closed_glob env sigma closure in
791 fix_detype gbody
792
793 [%%if coq = "9.0" || coq = "9.1"]
794 let detype_to_pattern env sigma c =
795 let c = detype env sigma c in
796 Patternops.pattern_of_glob_constr env c
797 [%%else]
798 let detype_to_pattern env sigma c =
799 let c = detype env sigma c in
800 let ids, p = Patternops.pattern_of_glob_constr env c in
801 ids, Patternops.interp_pattern env sigma Glob_ops.empty_lvar p
802 [%%endif]
803
804 type qualified_name = string list
805
806 let compare_qualified_name = Stdlib.compare
807 let pr_qualified_name = Pp.prlist_with_sep (fun () -> Pp.str ".") Pp.str
808 let show_qualified_name = String.concat "."
809 let pp_qualified_name fmt l = Format.fprintf fmt "%s" (String.concat "." l)
810
811 let option_map_acc f s = function
812 | None -> (s, None)
813 | Some x ->
814 let s, x = f s x in
815 (s, Some x)
816
817 let option_map_acc2 f s = function
818 | None -> (s, None, [])
819 | Some x ->
820 let s, x, gl = f s x in
821 (s, Some x, gl)
822
823 let option_default f = function Some x -> x | None -> f ()
824
825 let coq_version_parser version =
826 Elpi.API.Utils.version_parser ~what:"coq" version
827
828 let mp2path x =
829 let open Names in
830 let rec mp2sl = function
831 | MPfile dp -> CList.rev_map Id.to_string (DirPath.repr dp)
832 | MPbound id ->
833 let _, id, dp = MBId.repr id in
834 mp2sl (MPfile dp) @ [ Id.to_string id ]
835 | MPdot (mp, lbl) -> mp2sl mp @ [ Label.to_string lbl ]
836 in
837 mp2sl x
838
839 let gr2path gr =
840 let open Names in
841 match gr with
842 | Names.GlobRef.VarRef v -> mp2path (Lib.current_mp ())
843 | Names.GlobRef.ConstRef c -> mp2path @@ Constant.modpath c
844 | Names.GlobRef.IndRef (i, _) -> mp2path @@ MutInd.modpath i
845 | Names.GlobRef.ConstructRef ((i, _), j) -> mp2path @@ MutInd.modpath i
846
847 let eta_contract env sigma t =
848 let unzip l t = EConstr.it_mkLambda t l in
849 let not_occurs n t =
850 let fr = Termops.free_rels sigma t in
851 let rec aux i =
852 if n < i then true
853 else not (Int.Set.mem i fr) && aux (i+1) in
854 aux 1 in
855 (*let not_occurs n t =
856 let rc = not_occurs n t in
857 Printf.eprintf "not_occurs %d %s %b\n" n Pp.(string_of_ppcmds @@ Printer.pr_econstr_env env sigma t) rc;
858 rc in*)
859 let eta_condition vl nargs i t =
860 if i < nargs - vl then not_occurs vl t
861 else EConstr.eq_constr_nounivs sigma t (EConstr.mkRel (vl - (i - (nargs - vl)))) in
862 let rec contract env vl t =
863 match EConstr.kind sigma t with
864 | App(hdo,argso) ->
865 let hd = map env hdo in
866 let args = CArray.Smart.map (map env) argso in
867 let nargs = Array.length args in
868 if nargs >= vl &&
869 not_occurs vl hd &&
870 CArray.for_all_i (eta_condition vl nargs) 0 args
871 then
872 let args = Array.sub args 0 (nargs - vl) in
873 (* apperantly negative lift is a thing *)
874 EConstr.Vars.lift (-vl) (EConstr.mkApp(hd,args)), true
875 else
876 if hd == hdo && args == argso then t, false
877 else EConstr.mkApp(hd,args), false
878 | _ -> map env t, false
879 and cross env (o,vl,zip) t =
880 match EConstr.kind sigma t with
881 | Lambda(name,ty,bo) -> cross env (o,vl+1,(name,ty)::zip) bo
882 | _ ->
883 let t', b = contract env vl t in
884 if b then t'
885 else if t == t' then o
886 else unzip zip t'
887 and map env t =
888 match EConstr.kind sigma t with
889 | Lambda _ -> cross env (t,0,[]) t
890 | _ -> Termops.map_constr_with_full_binders env sigma EConstr.push_rel map env t
891 in
892 (*Printf.eprintf "------------- %s\n" Pp.(string_of_ppcmds @@ Printer.pr_econstr_env env sigma t);*)
893 map env t
894
895 [%%if coq = "8.20" || coq = "9.0" || coq = "9.1"]
896 let is_sync_anomaly = function
897 | Control.Timeout | Sys.Break | Out_of_memory | Stack_overflow -> false
898 | e -> if Memprof_coq.is_interrupted() then false else CErrors.is_anomaly e
899 [%%else]
900 let is_sync_anomaly = CErrors.is_sync_anomaly
901 [%%endif]
902
903 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
904 let push_named = Environ.push_named
905 [%%else]
906 let push_named = Environ.push_named ProofVar
907 [%%endif]
908
909 let prune_uvar state ev args =
910 let state, ev1 = API.FlexibleData.Elpi.make state in
911 let rec mkLam = function [] -> API.RawData.mkUnifVar ev1 ~args:[] state | _ :: rest -> API.RawData.mkLam (mkLam rest) in
912 state, API.Conversion.Unify(mkLam args,API.RawData.mkUnifVar ev ~args:[] state)
913