Debian Codegraph @

src/rocq_elpi_builtins.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 State = API.State
8 module P = API.RawPp
9 module Conv = API.Conversion
10 module CConv = API.ContextualConversion
11 module B = struct
12 include API.BuiltInData
13 include Elpi.Builtin
14 let ioarg = API.BuiltInPredicate.ioarg
15 let ioarg_any = API.BuiltInPredicate.ioarg_any
16 let ioargC = API.BuiltInPredicate.ioargC
17 let ioargC_flex = API.BuiltInPredicate.ioargC_flex
18 (* let ioarg_flex = API.BuiltInPredicate.ioarg_flex *)
19 let ioarg_poly s = { ioarg_any with API.Conversion.ty = API.Conversion.TyName s }
20
21 let listC (d : ('a,'h,'cst) CConv.t) =
22 let embed ~depth h cst s l =
23 let s, l, eg = API.Utils.map_acc (d.CConv.embed ~depth h cst ) s l in
24 s, API.Utils.list_to_lp_list l, eg in
25 let readback ~depth h cst s t =
26 API.Utils.map_acc (d.CConv.readback ~depth h cst) s
27 (API.Utils.lp_list_to_list ~depth t)
28 in
29 let pp fmt l =
30 Format.fprintf fmt "[%a]" (API.RawPp.list d.CConv.pp ~boxed:true "; ") l in
31 { CConv.embed; readback;
32 ty = TyApp ("list",d.CConv.ty,[]);
33 pp;
34 pp_doc = (fun fmt () -> ()) }
35
36 end
37 module Pred = API.BuiltInPredicate
38 module U = API.Utils
39
40 module CNotation = Notation
41
42 open Names
43
44 open Rocq_elpi_utils
45 open Rocq_elpi_HOAS
46
47 let string_of_ppcmds options pp =
48 let b = Buffer.create 512 in
49 let fmt = Format.formatter_of_buffer b in
50 Format.pp_set_margin fmt options.ppwidth;
51 Format.fprintf fmt "@[%a@]" Pp.pp_with pp;
52 Format.pp_print_flush fmt ();
53 Buffer.contents b
54
55
56 [%%if coq = "9.0" || coq = "9.1"]
57 let with_pp_options o f =
58 let raw_print = !Flags.raw_print in
59 let print_universes = !Detyping.print_universes in
60 let print_no_symbol = !Constrextern.print_no_symbol in
61 (* 8.14 let print_primitive_token = !Constrextern.print_primitive_token in*)
62 let print_implicits = !Constrextern.print_implicits in
63 let print_coercions = !Constrextern.print_coercions in
64 let print_parentheses = !Constrextern.print_parentheses in
65 let print_projections = !Constrextern.print_projections in
66 let print_evar_arguments = !Detyping.print_evar_arguments in
67 let f =
68 match o with
69 | All ->
70 Flags.raw_print := true;
71 f
72 | Most ->
73 Flags.raw_print := false;
74 Detyping.print_universes := false;
75 Constrextern.print_no_symbol := true;
76 (* 8.14 Constrextern.print_primitive_token := true; *)
77 Constrextern.print_implicits := true;
78 Constrextern.print_coercions := true;
79 Constrextern.print_parentheses := true;
80 Constrextern.print_projections := false;
81 Detyping.print_evar_arguments := false;
82 f
83 | Normal ->
84 (* If no preference is given, we print using Coq's current value *)
85 f
86 in
87 try
88 let rc = f () in
89 Flags.raw_print := raw_print;
90 Detyping.print_universes := print_universes;
91 Constrextern.print_no_symbol := print_no_symbol;
92 (* 8.14 Constrextern.print_primitive_token := print_primitive_token; *)
93 Constrextern.print_implicits := print_implicits;
94 Constrextern.print_coercions := print_coercions;
95 Constrextern.print_parentheses := print_parentheses;
96 Constrextern.print_projections := print_projections;
97 Detyping.print_evar_arguments := print_evar_arguments;
98 rc
99 with reraise ->
100 Flags.raw_print := raw_print;
101 Detyping.print_universes := print_universes;
102 Constrextern.print_no_symbol := print_no_symbol;
103 (* 8.14 Constrextern.print_primitive_token := print_primitive_token; *)
104 Constrextern.print_implicits := print_implicits;
105 Constrextern.print_coercions := print_coercions;
106 Constrextern.print_parentheses := print_parentheses;
107 Constrextern.print_projections := print_projections;
108 Detyping.print_evar_arguments := print_evar_arguments;
109 raise reraise
110
111 let extern_constr_flagged () = Constrextern.extern_constr
112 let pr_constr_expr_n_flagged () = Ppconstr.pr_constr_expr_n
113 let pr_econstr_env_flagged () = Printer.pr_econstr_env
114 let pr_named_decl_flagged () = Printer.pr_named_decl
115 let pr_named_context_flagged () = Printer.pr_named_context
116 let empty_extern_env () = Constrextern.empty_extern_env
117 [%%else]
118 let flags_of_pp_options o =
119 match o with
120 | Normal -> PrintingFlags.current()
121 | All -> PrintingFlags.(make_raw @@ current())
122 | Most -> {
123 detype = {
124 (PrintingFlags.Detype.current_ignore_raw()) with
125 universes = false;
126 evar_instances = false;
127 };
128 extern = {
129 (PrintingFlags.Extern.current_ignore_raw()) with
130 notations = false;
131 implicits = true;
132 coercions = true;
133 parentheses = true;
134 projections = false;
135 };
136 }
137
138 let with_pp_options o f =
139 f (flags_of_pp_options o)
140
141 let extern_constr_flagged flags env sigma c =
142 Constrextern.extern_constr ~flags env sigma c
143 let pr_constr_expr_n_flagged flags env sigma lev expr =
144 Ppconstr.pr_constr_expr_n ~flags:(Ppconstr.of_printing_flags flags) env sigma lev expr
145 let pr_econstr_env_flagged flags env sigma c =
146 Printer.pr_econstr_env ~flags env sigma c
147 let pr_named_decl_flagged flags env sigma d =
148 Printer.pr_named_decl ~flags env sigma d
149 let pr_named_context_flagged flags env sigma d =
150 Printer.pr_named_context ~flags env sigma d
151 let empty_extern_env () = Constrextern.empty_extern_env ~flags:(PrintingFlags.Extern.current())
152 [%%endif]
153
154
155 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
156 let pr_named_context_of options env sigma =
157 let make_decl_list env d pps =
158 with_pp_options options.pp (fun flags -> pr_named_decl_flagged flags env sigma d) :: pps in
159 let psl = List.rev (Environ.fold_named_context make_decl_list env ~init:[]) in
160 Pp.(v 0 (prlist_with_sep (fun _ -> ws 2) (fun x -> x) psl))
161 [%%else]
162 let pr_named_context_of options env sigma =
163 let make_decl_list env status d pps =
164 with_pp_options options.pp (fun flags -> pr_named_decl_flagged flags env sigma (Some status) d) :: pps in
165 let psl = List.rev (Environ.fold_named_context make_decl_list env ~init:[]) in
166 Pp.(v 0 (prlist_with_sep (fun _ -> ws 2) (fun x -> x) psl))
167 [%%endif]
168
169 let with_no_tc ~no_tc f sigma =
170 if no_tc then
171 let typeclass_evars = Evd.get_typeclass_evars sigma in
172 let sigma = Evd.set_typeclass_evars sigma Evar.Set.empty in
173 let sigma, rc = f sigma in
174 let typeclass_evars = Evar.Set.filter (fun x ->
175 try ignore (Evd.find_undefined sigma x); true
176 with Not_found -> false) typeclass_evars in
177 let sigma = Evd.set_typeclass_evars sigma typeclass_evars in
178 sigma, rc
179 else f sigma
180
181 let pr_econstr_env options env sigma t =
182 with_pp_options options.pp (fun flags ->
183 let expr = extern_constr_flagged flags env sigma t in
184 let expr =
185 let rec aux () ({ CAst.v } as orig) = match v with
186 | Constrexpr.CEvar _ -> CAst.make @@ Constrexpr.CHole(None)
187 | _ -> Constrexpr_ops.map_constr_expr_with_binders (fun _ () -> ()) aux () orig in
188 if options.hoas_holes = Some Heuristic then aux () expr else expr in
189 pr_constr_expr_n_flagged flags env sigma options.pplevel expr)
190
191 let tactic_mode : bool State.component = State.declare_component ~name:"rocq-elpi:tactic-mode" ~descriptor:interp_state
192 ~pp:(fun fmt x -> Format.fprintf fmt "%b" x)
193 ~init:(fun () -> false)
194 ~start:(fun x -> x) ()
195
196 let base =
197 API.State.declare_component ~name:"rocq-elpi:base" ~descriptor:interp_state
198 ~init:(fun () -> None)
199 ~pp:(fun fmt -> function Some _ -> () | None -> ())
200 ~start:(fun x -> x) ()
201
202 let abstract__grab_global_env_keep_sigma api thunk = (); (fun state ->
203 let uctx, state, result, gls = thunk state in
204 Rocq_elpi_HOAS.grab_global_env ~uctx state, result, gls)
205
206 let grab_global_env__drop_sigma_univs_if_option_is_set options api thunk = (); (fun state ->
207 if State.get tactic_mode state then
208 Rocq_elpi_utils.err Pp.(strbrk ("API " ^ api ^ " cannot be used in tactics"));
209 let uctx, state, result, gls = thunk state in
210 match options with
211 | { keepunivs = Some false } -> Rocq_elpi_HOAS.grab_global_env_drop_univs_and_sigma state, result, gls
212 | _ -> Rocq_elpi_HOAS.grab_global_env ~uctx state, result, gls)
213
214 let grab_global_env api thunk = (); (fun state ->
215 if State.get tactic_mode state then
216 Rocq_elpi_utils.err Pp.(strbrk ("API " ^ api ^ " cannot be used in tactics"));
217 let uctx, state, result, gls = thunk state in
218 Rocq_elpi_HOAS.grab_global_env ~uctx state, result, gls)
219
220 (* This is for stuff that is not monotonic in the env, eg section closing *)
221 let grab_global_env_drop_sigma api thunk = (); (fun state ->
222 if State.get tactic_mode state then
223 Rocq_elpi_utils.err Pp.(strbrk ("API " ^ api ^ " cannot be used in tactics"));
224 let state, result, gls = thunk state in
225 Rocq_elpi_HOAS.grab_global_env_drop_sigma state, result, gls)
226
227 let grab_global_env_drop_sigma_keep_univs api thunk = (); (fun state ->
228 if State.get tactic_mode state then
229 Rocq_elpi_utils.err Pp.(strbrk ("API " ^ api ^ " cannot be used in tactics"));
230 let uctx, state, result, gls = thunk state in
231 Rocq_elpi_HOAS.grab_global_env_drop_sigma_keep_univs ~uctx state, result, gls)
232
233 let bool = B.bool
234 let int = B.int
235 let list = B.list
236 let pair = B.pair
237 let option = B.option
238
239 let mk_algebraic_super x = Sorts.super x
240
241 (* I don't want the user to even know that algebraic universes exist *)
242
243 let univ_super state u v =
244 let state, u = match u with
245 | Sorts.(Set | Prop | SProp) -> state, u
246 | _ ->
247 let ul = Rocq_elpi_HOAS.univ_of_sort u in
248 if Univ.Universe.is_level ul then state, u
249 else
250 let state, (_,w) = new_univ_level_variable state in
251 let w = Sorts.sort_of_univ w in
252 add_universe_constraint state (constraint_leq u w), w in
253 add_universe_constraint state (constraint_leq (mk_algebraic_super u) v)
254
255 let univ_product state s1 s2 =
256 let s = Typeops.sort_of_product (get_global_env state) s1 s2 in
257 let state, (_,v) = new_univ_level_variable state in
258 let v = Sorts.sort_of_univ v in
259 let state = add_universe_constraint state (constraint_leq s v) in
260 state, v
261
262 let constr2lp ~depth hyps constraints state t =
263 constr2lp ~depth hyps constraints state t
264
265 let constr2lp_closed ~depth hyps constraints state t =
266 constr2lp_closed ~depth hyps constraints state t
267
268 let constr2lp_closed_ground ~depth hyps constraints state t =
269 constr2lp_closed_ground ~depth hyps constraints state t
270
271 let clauses_for_later_interp : _ State.component =
272 State.declare_component ~name:"rocq-elpi:clauses_for_later" ~descriptor:interp_state
273 ~init:(fun () -> [])
274 ~start:(fun x -> x)
275 ~pp:(fun fmt l ->
276 List.iter (fun (dbname, code,vars,scope) ->
277 Format.fprintf fmt "db:%s code:%a scope:%a\n"
278 (String.concat "." dbname)
279 Elpi.API.Pp.Ast.program code Rocq_elpi_utils.pp_scope scope) l) ()
280
281 let term = {
282 CConv.ty = Conv.TyName "term";
283 pp_doc = (fun fmt () -> Format.fprintf fmt "A Coq term containing evars");
284 pp = (fun fmt t -> Format.fprintf fmt "@[%a@]" Pp.pp_with ( (Printer.pr_econstr_env (Global.env()) Evd.empty t)));
285 readback = lp2constr;
286 embed = constr2lp;
287 }
288 let failsafe_term = {
289 CConv.ty = Conv.TyName "term";
290 pp_doc = (fun fmt () -> Format.fprintf fmt "A Coq term containing evars");
291 pp = (fun fmt t -> Format.fprintf fmt "@[%a@]" Pp.pp_with ( (Printer.pr_econstr_env (Global.env()) Evd.empty t)));
292 readback = (fun ~depth coq_ctx csts s t -> lp2constr ~depth { coq_ctx with options = { coq_ctx.options with failsafe = true }} csts s t);
293 embed = constr2lp;
294 }
295
296 let proof_context : (full conv_context, API.Data.constraints) CConv.ctx_readback =
297 fun ~depth hyps constraints state ->
298 let state, proof_context, _, gls = get_current_env_sigma ~depth hyps constraints state in
299 state, proof_context, constraints, gls
300
301 let closed_term = {
302 CConv.ty = Conv.TyName "term";
303 pp_doc = (fun fmt () -> Format.fprintf fmt "A closed Coq term");
304 pp = (fun fmt t -> Format.fprintf fmt "@[%a@]" Pp.pp_with ( (Printer.pr_econstr_env (Global.env()) Evd.empty t)));
305 readback = lp2constr_closed;
306 embed = constr2lp_closed
307 }
308 let global : (empty conv_context, API.Data.constraints) CConv.ctx_readback =
309 fun ~depth hyps constraints state ->
310 let state, proof_context, _, gls = get_global_env_current_sigma ~depth hyps constraints state in
311 state, proof_context, constraints, gls
312
313 let closed_ground_term = {
314 CConv.ty = Conv.TyName "term";
315 pp_doc = (fun fmt () -> Format.fprintf fmt "A ground, closed, Coq term");
316 pp = (fun fmt t -> Format.fprintf fmt "@[%a@]" Pp.pp_with ( (Printer.pr_econstr_env (Global.env()) Evd.empty t)));
317 readback = lp2constr_closed_ground;
318 embed = constr2lp_closed_ground
319 }
320
321 let term_skeleton = {
322 CConv.ty = Conv.TyName "term";
323 pp_doc = (fun fmt () -> Format.fprintf fmt "A Coq term containing holes");
324 pp = (fun fmt t ->
325 let env = Global.env() in
326 let sigma = Evd.from_env env in
327 Format.fprintf fmt "@[%a@]" Pp.pp_with ( (Printer.pr_glob_constr_env env sigma t)));
328 readback = lp2skeleton;
329 embed = (fun ~depth _ _ _ _ -> assert false);
330 }
331
332 let sealed_goal = {
333 Conv.ty = Conv.TyName "sealed-goal";
334 pp_doc = (fun fmt () -> ());
335 pp = (fun fmt _ -> Format.fprintf fmt "TODO");
336 embed = sealed_goal2lp;
337 readback = (fun ~depth _ _ -> assert false);
338 }
339
340 type goal = {
341 caller : E.term option; (* for error messages *)
342 proof_context : Rocq_elpi_HOAS.full Rocq_elpi_HOAS.conv_context;
343 evar : Evar.t;
344 tac_args : Rocq_elpi_arg_HOAS.coq_arg list;
345 }
346
347 let goal_readback ~depth hyps csts state g : State.t * goal * Conv.extra_goals =
348 let state, (proof_context, evar, raw_args), gls1 = Rocq_elpi_HOAS.lp2goal ~depth hyps csts state g in
349 let state, tac_args, gls2 = U.map_acc (Rocq_elpi_arg_HOAS.in_coq_arg ~depth proof_context csts) state raw_args in
350 state, { caller = None; proof_context; evar; tac_args }, gls1 @ gls2
351
352 let goal_embed ~depth _ csts state { caller = tac; proof_context; evar; tac_args } =
353 assert(tac_args=[]);
354 match Rocq_elpi_HOAS.goal2lp ~depth csts state proof_context evar with
355 | Result.Ok (st, r, gl) -> st,r,gl
356 | Result.Error env ->
357 let env = EConstr.Unsafe.to_named_context env in
358 let old_env = proof_context.env in
359 let msg =
360 Pp.string_of_ppcmds
361 Pp.(strbrk "coq.ltac.call-simple-ltac1: The tactic "
362 ++ Option.cata (fun tac -> str (pp2string (API.RawPp.term depth) tac)) (mt ()) tac
363 ++ strbrk " generates a subgoal that lives in a different context."
364 ++ fnl () ++ str "Input context:" ++ fnl ()
365 ++ pr_named_context_of proof_context.options old_env (get_sigma state)
366 ++ fnl () ++ str "Output context:" ++ fnl ()
367 ++ with_pp_options proof_context.options.pp (fun flags -> pr_named_context_flagged flags old_env (get_sigma state) env))
368 in
369 U.type_error msg
370
371 let goal : ( goal , API.Data.hyps, API.Data.constraints) CConv.t = {
372 CConv.ty = Conv.TyName "goal";
373 pp_doc = (fun fmt () -> ());
374 pp = (fun fmt _ -> Format.fprintf fmt "TODO");
375 embed = goal_embed;
376 readback = (fun ~depth hyps csts st g -> goal_readback ~depth (E.of_hyps hyps) csts st g)
377 }
378 let goal' : ( goal , Rocq_elpi_HOAS.full Rocq_elpi_HOAS.conv_context , API.Data.constraints) CConv.t = {
379 CConv.ty = Conv.TyName "goal";
380 pp_doc = (fun fmt () -> ());
381 pp = (fun fmt _ -> Format.fprintf fmt "TODO");
382 embed = (fun ~depth hyps csts state x -> goal_embed ~depth hyps.hyps csts state x);
383 readback = (fun ~depth hyps csts state g -> goal_readback ~depth hyps.hyps csts state g);
384 }
385
386 let tactic_arg : (Rocq_elpi_arg_HOAS.coq_arg, Rocq_elpi_HOAS.full Rocq_elpi_HOAS.conv_context, API.Data.constraints) CConv.t = {
387 CConv.ty = Conv.TyName "argument";
388 pp_doc = (fun fmt () -> ());
389 pp = (fun fmt _ -> Format.fprintf fmt "TODO");
390 embed = (fun ~depth _ _ _ _ -> assert false);
391 readback = Rocq_elpi_arg_HOAS.in_coq_arg;
392 }
393
394 let goals_of_term state proof_context proof =
395 let env = proof_context.env in
396 let sigma = get_sigma state in
397 let evars_of_term c =
398 let rec evrec env (acc_set,acc_rev_l as acc) c =
399 match EConstr.kind sigma c with
400 | Constr.Evar (n, l) ->
401 if Evar.Set.mem n acc_set then
402 acc
403 else
404 let acc = Evar.Set.add n acc_set, n :: acc_rev_l in
405 SList.Skip.fold (evrec env) acc l
406 | Constr.Proj (_, _, c) ->
407 let t = Retyping.get_type_of env sigma c in
408 let acc = evrec env acc t in
409 evrec env acc c
410 | _ -> Termops.fold_constr_with_full_binders env sigma EConstr.push_rel evrec env acc c
411 in
412 let _, rev_l = evrec env (Evar.Set.empty, []) c in
413 List.rev rev_l in
414 let subgoals = evars_of_term proof in
415 let free_evars =
416 let cache = Evarutil.create_undefined_evars_cache () in
417 let map ev =
418 let EvarInfo evi = Evd.find sigma ev in
419 let fevs = lazy (Evarutil.filtered_undefined_evars_of_evar_info ~cache sigma evi) in
420 (ev, fevs)
421 in
422 List.map map subgoals in
423 let shelved_subgoals, subgoals =
424 CList.partition
425 (fun g ->
426 CList.exists (fun (tgt, lazy evs) -> not (Evar.equal g tgt) && Evar.Set.mem g evs) free_evars)
427 subgoals in
428 shelved_subgoals, subgoals
429
430 let id = Rocq_elpi_builtins_synterp.id
431
432 let flag name = { (B.unspec bool) with Conv.ty = Conv.TyName name }
433
434 (* Unfortunately the data type is not symmeteric *)
435 let indt_decl_in = {
436 CConv.ty = Conv.TyName "indt-decl";
437 pp_doc = (fun fmt () -> Format.fprintf fmt "Declaration of an inductive type");
438 pp = (fun fmt _ -> Format.fprintf fmt "mutual_inductive_entry");
439 readback = (fun ~depth ctx csts state t -> lp2inductive_entry ~depth ctx csts state t);
440 embed = (fun ~depth ctx csts state t -> assert false);
441 }
442 let indt_decl_out = {
443 CConv.ty = Conv.TyName "indt-decl";
444 pp_doc = (fun fmt () -> Format.fprintf fmt "Declaration of an inductive type");
445 pp = (fun fmt _ -> Format.fprintf fmt "mutual_inductive_entry");
446 readback = (fun ~depth ctx csts state t -> assert false);
447 embed = (fun ~depth ctx csts state t -> inductive_decl2lp ~depth ctx csts state t);
448 }
449
450 let is_ground sigma t = Evar.Set.is_empty (Evd.evars_of_term sigma t)
451 let is_ground_one_inductive_entry sigma { Entries.mind_entry_arity; mind_entry_lc } =
452 is_ground sigma (EConstr.of_constr mind_entry_arity) &&
453 List.for_all (is_ground sigma) @@ List.map EConstr.of_constr mind_entry_lc
454 let is_ground_rel_ctx_entry sigma rc =
455 is_ground sigma @@ EConstr.of_constr @@ Context.Rel.Declaration.get_type rc &&
456 Option.cata (fun x -> is_ground sigma @@ EConstr.of_constr x) true @@ Context.Rel.Declaration.get_value rc
457 let is_mutual_inductive_entry_ground { Entries.mind_entry_params; mind_entry_inds } sigma =
458 List.for_all (is_ground_rel_ctx_entry sigma) mind_entry_params &&
459 List.for_all (is_ground_one_inductive_entry sigma) mind_entry_inds
460
461 [%%if coq = "9.0" || coq = "9.1"]
462 let evd_merge_sort_context_set rigid = Evd.merge_sort_context_set rigid
463 let check_univ_decl = UState.check_univ_decl
464 let univ_csts_to_list = Univ.Constraints.elements
465 let univs_of_csts = UState.constraints
466 let ucsts_filter = Univ.Constraints.filter
467 let default_polyflags = false
468 [%%else]
469 let evd_merge_sort_context_set rigid = Evd.merge_sort_context_set rigid
470 let check_univ_decl = UState.check_univ_decl
471 let univ_csts_to_list = Univ.UnivConstraints.elements
472 let univs_of_csts x = PConstraints.univs @@ UState.constraints x
473 let ucsts_filter = Univ.UnivConstraints.filter
474 let default_polyflags = PolyFlags.default
475 [%%endif]
476
477 let handle_uinst_option_for_inductive ~depth options i state =
478 match options.uinstance with
479 | NoInstance ->
480 let term, ctx = UnivGen.fresh_global_instance (get_global_env state) (GlobRef.IndRef i) in
481 let state = update_sigma state (fun sigma -> evd_merge_sort_context_set UState.univ_flexible_alg sigma ctx) in
482 snd @@ Constr.destInd term, state, []
483 | ConcreteInstance i -> i, state, []
484 | VarInstance (v_head, v_args, v_depth) ->
485 let v' = U.move ~from:v_depth ~to_:depth (E.mkUnifVar v_head ~args:v_args state) in
486 let term, ctx =
487 UnivGen.fresh_global_instance (get_global_env state) (GlobRef.IndRef i) in
488 let uinst = snd @@ Constr.destInd term in
489 let state, lp_uinst, extra_goals = uinstance.Conv.embed ~depth state uinst in
490 let state = update_sigma state (fun sigma -> evd_merge_sort_context_set UState.univ_flexible_alg sigma ctx) in
491 uinst, state, API.Conversion.Unify (v', lp_uinst) :: extra_goals
492
493 (* FIXME PARTIAL API
494 *
495 * Record foo A1..Am := K { f1; .. fn }. -- m params, n fields
496 * Canonical c (x1 : b1)..(xk : bk) := K p1..pm t1..tn.
497 *
498 * fi v1..vm ? rest1 == (ci w1..wr) rest2
499 *
500 * ?i : bi
501 * vi =?= pi[xi/?i]
502 * wi =?= ui[xi/?i]
503 * ? == c ?1 .. ?k
504 * rest1 == rest2
505 * ?j =<= (ci w1..wr) -- default proj, ti = xj
506 * ci == gr
507 *
508 * unif (const fi) [V1,..VM, C | R1] (const ci) [W1,..WR| R2] M U :-
509 * of (app[c, ?1,..?k]) _ CR, -- saturate
510 * hd-beta CR [] (indc _) [P1,..PM,T1,..TN],
511 * unify-list-U Vi Pi,
512 * Ti = app[const ci|U1,..,UN],
513 * unify-list-U Wi Ui,
514 * unify-eq C CR,
515 * unify-list-eq R1 R2.
516 *
517 *)
518 [%%if coq = "9.0"]
519 let build_of_sort = API.AlgebraicData.B (fun s -> Structures.ValuePattern.Sort_cs (Sorts.family s))
520 let match_of_sort =
521 let open API.AlgebraicData in let open Structures.ValuePattern in
522 MS (fun ~ok ~ko p state -> match p with
523 | Sort_cs Sorts.InSet -> ok Sorts.set state
524 | Sort_cs Sorts.InProp -> ok Sorts.prop state
525 | Sort_cs Sorts.InType ->
526 let state, (_,u) = new_univ_level_variable state in
527 let u = Sorts.sort_of_univ u in
528 ok u state
529 | _ -> ko state)
530 [%%else]
531 let build_of_sort = API.AlgebraicData.B (fun s -> Structures.ValuePattern.Sort_cs (UnivGen.QualityOrSet.of_sort s))
532 let match_of_sort =
533 let open API.AlgebraicData in let open Structures.ValuePattern in
534 MS (fun ~ok ~ko p state -> match p with
535 | Sort_cs UnivGen.QualityOrSet.Set -> ok Sorts.set state
536 | Sort_cs UnivGen.QualityOrSet.(Qual (QConstant QProp)) -> ok Sorts.prop state
537 | Sort_cs UnivGen.QualityOrSet.(Qual (QConstant QType)) ->
538 let state, (_,u) = new_univ_level_variable state in
539 let u = Sorts.sort_of_univ u in
540 ok u state
541 | _ -> ko state)
542 [%%endif]
543
544 [%%if coq = "9.0" || coq = "9.1"]
545 let hint_globref = Hints.hint_globref
546 [%%else]
547 let hint_globref gr = gr
548 [%%endif]
549
550 [%%if coq = "9.0" || coq = "9.1"]
551 let abbreviation_find_interp = Abbreviation.search_abbreviation
552 let abbreviation_declare = Abbreviation.declare_abbreviation
553 [%%else]
554 let abbreviation_find_interp = Abbreviation.find_interp
555 let abbreviation_declare = Abbreviation.declare
556 [%%endif]
557
558 [%%if coq = "9.0" || coq = "9.1"]
559 let for_scheme = function
560 | GlobRef.ConstRef c -> c
561 | _ -> U.type_error "Register Scheme: expecing a constant."
562 let lookup_scheme_opt k gr =
563 match gr with
564 | GlobRef.IndRef ind ->
565 (try Some (GlobRef.ConstRef (DeclareScheme.lookup_scheme k ind))
566 with Not_found -> None)
567 | _ -> None
568 [%%elif coq = "9.2"]
569 let for_scheme gr = gr
570 let lookup_scheme_opt k gr =
571 match gr with
572 | GlobRef.IndRef ind -> DeclareScheme.lookup_scheme_opt k ind
573 | _ -> None
574 [%%else]
575 let for_scheme gr = gr
576 let lookup_scheme_opt k gr =
577 DeclareScheme.lookup_scheme_opt k gr
578 [%%endif]
579
580 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
581 let declare_scheme_for local k x gr =
582 let ind = match x with
583 | GlobRef.IndRef i -> i
584 | _ -> U.type_error "Register_scheme: expecting an inductive" in
585 DeclareScheme.declare_scheme local k (ind, for_scheme gr)
586 [%%else]
587 let declare_scheme_for local k x gr =
588 DeclareScheme.declare_scheme local k (x, for_scheme gr)
589 [%%endif]
590
591 let cs_pattern =
592 let open Conv in let open API.AlgebraicData in let open Structures.ValuePattern in declare {
593 ty = TyName "cs-pattern";
594 doc = "Pattern for canonical values";
595 pp = (fun fmt -> function
596 | Const_cs x -> Format.fprintf fmt "Const_cs %s" "<todo>"
597 | Proj_cs x -> Format.fprintf fmt "Proj_cs %s" "<todo>"
598 | Prod_cs -> Format.fprintf fmt "Prod_cs"
599 | Sort_cs _ -> Format.fprintf fmt "Sort_cs"
600 | Default_cs -> Format.fprintf fmt "Default_cs");
601 constructors = [
602 K("cs-gref","",A(gref,N),
603 B (function
604 | GlobRef.ConstructRef _ | GlobRef.IndRef _ | GlobRef.VarRef _ as x -> Const_cs x
605 | GlobRef.ConstRef cst as x ->
606 match Structures.PrimitiveProjections.find_opt cst with
607 | None -> Const_cs x
608 | Some p -> Proj_cs p),
609 MS (fun ~ok ~ko p state -> match p with Const_cs x -> ok x state | Proj_cs p -> ok (GlobRef.ConstRef (get_projection_constant (get_global_env state) p)) state | _ -> ko state));
610 K("cs-prod","",N,
611 B Prod_cs,
612 M (fun ~ok ~ko -> function Prod_cs -> ok | _ -> ko ()));
613 K("cs-default","",N,
614 B Default_cs,
615 M (fun ~ok ~ko -> function Default_cs -> ok | _ -> ko ()));
616 K("cs-sort","",CA(sort,N),build_of_sort,match_of_sort)
617 ]
618 }
619
620 let cs_instance = let open Conv in let open API.AlgebraicData in let open Structures.CSTable in declare {
621 ty = TyName "cs-instance";
622 doc = "Canonical Structure instances: (cs-instance Proj ValPat Inst)";
623 pp = (fun fmt { solution } -> Format.fprintf fmt "@[%a@]" Pp.pp_with ((Printer.pr_global solution)));
624 constructors = [
625 K("cs-instance","",A(gref,CA(cs_pattern,A(gref,N))),
626 B (fun p v i -> assert false),
627 M (fun ~ok ~ko { solution; value; projection } -> ok projection value solution))
628 ]
629 }
630
631
632 [%%if coq = "9.0" || coq = "9.1"]
633 let cs_entries_for_proj env p =
634 Structures.CSTable.entries_for ~projection:p
635
636 let arguments_names env c =
637 Arguments_renaming.arguments_names c
638
639 let find_arguments_scope env c =
640 CNotation.find_arguments_scope c
641 [%%else]
642 let cs_entries_for_proj env p =
643 Structures.CSTable.entries_for env ~projection:p
644
645 let arguments_names env c =
646 Arguments_renaming.arguments_names env c
647
648 let find_arguments_scope env c =
649 CNotation.find_arguments_scope env c
650 [%%endif]
651
652 type type_class_instance = {
653 implementation : GlobRef.t;
654 priority : int;
655 }
656
657 [%%if coq = "9.0" || coq = "9.1"]
658 let tc_is_class env gr =
659 Typeclasses.is_class gr
660 [%%else]
661 let tc_is_class env gr =
662 Typeclasses.is_class env gr
663 [%%endif]
664
665 let tc_instance = let open Conv in let open API.AlgebraicData in declare {
666 ty = TyName "tc-instance";
667 doc = "Type class instance with priority";
668 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
669 constructors = [
670 K("tc-instance","",A(gref,A(int,N)),
671 B (fun implementation priority -> { implementation; priority }),
672 M (fun ~ok ~ko { implementation; priority } -> ok implementation priority));
673 ]
674 } |> CConv.(!<)
675
676 let get_instance_prio env class_gr inst_gr =
677 let exception STOP in
678 (* db contains the hints stored in the typeclassses_db *)
679 let db = Hints.searchtable_map Class_tactics.typeclasses_db in
680 (* full_hint is the **list** of hints for a typeclass *)
681 let full_hint = ref None in
682 (try
683 (* since we have not a "find" API in Hints.Hint_db to get the value associated to a class gref
684 we iterate over the list until finding the wanted result *)
685 (* complexity: O(N) where N is the number of typeclasses *)
686 Hints.Hint_db.iter (fun gro _ fh ->
687 Option.iter (fun gr ->
688 if Environ.QGlobRef.equal env gr class_gr then
689 (full_hint := Some fh; raise STOP)) gro) db;
690 with STOP -> ());
691 match !full_hint with
692 (* None means that we cannot find the class gref in the db *)
693 | None -> err Pp.(str"Cannot find the gref" ++ GlobRef.print class_gr ++ str" in typeclass_instances: is it a valid typeclass?")
694 | Some full_hint ->
695 let same_inst e =
696 match Hints.FullHint.name e with
697 | Some hint_name when Environ.QGlobRef.equal env hint_name inst_gr -> Some (Hints.FullHint.priority e)
698 | _ -> None
699 in
700 (* We look in the list of hint for the one associated to inst_gr, if it does not exists: error *)
701 (* complexity: O(N) where N is the number of instances of class_gr *)
702 match List.find_map same_inst full_hint with
703 | None -> err Pp.(str"Cannot find the priority of " ++ GlobRef.print inst_gr ++
704 str": either it is not an instance of " ++ GlobRef.print class_gr ++
705 str" or it is not stored as a hint in typeclasses_instances")
706 | Some e -> e
707
708 let get_instance env class_gr inst_gr : type_class_instance =
709 let priority = get_instance_prio env class_gr inst_gr in
710 { implementation = inst_gr; priority }
711
712 let warning_tc_hints = CWarnings.create ~name:"elpi.TC.hints" ~category:elpi_cat Pp.str
713
714 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
715 let hints_map_all env ~secvars tc db =
716 Hints.Hint_db.map_all ~secvars tc db
717 [%%else]
718 let hints_map_all env ~secvars tc db =
719 Hints.Hint_db.map_all env ~secvars tc db
720 [%%endif]
721
722 let get_instances (env: Environ.env) (sigma: Evd.evar_map) tc : type_class_instance list =
723 let hint_db = Hints.searchtable_map "typeclass_instances" in
724 let secvars : Names.Id.Pred.t = Names.Id.Pred.full in
725 let full_hints = hints_map_all env ~secvars:secvars tc hint_db in
726 (* let hint_asts = List.map Hints.FullHint.repr full_hints in *)
727 let hints = List.filter_map (fun (e : Hints.FullHint.t) -> match Hints.FullHint.repr e with
728 | Hints.Res_pf a | ERes_pf a | Give_exact a -> Some a (* Respectively Hint Apply | EApply | Exact *)
729 | Extern _ ->
730 warning_tc_hints (Printf.sprintf "There is an hint extern in the typeclass db: \n%s" (Pp.string_of_ppcmds @@ Hints.FullHint.print env sigma e));
731 None
732 | Res_pf_THEN_trivial_fail _ -> (* Hint Immediate *)
733 warning_tc_hints (Printf.sprintf "There is an hint immediate in the typeclass db: \n%s" (Pp.string_of_ppcmds @@ Hints.FullHint.print env sigma e));
734 None
735 | Unfold_nth _ ->
736 warning_tc_hints (Printf.sprintf "There is an hint unfold in the typeclass db: \n%s" (Pp.string_of_ppcmds @@ Hints.FullHint.print env sigma e));
737 None) full_hints in
738 let constrs = List.map (fun a -> Hints.hint_as_term a |> snd) hints in
739 (* Printer.pr_global tc |> Pp.string_of_ppcmds |> Printf.printf "%s\n"; *)
740 let instances_grefs = List.filter_map (fun e ->
741 match EConstr.kind sigma e with
742 | Constr.Ind (a, _) -> Some (Names.GlobRef.IndRef a)
743 | Constr.Const (a, _) -> Some (Names.GlobRef.ConstRef a)
744 | Constr.Construct (a, _) -> Some (Names.GlobRef.ConstructRef a)
745 | _ -> None) constrs in
746 List.map (get_instance env tc) instances_grefs
747
748 let set_accumulate_to_db_interp, get_accumulate_to_db_interp =
749 let f = ref (fun ~loc:_ _ -> assert false) in
750 (fun x -> f := x),
751 (fun () -> !f)
752
753 let is_global_level env u =
754 let set = Univ.Level.Set.singleton u in
755 match UGraph.check_declared_universes (Environ.universes env) set with
756 | Ok () -> true
757 | Error _ -> false
758
759 let err_if_contains_alg_univ ~depth t =
760 let env = Global.env () in
761 let is_global u =
762 match Univ.Universe.level u with
763 | None -> true
764 | Some l -> is_global_level env l in
765 let rec aux ~depth acc t =
766 match E.look ~depth t with
767 | E.CData c when isuniv c ->
768 let u = univout c in
769 if is_global u then acc
770 else
771 begin match Univ.Universe.level u with
772 | None ->
773 err Pp.(strbrk "The hypothetical clause contains terms of type univ which are not global, you should abstract them out or replace them by global ones: " ++
774 Univ.Universe.pr UnivNames.pr_level_with_global_universes u)
775 | _ -> Univ.Universe.Set.add u acc
776 end
777 | x -> Rocq_elpi_utils.fold_elpi_term aux acc ~depth x
778 in
779 let univs = aux ~depth Univ.Universe.Set.empty t in
780 univs
781
782 let preprocess_clause ~depth clause =
783 let levels_to_abstract = err_if_contains_alg_univ ~depth clause in
784 let levels_to_abstract_no = Univ.Universe.Set.cardinal levels_to_abstract in
785 let rec subst ~depth m t =
786 match E.look ~depth t with
787 | E.CData c when isuniv c ->
788 begin try E.mkBound (Univ.Universe.Map.find (univout c) m)
789 with Not_found -> t end
790 | E.App(c,x,xs) ->
791 E.mkApp c (subst ~depth m x) (List.map (subst ~depth m) xs)
792 | E.Cons(x,xs) ->
793 E.mkCons (subst ~depth m x) (subst ~depth m xs)
794 | E.Lam x ->
795 E.mkLam (subst ~depth:(depth+1) m x)
796 | E.Builtin(c,xs) ->
797 E.mkBuiltin c (List.map (subst ~depth m) xs)
798 | E.UnifVar _ -> CErrors.user_err Pp.(str"The clause being accumulated contains unification variables, this is forbidden. You must quantify them out using 'pi'.")
799 | E.Const _ | E.Nil | E.CData _ -> t
800 in
801 let clause =
802 let rec bind d map = function
803 | [] ->
804 subst ~depth:d map
805 (API.Utils.move ~from:depth ~to_:(depth + levels_to_abstract_no) clause)
806 | l :: ls ->
807 E.mkBuiltin E.Pi [E.mkLam (* pi x\ *)
808 (bind (d+1) (Univ.Universe.Map.add l d map) ls)]
809 in
810 bind depth Univ.Universe.Map.empty
811 (Univ.Universe.Set.elements levels_to_abstract)
812 in
813 let vars = collect_term_variables ~depth clause in
814 vars, clause
815
816 let argument_mode = let open Conv in let open API.AlgebraicData in declare {
817 ty = TyName "argument_mode";
818 doc = "Specify if a predicate argument is in input or output mode";
819 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
820 constructors = [
821 K("in","",N,
822 B `Input,
823 M (fun ~ok ~ko -> function `Input -> ok | _ -> ko ()));
824 K("out","",N,
825 B `Output,
826 M (fun ~ok ~ko -> function `Output -> ok | _ -> ko ()));
827 ]
828 } |> CConv.(!<)
829
830
831 let set_accumulate_text_to_db_interp, get_accumulate_text_to_db_interp =
832 let f = ref (fun ~loc:_ _ _ _ -> assert false) in
833 (fun x -> f := x),
834 (fun () -> !f)
835
836
837 let class_ = let open Conv in let open API.AlgebraicData in let open Coercionops in declare {
838 ty = TyName "class";
839 doc = "Node of the coercion graph";
840 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
841 constructors = [
842 K("funclass","",N,
843 B CL_FUN,
844 M (fun ~ok ~ko -> function Coercionops.CL_FUN -> ok | _ -> ko ()));
845 K("sortclass","",N,
846 B CL_SORT,
847 M (fun ~ok ~ko -> function CL_SORT -> ok | _ -> ko ()));
848 K("grefclass","",A(gref,N),
849 B ComCoercion.class_of_global,
850 MS (fun ~ok ~ko p state -> match p with
851 | CL_SECVAR v -> ok (GlobRef.VarRef v) state
852 | CL_CONST c -> ok (GlobRef.ConstRef c) state
853 | CL_IND i -> ok (GlobRef.IndRef i) state
854 | CL_PROJ p -> ok (GlobRef.ConstRef (get_projection_constant (get_global_env state) p)) state
855 | _ -> ko state))
856 ]
857 } |> CConv.(!<)
858
859 let src_class_of_class env = function
860 | (Coercionops.CL_FUN | Coercionops.CL_SORT) -> CErrors.anomaly Pp.(str "src_class_of_class on a non source coercion class")
861 | Coercionops.CL_SECVAR v -> GlobRef.VarRef v
862 | Coercionops.CL_CONST c -> GlobRef.ConstRef c
863 | Coercionops.CL_IND i -> GlobRef.IndRef i
864 | Coercionops.CL_PROJ p -> GlobRef.ConstRef (get_projection_constant env p)
865
866 let coercion = let open Conv in let open API.AlgebraicData in declare {
867 ty = TyName "coercion";
868 doc = "Edge of the coercion graph";
869 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
870 constructors = [
871 K("coercion","ref, nparams, src, tgt", A(gref,A(B.unspec int,A(B.unspec gref,A(B.unspec class_,N)))),
872 B (fun t np src tgt -> t,np,src,tgt),
873 M (fun ~ok ~ko:_ -> function (t,np,src,tgt) -> ok t np src tgt))
874 ]
875 } |> CConv.(!<)
876
877
878 let implicit_kind_of_status = function
879 | None -> Glob_term.Explicit
880 | Some imp ->
881 if imp.Impargs.impl_max then Glob_term.MaxImplicit else Glob_term.NonMaxImplicit
882
883
884 let simplification_strategy = let open API.AlgebraicData in let open Reductionops.ReductionBehaviour in declare {
885 ty = Conv.TyName "simplification_strategy";
886 doc = "Strategy for simplification tactics";
887 pp = (fun fmt (x : t) -> Format.fprintf fmt "TODO");
888 constructors = [
889 K ("never", "Arguments foo : simpl never",N,
890 B NeverUnfold,
891 M (fun ~ok ~ko -> function NeverUnfold -> ok | _ -> ko ()));
892 K("when","Arguments foo .. / .. ! ..",A(B.list B.int, A(B.option B.int, N)),
893 B (fun recargs nargs -> UnfoldWhen { recargs; nargs }),
894 M (fun ~ok ~ko -> function UnfoldWhen { recargs; nargs } -> ok recargs nargs | _ -> ko ()));
895 K("when-nomatch","Arguments foo .. / .. ! .. : simpl nomatch",A(B.list B.int, A(B.option B.int, N)),
896 B (fun recargs nargs -> UnfoldWhenNoMatch { recargs; nargs }),
897 M (fun ~ok ~ko -> function UnfoldWhenNoMatch { recargs; nargs } -> ok recargs nargs | _ -> ko ()));
898 ]
899 } |> CConv.(!<)
900
901 let conversion_strategy = let open API.AlgebraicData in let open Conv_oracle in declare {
902 ty = Conv.TyName "conversion_strategy";
903 doc = "Strategy for conversion test\nexpand < ... < level -1 < level 0 < level 1 < ... < opaque";
904 pp = (fun fmt (x : level) -> Pp.pp_with fmt (pr_level x));
905 constructors = [
906 K ("opaque", "",N,
907 B Opaque,
908 M (fun ~ok ~ko -> function Opaque -> ok | _ -> ko ()));
909 K("expand","",N,
910 B Expand,
911 M (fun ~ok ~ko -> function Expand -> ok | _ -> ko ()));
912 K("level","default is 0, aka transparent",A(B.int,N),
913 B (fun x -> Level x),
914 M (fun ~ok ~ko -> function Level x -> ok x | _ -> ko ()));
915 ]
916 } |> CConv.(!<)
917
918 let reduction_kind = let open API.AlgebraicData in let open RedFlags in declare {
919 ty = Conv.TyName "coq.redflag";
920 doc = "Flags for lazy, cbv, ... reductions";
921 pp = (fun fmt (x : red_kind) -> Format.fprintf fmt "TODO");
922 constructors = [
923 K ("coq.redflags.beta", "",N,
924 B fBETA,
925 M (fun ~ok ~ko x -> if x = fBETA then ok else ko ()));
926 K ("coq.redflags.delta", "if set then coq.redflags.const disables unfolding",N,
927 B fDELTA,
928 M (fun ~ok ~ko x -> if x = fDELTA then ok else ko ()));
929 K ("coq.redflags.match", "",N,
930 B fMATCH,
931 M (fun ~ok ~ko x -> if x = fMATCH then ok else ko ()));
932 K ("coq.redflags.fix", "",N,
933 B fFIX,
934 M (fun ~ok ~ko x -> if x = fFIX then ok else ko ()));
935 K ("coq.redflags.cofix", "",N,
936 B fCOFIX,
937 M (fun ~ok ~ko x -> if x = fCOFIX then ok else ko ()));
938 K ("coq.redflags.zeta", "",N,
939 B fZETA,
940 M (fun ~ok ~ko x -> if x = fZETA then ok else ko ()));
941 K("coq.redflags.const","enable/disable unfolding",A(constant,N),
942 B (function Constant x -> fCONST x | Variable x -> fVAR x),
943 M (fun ~ok ~ko x -> nYI "readback for coq.redflags.const"));
944 K("coq.redflags.proj","enable/disable unfolding",A(projection,N),
945 B (function x -> fPROJ @@ Projection.repr x),
946 M (fun ~ok ~ko x -> nYI "readback for coq.redflags.proj"));
947 ]
948 } |> CConv.(!<)
949
950
951 let module_item = let open API.AlgebraicData in declare {
952 ty = Conv.TyName "module-item";
953 doc = "Contents of a module";
954 pp = (fun fmt a -> Format.fprintf fmt "TODO");
955 constructors = [
956 K("submodule","",A(modpath,C(CConv.(!>>) B.list,N)),
957 B (fun s l -> Module(s,l) ),
958 M (fun ~ok ~ko -> function Module(s,l) -> ok s l | _ -> ko ()));
959 K("module-type","",A(modtypath,N),
960 B (fun s -> ModuleType s),
961 M (fun ~ok ~ko -> function ModuleType s -> ok s | _ -> ko ()));
962 K("gref","",A(gref,N),
963 B (fun s -> Gref s),
964 M (fun ~ok ~ko -> function Gref x -> ok x | _ -> ko ()));
965 K("module-functor","",A(modpath,A(B.list modtypath,N)),
966 B (fun s a -> Functor(s,a)),
967 M (fun ~ok ~ko -> function Functor(s,a) -> ok s a | _ -> ko ()));
968 K("module-type-functor","",A(modtypath,A(B.list modtypath,N)),
969 B (fun s a -> FunctorType(s,a)),
970 M (fun ~ok ~ko -> function FunctorType(s,a) -> ok s a | _ -> ko ()));
971 ]
972 } |> CConv.(!<)
973
974
975 let warning = CWarnings.create ~name:"lib" ~category:elpi_cat Pp.str
976
977 let keep x = (x = Pred.Keep)
978
979 let if_keep x f =
980 match x with
981 | Pred.Discard -> None
982 | Pred.Keep -> Some (f ())
983
984 let _if_keep_acc x state f =
985 match x with
986 | Pred.Discard -> state, None
987 | Pred.Keep ->
988 let state, x = f state in
989 state, Some x
990
991 let gr2id state gr =
992 let open GlobRef in
993 match gr with
994 | VarRef v ->
995 (Id.to_string v)
996 | ConstRef c ->
997 (Id.to_string (Label.to_id (Constant.label c)))
998 | IndRef (i,j) ->
999 let open Declarations in
1000 let env = get_global_env state in
1001 let { mind_packets } = Environ.lookup_mind i env in
1002 (Id.to_string (mind_packets.(j).mind_typename))
1003 | ConstructRef ((i,k),j) ->
1004 let open Declarations in
1005 let env = get_global_env state in
1006 let { mind_packets } = Environ.lookup_mind i env in
1007 (Id.to_string (mind_packets.(k).mind_consnames.(j-1)))
1008
1009 let ppbox = let open Conv in let open Pp in let open API.AlgebraicData in declare {
1010 ty = TyName "coq.pp.box";
1011 doc = {|Coq box types for pretty printing:
1012 - Vertical block: each break leads to a new line
1013 - Horizontal block: no line breaking
1014 - Horizontal-vertical block: same as Vertical block, except if this block
1015 is small enough to fit on a single line in which case it is the same
1016 as a Horizontal block
1017 - Horizontal or Vertical block: breaks lead to new line only when
1018 necessary to print the content of the block (the contents flow
1019 inside the box)|};
1020 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
1021 constructors = [
1022 K("coq.pp.v","",A(B.int,N),
1023 B (fun i -> Pp_vbox i),
1024 M (fun ~ok ~ko -> function Pp_vbox i -> ok i | _ -> ko ()));
1025 K("coq.pp.h","",N,
1026 B Pp_hbox,
1027 M (fun ~ok ~ko -> function Pp_hbox -> ok | _ -> ko ()));
1028 K("coq.pp.hv","",A(B.int,N),
1029 B (fun i -> Pp_hvbox i),
1030 M (fun ~ok ~ko -> function Pp_hvbox i -> ok i | _ -> ko ()));
1031 K("coq.pp.hov","",A(B.int,N),
1032 B (fun i -> Pp_hovbox i),
1033 M (fun ~ok ~ko -> function Pp_hovbox i -> ok i | _ -> ko ()));
1034 ]
1035 } |> CConv.(!<)
1036
1037 let ppboxes = let open Conv in let open Pp in let open API.AlgebraicData in declare {
1038 ty = TyName "coq.pp";
1039 doc = {|Coq box model for pretty printing. Items:
1040 - empty
1041 - spc: a spacem, also a breaking hint
1042 - str: a non breakable string
1043 - brk L I: a breaking hint of a given length L contributing I spaces to
1044 indentation when taken
1045 - glue: puts things together
1046 - box B: a box with automatic line breaking according to B
1047 - comment: embedded \\n are turned into nl (see below)
1048 - tag: ignored
1049 - nl: break the line (should not be used)|};
1050 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
1051 constructors = [
1052 K("coq.pp.empty","",N,
1053 B Ppcmd_empty,
1054 M (fun ~ok ~ko -> function Ppcmd_empty -> ok | _ -> ko ()));
1055 K("coq.pp.spc","",N,
1056 B (Ppcmd_print_break(1,0)),
1057 M (fun ~ok ~ko -> function Ppcmd_print_break(1,0) -> ok | _ -> ko ()));
1058 K("coq.pp.str","",A(B.string,N),
1059 B (fun s -> Ppcmd_string s),
1060 M (fun ~ok ~ko -> function Ppcmd_string s -> ok s | _ -> ko ()));
1061 K("coq.pp.brk","",A(B.int,A(B.int,N)),
1062 B (fun i j -> Ppcmd_print_break(i,j)),
1063 M (fun ~ok ~ko -> function Ppcmd_print_break(i,j) -> ok i j | _ -> ko ()));
1064 K("coq.pp.glue","",C((fun pp -> CConv.(!>>) B.list pp),N),
1065 B (fun l -> Ppcmd_glue (List.map Pp.unrepr l)),
1066 M (fun ~ok ~ko -> function Ppcmd_glue l -> ok (List.map Pp.repr l) | _ -> ko ()));
1067 K("coq.pp.box","",A(ppbox,C((fun pp -> CConv.(!>>) B.list pp),N)),
1068 B (fun b l -> Ppcmd_box(b,Pp.unrepr @@ Ppcmd_glue (List.map Pp.unrepr l))),
1069 M (fun ~ok ~ko -> function
1070 | Ppcmd_box(b,x) ->
1071 begin match Pp.repr x with
1072 | Ppcmd_glue l -> ok b (List.map Pp.repr l)
1073 | x -> ok b [x]
1074 end
1075 | _ -> ko ()));
1076 K("coq.pp.comment","",A(B.list B.string,N),
1077 B (fun l -> Ppcmd_comment l),
1078 M (fun ~ok ~ko -> function Ppcmd_comment l -> ok l | _ -> ko ()));
1079 K("coq.pp.tag","",A(B.string,S N),
1080 B (fun b x -> Ppcmd_tag(b,Pp.unrepr x)),
1081 M (fun ~ok ~ko -> function Ppcmd_tag(b,x) -> ok b (Pp.repr x) | _ -> ko ()));
1082 K("coq.pp.nl","",N,
1083 B Ppcmd_force_newline,
1084 M (fun ~ok ~ko -> function Ppcmd_force_newline -> ok | _ -> ko ()));
1085 ]
1086 } |> CConv.(!<)
1087
1088 let warn_deprecated_add_axiom =
1089 CWarnings.create
1090 ~name:"elpi.add-const-for-axiom-or-sectionvar"
1091 ~category:elpi_depr_cat
1092 Pp.(fun () ->
1093 strbrk ("elpi: Using coq.env.add-const for declaring axioms or " ^
1094 "section variables is deprecated. Use coq.env.add-axiom or " ^
1095 "coq.env.add-section-variable instead"))
1096
1097 let comAssumption_declare_variable coe ~kind ty ~univs ~impargs impl ~name =
1098 ComAssumption.declare_variable ~coe ~kind ty ~univs ~impargs ~impl ~name:name.CAst.v
1099 [%%if coq = "9.0"]
1100 let comAssumption_declare_axiom coe ~local ~kind ~univs ~impargs ~inline ~name ty =
1101 ComAssumption.declare_axiom ~coe ~local ~kind ~univs ~impargs ~inline ~name:name.CAst.v ty
1102 let declare_mutual_inductive_with_eliminations ~primitive_expected ~default_dep_elim x y z =
1103 DeclareInd.declare_mutual_inductive_with_eliminations ~primitive_expected ~default_dep_elim x y z
1104 [%%else]
1105 let comAssumption_declare_axiom coe ~local ~kind ~univs ~impargs ~inline ~name ty =
1106 ComAssumption.declare_axiom ~coe ~local ~kind ~univs ~impargs ~inline ~name ty
1107 let declare_mutual_inductive_with_eliminations ~primitive_expected ~default_dep_elim x y z =
1108 DeclareInd.declare_mutual_inductive_with_eliminations ~default_dep_elim x y z
1109 [%%endif]
1110
1111 let cinfo_make _ _ _using =
1112 Declare.CInfo.make
1113 let eval_of_constant c =
1114 match c with
1115 | Variable v -> Evaluable.EvalVarRef v
1116 | Constant c ->
1117 match Structures.PrimitiveProjections.find_opt c with
1118 | None -> Evaluable.EvalConstRef c
1119 | Some p -> Evaluable.EvalProjectionRef p
1120 let eval_to_oeval = Evaluable.to_kevaluable
1121 let mkCLocalAssum x y z = Constrexpr.CLocalAssum(x,None,y,z)
1122 let pattern_of_glob_constr env g = Patternops.pattern_of_glob_constr env g
1123
1124 let get_entry_context = function
1125 | UState.Monomorphic_entry x, _ -> x
1126 | _ -> Univ.ContextSet.empty
1127
1128 [%%if coq = "9.0" || coq = "9.1"]
1129 let make_polyflags poly cumul = poly
1130 [%%else]
1131 let make_polyflags poly cumul =
1132 PolyFlags.make ~univ_poly:poly ~cumulative:cumul ~collapse_sort_variables:true
1133 [%%endif]
1134
1135 let declare_definition using ~cinfo ~info ~opaque ~body sigma =
1136 let using = Option.map Proof_using.using_from_string using in
1137 let (kn, uctx) = Declare.declare_definition_full ~cinfo ~info ~opaque ~body ?using sigma in
1138 kn, uctx
1139
1140 let warns_of_options options = options.user_warns |> Option.map UserWarn.with_empty_qf
1141
1142 let add_axiom_or_variable api id ty local_bkind options state =
1143 let state, poly, cumul, udecl, _ = poly_cumul_udecl_variance_of_options state options in
1144 let used = universes_of_term state ty in
1145 let sigma = restricted_sigma_of used state in
1146 if cumul then
1147 err Pp.(str api ++ str": unsupported attribute @udecl-cumul! or @univpoly-cumul!");
1148 if poly && Option.has_some local_bkind then
1149 err Pp.(str api ++ str": section variables cannot be universe polymorphic");
1150 let univs = check_univ_decl (Evd.ustate sigma) udecl ~poly:(make_polyflags poly cumul) in
1151 let kind = Decls.Logical in
1152 let impargs = [] in
1153 let loc = to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state in
1154 let id = Id.of_string id in
1155 let name = CAst.(make ~loc id) in
1156 if not (is_ground sigma ty) then
1157 err Pp.(str"coq.env.add-const: the type must be ground. Did you forge to call coq.typecheck-indt-decl?");
1158 let gr, _ =
1159 match local_bkind with
1160 | Some implicit_kind -> begin
1161 Dumpglob.dump_definition name true "var";
1162 comAssumption_declare_variable Vernacexpr.NoCoercion ~kind (EConstr.to_constr sigma ty) ~univs ~impargs implicit_kind ~name
1163 end
1164 | None -> begin
1165 Dumpglob.dump_definition name false "ax";
1166 comAssumption_declare_axiom Vernacexpr.NoCoercion ~local:Locality.ImportDefaultBehavior ~kind (EConstr.to_constr sigma ty)
1167 ~univs ~impargs ~inline:options.inline ~name
1168 end
1169 in
1170 let ucsts = get_entry_context univs in
1171 gr, ucsts
1172 ;;
1173
1174 type tac_abbrev = {
1175 abbrev_name : qualified_name;
1176 tac_name : qualified_name;
1177 tac_fixed_args : Rocq_elpi_arg_HOAS.Tac.glob list;
1178 }
1179
1180 type ('a,'d) gbpmp = Gbpmp : ('d, _, 'b, Loc.t -> 'd) Procq.Rule.t * ('a -> 'b) -> ('a,'d) gbpmp
1181
1182 let rec gbpmp f = function
1183 | [x] -> Gbpmp (Procq.Rule.next Procq.Rule.stop (Procq.Symbol.token (Tok.PIDENT(Some x))), (fun a _ -> f a))
1184 | x :: xs ->
1185 let Gbpmp (r, f) = gbpmp f xs in
1186 Gbpmp (Procq.Rule.next r (Procq.Symbol.token (Tok.PFIELD (Some x))), (fun a _ -> f a))
1187 | [] -> assert false
1188
1189 [%%if coq = "9.0"]
1190 let wit_ltac_in_term = Ltac_plugin.Tacarg.wit_tactic
1191 [%%else]
1192 let wit_ltac_in_term = Ltac_plugin.Tacarg.wit_ltac_in_term
1193 [%%endif]
1194
1195 [%%if coq = "9.0" || coq = "9.1"]
1196 let with_hack_synterp f () = f ()
1197
1198 let grammar_extend e ext : unit = Procq.grammar_extend e ext
1199 [%%else]
1200 let with_hack_synterp f () =
1201 Flags.with_modified_ref Flags.in_synterp_phase (fun _ -> None) f ()
1202
1203 let grammar_extend e ext : unit = Procq.grammar_extend ~ignore_kw:false e ext
1204 [%%endif]
1205
1206 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
1207 let mk_ltac_in_term ?loc tac =
1208 CAst.make ?loc @@ Constrexpr.CGenarg (Genarg.in_gen (Genarg.rawwit wit_ltac_in_term) tac)
1209 [%%else]
1210 let mk_ltac_in_term ?loc tac =
1211 CAst.make ?loc @@ Constrexpr.CGenarg (Raw (wit_ltac_in_term, tac))
1212 [%%endif]
1213
1214 let cache_abbrev_for_tac { abbrev_name; tac_name = tacname; tac_fixed_args = more_args } =
1215 let action args loc =
1216 let open Ltac_plugin in
1217 let tac =
1218 let open Tacexpr in
1219 let elpi_tac = {
1220 mltac_plugin = "rocq-elpi.elpi";
1221 mltac_tactic = "elpi_tac"; } in
1222 let elpi_tac_entry = {
1223 mltac_name = elpi_tac;
1224 mltac_index = 0; } in
1225 let more_args = more_args |> List.map (function
1226 | Rocq_elpi_arg_HOAS.Tac.Int _ as t -> t
1227 | Rocq_elpi_arg_HOAS.Tac.String _ as t -> t
1228 | Rocq_elpi_arg_HOAS.Tac.Term (t,_) ->
1229 let eenv = empty_extern_env () in
1230 let expr = Constrextern.extern_glob_constr eenv t in
1231 let rec aux () ({ CAst.v } as orig) = match v with
1232 | Constrexpr.CEvar _ -> CAst.make @@ Constrexpr.CHole(None)
1233 | _ -> Constrexpr_ops.map_constr_expr_with_binders (fun _ () -> ()) aux () orig in
1234 Rocq_elpi_arg_HOAS.Tac.Term (aux () expr)
1235 | _ -> assert false) in
1236 let tacname = loc, tacname in
1237 let tacname = Genarg.in_gen (Genarg.rawwit Rocq_elpi_arg_syntax.wit_qualified_name) tacname in
1238 let args = args |> List.map (fun (arg,_) -> Rocq_elpi_arg_HOAS.Tac.Term(arg)) in
1239 let args = Genarg.in_gen (Genarg.rawwit (Genarg.wit_list Rocq_elpi_arg_syntax.wit_elpi_tactic_arg)) (more_args @ args) in
1240 (TacML (elpi_tac_entry, [TacGeneric(None, tacname); TacGeneric(None, args)])) in
1241 mk_ltac_in_term (CAst.make tac) in
1242 let Gbpmp (rule, action) = gbpmp action (List.rev abbrev_name) in
1243 (* HACK!!! changes the grammar but is called in interp phase *)
1244 with_hack_synterp (fun () ->
1245 grammar_extend Procq.Constr.term (Procq.Fresh
1246 (Gramlib.Gramext.Before "10",
1247 [ (None, None, [ Procq.Production.make
1248 (Procq.Rule.next rule (Procq.Symbol.list0 (Procq.Symbol.nterm Procq.Constr.arg)))
1249 action
1250 ])])))
1251 ()
1252
1253 let subst_abbrev_for_tac (subst, { abbrev_name; tac_name; tac_fixed_args }) = {
1254 abbrev_name;
1255 tac_name;
1256 tac_fixed_args = List.map (Rocq_elpi_arg_HOAS.Tac.subst subst) tac_fixed_args
1257 }
1258
1259 let inAbbreviationForTactic : tac_abbrev -> Libobject.obj =
1260 Libobject.declare_object @@ Libobject.global_object_nodischarge "ELPI-EXPORTED-TAC-ABBREV"
1261 ~cache:cache_abbrev_for_tac ~subst:(Some subst_abbrev_for_tac)
1262
1263 let cache_tac_abbrev ~code:elpi_qualid ~name:other_qualid = cache_abbrev_for_tac {
1264 abbrev_name = other_qualid;
1265 tac_name = elpi_qualid;
1266 tac_fixed_args = [];
1267 }
1268
1269 let is_available_option name =
1270 let table = Goptions.get_tables () in
1271 (* let table = Goptions.get_string_table () in *)
1272 match Goptions.OptionMap.find_opt name table with
1273 | Some { Goptions.opt_depr = x; _ } -> Some (Option.has_some x)
1274 | None -> None
1275
1276 let goption_set name value =
1277 let open Goptions in
1278 match value with
1279 | BoolValue x -> Goptions.set_bool_option_value name x
1280 | IntValue x -> Goptions.set_int_option_value name x
1281 | StringOptValue None -> Goptions.unset_option_value_gen name
1282 | StringOptValue (Some x) -> Goptions.set_string_option_value name x
1283 | StringValue _ -> assert false
1284
1285 let cache_goption_declaration (depr,key,value) =
1286 let open Goptions in
1287 if is_available_option key <> None then goption_set key value else
1288 let depr = if depr then Some (Deprecation.make ~note:"elpi" ()) else None in
1289 match value with
1290 | BoolValue x ->
1291 let _ : bool Goptions.getter = Goptions.declare_bool_option_and_ref ~key ~value:x ?depr () in
1292 ()
1293 | IntValue x ->
1294 let _ : int option Goptions.getter = Goptions.declare_intopt_option_and_ref ~stage:Interp ~key ?depr ~value:x () in
1295 ()
1296 | StringOptValue x ->
1297 let _ : string option Goptions.getter = Goptions.declare_stringopt_option_and_ref ~stage:Interp ~key ?depr ~value:x () in
1298 ()
1299 | StringValue _ -> assert false
1300
1301 let subst_goption_declaration (_,x) = x
1302
1303 let inGoption : _ -> Libobject.obj =
1304 Libobject.declare_object @@ Libobject.superglobal_object_nodischarge "ELPI-EXPORTED-GOPTION"
1305 ~cache:cache_goption_declaration ~subst:(Some subst_goption_declaration)
1306
1307 let mode = let open API.AlgebraicData in let open Hints in declare {
1308 ty = Conv.TyName "hint-mode";
1309 doc = "Hint Mode";
1310 pp = (fun fmt (x : hint_mode) -> Pp.pp_with fmt (pp_hint_mode x));
1311 constructors = [
1312 K ("mode-ground", "No Evar",N,
1313 B ModeInput,
1314 M (fun ~ok ~ko -> function ModeInput -> ok | _ -> ko ()));
1315 K("mode-input","No Head Evar",N,
1316 B ModeNoHeadEvar,
1317 M (fun ~ok ~ko -> function ModeNoHeadEvar -> ok | _ -> ko ()));
1318 K("mode-output","Anything",N,
1319 B ModeOutput,
1320 M (fun ~ok ~ko -> function ModeOutput -> ok | _ -> ko ()));
1321 ]
1322 } |> CConv.(!<)
1323
1324 module WMsg = Set.Make(struct
1325 type t = Loc.t option * string
1326 let compare = Stdlib.compare
1327 end)
1328
1329 let coq_warning_cache : WMsg.t API.Data.StrMap.t ref =
1330 Summary.ref ~name:"elpi-warning-cache" API.Data.StrMap.empty
1331 let coq_warning_cache category name loc txt =
1332 let key = category ^ " " ^ name in
1333 let msg = loc, txt in
1334 try
1335 let s = API.Data.StrMap.find key !coq_warning_cache in
1336 if WMsg.mem msg s then false
1337 else
1338 let s = WMsg.add msg s in
1339 coq_warning_cache := API.Data.StrMap.add key s !coq_warning_cache;
1340 true
1341 with
1342 Not_found ->
1343 coq_warning_cache := API.Data.StrMap.add key (WMsg.singleton msg) !coq_warning_cache;
1344 true
1345
1346 let pp_option_value fmt = function
1347 | Goptions.IntValue None | Goptions.StringOptValue None -> Format.fprintf fmt "unset"
1348 | Goptions.IntValue (Some x) -> Format.fprintf fmt "%d" x
1349 | Goptions.StringOptValue (Some x) -> Format.fprintf fmt "%s" x
1350 | Goptions.StringValue x -> Format.fprintf fmt "%s" x
1351 | Goptions.BoolValue x -> Format.fprintf fmt "%b" x
1352
1353 let goption = let open API.AlgebraicData in let open Goptions in declare {
1354 ty = Conv.TyName "coq.option";
1355 doc = "Coq option value";
1356 pp = pp_option_value;
1357 constructors = [
1358 K("coq.option.int", "none means unset",A(B.option B.int,N),
1359 B (fun x -> IntValue x),
1360 M (fun ~ok ~ko -> function IntValue x -> ok x | _ -> ko ()));
1361 K("coq.option.string","none means unset",A(B.option B.string,N),
1362 B (fun x -> StringOptValue x),
1363 M (fun ~ok ~ko -> function StringOptValue x -> ok x | StringValue x -> ok (Some x) | _ -> ko ()));
1364 K("coq.option.bool","",A(B.bool,N),
1365 B (fun x -> BoolValue x),
1366 M (fun ~ok ~ko -> function BoolValue x -> ok x | _ -> ko ()));
1367 ]
1368 } |> CConv.(!<)
1369
1370
1371 type scheme_kind =
1372 | Rect_dep
1373 | Rec_dep
1374 | Ind_dep
1375 | Sind_dep
1376 | Rect_nodep
1377 | Rec_nodep
1378 | Ind_nodep
1379 | Sind_nodep
1380 | Case_dep
1381 | Case_nodep
1382 | Casep_dep
1383 | Casep_nodep
1384 | Sym_internal
1385 | Sym_involutive
1386 | Rew_r_dep
1387 | Rew_dep
1388 | Rew_fwd_dep
1389 | Rew_fwd_r_dep
1390 | Rew_r
1391 | Rew
1392 | Congr
1393 | Beq
1394 | Dec_bl
1395 | Dec_lb
1396 | Eq_dec
1397 | Other of string
1398
1399 type register =
1400 | Scheme of GlobRef.t * scheme_kind
1401 | Rocqlib of string
1402 | Inline
1403
1404 let string_of_scheme_kind = function
1405 | Rect_dep -> "rect_dep"
1406 | Rec_dep -> "rec_dep"
1407 | Ind_dep -> "ind_dep"
1408 | Sind_dep -> "sind_dep"
1409 | Rect_nodep -> "rect_nodep"
1410 | Rec_nodep -> "rec_nodep"
1411 | Ind_nodep -> "ind_nodep"
1412 | Sind_nodep -> "sind_nodep"
1413 | Case_dep -> "case_dep"
1414 | Case_nodep -> "case_nodep"
1415 | Casep_dep -> "casep_dep"
1416 | Casep_nodep -> "casep_nodep"
1417 | Sym_internal -> "sym_internal"
1418 | Sym_involutive -> "sym_involutive"
1419 | Rew_r_dep -> "rew_r_dep"
1420 | Rew_dep -> "rew_dep"
1421 | Rew_fwd_dep -> "rew_fwd_dep"
1422 | Rew_fwd_r_dep -> "rew_fwd_r_dep"
1423 | Rew_r -> "rew_r"
1424 | Rew -> "rew"
1425 | Congr -> "congr"
1426 | Beq -> "beq"
1427 | Dec_bl -> "dec_bl"
1428 | Dec_lb -> "dec_lb"
1429 | Eq_dec -> "eq_dec"
1430 | Other x -> x
1431
1432 let scheme_kind = let open API.AlgebraicData in declare {
1433 ty = Conv.TyName "coq.register.scheme-kind";
1434 doc = "Coq scheme kind (currently undocumented in Rocq)";
1435 pp = (fun fmt k -> Format.fprintf fmt "%s" (string_of_scheme_kind k));
1436 constructors =
1437 List.map (fun k ->
1438 let s = string_of_scheme_kind k in
1439 K("coq.register.scheme."^s,"",N,B k,M (fun ~ok ~ko x -> if x = k then ok else ko ()))
1440 ) [ Rect_dep ; Rec_dep ; Ind_dep ; Sind_dep ; Rect_nodep ; Rec_nodep ; Ind_nodep ; Sind_nodep ; Case_dep ; Case_nodep ; Casep_dep ; Casep_nodep ; Sym_internal ; Sym_involutive ; Rew_r_dep ; Rew_dep ; Rew_fwd_dep ; Rew_fwd_r_dep ; Rew_r ; Rew ; Congr ; Beq ; Dec_bl ; Dec_lb ; Eq_dec ] @
1441 [K("coq.register.scheme.other","",A(B.string,N),B (fun x -> Other x), M (fun ~ok ~ko -> function Other x -> ok x | _ -> ko ()))]
1442 } |> CConv.(!<)
1443
1444 let register = let open API.AlgebraicData in declare {
1445 ty = Conv.TyName "coq.register";
1446 doc = "Coq register value";
1447 pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
1448 constructors = [
1449 K("coq.register.inline", "",N,
1450 B (Inline),
1451 M (fun ~ok ~ko -> function (Inline) -> ok | _ -> ko ()));
1452 K("coq.register.lib","",A(B.string,N),
1453 B (fun y -> Rocqlib(y)),
1454 M (fun ~ok ~ko -> function (Rocqlib y) -> ok y | _ -> ko ()));
1455 K("coq.register.scheme","",A(gref,A(scheme_kind,N)),
1456 B (fun i k -> Scheme(i,k)),
1457 M (fun ~ok ~ko -> function (Scheme(i,k))-> ok i k | _ -> ko ()));
1458 ]
1459 } |> CConv.(!<)
1460
1461 let register_ref = Rocqlib.register_ref
1462 let declare_scheme = DeclareScheme.declare_scheme
1463
1464 let find_hint_db s =
1465 try
1466 Hints.searchtable_map s
1467 with Not_found ->
1468 err Pp.(str "Hint DB not found: " ++ str s)
1469
1470 [%%if coq = "9.0"]
1471 let hint_mode env gr db =
1472 let modes = Hints.Hint_db.modes db in
1473 List.map (fun a -> Array.to_list a) @@ GlobRef.Map.find gr modes
1474 [%%else]
1475 let hint_mode env gr db =
1476 List.map (fun a -> Array.to_list a) @@ Hints.Hint_db.find_mode env gr db
1477 [%%endif]
1478
1479 let hint_db : (string * Hints.Hint_db.t) Conv.t = {
1480 Conv.ty = B.string.Conv.ty;
1481 Conv.pp_doc = B.string.Conv.pp_doc;
1482 Conv.pp = (fun fmt (s,_) -> B.string.Conv.pp fmt s);
1483 Conv.readback = (fun ~depth x state ->
1484 let state, x, _ = B.string.Conv.readback ~depth x state in
1485 state,(x, find_hint_db x),[]);
1486 embed = (fun ~depth _ _ -> assert false);
1487 }
1488
1489 let hint_locality (options : options) =
1490 match options.local with
1491 | Some true -> Hints.Local
1492 | Some false -> Hints.SuperGlobal
1493 | None -> Hints.Export
1494
1495 let hint_locality_doc = {|
1496 - @local! (default is export)
1497 - @global! (discouraged, may become deprecated)|}
1498
1499 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
1500 let explain_incon sigma p =
1501 UGraph.explain_universe_inconsistency
1502 (Termops.pr_evd_qvar sigma)
1503 (Termops.pr_evd_level sigma)
1504 p
1505 [%%else]
1506 let explain_incon sigma p =
1507 UGraph.explain_universe_inconsistency
1508 (Evd.sort_printer sigma)
1509 p
1510 [%%endif]
1511
1512 let unify_instances_gref gr ui1 ui2 diag env state cmp_constr_universes =
1513 let open Pred in
1514 let open Notation in
1515 let nargs, poly_ctx_size =
1516 let open Names.GlobRef in
1517 match gr with
1518 | VarRef _ -> 0, (0, 0)
1519 | ConstRef c ->
1520 let cb = Environ.lookup_constant c env in
1521 let univs = Declareops.constant_polymorphic_context cb in
1522 0, UVars.AbstractContext.size univs
1523 | IndRef ind ->
1524 let (mib,_ as specif) = Inductive.lookup_mind_specif env ind in
1525 let univs = Declareops.inductive_polymorphic_context mib in
1526 Conversion.inductive_cumulativity_arguments (mib,snd ind), UVars.AbstractContext.size univs
1527 | ConstructRef (ind,kno) ->
1528 let (mib,_ as specif) =
1529 Inductive.lookup_mind_specif env ind in
1530 let univs = Declareops.inductive_polymorphic_context mib in
1531 Conversion.constructor_cumulativity_arguments (mib,snd ind,kno), UVars.AbstractContext.size univs
1532 in
1533 let l1 = UVars.Instance.length ui1 in
1534 let l2 = UVars.Instance.length ui2 in
1535 if l1 <> l2 then
1536 state, !: (B.mkERROR "different universe instance lengths"), []
1537 else if l1 <> poly_ctx_size then
1538 let msg =
1539 Printf.sprintf "global reference %s expects instances of length (%d, %d), got (%d, %d)"
1540 (Pp.string_of_ppcmds (Printer.pr_global gr)) (fst poly_ctx_size) (snd poly_ctx_size) (fst l1) (snd l1) in
1541 state, !: (B.mkERROR msg), []
1542 else
1543 let t1 = EConstr.mkRef (gr, EConstr.EInstance.make ui1) in
1544 let t2 = EConstr.mkRef (gr, EConstr.EInstance.make ui2) in
1545 let sigma = get_sigma state in
1546 match cmp_constr_universes env sigma ?nargs:(Some nargs) t1 t2 with
1547 | None -> assert false
1548 | Some problem_set ->
1549 try
1550 let state = add_constraints state problem_set in
1551 state, !: B.mkOK, []
1552 with
1553 | Evd.UniversesDiffer | UState.UniversesDiffer ->
1554 state, !: (B.mkERROR "UniversesDiffer"), []
1555 | UGraph.UniverseInconsistency p ->
1556 match diag with
1557 | Data B.OK -> raise No_clause
1558 | _ ->
1559 let sigma = get_sigma state in
1560 let msg = explain_incon sigma p in
1561 state, !: (B.mkERROR (Pp.string_of_ppcmds msg)), []
1562
1563 let gref_set, gref_set_decl = B.ocaml_set_conv ~name:"coq.gref.set" gref (module GRSet)
1564
1565
1566 let grefs_of_term sigma t add_to_acc acc =
1567 let open GlobRef in
1568 let open Constr in
1569 let rec aux acc c =
1570 match EConstr.kind sigma c with
1571 | Var x -> add_to_acc (VarRef x) acc
1572 | Const (c,_) -> add_to_acc (ConstRef c) acc
1573 | Ind (i,_) -> add_to_acc (IndRef i) acc
1574 | Construct (k,_) -> add_to_acc (ConstructRef k) acc
1575 | _ -> EConstr.fold sigma aux acc c
1576 in
1577 aux acc t
1578
1579 let dep1 ?inside sigma gr =
1580 let open GlobRef in
1581 let modpath_of_gref = function
1582 | VarRef _ -> Safe_typing.current_modpath (Global.safe_env ())
1583 | IndRef (i,_) -> MutInd.modpath i
1584 | ConstructRef ((i,_),_) -> MutInd.modpath i
1585 | ConstRef c -> Constant.modpath c in
1586 let add_if_inside =
1587 match inside with
1588 | None -> GRSet.add
1589 | Some modpath -> fun x acc ->
1590 if ModPath.equal (modpath_of_gref x) modpath
1591 then GRSet.add x acc
1592 else acc in
1593 let add acc t = grefs_of_term sigma (EConstr.of_constr t) add_if_inside acc in
1594 GRSet.remove gr @@
1595 match gr with
1596 | VarRef id ->
1597 let decl = Environ.lookup_named id (Global.env()) in
1598 let ty = Context.Named.Declaration.get_type decl in
1599 let bo = Context.Named.Declaration.get_value decl in
1600 let l =
1601 match bo with
1602 | None -> [ty]
1603 | Some bo -> [ty; bo] in
1604 List.fold_left add GRSet.empty l
1605 | ConstRef cst ->
1606 let cb = Environ.lookup_constant cst (Global.env()) in
1607 let ty = cb.Declarations.const_type in
1608 let bo = Global.body_of_constant_body (Library.indirect_accessor[@warning "-3"]) cb in
1609 let l =
1610 match bo with
1611 | Some (e,_,_) -> [ty; e]
1612 | None -> [ty] in
1613 List.fold_left add GRSet.empty l
1614 | IndRef i | ConstructRef (i,_) ->
1615 let _, indbody = Global.lookup_inductive i in
1616 let l = indbody.Declarations.mind_user_lc in
1617 CArray.fold_left add GRSet.empty l
1618
1619 let universe_level_set, universe_level_set_decl =
1620 B.ocaml_set_conv ~name:"coq.univ.variable.set" universe_level_variable (module UnivLevelSet)
1621
1622 let coq_print pp msg_f =
1623 (fun args ~depth _hyps _constraints state ->
1624 let pp = pp ~depth in
1625 msg_f Pp.(str (pp2string (P.list ~boxed:true pp " ") args));
1626 state, (), [])
1627
1628 (*****************************************************************************)
1629 (*****************************************************************************)
1630 (*****************************************************************************)
1631 (*****************************************************************************)
1632 (*****************************************************************************)
1633 (*****************************************************************************)
1634 (*****************************************************************************)
1635 (*****************************************************************************)
1636 (*****************************************************************************)
1637 (*****************************************************************************)
1638 (*****************************************************************************)
1639
1640 let coq_header_builtins =
1641 let open API.BuiltIn in
1642 [LPCode
1643 {|% Coq terms as the object language of elpi and basic API to access Coq
1644 % license: GNU Lesser General Public License Version 2.1 or later
1645 % -------------------------------------------------------------------------
1646
1647 % This file is automatically generated from
1648 % - coq-HOAS.elpi
1649 % - rocq_elpi_builtin.ml
1650 % and contains the description of the data type of Coq terms and the
1651 % API to access Coq.
1652
1653 |};
1654 LPCode Rocq_elpi_builtins_arg_HOAS.code;
1655 LPCode Rocq_elpi_builtins_HOAS.code;
1656 MLData Rocq_elpi_HOAS.record_field_att;
1657 MLData Rocq_elpi_HOAS.coercion_status;
1658
1659 LPCode {|
1660 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1661 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% builtins %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1662 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1663
1664 % This section contains the API to access Coq
1665 % The marker *E* means *experimental*, i.e. use at your own risk, it may change
1666 % substantially or even disappear in future versions.
1667 |};
1668 ]
1669
1670 let compat_reduction_behavior_set ~local gref strategy =
1671 Reductionops.ReductionBehaviour.set ~local gref (Some strategy)
1672
1673 let compat_reset_simplification =
1674 let open API.BuiltIn in
1675 let open Pred in
1676 [MLCode(Pred("coq.arguments.reset-simplification",
1677 In(gref,"GR",
1678 Full(global,
1679 {|resets the behavior of the simplification tactics.
1680 Also resets the ! and / modifiers for the Arguments command.
1681 Supported attributes:
1682 - @global! (default: false)|})),
1683 (fun gref ~depth { options } _ -> grab_global_env "coq.arguments.reset-simplification" (fun state ->
1684 match gref with
1685 | ConstRef gref ->
1686 let local = options.local <> Some false in
1687 Reductionops.ReductionBehaviour.set ~local gref None;
1688 Univ.ContextSet.empty, state, (), []
1689 | _ -> err Pp.(str "reset-simplification must be called on constant")))),
1690 DocAbove)]
1691
1692 [%%if coq = "9.0"]
1693 let declare_projections ind ~kind univs id flags implicits fields =
1694 Record.Internal.declare_projections ind ~kind univs id flags implicits fields
1695 [%%else]
1696 let declare_projections ind ~kind _ id flags implicits _ =
1697 Record.Internal.declare_projections ind ~kind ~inhabitant_id:id flags implicits
1698 [%%endif]
1699
1700 [%%if coq = "9.0"]
1701 let apply_proof ~name ~poly env tac pf =
1702 let (), pv, _, _ = Proofview.apply ~name ~poly env tac pf in
1703 pv
1704 [%%else]
1705 let apply_proof ~name ~poly env tac pf =
1706 let (), pv, _, _, _ = Proofview.apply ~name ~poly env tac pf in
1707 pv
1708 [%%endif]
1709
1710 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
1711 let ltac1closure = Ltac_plugin.Tacinterp.Value.of_closure
1712 [%%else]
1713 let ltac1closure = Ltac_plugin.Tacinterp.Value.closure
1714 [%%endif]
1715
1716 let apply_ltac1 ~depth tac tac_args =
1717 let open Ltac_plugin in
1718 let tac =
1719 match E.look ~depth tac with
1720 | E.CData s when API.RawOpaqueData.is_string s ->
1721 let tac_name = API.RawOpaqueData.to_string s in
1722 let tac_name =
1723 let q = Libnames.qualid_of_string tac_name in
1724 try Tacenv.locate_tactic q
1725 with Not_found ->
1726 match Tacenv.locate_extended_all_tactic q with
1727 | [x] -> x
1728 | _::_::_ -> err Pp.(str"Ltac1 tactic " ++ str tac_name ++ str" is ambiguous, qualify the name")
1729 | [] -> err Pp.(str"Ltac1 tactic " ++ str tac_name ++ str" not found") in
1730 let tacref = Locus.ArgArg (Loc.tag @@ tac_name) in
1731 let tacexpr = Tacexpr.(CAst.make @@ TacArg (TacCall (CAst.make @@ (tacref, [])))) in
1732 ltac1closure (Tacinterp.default_ist ()) tacexpr
1733 | E.CData t when Rocq_elpi_arg_HOAS.is_ltac_tactic t ->
1734 Rocq_elpi_arg_HOAS.to_ltac_tactic t
1735 | _ -> U.type_error ("coq.ltac.call-ltac1: string or ltac1-tactic are expected as the tactic to call")
1736 in
1737 Tacinterp.Value.apply tac tac_args
1738
1739 exception TacticFails of Exninfo.iexn
1740
1741 let call_tactic ~depth state ~no_tc proof_context goal tactic =
1742 let sigma = get_sigma state in
1743 try
1744 let sigma, subgoals =
1745 let open Proofview in let open Notations in
1746 let focused_tac =
1747 Unsafe.tclSETGOALS [with_empty_state goal] <*> tactic in
1748 with_no_tc ~no_tc (fun sigma ->
1749 let _, pv = init sigma [] in
1750 let pv =
1751 let vernac_state = Vernacstate.freeze_full_state () in
1752 try
1753 let rc = apply_proof ~name:(Id.of_string "elpi") ~poly:default_polyflags proof_context.env focused_tac pv in
1754 let pstate = Vernacstate.Stm.pstate (Vernacstate.freeze_full_state ()) in
1755 let vernac_state = Vernacstate.Stm.set_pstate vernac_state pstate in
1756 Vernacstate.unfreeze_full_state vernac_state;
1757 rc
1758 with e when CErrors.noncritical e ->
1759 let e = Exninfo.capture e in
1760 Vernacstate.unfreeze_full_state vernac_state;
1761 raise (TacticFails e)
1762 in
1763 let subgoals, sigma = proofview pv in
1764 sigma, subgoals)
1765 sigma in
1766 Declare.Internal.export_side_effects (Evd.eval_side_effects sigma);
1767 let state, assignments = set_current_sigma ~depth state sigma in
1768 Result.Ok (state, subgoals, assignments)
1769 with TacticFails e -> Result.Error e
1770
1771 [%%if coq = "9.0"]
1772 let section_close_section x =
1773 let a,b,_,_ = Section.close_section x in
1774 a, b
1775 [%%elif coq = "9.1"]
1776 let section_close_section x =
1777 let a,b,_,_,_ = Section.close_section x in
1778 a, b
1779 [%%else]
1780 let section_close_section x =
1781 let a,b,_,_ = Section.close_section x in
1782 a, b
1783 [%%endif]
1784
1785
1786
1787 let coq_misc_builtins =
1788 let open API.BuiltIn in
1789 let open Pred in
1790 let open Notation in
1791 let open CConv in
1792 let pp ~depth = P.term depth in
1793 [
1794 LPDoc "-- Misc ---------------------------------------------------------";
1795
1796 MLCode(Pred("coq.info",
1797 VariadicIn(unit_ctx, !> B.any, "Prints an info message"),
1798 coq_print pp Feedback.msg_info
1799 ),
1800 DocAbove);
1801
1802 MLCode(Pred("coq.notice",
1803 VariadicIn(unit_ctx, !> B.any, "Prints a notice message"),
1804 coq_print pp Feedback.msg_notice
1805 ),
1806 DocAbove);
1807
1808 MLCode(Pred("coq.say",
1809 VariadicIn(unit_ctx, !> B.any, "Prints a notice message"),
1810 coq_print pp Feedback.msg_notice
1811 ),
1812 DocAbove);
1813
1814 MLCode(Pred("coq.debug",
1815 VariadicIn(unit_ctx, !> B.any, "Prints a debug message"),
1816 coq_print pp Feedback.msg_debug
1817 ),
1818 DocAbove);
1819
1820 MLCode(Pred("coq.warn",
1821 VariadicIn(unit_ctx, !> B.any, "Prints a generic warning message"),
1822 (fun args ~depth _hyps _constraints state ->
1823 let pp = pp ~depth in
1824 let loc, args =
1825 if args = [] then None, args
1826 else
1827 let x, args = List.hd args, List.tl args in
1828 match E.look ~depth x with
1829 | E.CData loc when API.RawOpaqueData.is_loc loc ->
1830 Some (Rocq_elpi_utils.to_coq_loc (API.RawOpaqueData.to_loc loc)), args
1831 | _ -> None, x :: args
1832 in
1833 warning ?loc (pp2string (P.list ~boxed:true pp " ") args);
1834 state, (), []
1835 )),
1836 DocAbove);
1837
1838 MLCode(Pred("coq.warning",
1839 In(B.string,"Category",
1840 In(B.string,"Name",
1841 VariadicIn(unit_ctx, !> B.any, {|
1842 Prints a warning message with a Name and Category which can be used
1843 to silence this warning or turn it into an error. See coqc -w command
1844 line option|}))),
1845 (fun category_name name args ~depth _hyps _constraints state ->
1846 let category = match CWarnings.get_category category_name with
1847 | There c -> c
1848 | OtherType -> CErrors.anomaly Pp.(str category_name ++ str "is a warning, not a warning category.")
1849 | NotThere -> CWarnings.create_category ~from:[elpi_cat] ~name:category_name ()
1850 in
1851 let w = match CWarnings.get_warning name with
1852 | There w -> w
1853 | OtherType -> CErrors.anomaly Pp.(str name ++ str " is a warning category, not a warning.")
1854 | NotThere -> CWarnings.create_warning ~from:[category] ~name ()
1855 in
1856 let warning = CWarnings.create_in w Pp.str in
1857 let pp = pp ~depth in
1858 let loc, args =
1859 if args = [] then None, args
1860 else
1861 let x, args = List.hd args, List.tl args in
1862 match E.look ~depth x with
1863 | E.CData loc when API.RawOpaqueData.is_loc loc ->
1864 Some (Rocq_elpi_utils.to_coq_loc (API.RawOpaqueData.to_loc loc)), args
1865 | _ -> None, x :: args
1866 in
1867 let txt = pp2string (P.list ~boxed:true pp " ") args in
1868 if coq_warning_cache category_name name loc txt then warning ?loc txt;
1869 state, (), [])),
1870 DocAbove);
1871
1872 MLCode(Pred("coq.error",
1873 VariadicIn(unit_ctx, !> B.any, "Prints and *aborts* the program. It is a fatal error for Elpi and Ltac"),
1874 (fun args ~depth _hyps _constraints _state ->
1875 let pp = pp ~depth in
1876 let loc, args =
1877 match args with
1878 | [] -> None, args
1879 | x :: rest ->
1880 match E.look ~depth x with
1881 | E.CData x when API.RawOpaqueData.is_loc x ->
1882 let loc = API.RawOpaqueData.to_loc x in
1883 Some loc, args
1884 | _ -> None, args
1885 in
1886 err ?loc Pp.(str (pp2string (P.list ~boxed:true pp " ") args)))),
1887 DocAbove);
1888
1889 MLCode(Pred("coq.version",
1890 Out(B.string, "VersionString",
1891 Out(int, "Major",
1892 Out(int, "Minor",
1893 Out(int, "Patch",
1894 Easy "Fetches the version of Coq, as a string and as 3 numbers")))),
1895 (fun _ _ _ _ ~depth:_ ->
1896 let version = Coq_config.version in
1897 let major, minor, patch = coq_version_parser version in
1898 !: version +! major +! minor +! patch)),
1899 DocAbove);
1900 ]
1901
1902 let coq_locate_builtins =
1903 let open API.BuiltIn in
1904 let open Pred in
1905 let open Notation in
1906 [ LPCode {|
1907 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1908 % API for objects belonging to the logic
1909 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|};
1910 LPDoc "-- Environment: names -----------------------------------------------";
1911 LPDoc {|To make the API more precise we use different data types for the names of global objects.
1912 Note: [ctype "bla"] is an opaque data type and by convention it is written [@bla].|};
1913
1914 MLData constant;
1915 MLData inductive;
1916 MLData constructor;
1917 MLData gref;
1918 MLData id;
1919 MLData modpath;
1920 MLData modtypath;
1921 MLData Rocq_elpi_builtins_synterp.located;
1922
1923 MLCode(Pred("coq.locate-all",
1924 In(id, "Name",
1925 Out(B.list Rocq_elpi_builtins_synterp.located, "Located",
1926 Easy {|finds all possible meanings of a string. Does not fail.|})),
1927 (fun s _ ~depth ->
1928 let qualid = Libnames.qualid_of_string s in
1929 let l = ref [] in
1930 let add x = l := !l @ [x] in
1931 begin
1932 match locate_qualid qualid with
1933 | Some (`Gref gr) -> add @@ Rocq_elpi_builtins_synterp.LocGref gr
1934 | Some (`Abbrev sd) -> add @@ Rocq_elpi_builtins_synterp.LocAbbreviation sd
1935 | None -> ()
1936 end;
1937 begin
1938 try add @@ Rocq_elpi_builtins_synterp.LocModule (Nametab.locate_module qualid)
1939 with Not_found -> ()
1940 end;
1941 begin
1942 try add @@ Rocq_elpi_builtins_synterp.LocModuleType (Nametab.locate_modtype qualid)
1943 with Not_found -> ()
1944 end;
1945 !: !l)),
1946 DocAbove);
1947
1948 MLCode(Pred("coq.locate",
1949 In(id, "Name",
1950 Out(gref, "GlobalReference",
1951 Easy {|locates a global definition, inductive type or constructor via its name.
1952 It unfolds syntactic notations, e.g. "Notation old_name := new_name."
1953 It understands qualified names, e.g. "Nat.t".
1954 It understands Rocqlib Registered names using the "lib:" prefix,
1955 eg "lib:core.bool.true".
1956 It's a fatal error if Name cannot be located.|})),
1957 (fun s _ ~depth:_ -> !: (locate_gref s))),
1958 DocAbove);
1959 ]
1960
1961 [%%if coq = "9.0" || coq= "9.1"]
1962 let locality_of_options (o : options) = o.local <> Some false
1963 [%%else]
1964 let locality_of_options (o : options) = match o.local with
1965 | Some true -> Libobject.Local
1966 | Some false -> Libobject.SuperGlobal
1967 | None -> Libobject.Export
1968 [%%endif]
1969
1970 [%%if coq = "9.0" || coq = "9.1"]
1971 let find_structure_from_projection env ind = Structures.Structure.find_from_projection ind
1972 let find_structure_projections env ind = Structures.Structure.find_projections ind
1973 [%%else]
1974 let find_structure_from_projection env ind = Structures.Structure.find_from_projection env ind
1975 let find_structure_projections env ind = Structures.Structure.find_projections env ind
1976 [%%endif]
1977
1978 [%%if coq = "9.0" || coq = "9.1"]
1979 let next_name_away_with_default_using_types _ _ id na names ty =
1980 Namegen.next_name_away_with_default_using_types id na names ty
1981 [%%else]
1982 let next_name_away_with_default_using_types = Namegen.next_name_away_with_default_using_types
1983 [%%endif]
1984
1985 [%%if coq = "9.0" ]
1986 let univ_binder_compat_820 a b = a
1987 [%%else]
1988 let univ_binder_compat_820 a b = b
1989 [%%endif]
1990
1991 [%%if coq = "9.0" || coq = "9.1"]
1992 let mis_is_recursive { Declarations.mind_recargs } =
1993 Rtree.is_infinite Declareops.eq_recarg mind_recargs
1994 [%%else]
1995 let mis_is_recursive = Inductiveops.mis_is_recursive
1996 [%%endif]
1997
1998 let coq_rest_builtins =
1999 let open API.BuiltIn in
2000 let open Pred in
2001 let open Notation in
2002 let open CConv in
2003 let pp ~depth = P.term depth in
2004 [
2005 LPDoc "-- Environment: read ------------------------------------------------";
2006 LPDoc "Note: The type [term] is defined in coq-HOAS.elpi";
2007
2008 MLCode(Pred("coq.env.typeof",
2009 In(gref, "GR",
2010 COut(closed_ground_term, "Ty",
2011 Full(global, {|reads the type Ty of a global reference.
2012 Supported attributes:
2013 - @uinstance! I (default: fresh instance I)|}))),
2014 (fun gr _ ~depth { options } _ state ->
2015 let type_of_global' state term inst_opt =
2016 let state, (ty, inst) = type_of_global state term inst_opt in
2017 state, ty, Some inst
2018 in
2019 let state, ty, _, gls =
2020 compute_with_uinstance ~depth options state type_of_global' gr None in
2021 state, !: ty, gls)),
2022 DocAbove);
2023
2024 MLCode(Pred("coq.env.global",
2025 InOut(B.ioarg (B.poly "gref"), "GR",
2026 InOut(B.ioarg (B.poly "term"), "T",
2027 Full(global, {|turns a global reference GR into a term, or viceversa.
2028 T = (global GR) or, if GR points to a universe polymorphic term,
2029 T = (pglobal GR I).
2030 Supported attributes:
2031 - @uinstance! I (default: fresh instance I)|}))),
2032 (fun gr t ~depth ({ options } as ctx) csts state ->
2033 let state, gr_in, _ =
2034 match gr with
2035 | NoData -> state, None, []
2036 | Data maybe_gr ->
2037 match E.look ~depth maybe_gr with
2038 | E.App(_,x,[]) ->
2039 begin match E.look ~depth x with
2040 | E.CData _ ->
2041 let state, gr, gls = gref.Conv.readback ~depth state maybe_gr in
2042 state, Some gr, gls
2043 | _ -> state, None, []
2044 end
2045 | _ -> state, None, []
2046 in
2047 let state, gr_out, ui_in =
2048 match t with
2049 | NoData -> state, None, None
2050 | Data maybe_t ->
2051 match is_global_or_pglobal ~depth maybe_t with
2052 | NotGlobal -> raise No_clause
2053 | Var -> state, None, None
2054 | (Global maybe_gr) -> state, maybe_gr, None
2055 | (PGlobal(maybe_gr,maybe_ui)) -> state, maybe_gr, maybe_ui
2056 in
2057 match gr_in, gr_out with
2058 | Some gr, _ ->
2059 let state, t, _, gls1 =
2060 compute_with_uinstance ~depth options state mk_global gr ui_in in
2061 let state, t, gls2 =
2062 closed_ground_term.CConv.embed ~depth ctx csts state t in
2063 state, ?: None +! t, gls1 @ gls2
2064 | None, Some maybe_gr ->
2065 let state, gr, gls = gref.Conv.readback ~depth state maybe_gr in
2066 let state, t, _, gls1 =
2067 compute_with_uinstance ~depth options state mk_global gr ui_in in
2068 let state, t, gls2 =
2069 closed_ground_term.CConv.embed ~depth ctx csts state t in
2070 state, !: maybe_gr +! t, gls @ gls1 @ gls2
2071 | None, None -> err Pp.(str "coq.env.global: no input, all arguments are variables"))),
2072 DocAbove);
2073
2074 MLCode(Pred("coq.env.indt",
2075 In(inductive, "reference to the inductive type",
2076 Out(bool, "tt if the type is inductive (ff for co-inductive)",
2077 Out(int, "number of parameters",
2078 Out(int, "number of parameters that are uniform (<= parameters)",
2079 COut(closed_ground_term, "type of the inductive type constructor including parameters",
2080 Out(list constructor, "list of constructor names",
2081 COut(!>> B.list closed_ground_term, "list of the types of the constructors (type of KNames) including parameters",
2082 Full(global, {|reads the inductive type declaration for the environment.
2083 % Supported attributes:
2084 % - @uinstance! I (default: fresh instance I)|})))))))),
2085 (fun i _ _ _ arity knames ktypes ~depth { env ; options } _ state ->
2086 let open Declarations in
2087 let mind, indbo as ind = lookup_inductive env i in
2088 let co = mind.mind_finite <> Declarations.CoFinite in
2089 let lno = mind.mind_nparams in
2090 let luno = mind.mind_nparams_rec in
2091 let uinst, state, extra_goals = handle_uinst_option_for_inductive ~depth options i state in
2092 let arity = if_keep arity (fun () ->
2093 Inductive.type_of_inductive (ind,uinst)
2094 |> EConstr.of_constr) in
2095 let knames = if_keep knames (fun () ->
2096 CList.(init (Array.length Declarations.(indbo.mind_consnames)) (fun k -> i,k+1))) in
2097 let ktypes = if_keep ktypes (fun () ->
2098 Inductive.type_of_constructors (i,uinst) ind
2099 |> CArray.map_to_list EConstr.of_constr) in
2100 state, !: co +! lno +! luno +? arity +? knames +? ktypes, extra_goals)),
2101
2102 DocNext);
2103
2104 MLCode(Pred("coq.env.indt-block",
2105 In(inductive, "Ind",
2106 Out(bool, "tt if the type is inductive (ff for co-inductive)",
2107 Out(int, "number of parameters",
2108 Out(int, "number of parameters that are uniform (<= parameters)",
2109 Out(list inductive, "all inductives in the block",
2110 COut(B.listC closed_ground_term, "types of the inductive types constructors including parameters",
2111 Out(list (list constructor), "lists of constructor names",
2112 COut(B.listC (B.listC closed_ground_term), "lists of the types of the constructors (type of KNames) including parameters",
2113 Full(global, {|reads the inductive type declaration for the environment.|}))))))))),
2114 (fun i _ _ _ _ arity knames ktypes ~depth { env ; options } _ state ->
2115 let open Declarations in
2116 let mind, _indbo as _ind = lookup_inductive env i in
2117 let co = mind.mind_finite <> Declarations.CoFinite in
2118 let lno = mind.mind_nparams in
2119 let luno = mind.mind_nparams_rec in
2120 let uinst, state, extra_goals = handle_uinst_option_for_inductive ~depth options i state in
2121 let arity = if_keep arity (fun () ->
2122 mind.mind_packets |> CArray.map_to_list (fun ind -> Inductive.type_of_inductive ((mind,ind),uinst) |> EConstr.of_constr)) in
2123 let knames = if_keep knames (fun () ->
2124 mind.mind_packets |> CArray.map_to_list (fun ind ->
2125 CList.(init (Array.length Declarations.(ind.mind_consnames)) (fun k -> i,k+1)))) in
2126 let ktypes = if_keep ktypes (fun () ->
2127 mind.mind_packets |> CArray.map_to_list (fun ind ->
2128 Inductive.type_of_constructors (i,uinst) (mind,ind)
2129 |> CArray.map_to_list EConstr.of_constr)) in
2130 let inames = CList.(init (Array.length Declarations.(mind.mind_packets)) (fun k -> fst i, k)) in
2131 state, !: co +! lno +! luno +! inames +? arity +? knames +? ktypes, extra_goals)),
2132 DocNext);
2133
2134 MLCode(Pred("coq.env.indt-decl",
2135 In(inductive, "reference to the inductive type",
2136 COut(indt_decl_out,"HOAS description of the inductive type",
2137 Full(global,{|reads the inductive type declaration for the environment.
2138 % Supported attributes:
2139 % - @uinstance! I (default: fresh instance I)|}))),
2140 (fun i _ ~depth { env; options } _ state ->
2141 let mind, _indbo = lookup_inductive env i in
2142 let uinst, state, extra_goals = handle_uinst_option_for_inductive ~depth options i state in
2143 let hd x = match x with [] -> [] | (_,x) :: _ -> List.map implicit_kind_of_status x in
2144 let packets = Array.to_list mind.Declarations.mind_packets in
2145 let i_impls = List.mapi (fun indno _ ->
2146 Impargs.extract_impargs_data (Impargs.implicits_of_global (GlobRef.IndRef (fst i, indno))) |> hd) packets in
2147 let k_impls = List.mapi (fun indno indbo ->
2148 let ind = (fst i, indno) in
2149 let knames = CList.(init (Array.length Declarations.(indbo.mind_consnames)) (fun k -> GlobRef.ConstructRef(ind,k+1))) in
2150 List.map (fun x -> Impargs.extract_impargs_data (Impargs.implicits_of_global x) |> hd) knames) packets in
2151 state, !: (fst i, uinst, mind, (i_impls,k_impls)), extra_goals)),
2152 DocNext);
2153
2154 MLCode(Pred("coq.env.indc->indt",
2155 In(constructor,"K",
2156 Out(inductive,"I",
2157 Out(int,"N",
2158 Easy {|finds the inductive I to which constructor K belongs and its position N among the other constructors|}))),
2159 (fun (i,n) _ _ ~depth -> !: i +! n)),
2160 DocAbove);
2161
2162 MLCode(Pred("coq.env.indc",
2163 In(constructor, "GR",
2164 Out(int, "ParamNo",
2165 Out(int, "UnifParamNo",
2166 Out(int, "Kno",
2167 COut(closed_ground_term,"Ty",
2168 Full (global, {|reads the type Ty of an inductive constructor GR, as well as
2169 the number of parameters ParamNo and uniform parameters
2170 UnifParamNo and the number of the constructor Kno (0 based).
2171 Supported attributes:
2172 - @uinstance! I (default: fresh instance I)|})))))),
2173 (fun (i,k as kon) _ _ _ ty ~depth { env; options } _ state ->
2174 let open Declarations in
2175 let mind, indbo as ind = Inductive.lookup_mind_specif env i in
2176 let lno = mind.mind_nparams in
2177 let luno = mind.mind_nparams_rec in
2178 let uinst, state, extra_goals =
2179 match options.uinstance with
2180 | NoInstance ->
2181 if keep ty then
2182 let term, ctx =
2183 UnivGen.fresh_global_instance (get_global_env state) (GlobRef.ConstructRef kon) in
2184 snd @@ Constr.destConstruct term,
2185 update_sigma state
2186 (fun sigma -> evd_merge_sort_context_set UState.univ_flexible_alg sigma ctx),
2187 []
2188 else
2189 UVars.Instance.empty, state, []
2190 | ConcreteInstance i -> i, state, []
2191 | VarInstance (v_head, v_args, v_depth) ->
2192 let v' = U.move ~from:v_depth ~to_:depth (E.mkUnifVar v_head ~args:v_args state) in
2193 let term, ctx =
2194 UnivGen.fresh_global_instance (get_global_env state) (GlobRef.ConstructRef kon) in
2195 let uinst = snd @@ Constr.destConstruct term in
2196 let state, lp_uinst, extra_goals = uinstance.Conv.embed ~depth state uinst in
2197 uinst,
2198 update_sigma state
2199 (fun sigma -> evd_merge_sort_context_set UState.univ_flexible_alg sigma ctx),
2200 API.Conversion.Unify (v', lp_uinst) :: extra_goals
2201 in
2202 let ty = if_keep ty (fun () ->
2203 Inductive.type_of_constructor (kon, uinst) ind
2204 |> EConstr.of_constr) in
2205 state, !: lno +! luno +! (k-1) +? ty, extra_goals)),
2206 DocAbove);
2207
2208 MLCode(Pred("coq.env.informative?",
2209 In(inductive, "Ind",
2210 Read(global, {|Checks if Ind is informative, that is, if
2211 it can be eliminated to build a Type. Inductive types in Type are
2212 informative, as well a singleton types in Prop (which are
2213 regarded as not non-informative).|})),
2214 (fun i ~depth {env} _ state ->
2215 let _, indbo = Inductive.lookup_mind_specif env i in
2216 if Option.has_some indbo.Declarations.mind_squashed then raise No_clause
2217 )),
2218 DocAbove);
2219
2220 MLCode(Pred("coq.env.record?",
2221 In(inductive, "Ind",
2222 Out(bool,"PrimProjs",
2223 Read(global, "checks if Ind is a record (PrimProjs = tt if Ind has primitive projections)"))),
2224 (fun i _ ~depth {env} _ state ->
2225 let specif = Inductive.lookup_mind_specif env i in
2226 match Rocq_elpi_HOAS.mind_record specif with
2227 | Declarations.PrimRecord _ -> !: true
2228 | Declarations.FakeRecord -> !: false
2229 | _ -> raise No_clause
2230 )),
2231 DocAbove);
2232
2233 MLCode(Pred("coq.env.recursive?",
2234 In(inductive, "Ind",
2235 Read(global, "checks if Ind is recursive")),
2236 (fun i ~depth {env} _ state ->
2237 let _, indbo = Inductive.lookup_mind_specif env i in
2238 if mis_is_recursive indbo then ()
2239 else raise No_clause
2240 )),
2241 DocAbove);
2242
2243 MLCode(Pred("coq.env.opaque?",
2244 In(constant, "GR",
2245 Read(global, "checks if GR is an opaque constant")),
2246 (fun c ~depth {env} _ state ->
2247 match c with
2248 | Constant c ->
2249 let open Declareops in
2250 let cb = Environ.lookup_constant c env in
2251 if is_opaque cb || not(constant_has_body cb) then ()
2252 else raise Pred.No_clause
2253 | Variable v ->
2254 match Environ.lookup_named v env with
2255 | Context.Named.Declaration.LocalDef _ -> raise Pred.No_clause
2256 | Context.Named.Declaration.LocalAssum _ -> ())),
2257 DocAbove);
2258
2259 MLCode(Pred("coq.env.univpoly?",
2260 In(gref, "GR",
2261 Out(B.int, "PolyArity",
2262 Read(global, "checks if GR is universe polymorphic and if so returns the number of universe variables"))),
2263 (fun gr _ ~depth {env} _ _ ->
2264 if Environ.is_polymorphic env gr then
2265 let open Declareops in let open Environ in
2266 let size auctx =
2267 let qsize, usize = UVars.AbstractContext.size auctx in
2268 let () = if qsize <> 0 then nYI "sort poly" in
2269 usize
2270 in
2271 match gr with
2272 | GlobRef.ConstRef c -> !: (size (constant_polymorphic_context (lookup_constant c env)))
2273 | GlobRef.ConstructRef ((i,_),_)
2274 | GlobRef.IndRef (i,_) -> !: (size (inductive_polymorphic_context (lookup_mind i env)))
2275 | GlobRef.VarRef _ -> assert false
2276 else raise No_clause)),
2277 DocAbove);
2278
2279 MLCode(Pred("coq.env.const",
2280 In(constant, "GR",
2281 COut(!>> option closed_ground_term, "Bo",
2282 COut(closed_ground_term, "Ty",
2283 Full (global, {|reads the type Ty and the body Bo of constant GR.
2284 Opaque constants have Bo = none.
2285 Supported attributes:
2286 - @uinstance! I (default: fresh instance I)|})))),
2287 (fun c bo ty ~depth { env ; options } _ state ->
2288 let type_of_global' state term inst_opt =
2289 let state, (ty, inst) = type_of_global state term inst_opt in
2290 state, ty, Some inst
2291 in
2292 match c with
2293 | Constant c ->
2294 let state, ty_opt, uinst_opt, gl_opt1 =
2295 if keep ty then
2296 let state, ty, uinst_opt, gls =
2297 compute_with_uinstance ~depth options state type_of_global' (GlobRef.ConstRef c) None in
2298 state, Some ty, uinst_opt, gls
2299 else
2300 let uinst_opt =
2301 match options.uinstance with
2302 | ConcreteInstance i -> Some i
2303 | _ -> None
2304 in
2305 state, None, uinst_opt, []
2306 in
2307 let state, bo_opt, gl_opt2 =
2308 if keep bo then
2309 if Declareops.is_opaque (Environ.lookup_constant c env) then
2310 state, Some None, []
2311 else
2312 let state, bo, _, gls2 =
2313 compute_with_uinstance ~depth options state body_of_constant c uinst_opt in
2314 state, Some bo, gls2
2315 else
2316 state, None, []
2317 in
2318 state, ?: bo_opt +? ty_opt, gl_opt1 @ gl_opt2
2319 | Variable v ->
2320 let state, ty, gls =
2321 if keep ty then
2322 let state, ty, _, gls =
2323 compute_with_uinstance ~depth options state type_of_global' (GlobRef.VarRef v) None in
2324 state, Some ty, gls
2325 else
2326 state, None, []
2327 in
2328 let bo = if_keep bo (fun () ->
2329 match Environ.lookup_named v env with
2330 | Context.Named.Declaration.LocalDef(_,bo,_) -> Some (bo |> EConstr.of_constr)
2331 | Context.Named.Declaration.LocalAssum _ -> None) in
2332 state, ?: bo +? ty, gls)),
2333 DocAbove);
2334
2335 MLCode(Pred("coq.env.const-body",
2336 In(constant, "GR",
2337 COut(!>> option closed_ground_term, "Bo",
2338 Full (global, {|reads the body of a constant, even if it is opaque.
2339 If such body is none, then the constant is a true axiom.
2340 Supported attributes:
2341 - @uinstance! I (default: fresh instance I)|}))),
2342 (fun c _ ~depth { env ; options } _ state ->
2343 match c with
2344 | Constant c ->
2345 let state, bo, gls =
2346 let state, bo, _, gls =
2347 compute_with_uinstance ~depth options state body_of_constant c None in
2348 state, bo, gls
2349 in
2350 state, !: bo, gls
2351 | Variable v ->
2352 state, !: begin
2353 match Environ.lookup_named v env with
2354 | Context.Named.Declaration.LocalDef(_,bo,_) -> Some (bo |> EConstr.of_constr)
2355 | Context.Named.Declaration.LocalAssum _ -> None
2356 end, [])),
2357 DocAbove);
2358
2359 MLCode(Pred("coq.env.primitive?",
2360 In(constant, "GR",
2361 Read (global,"tests if GR is a primitive constant (like uin63 addition) or a primitive type (like uint63)")),
2362 (fun c ~depth {env} _ state ->
2363 match c with
2364 | Constant c ->
2365 if Environ.is_primitive env c || Environ.is_primitive_type env c then ()
2366 else raise No_clause
2367 | Variable v -> raise No_clause)),
2368 DocAbove);
2369
2370 Rocq_elpi_builtins_synterp.locate_module;
2371 Rocq_elpi_builtins_synterp.locate_module_type;
2372
2373 MLData module_item;
2374
2375 MLCode(Pred("coq.env.module",
2376 In(modpath, "MP",
2377 Out(list module_item, "Contents",
2378 Read(global, "lists the contents of a module (recurses on submodules) *E*"))),
2379 (fun mp _ ~depth {env} _ state ->
2380 let t = in_elpi_module ~depth state mp (Environ.lookup_module mp env) in
2381 !: t)),
2382 DocAbove);
2383
2384 MLCode(Pred("coq.env.module-type",
2385 In(modtypath, "MTP",
2386 Out(list id, "Entries",
2387 Read (global, "lists the items made visible by module type "^
2388 "(does not recurse on submodules) *E*"))),
2389 (fun mp _ ~depth {env} _ state ->
2390 !: (in_elpi_module_type (Environ.lookup_modtype mp env)))),
2391 DocAbove);
2392
2393 MLCode(Pred("coq.env.section-variables",
2394 Out(list constant, "ConstantsRepresentingVariables",
2395 Read(unit_ctx, "lists all the section variables, i.e. the global objects that are marked as to be abstracted at the end of the enclosing sections")),
2396 (fun _ ~depth _ _ state ->
2397 let { section } = empty_conv_context ~options:(default_options ()) state in
2398 !: (section |> List.map (fun x -> Variable x)) )),
2399 DocAbove);
2400
2401 MLCode(Pred("coq.env.section-contents",
2402 Out(list (list gref), "GlobalObjects",
2403 Read(unit_ctx, "lists the global objects that are defined withing the open sections. Inner section first.")),
2404 (fun _ ~depth _ _ state ->
2405 let l =
2406 let safe_env = Global.safe_env () in
2407 let section = Safe_typing.sections_of_safe_env safe_env in
2408 let rec aux section =
2409 match section with
2410 | None -> []
2411 | Some s ->
2412 let section,l = section_close_section s in
2413 List.concat_map (function
2414 | Section.SecDefinition c -> [GlobRef.ConstRef c]
2415 | Section.SecInductive m ->
2416 let { Declarations.mind_packets } = Environ.lookup_mind m (Safe_typing.env_of_safe_env safe_env) in
2417 List.init (Array.length mind_packets) (fun i -> GlobRef.IndRef(m,i))
2418 ) l :: aux section
2419 in
2420 aux section
2421 in
2422 !: l)),
2423 DocAbove);
2424
2425 LPCode {|% Deprecated, use coq.env.section-variables
2426 func coq.env.section -> list constant.
2427 coq.env.section L :-
2428 coq.warning "elpi.deprecated" "elpi.env.section" "use coq.env.section-variables in place of coq.env.section",
2429 coq.env.section-variables L.
2430 |};
2431
2432 MLCode(Pred("coq.env.dependencies",
2433 In(gref, "GR",
2434 In(B.unspec modpath, "MP",
2435 Out(gref_set, "Deps",
2436 Read(unit_ctx, "Computes the direct dependencies of GR. If MP is given, Deps only contains grefs from that module")))),
2437 (fun root inside _ ~depth _ _ state ->
2438 let inside = unspec2opt inside in
2439 !: (dep1 ?inside (get_sigma state) root))),
2440 DocAbove);
2441
2442 MLCode(Pred("coq.env.transitive-dependencies",
2443 In(gref, "GR",
2444 In(B.unspec modpath, "MP",
2445 Out(gref_set, "Deps",
2446 Read(unit_ctx, "Computes the transitive dependencies of GR. If MP is given, Deps only contains grefs from that module")))),
2447 (fun root inside _ ~depth _ _ state ->
2448 let inside = unspec2opt inside in
2449 let sigma = get_sigma state in
2450 let rec aux seen = function
2451 | [] -> seen
2452 | s :: xs when GRSet.is_empty s -> aux seen xs
2453 | s :: rest ->
2454 let x = GRSet.min_elt s in
2455 let s = GRSet.remove x s in
2456 if GRSet.mem x seen then aux seen (s :: rest)
2457 else
2458 let deps = dep1 ?inside sigma x in
2459 let seen = GRSet.add x seen in
2460 aux seen (deps :: s :: rest)
2461 in
2462 !: (GRSet.remove root @@ aux GRSet.empty [dep1 ?inside sigma root]))),
2463 DocAbove);
2464
2465 MLCode(Pred("coq.env.term-dependencies",
2466 CIn(failsafe_term,"T",
2467 Out(gref_set, "S",
2468 Full(proof_context, {|Computes all the grefs S occurring in the term T|}))),
2469 (fun t _ ~depth proof_context constraints state ->
2470 let sigma = get_sigma state in
2471 let s = grefs_of_term sigma t GRSet.add GRSet.empty in
2472 state, !: s, [])),
2473 DocAbove);
2474
2475 MLCode(Pred("coq.env.current-path",
2476 Out(list B.string, "Path",
2477 Read(unit_ctx, "lists the current module path")),
2478 (fun _ ~depth _ _ state -> !: (mp2path (Global.current_modpath ())))),
2479 DocAbove);
2480
2481 Rocq_elpi_builtins_synterp.current_section_path;
2482
2483 LPCode {|% Deprecated, use coq.env.opaque?
2484 pred coq.env.const-opaque? i:constant.
2485 coq.env.const-opaque? C :-
2486 coq.warning "elpi.deprecated" "elpi.const-opaque" "use coq.env.opaque? in place of coq.env.const-opaque?",
2487 coq.env.opaque? C.
2488 |};
2489
2490 LPCode {|% Deprecated, use coq.env.primitive?
2491 pred coq.env.const-primitive? i:constant.
2492 coq.env.const-primitive? C :-
2493 coq.warning "elpi.deprecated" "elpi.const-primitive" "use coq.env.primitive? in place of coq.env.const-primitive?",
2494 coq.env.primitive? C.
2495 |};
2496
2497 LPDoc "-- Environment: write -----------------------------------------------";
2498
2499 LPDoc ("Note: (monomorphic) universe constraints are taken from ELPI's constraints "^
2500 "store. Use coq.univ-* in order to add constraints (or any higher "^
2501 "level facility as coq.typecheck). Load in the context attributes such as "^
2502 "@univpoly!, @univpoly-cumul!, @udecl! or @udecl-cumul! in order to declare "^
2503 "universe polymorphic constants or inductives."
2504 );
2505
2506 MLCode(Pred("coq.env.add-const",
2507 In(id, "Name",
2508 CIn(B.unspecC closed_ground_term, "Bo",
2509 CIn(B.unspecC closed_ground_term, "Ty",
2510 In(flag "opaque?", "Opaque",
2511 Out(constant, "C",
2512 Full (global, {|Declare a new constant: C gets a constant derived from Name
2513 and the current module; Ty can be left unspecified and in that case the
2514 inferred one is taken (as in writing Definition x := t); Bo can be left
2515 unspecified and in that case an axiom is added (or a section variable,
2516 if a section is open and @local! is used). Omitting the body and the type is
2517 an error. Note: using this API for declaring an axiom or a section variable is
2518 deprecated, use coq.env.add-axiom or coq.env.add-section-variable instead.
2519 Supported attributes:
2520 - @local! (default: false)
2521 - @using! (default: section variables actually used)
2522 - @univpoly! (default unset)
2523 - @udecl! (default unset)
2524 - @dropunivs! (default: false, drops all universe constraints from the store after the definition)
2525 |})))))),
2526 (fun id body types opaque _ ~depth {options} _ -> grab_global_env__drop_sigma_univs_if_option_is_set options "coq.env.add-const" (fun state ->
2527 let local_bkind = if options.local = Some true then Some Glob_term.Explicit else None in
2528 let state = minimize_universes state in
2529 (* Maybe: UState.nf_universes on body and type *)
2530 match body with
2531 | B.Unspec -> (* axiom *)
2532 begin match types with
2533 | B.Unspec ->
2534 err Pp.(str "coq.env.add-const: both Type and Body are unspecified")
2535 | B.Given ty ->
2536 warn_deprecated_add_axiom ();
2537 let gr, uctx = add_axiom_or_variable "coq.env.add-const" id ty local_bkind options state in
2538 uctx, state, !: (global_constant_of_globref gr), []
2539 end
2540 | B.Given body ->
2541 let sigma = get_sigma state in
2542 if not (is_ground sigma body) then
2543 err Pp.(str"coq.env.add-const: the body must be ground. Did you forge to call coq.typecheck-indt-decl?");
2544 let opaque = opaque = B.Given true in
2545 let types =
2546 match types, opaque with
2547 | B.Unspec, false -> None
2548 | B.Unspec, true -> (* Coq does not accept opaque definitions with no body *)
2549 begin try Some (Retyping.get_type_of (get_global_env state) sigma body)
2550 with
2551 | Retyping.RetypeError _ -> err Pp.(str"coq.env.add-const: illtyped opaque")
2552 | e when Rocq_elpi_utils.is_sync_anomaly e -> err Pp.(str"coq.env.add-const: illtyped opaque") end
2553 | B.Given ty, _ ->
2554 if not (is_ground sigma ty) then
2555 err Pp.(str"coq.env.add-const: the type must be ground. Did you forge to call coq.typecheck-indt-decl?");
2556 Some ty in
2557 let state, poly, cumul, udecl, _ = poly_cumul_udecl_variance_of_options state options in
2558 if cumul then err Pp.(str"coq.env.add-const: unsupported attribute @udecl-cumul! or @univpoly-cumul!");
2559 let kind = Decls.(IsDefinition Definition) in
2560 let scope = if Option.has_some local_bkind
2561 then Locality.Discharge
2562 else Locality.(Global ImportDefaultBehavior) in
2563 let cinfo = cinfo_make state types options.using ~name:(Id.of_string id) ~typ:types ~impargs:[] () in
2564
2565 let info = Declare.Info.make ~scope ~kind ~poly:(make_polyflags poly cumul) ~udecl () in
2566
2567 let used =
2568 Univ.Level.Set.union
2569 (universes_of_term state body)
2570 (Option.default (EConstr.mkRel 1) types |> universes_of_term state) in
2571 let used = Univ.Level.Set.union used (universes_of_udecl state udecl) in
2572 let sigma = restricted_sigma_of used state in
2573
2574 let gr, uctx = declare_definition options.using ~cinfo ~info ~opaque ~body sigma in
2575 let () =
2576 let lid = CAst.make ~loc:(to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state) (Id.of_string id) in
2577 match scope with
2578 | Locality.Discharge -> Dumpglob.dump_definition lid true "var"
2579 | Locality.Global _ -> Dumpglob.dump_definition lid false "def"
2580 in
2581 uctx, state, !: (global_constant_of_globref gr), []))),
2582 DocAbove);
2583
2584 MLCode(Pred("coq.env.add-axiom",
2585 In(id, "Name",
2586 CIn(closed_ground_term, "Ty",
2587 Out(constant, "C",
2588 Full (global, {|Declare a new axiom: C gets a constant derived from Name
2589 and the current module.
2590 Supported attributes:
2591 - @local! (default: false)
2592 - @univpoly! (default unset)
2593 - @using! (default: section variables actually used)
2594 - @inline! (default: no inlining)
2595 - @inline-at! N (default: no inlining)|})))),
2596 (fun id ty _ ~depth {options} _ -> grab_global_env "coq.env.add-axiom" (fun state ->
2597 let gr, uctx = add_axiom_or_variable "coq.env.add-axiom" id ty None options state in
2598 uctx, state, !: (global_constant_of_globref gr), []))),
2599 DocAbove);
2600
2601 MLCode(Pred("coq.env.add-section-variable",
2602 In(id, "Name",
2603 In(B.unspec implicit_kind, "I",
2604 CIn(closed_ground_term, "Ty",
2605 Out(constant, "C",
2606 Full (global, {|Declare a new section variable: C gets a constant derived from Name
2607 and the current module.
2608 |}))))),
2609 (fun id bkind ty _ ~depth {options} _ -> grab_global_env_drop_sigma_keep_univs "coq.env.add-section-variable" (fun state ->
2610 let bkind = Option.default Glob_term.Explicit (unspec2opt bkind) in
2611 let gr, uctx = add_axiom_or_variable "coq.env.add-section-variable" id ty (Some bkind) options state in
2612 uctx, state, !: (global_constant_of_globref gr), []))),
2613 DocAbove);
2614
2615 LPCode {|
2616 pred coq.env.add-context i:context-decl.
2617 coq.env.add-context context-end.
2618 coq.env.add-context (context-item Name I Ty none Rest) :-
2619 coq.env.add-section-variable Name I Ty C,
2620 coq.env.add-context (Rest {coq.env.global (const C)}).
2621 coq.env.add-context (context-item Name _I Ty (some Bo) Rest) :-
2622 coq.env.add-const Name Bo Ty ff C,
2623 coq.env.add-context (Rest {coq.env.global (const C)}).
2624 |};
2625
2626 MLCode(Pred("coq.env.add-indt",
2627 CIn(indt_decl_in, "Decl",
2628 Out(inductive, "I",
2629 Full(global, {|Declares an inductive type.
2630 Supported attributes:
2631 - @dropunivs! (default: false, drops all universe constraints from the store after the definition)
2632 - @primitive! (default: false, makes records primitive)|}))),
2633 (fun (default_dep_elim,me, uctx, univ_binders, record_info, ind_impls) _ ~depth {options} _ -> grab_global_env__drop_sigma_univs_if_option_is_set options "coq.env.add-indt" (fun state ->
2634 let sigma = get_sigma state in
2635 if not (is_mutual_inductive_entry_ground me sigma) then
2636 err Pp.(str"coq.env.add-indt: the inductive type declaration must be ground. Did you forget to call coq.typecheck-indt-decl?");
2637 let primitive_expected = match record_info with Some(p, _) -> p | _ -> false in
2638 let (uentry, uentry', ubinders) =
2639 let open Entries in
2640 match me.mind_entry_universes with
2641 | Monomorphic_ind_entry -> (Monomorphic_entry, UState.Monomorphic_entry uctx, univ_binders)
2642 | Template_ind_entry _ -> nYI "template polymorphic inductives"
2643 | Polymorphic_ind_entry uctx ->
2644 (Polymorphic_entry uctx, UState.Polymorphic_entry uctx, univ_binders)
2645 in
2646 let () = Global.push_context_set uctx in
2647 let mind =
2648 let univ_binders = univ_binder_compat_820 (uentry', ubinders) univ_binders in
2649 declare_mutual_inductive_with_eliminations ~primitive_expected ~default_dep_elim me univ_binders ind_impls in
2650 let ind = mind, 0 in
2651 let lid_of id = CAst.make ~loc:(to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state) id in
2652 begin match record_info with
2653 | None -> (* regular inductive *)
2654 List.iter (fun { Entries.mind_entry_typename = id; mind_entry_consnames = cids; _ } ->
2655 Dumpglob.dump_definition (lid_of id) false "ind";
2656 List.iter (fun x -> Dumpglob.dump_definition (lid_of x) false "constr") cids)
2657 me.Entries.mind_entry_inds
2658 | Some (primitive,field_specs) -> (* record: projection... *)
2659 let id = match me.Entries.mind_entry_inds with
2660 | [ { Entries.mind_entry_typename = id; _ } ] -> id
2661 | _ -> assert false in
2662 let names, flags =
2663 List.(split (map lp2record_field_spec field_specs))
2664 in
2665 let is_implicit = List.map (fun _ -> []) names in
2666 let open Entries in
2667 let k_ty = List.(hd (hd me.mind_entry_inds).mind_entry_lc) in
2668 let fields_as_relctx = Term.prod_decls k_ty in
2669 let projections =
2670 declare_projections ind ~kind:Decls.Definition
2671 (uentry, ubinders)
2672 (Names.Id.of_string "record")
2673 flags is_implicit fields_as_relctx
2674 in
2675 let struc = Structures.Structure.make (Global.env()) ind projections in
2676 Record.Internal.declare_structure_entry struc;
2677 Dumpglob.dump_definition (lid_of id) false "rec";
2678 List.iter (function
2679 | Names.Name id -> Dumpglob.dump_definition (lid_of id) false "proj"
2680 | Names.Anonymous -> ()) names;
2681 end;
2682 uctx,state, !: ind, []))),
2683 DocAbove);
2684
2685 LPDoc "Interactive module construction";
2686
2687 MLData module_inline_default;
2688
2689 MLCode(Pred("coq.env.fresh-global-id",
2690 In(id,"ID",
2691 Out(id,"FID",
2692 Easy {|Generates an id FID which is fresh in
2693 the current module and looks similar to ID, i.e. it is ID concatenated
2694 with a number, starting from 1.
2695 [coq.env.fresh-global-id X X] can be used to check if X is taken|})),
2696 (fun id _ ~depth ->
2697 let l = Names.Label.of_id (Names.Id.of_string_soft id) in
2698 if not (Safe_typing.exists_objlabel l (Global.safe_env ())) then !: id
2699 else
2700 let rec fresh n =
2701 let id = id ^ string_of_int n in
2702 let l = Names.Label.of_id (Names.Id.of_string_soft id) in
2703 if not (Safe_typing.exists_objlabel l (Global.safe_env ())) then !: id
2704 else fresh (n+1)
2705 in
2706 fresh 1
2707 )),
2708 DocAbove);
2709
2710 (* XXX When Coq's API allows it, call vernacentries directly *)
2711 MLCode(Pred("coq.env.begin-module-functor",
2712 In(id, "The name of the functor",
2713 In(B.unspec (option modtypath), "Its module type (optional)",
2714 In(B.unspec (list (pair id modtypath)), "Parameters of the functor (optional)",
2715 Full(unit_ctx, "Starts a functor" ^ Rocq_elpi_builtins_synterp.synterp_api_doc)))),
2716 (fun name mp params ~depth _ _ -> grab_global_env "coq.env.begin-module-functor" (fun state ->
2717 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_BeginModule (name,mp,params) state in
2718 Univ.ContextSet.empty, state, (), []))),
2719 DocNext);
2720
2721 LPCode {|
2722 func coq.env.begin-module id, option modtypath -> .
2723 coq.env.begin-module Name MP :- coq.env.begin-module-functor Name MP [].
2724 |};
2725
2726 (* XXX When Coq's API allows it, call vernacentries directly *)
2727 MLCode(Pred("coq.env.end-module",
2728 Out(modpath, "ModPath",
2729 Full(unit_ctx, "end the current module that becomes known as ModPath *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc)),
2730 (fun _ ~depth _ _ -> grab_global_env_drop_sigma "coq.env.end-module" (fun state ->
2731 let state, mp = Rocq_elpi_builtins_synterp.SynterpAction.pop_EndModule () state in
2732 state, ?: mp, []))),
2733 DocAbove);
2734
2735 (* XXX When Coq's API allows it, call vernacentries directly *)
2736 MLCode(Pred("coq.env.begin-module-type-functor",
2737 In(id, "The name of the functor",
2738 In(B.unspec (list (pair id modtypath)), "The parameters of the functor (optional)",
2739 Full(unit_ctx,"Starts a module type functor *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc))),
2740 (fun id params ~depth _ _ -> grab_global_env "coq.env.begin-module-type-functor" (fun state ->
2741 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_BeginModuleType (id,params) state in
2742 Univ.ContextSet.empty, state, (), []))),
2743 DocNext);
2744
2745 LPCode {|
2746 func coq.env.begin-module-type id ->.
2747 coq.env.begin-module-type Name :-
2748 coq.env.begin-module-type-functor Name [].
2749 |};
2750
2751 (* XXX When Coq's API allows it, call vernacentries directly *)
2752 MLCode(Pred("coq.env.end-module-type",
2753 Out(modtypath, "ModTyPath",
2754 Full(unit_ctx, "end the current module type that becomes known as ModPath *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc)),
2755 (fun _ ~depth _ _ -> grab_global_env_drop_sigma "coq.env.end-module-type" (fun state ->
2756 let state, mp = Rocq_elpi_builtins_synterp.SynterpAction.pop_EndModuleType () state in
2757 state, ?: mp, []))),
2758 DocAbove);
2759
2760 MLCode(Pred("coq.env.apply-module-functor",
2761 In(id, "The name of the new module",
2762 In(B.unspec (option modtypath), "Its module type (optional)",
2763 In(B.unspec modpath, "The functor being applied (optional)",
2764 In(B.unspec (list modpath), "Its arguments (optional)",
2765 In(B.unspec module_inline_default, "Arguments inlining (optional)",
2766 Out(modpath, "The modpath of the new module",
2767 Full(unit_ctx, "Applies a functor *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc))))))),
2768 (fun name mp f arguments inline _ ~depth _ _ -> grab_global_env "coq.env.apply-module-functor" (fun state ->
2769 let state, mp = Rocq_elpi_builtins_synterp.SynterpAction.pop_ApplyModule (name,mp,f,arguments,inline) state in
2770 Univ.ContextSet.empty, state, ?: mp, []))),
2771 DocNext);
2772
2773 MLCode(Pred("coq.env.apply-module-type-functor",
2774 In(id, "The name of the new module type",
2775 In(B.unspec modtypath, "The functor (optional)",
2776 In(B.unspec (list modpath), "Its arguments (optional)",
2777 In(B.unspec module_inline_default, "Arguments inlining (optional)",
2778 Out(modtypath, "The modtypath of the new module type",
2779 Full(unit_ctx, "Applies a type functor *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc)))))),
2780 (fun name f arguments inline _ ~depth _ _ -> grab_global_env "coq.env.apply-module-type-functor" (fun state ->
2781 let state, mp = Rocq_elpi_builtins_synterp.SynterpAction.pop_ApplyModuleType (name,f,arguments,inline) state in
2782 Univ.ContextSet.empty, state, ?: mp, []))),
2783 DocNext);
2784
2785 (* XXX When Coq's API allows it, call vernacentries directly *)
2786 MLCode(Pred("coq.env.include-module",
2787 In(modpath, "ModPath",
2788 In(B.unspec module_inline_default, "Inline (optional)",
2789 Full(unit_ctx, "is like the vernacular Include, Inline can be omitted *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc))),
2790 (fun mp i ~depth _ _ -> grab_global_env "coq.env.include-module" (fun state ->
2791 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_IncludeModule (mp,i) state in
2792 Univ.ContextSet.empty, state, (), []))),
2793 DocAbove);
2794
2795 (* XXX When Coq's API allows it, call vernacentries directly *)
2796 MLCode(Pred("coq.env.include-module-type",
2797 In(modtypath, "ModTyPath",
2798 In(B.unspec module_inline_default, "Inline (optional)",
2799 Full(unit_ctx, "is like the vernacular Include Type, Inline can be omitted *E*" ^ Rocq_elpi_builtins_synterp.synterp_api_doc))),
2800 (fun mp i ~depth _ _ -> grab_global_env "coq.env.include-module-type" (fun state ->
2801 let state,_ = Rocq_elpi_builtins_synterp.SynterpAction.pop_IncludeModuleType (mp,i) state in
2802 Univ.ContextSet.empty, state, (), []))),
2803 DocAbove);
2804
2805 MLCode(Pred("coq.env.import-module",
2806 In(modpath, "ModPath",
2807 Full(unit_ctx, "is like the vernacular Import *E*")),
2808 (fun mp ~depth _ _ -> grab_global_env "coq.env.import-module" (fun state ->
2809 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_ImportModule mp state in
2810 Univ.ContextSet.empty, state, (), []))),
2811 DocAbove);
2812
2813 MLCode(Pred("coq.env.export-module",
2814 In(modpath, "ModPath",
2815 Full(unit_ctx, "is like the vernacular Export *E*")),
2816 (fun mp ~depth _ _ -> grab_global_env "coq.env.export-module" (fun state ->
2817 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_ExportModule mp state in
2818 Univ.ContextSet.empty, state, (), []))),
2819 DocAbove);
2820
2821 LPDoc
2822 {|Support for sections is limited, in particular sections and
2823 Coq quotations may interact in surprising ways. For example
2824 Section Test.
2825 Variable x : nat.
2826 Elpi Query lp:{{ coq.say {{ x }} }}.
2827 works since x is a global Coq term while
2828 Elpi Query lp:{{
2829 coq.env.begin-section "Test",
2830 coq.env.add-const "x" _ {{ nat }} _ @local! GRX,
2831 coq.say {{ x }}
2832 }}.
2833 may work in a surprising way or may not work at all since
2834 x is resolved before the section is started hence it cannot
2835 denote the same x as before.|};
2836
2837 MLCode(Pred("coq.env.begin-section",
2838 In(id, "Name",
2839 Full(unit_ctx, "starts a section named Name *E*")),
2840 (fun id ~depth _ _ -> grab_global_env "coq.env.begin-section" (fun state ->
2841 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_BeginSection id state in
2842 Univ.ContextSet.empty, state, (), []))),
2843 DocAbove);
2844
2845 MLCode(Pred("coq.env.end-section",
2846 Full(unit_ctx, "end the current section *E*"),
2847 (fun ~depth _ _ -> grab_global_env_drop_sigma "coq.env.end-section" (fun state ->
2848 let { section } = empty_conv_context ~options:(default_options ()) state in
2849 let state = State.update clauses_for_later_interp state (List.filter (fun (_, _, vars, _) ->
2850 not (List.exists (fun v -> List.mem v section) vars)
2851 )) in
2852 let state, _ = Rocq_elpi_builtins_synterp.SynterpAction.pop_EndSection () state in
2853 state, (), []))),
2854 DocAbove);
2855
2856 MLCode(Pred("coq.env.projections",
2857 In(inductive, "StructureName",
2858 Out(list (option constant), "Projections",
2859 Read (global, "given a record StructureName lists all projections"))),
2860 (fun i _ ~depth _ _ state ->
2861 let env = get_global_env state in
2862 !: ((try find_structure_projections env i with Not_found -> []) |>
2863 CList.map (Option.map (fun x -> Constant x))))),
2864 DocAbove);
2865
2866 MLCode(Pred("coq.env.projection?",
2867 In(constant, "Constant",
2868 Out(B.int, "Number of parameters",
2869 Read (global, "if the constant is a projection, returns the number of parameters of its record."))),
2870 (fun c _ ~depth _ _ state ->
2871 let env = get_global_env state in
2872 let c = match c with Constant t -> t | _ -> raise No_clause in
2873 try !: ((find_structure_from_projection env c).nparams)
2874 with Not_found -> raise No_clause)),
2875 DocAbove);
2876
2877 MLCode(Pred("coq.env.primitive-projections",
2878 In(inductive, "StructureName",
2879 Out(list (option (pair projection int)), "Projections",
2880 Read (global, "given a record StructureName lists all primitive projections"))),
2881 (fun i _ ~depth _ _ state ->
2882 let env = get_global_env state in
2883 !: (find_structure_projections env i |>
2884 CList.map (fun o -> Option.bind o (fun x ->
2885 Option.bind (Structures.PrimitiveProjections.find_opt x) (fun c ->
2886 let c = Names.Projection.make c false in
2887 let np = Names.Projection.npars c in
2888 let na = Names.Projection.arg c in
2889 Some (c, np + na))))))),
2890 DocAbove);
2891
2892 MLCode(Pred("coq.env.primitive-projection?",
2893 InOut(B.ioarg projection, "Projection",
2894 InOut(B.ioarg constant, "Compatibility constant",
2895 Out(int, "Index",
2896 Read(global, "Relates a primitive projection to its compatibility constant. Index is set to the constructor argument extracted by the projection (starting from 0).")))),
2897 (fun p c _ ~depth conv_context _ _ ->
2898 match p, c with
2899 | _, Data (Variable c) -> raise No_clause
2900 | Data p, Data (Constant c) ->
2901 if Environ.QConstant.equal conv_context.env (get_projection_constant conv_context.env (Projection.repr p)) c then ?: None +? None +! Names.Projection.(arg p + npars p) else raise No_clause
2902 | NoData, NoData -> U.type_error "coq.env.primitive-projection?: got no input data"
2903 | Data p, NoData -> ?: None +! (Constant (get_projection_constant conv_context.env (Projection.repr p))) +! Names.Projection.(arg p + npars p)
2904 | NoData, Data (Constant c) ->
2905 (match Environ.constant_opt_value_in conv_context.env (UVars.in_punivs c) with
2906 | None -> raise No_clause
2907 | Some p ->
2908 let rec get_proj c =
2909 match Constr.kind c with
2910 | Lambda (_, _, t) -> get_proj t
2911 | App (hd, _) -> get_proj hd
2912 | Proj (p, _, _) -> p
2913 | _ -> raise No_clause
2914 in
2915 let p = get_proj p in
2916 !: p +? None +! Names.Projection.(arg p + npars p)))),
2917 DocAbove);
2918
2919 LPDoc "-- Sorts (and their universe level, if applicable) ----------------";
2920 LPDoc {|Warning: universe polymorphism has to be considered experimental *E* as
2921 a feature, not just as a set of APIs. Unfortunately some of the
2922 current complexity is exposed to the programmer, bare with us.
2923
2924 The big bang is that in Coq one has terms, types and sorts (which are
2925 the types of types). Some sorts (as of today only Type) some with
2926 a universe level, on paper Type_i for some i. At the sort level
2927 Coq features some form of subtyping: a function expecting a function
2928 to Type, e.g. nat -> Type, can receive a function to Prop, since
2929 Prop <= Type. So far, so good. But what are these levels i exactly?
2930
2931 Universe levels are said to be "algebraic", they are made of
2932 variables (see the next section) and the two operators +1 and max.
2933 This is a sort of internal optimization that leaks to the
2934 user/programmer. Indeed these universe levels cannot be (directly) used
2935 in all APIs morally expecting a universe level "i", in particular
2936 the current constraint engine cannot handle constraint with an
2937 algebraic level on the right, e.g. i <= j+1. Since some APIs only
2938 accept universe variables, we provide the coq.univ.variable API
2939 which is able to craft a universe variable which is roughly
2940 equivalent to an algebraic universe, e.g. k such that j+1 = k.
2941
2942 Rocq-Elpi systematically purges algebraic universes from terms (and
2943 types and sorts) when one reads them from the environment. This
2944 makes the embedding of terms less precise than what it could be.
2945 The different data types stay, since Coq will eventually become
2946 able to handle algebraic universes consistently, making this purging
2947 phase unnecessary.|};
2948 MLData univ;
2949 MLDataC sort;
2950
2951 MLCode(Pred("coq.sort.leq",
2952 CIn(sort, "S1",
2953 CIn(sort, "S2",
2954 Full(global, "constrains S1 <= S2"))),
2955 (fun u1 u2 ~depth { options } _ -> grab_global_env "coq.sort.leq" (fun state ->
2956 if Sorts.equal u1 u2 then Univ.ContextSet.empty, state, (),[]
2957 else
2958 let state, u2 = if true (* options.algunivs != Some true *)
2959 then purge_algebraic_univs_sort state (EConstr.ESorts.make u2)
2960 else state, u2 in
2961 Univ.ContextSet.empty, add_universe_constraint state (constraint_leq u1 u2), (),[]))),
2962 DocAbove);
2963
2964 MLCode(Pred("coq.sort.eq",
2965 CIn(sort, "S1",
2966 CIn(sort, "S2",
2967 Full(global, "constrains S1 = S2"))),
2968 (fun u1 u2 ~depth { options } _ -> grab_global_env "coq.sort.eq" (fun state ->
2969 if Sorts.equal u1 u2 then Univ.ContextSet.empty, state, (),[]
2970 else
2971 let state, u2 = if true (* options.algunivs != Some true *)
2972 then purge_algebraic_univs_sort state (EConstr.ESorts.make u2)
2973 else state, u2 in
2974 Univ.ContextSet.empty, add_universe_constraint state (constraint_eq u1 u2), (), []))),
2975 DocAbove);
2976
2977 MLCode(Pred("coq.sort.sup",
2978 CIn(sort, "S1",
2979 CIn(sort, "S2",
2980 Full(global, "constrains S2 = S1 + 1"))),
2981 (fun u1 u2 ~depth _ _ state -> univ_super state u1 u2, (), [])),
2982 DocAbove);
2983
2984 MLCode(Pred("coq.sort.pts-triple",
2985 CIn(sort, "S1",
2986 CIn(sort, "S2",
2987 CInOut(B.ioargC_flex sort, "S3",
2988 Full(global, "constrains S3 = sort of product with domain in S1 and codomain in S2")))),
2989 (fun u1 u2 u3 ~depth _ _ state ->
2990 let state, u3' = univ_product state u1 u2 in
2991 match u3 with
2992 | NoData -> state, !: u3', []
2993 | Data u3 -> add_universe_constraint state (constraint_eq u3 u3'), ?: None, [])),
2994 DocAbove);
2995
2996 MLCode(Pred("coq.univ.print",
2997 Read(unit_ctx, "prints the set of universe constraints"),
2998 (fun ~depth _ _ state ->
2999 let sigma = get_sigma state in
3000 let uc = Evd.ustate sigma in
3001 Feedback.msg_notice Pp.(str "Universe constraints: " ++ UState.pr uc);
3002 ())),
3003 DocAbove);
3004
3005 MLCode(Pred("coq.univ.new",
3006 Out(univ, "U",
3007 Full(unit_ctx, "A fresh universe.")),
3008 (fun _ ~depth _ _ state ->
3009 let state, (_,u) = new_univ_level_variable state in
3010 state, !: u, [])),
3011 DocAbove);
3012
3013 MLCode(Pred("coq.univ.alg-super",
3014 In(univ,"U",
3015 Out(univ,"V",
3016 Full(unit_ctx, "relates a univ U to its algebraic successor V, that is U+1 and not any V s.t. U < V"))),
3017 (fun u _ ~depth _ _ state ->
3018 state, !: (Univ.Universe.super u), [])),
3019 DocAbove);
3020
3021 MLCode(Pred("coq.univ.alg-max",
3022 In(univ, "U1",
3023 In(univ, "U2",
3024 Out(univ, "UMax",
3025 Full(unit_ctx, "relates univs U1 and U2 to their algebraic maximum UMax, that is max(U1, U2)")))),
3026 (fun u1 u2 _ ~depth _ _ state ->
3027 state, !: (Univ.Universe.sup u1 u2), [])),
3028 DocAbove);
3029
3030 MLCode(Pred("coq.univ",
3031 InOut(B.ioarg id, "Name",
3032 InOut(B.ioarg univ, "U",
3033 Read(unit_ctx, "Finds a named unvierse. Can fail."))),
3034 (fun nl u ~depth _ _ state ->
3035 match nl, u with
3036 | Data nl, _ ->
3037 begin try ?: None +! (Univ.Universe.make @@ Evd.universe_of_name (get_sigma state) (Id.of_string_soft nl))
3038 with Not_found -> raise No_clause end
3039 | _, Data u ->
3040 begin match Univ.Universe.level u with
3041 | None -> raise Not_found
3042 | Some u ->
3043 let l = Id.Map.bindings @@ snd @@ Evd.universe_binders (get_sigma state) in
3044 begin try !: (Id.to_string @@ fst @@ List.find (fun (_,u') -> Univ.Level.equal u u') l) +? None
3045 with Not_found -> raise No_clause end end
3046 | NoData, NoData -> err Pp.(str "coq.univ: both argument were omitted"))),
3047 DocAbove);
3048
3049 MLCode(Pred("coq.univ.global?",
3050 In(univ, "U",
3051 Easy "succeeds if U is a global universe"),
3052 (fun u ~depth ->
3053 let env = Global.env () in
3054 match Univ.Universe.level u with
3055 | Some l when is_global_level env l -> ()
3056 | _ -> raise No_clause (* err Pp.(Univ.Universe.pr u ++ str " is not global") *)
3057 )),
3058 DocAbove);
3059
3060 MLCode(Pred("coq.univ.constraints",
3061 Out(B.list universe_constraint, "CL",
3062 Full(unit_ctx, "gives the list of constraints, see also coq.univ.variable.constraints")),
3063 (fun _ ~depth _ _ state ->
3064 let sigma = get_sigma state in
3065 let ustate = Evd.ustate sigma in
3066 let constraints = univs_of_csts ustate in
3067 state, !: (univ_csts_to_list constraints), []
3068 )),
3069 DocAbove);
3070
3071 LPDoc "-- Universe variables ------";
3072
3073 MLData universe_level_variable;
3074
3075 MLCode(Pred("coq.univ.variable",
3076 InOut(B.ioarg univ,"U",
3077 InOut(B.ioarg universe_level_variable,"L",
3078 Full(unit_ctx, "relates a univ.variable L to a univ U"))),
3079 (fun u l ~depth _ _ state ->
3080 match u, l with
3081 | Data u, NoData ->
3082 let state, l, _, _ = force_level_of_universe state u in
3083 state, ?: None +! l, []
3084 | NoData, Data l ->
3085 state, !: (Univ.Universe.make l) +? None, []
3086 | NoData, NoData ->
3087 let state, (l,u) = new_univ_level_variable state in
3088 state, !: u +! l, []
3089 | Data u, Data l ->
3090 let w = Sorts.sort_of_univ (Univ.Universe.make l) in
3091 let state = add_universe_constraint state (constraint_leq (Sorts.sort_of_univ u) w) in
3092 state, ?: None +? None, [])),
3093 DocAbove);
3094
3095 MLCode(Pred("coq.univ.variable.constraints",
3096 In(universe_level_variable, "L",
3097 Out(B.list universe_constraint, "CL",
3098 Full(unit_ctx, "gives the list of constraints on L. Can be used to craft a strict upoly-decl"))),
3099 (fun v _ ~depth _ _ state ->
3100 let sigma = get_sigma state in
3101 let ustate = Evd.ustate sigma in
3102 let constraints = univs_of_csts ustate in
3103 let v_constraints = ucsts_filter (fun (l1,_,l2) -> Univ.Level.(equal v l1 || equal v l2)) constraints in
3104 state, !: (univ_csts_to_list v_constraints), []
3105 )),
3106 DocAbove);
3107
3108 MLCode(Pred("coq.univ.variable.of-term",
3109 CIn(term,"T",
3110 Out(universe_level_set,"S",
3111 Full (proof_context,"collects all univ.variables occurring in T"))),
3112 (fun t _ ~depth coq_ctx _ state ->
3113 let s = universes_of_term state t in
3114 let s = Univ.Level.Set.fold UnivLevelSet.add s UnivLevelSet.empty in
3115 state, !: s, [])),
3116 DocAbove);
3117
3118 LPDoc "-- Universe instance (for universe polymorphic global terms) ------";
3119
3120 LPDoc {|As of today a universe polymorphic constant can only be instantiated
3121 with universe level variables. That is f@{Prop} is not valid, nor
3122 is f@{u+1}. One can only write f@{u} for any u.
3123
3124 A univ-instance is morally a list of universe level variables,
3125 but its list syntax is hidden in the terms. If you really need to
3126 craft or inspect one of these, the following APIs can help you.
3127
3128 Most of the time the user is expected to use coq.env.global which
3129 crafts a fresh, appropriate, universe instance and possibly unify that
3130 term (of the instance it contains) with another one.|};
3131
3132 MLData uinstance;
3133
3134 MLCode(Pred("coq.univ-instance",
3135 InOut(B.ioarg uinstance, "UI",
3136 InOut(B.ioarg (list B.(ioarg_poly "univ.variable")), "UL",
3137 Full(global, "relates a univ-instance UI and a list of universe level variables UL"))),
3138 (fun uinst_arg univs_arg ~depth { env ; options } _ state ->
3139 match uinst_arg, univs_arg with
3140 | Data uinst, _ ->
3141 let elpi_term_of_level state l =
3142 let state, t, gls = universe_level_variable.Conv.embed ~depth state l in
3143 assert (gls = []);
3144 state, mkData t
3145 in
3146 let quals, univs = UVars.Instance.to_array uinst in
3147 let () = if not (CArray.is_empty quals) then nYI "sort poly" in
3148 let state, univs =
3149 CArray.fold_left_map elpi_term_of_level state univs in
3150 state, ?: None +! Array.to_list univs, []
3151 | NoData, Data univs ->
3152 let readback_or_new state = function
3153 | NoData -> let state, (l,_) = new_univ_level_variable state in state, l, []
3154 | Data t -> universe_level_variable.Conv.readback ~depth state t in
3155 let state, levels, gls = U.map_acc readback_or_new state univs in
3156 state, !: (UVars.Instance.of_array ([||], Array.of_list levels)) +? None, gls
3157 | NoData, NoData ->
3158 err (Pp.str "coq.univ-instance called with no input argument")
3159 )),
3160 DocAbove);
3161
3162 MLCode(Pred("coq.univ-instance.unify-eq",
3163 In(gref, "GR",
3164 In(uinstance, "UI1",
3165 In(uinstance, "UI2",
3166 InOut(B.ioarg B.diagnostic, "Diagnostic",
3167 Full(global, "unifies the two universe instances for the same gref"))))),
3168 (fun gr ui1 ui2 diag ~depth { env } _ state ->
3169 unify_instances_gref gr ui1 ui2 diag env state EConstr.eq_constr_universes)),
3170 DocAbove);
3171
3172 MLCode(Pred("coq.univ-instance.unify-leq",
3173 In(gref, "GR",
3174 In(uinstance, "UI1",
3175 In(uinstance, "UI2",
3176 InOut(B.ioarg B.diagnostic, "Diagnostic",
3177 Full(global, "unifies the two universe instances for the same gref. Note: if the GR is not *cumulative* (see Cumulative or #[universes(cumulative)]) then this API imposes an equality constraint."))))),
3178 (fun gr ui1 ui2 diag ~depth { env } _ state ->
3179 unify_instances_gref gr ui1 ui2 diag env state EConstr.leq_constr_universes)),
3180 DocAbove);
3181
3182 LPDoc "-- Declaration of universe polymorphic global terms -----------";
3183
3184 LPDoc {|These are the data types used to declare how constants
3185 and inductive types should be declared (see also the @udecl! and
3186 @udecl-cumul! macros). Note that only inductive types can be
3187 declared as cumulative.|};
3188
3189 MLData universe_constraint;
3190 MLData universe_variance;
3191 MLData universe_decl;
3192
3193 LPDoc "-- Primitive --------------------------------------------------------";
3194
3195 MLData Rocq_elpi_utils.uint63;
3196 MLData Rocq_elpi_utils.float64;
3197 MLData Rocq_elpi_utils.pstring;
3198 MLData Rocq_elpi_utils.projection;
3199 MLData primitive_value;
3200
3201 MLCode(Pred("coq.uint63->int",
3202 In(Rocq_elpi_utils.uint63,"U",
3203 Out(B.int,"I",
3204 Easy "Transforms a primitive unsigned integer U into an elpi integer I. Fails if it does not fit.")),
3205 (fun u _ ~depth:_ ->
3206 if Uint63.le u (Uint63.of_int max_int) then
3207 let _, l = Uint63.to_int2 u in
3208 !: l
3209 else raise No_clause)),
3210 DocAbove);
3211
3212 MLCode(Pred("coq.int->uint63",
3213 In(B.int,"I",
3214 Out(Rocq_elpi_utils.uint63,"U",
3215 Easy "Transforms an elpi integer I into a primitive unsigned integer U. Fails if I is negative.")),
3216 (fun i _ ~depth:_ ->
3217 if i >= 0 then !: (Uint63.of_int i) else raise No_clause)),
3218 DocAbove);
3219
3220 MLCode(Pred("coq.float64->float",
3221 In(Rocq_elpi_utils.float64,"F64",
3222 Out(B.float,"F",
3223 Easy "Transforms a primitive float on 64 bits to an elpi one. Currently, it should not fail.")),
3224 (fun f _ ~depth:_ ->
3225 let s = Float64.to_hex_string f in
3226 try !: (float_of_string s)
3227 with Failure _ -> raise No_clause)),
3228 DocAbove);
3229
3230 MLCode(Pred("coq.float->float64",
3231 In(B.float,"F",
3232 Out(Rocq_elpi_utils.float64,"F64",
3233 Easy "Transforms an elpi float F to a primitive float on 64 bits. Currently, it should not fail.")),
3234 (fun f _ ~depth:_ ->
3235 !: (Float64.of_float f))),
3236 DocAbove);
3237
3238 MLCode(Pred("coq.primitive.projection-unfolded",
3239 InOut(B.ioarg projection,"P",
3240 InOut(B.ioarg projection,"PU",
3241 Read(global, "Relates a primitive projection P to its unfolded version PU. PU is still a primitive projection, but it is displayed as a match and some Ltac code can see that."))),
3242 (fun p q ~depth:_ conv_context _ _ ->
3243 let test_folded = function Data x -> if Projection.unfolded x then raise No_clause | _ -> () in
3244 let test_unfolded = function Data x -> if not (Projection.unfolded x) then raise No_clause | _ -> () in
3245 test_folded p;
3246 test_unfolded q;
3247 match p, q with
3248 | Data p, Data q ->
3249 if Environ.QProjection.Repr.equal conv_context.env (Projection.repr p) (Projection.repr q) then ?: None +? None else raise No_clause
3250 | NoData, NoData -> U.type_error "coq.projection.unfolded: got no input data"
3251 | Data p, NoData -> ?: None +! Projection.(make (repr p) true)
3252 | NoData, Data q -> !: Projection.(make (repr q) false) +? None
3253 )),
3254 DocAbove);
3255
3256 MLCode(Pred("coq.pstring->string",
3257 In(Rocq_elpi_utils.pstring,"PS",
3258 Out(B.string,"S",
3259 Easy "Transforms a Coq primitive string to an elpi string. It does not fail.")),
3260 (fun s _ ~depth:_ -> !: (string_of_pstring s))),
3261 DocAbove);
3262
3263 MLCode(Pred("coq.string->pstring",
3264 In(B.string,"S",
3265 Out(Rocq_elpi_utils.pstring,"PS",
3266 Easy "Transforms an elpi string into a Coq primitive string. It fails if the lenght of S is greater than the maximal primitive string length.")),
3267 (fun s _ ~depth:_ ->
3268 match pstring_of_string s with
3269 | Some s -> !: s
3270 | None -> raise No_clause)),
3271 DocAbove);
3272
3273 LPCode {|
3274 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3275 % API for extra logical objects
3276 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|};
3277
3278 LPDoc "-- Databases (TC, CS, Coercions) ------------------------------------";
3279
3280 MLDataC cs_pattern;
3281 MLDataC cs_instance;
3282
3283 MLCode(Pred("coq.CS.declare-instance",
3284 In(gref, "GR",
3285 Full(global, {|Declares GR as a canonical structure instance.
3286 Supported attributes:
3287 - @local! (default: false)|})),
3288 (fun gr ~depth { options } _ -> grab_global_env "coq.CS.declare-instance" (fun state ->
3289 Canonical.declare_canonical_structure ?local:options.local gr;
3290 Univ.ContextSet.empty, state, (), []))),
3291 DocAbove);
3292
3293 MLCode(Pred("coq.CS.db",
3294 COut(CConv.(!>>) list cs_instance, "Db",
3295 Read(global,"reads all instances")),
3296 (fun _ ~depth _ _ _ ->
3297 !: (Structures.CSTable.(entries ())))),
3298 DocAbove);
3299
3300 MLCode(Pred("coq.CS.db-for",
3301 In(B.unspec gref, "Proj",
3302 CIn(B.unspecC cs_pattern, "Value",
3303 COut(CConv.(!>>) list cs_instance, "Db",
3304 Read(global,"reads all instances for a given Projection or canonical Value, or both")))),
3305 (fun proj value _ ~depth _ _ state ->
3306 let env = get_global_env state in
3307 let sigma = get_sigma state in
3308 let open Structures in
3309 (* This comes from recordops, it should be exported *)
3310 match proj, value with
3311 | B.Unspec, B.Unspec -> !: (CSTable.entries ())
3312 | B.Given p, B.Unspec ->
3313 !: (cs_entries_for_proj env p)
3314 | B.Unspec, B.Given v ->
3315 !: (CSTable.entries () |> List.filter (fun { CSTable.value = v1 } -> ValuePattern.equal env v v1))
3316 | B.Given p, B.Given v ->
3317 try
3318 let _, { CanonicalSolution.constant } = CanonicalSolution.find env sigma (p,v) in
3319 !: [{ CSTable.projection = p; value = v; solution = fst @@ EConstr.destRef sigma constant }]
3320 with Not_found -> !: [])),
3321 DocAbove);
3322
3323 MLCode(Pred("coq.CS.canonical-projection?",
3324 In(constant, "Projection",
3325 Read (global, "Tells if the projection can be used for CS inference.")),
3326 (fun c ~depth _ _ state ->
3327 let env = get_global_env state in
3328 match c with
3329 | Variable _ -> raise No_clause
3330 | Constant c ->
3331 try
3332 (* TODO: this can be optimized with ad-hoc API in rocq *)
3333 (* here we look twice for env to get some partial information from c *)
3334 (* we could have: Structures.Structure.is_canon_proj : Names.Constant.t -> bool *)
3335 let s = (find_structure_from_projection env c) in
3336 let n = Structures.Structure.projection_number env c in
3337 if (List.nth s.projections n).proj_canonical then ()
3338 else raise No_clause
3339 with Not_found -> raise No_clause)),
3340 DocAbove);
3341
3342 MLCode(Pred("coq.TC.declare-class",
3343 In(gref, "GR",
3344 Full(global, {|Declare GR as a type class|})),
3345 (fun gr ~depth { options } _ -> grab_global_env "coq.TC.declare-class" (fun state ->
3346 (* CAVEAT: declare_existing_class creates the new class but methods are not added *)
3347 Record.declare_existing_class gr;
3348 Univ.ContextSet.empty, state, (), []))),
3349 DocAbove);
3350
3351 MLCode(Pred("coq.elpi.toposort",
3352 In(B.list (pair (B.poly "A") (B.list (B.poly "A"))), "Graph",
3353 Out(B.list (B.poly "A"), "Nodes in toposort order",
3354 Read(global,"takes a graph and returns the nodes in topological order"))),
3355 (fun graph _ ~depth { options } _ _ ->
3356 let graph = Rocq_elpi_graph.Graph.build graph in
3357 let topo_sort = Rocq_elpi_graph.Graph.topo_sort graph in
3358 (* Rocq_elpi_graph.Graph.print string_of_int graph; *)
3359 !: topo_sort)),
3360 DocAbove);
3361
3362 MLData tc_instance;
3363
3364 MLCode(Pred("coq.TC.declare-instance",
3365 In(gref, "GR",
3366 In(int, "Priority",
3367 Full(global, {|Declare GR as a Global type class instance with Priority.
3368 Supported attributes:
3369 - @global! (default: true)|}))),
3370 (fun gr priority ~depth { options } _ -> grab_global_env "coq.TC.declare-instance" (fun state ->
3371 let global = hint_locality options in
3372 let hint_priority = Some priority in
3373 Classes.existing_instance global gr
3374 (Some { Hints.empty_hint_info with Typeclasses.hint_priority });
3375 Univ.ContextSet.empty, state, (), []))),
3376 DocAbove);
3377
3378 MLCode(Pred("coq.TC.db",
3379 Out(list tc_instance, "Instances",
3380 Read(global, "reads all type class instances")),
3381 (fun _ ~depth { env } _ state ->
3382 let sigma = get_sigma state in
3383 let x = Typeclasses.typeclasses () in
3384 let classes = List.map (fun x -> x.Typeclasses.cl_impl) x in
3385 !: (classes |> List.map (get_instances env sigma) |> List.concat))),
3386 DocAbove);
3387
3388 MLCode(Pred("coq.TC.db-tc",
3389 Out(list gref, "TypeClasses",
3390 Easy "reads all type classes"),
3391 (fun _ ~depth -> !: (
3392 let x = Typeclasses.typeclasses () in
3393 let l = List.map (fun x -> x.Typeclasses.cl_impl) x in
3394 l))),
3395 DocAbove);
3396
3397 MLCode(Pred("coq.TC.db-for",
3398 In(gref, "GR",
3399 Out(list tc_instance, "InstanceList",
3400 Read (global, "reads all instances of the given class GR. Instances are in their precedence order."))),
3401 (fun gr _ ~depth { env } _ state -> !: (get_instances env (get_sigma state) gr))),
3402 DocAbove);
3403
3404 MLCode(Pred("coq.TC.get-inst-prio",
3405 In(gref, "ClassGR",
3406 In(gref, "InstGR",
3407 Out(int, "InstPrio",
3408 Read (global, "reads the priority of an instance")))),
3409 (fun class_gr inst_gr _ ~depth { env } _ state ->
3410 !: (get_instance_prio env class_gr inst_gr))),
3411 DocAbove);
3412
3413 MLCode(Pred("coq.TC.class?",
3414 In(gref, "GR",
3415 Read (global, "checks if GR is a class")),
3416 (fun gr ~depth { env } _ _ ->
3417 if tc_is_class env gr then () else raise Pred.No_clause)),
3418 DocAbove);
3419
3420 MLData class_;
3421 MLData coercion;
3422
3423 MLCode(Pred("coq.coercion.declare",
3424 In(coercion, "C",
3425 Full (global,{|Declares C = (coercion GR NParams From To) as a coercion From >-> To.
3426 NParams can always be omitted, since it is inferred.
3427 |}^ (* , but if passed it will be checked to be the correct value. TODO needs https://github.com/coq/coq/pull/13902 Coq 8.14 *)
3428 {|If From or To is unspecified, then the endpoints are inferred.
3429 |}^ (* , but if one of the two it is passed it will be checked to be the correct value. TODO needs https://github.com/coq/coq/pull/13902 Coq 8.14 *)
3430 {|Supported attributes:
3431 - @global! (default: false)
3432 - @nonuniform! (default: false)
3433 - @reversible! (default: false)|})),
3434 (fun (gr, _, source, target) ~depth { options } _ -> grab_global_env "coq.coercion.declare" (fun state ->
3435 let local = options.local <> Some false in
3436 let reversible = options.reversible = Some true in
3437 begin match source, target with
3438 | B.Given source, B.Given target ->
3439 let source = ComCoercion.class_of_global source in
3440 ComCoercion.try_add_new_coercion_with_target gr ~local
3441 ~reversible ~source ~target
3442 | _, _ ->
3443 ComCoercion.try_add_new_coercion gr ~local ~reversible
3444 end;
3445 Univ.ContextSet.empty, state, (), []))),
3446 DocAbove);
3447
3448 MLCode(Pred("coq.coercion.db",
3449 Out(list coercion, "L",
3450 Read (global, "reads all declared coercions")),
3451 (fun _ ~depth { env } _ _ ->
3452 (* TODO: fix API in Coq *)
3453 let pats = Coercionops.inheritance_graph () in
3454 let coercions = pats |> CList.map_filter (function
3455 | (source,target),[c] ->
3456 Some(c.Coercionops.coe_value,
3457 B.Given c.Coercionops.coe_param,
3458 B.Given (src_class_of_class env source),
3459 B.Given target)
3460 | _ -> None) in
3461 !: coercions)),
3462 DocAbove);
3463
3464 MLCode(Pred("coq.coercion.db-for",
3465 In(class_,"From",
3466 In(class_,"To",
3467 Out(list (pair gref int), "L",
3468 Easy ("L is a path From -> To")))),
3469 (fun source target _ ~depth ->
3470 try
3471 let path = Coercionops.lookup_path_between_class (source,target) in
3472 let coercions = path |> List.map (fun c ->
3473 c.Coercionops.coe_value, c.Coercionops.coe_param) in
3474 !: coercions
3475 with Not_found -> !: [])),
3476 DocAbove);
3477
3478 LPCode {|% Deprecated, use coq.env.projections
3479 pred coq.CS.canonical-projections i:inductive, o:list (option constant).
3480 coq.CS.canonical-projections I L :-
3481 coq.warning "elpi.deprecated" "elpi.canonical-projections" "use coq.env.projections in place of coq.CS.canonical-projections",
3482 coq.env.projections I L.
3483 |};
3484
3485 LPDoc "-- Coq's Hint DB -------------------------------------";
3486 LPDoc {|Locality of hints is a delicate matter since the Coq default
3487 is, in some cases, to make an hint active even if the module it belongs
3488 to is not imported (just merely required, which can happen transitively).
3489 Coq is aiming at changing the default to #[export], that makes an
3490 hint active only when its enclosing module is imported. See:
3491 https://coq.discourse.group/t/change-of-default-locality-for-hint-commands-in-coq-8-13/1140
3492
3493 This old behavior is available via the @global! flag, but is discouraged.
3494 |};
3495
3496 MLData mode;
3497
3498 MLCode(Pred("coq.hints.add-mode",
3499 In(gref, "GR",
3500 In(hint_db, "DB",
3501 In(B.list mode, "Mode",
3502 Full(global, {|Adds a mode declaration to DB about GR.
3503 Supported attributes:|} ^ hint_locality_doc)))),
3504 (fun gr (db,_) mode ~depth:_ {options} _ -> grab_global_env "coq.hints.add-mode" (fun state ->
3505 let locality = hint_locality options in
3506 Hints.add_hints ~locality [db] (Hints.HintsModeEntry(gr,mode));
3507 Univ.ContextSet.empty, state, (), []
3508 ))),
3509 DocAbove);
3510
3511 MLCode(Pred("coq.hints.modes",
3512 In(gref, "GR",
3513 In(hint_db, "DB",
3514 Out(B.list (B.list mode), "Modes",
3515 Read(global, {|Gets all the mode declarations in DB about GR|})))),
3516 (fun gr (_,db) _ ~depth:_ { env } _ _ ->
3517 try !: (hint_mode env gr db)
3518 with Not_found ->
3519 !: []
3520 )),
3521 DocAbove);
3522
3523 MLCode(Pred("coq.hints.set-opaque",
3524 In(constant, "C",
3525 In(hint_db, "DB",
3526 In(B.bool, "Opaque",
3527 Full(global,{|Like Hint Opaque C : DB (or Hint Transparent, if the boolean is ff).
3528 Supported attributes:|} ^ hint_locality_doc)))),
3529 (fun c (db,_) opaque ~depth:_ {options} _ -> grab_global_env "coq.hints.set-opaque" (fun state ->
3530 let locality = hint_locality options in
3531 let transparent = not opaque in
3532 let r = eval_of_constant c in
3533 Hints.add_hints ~locality [db] Hints.(HintsTransparencyEntry(HintsReferences [r],transparent));
3534 Univ.ContextSet.empty, state, (), []
3535 ))),
3536 DocAbove);
3537
3538 MLCode(Pred("coq.hints.opaque",
3539 In(constant, "C",
3540 In(hint_db, "DB",
3541 Out(B.bool, "Opaque",
3542 Easy {|Reads if constant C is opaque (tt) or transparent (ff) in DB|}))),
3543 (fun c (_,db) _ ~depth:_ ->
3544 let tr = Hints.Hint_db.transparent_state db in
3545 match c with
3546 | Variable v -> !: (not @@ TransparentState.is_transparent_variable tr v)
3547 | Constant c -> !: (not @@ TransparentState.is_transparent_constant tr c))),
3548 DocAbove);
3549
3550 MLCode(Pred("coq.hints.add-resolve",
3551 In(gref, "GR",
3552 In(hint_db, "DB",
3553 In(B.unspec B.int, "Priority",
3554 CIn(B.unspecC closed_term, "Pattern",
3555 Full(global,{|Like Hint Resolve GR | Priority Pattern : DB.
3556 Supported attributes:|} ^ hint_locality_doc))))),
3557 (fun gr (db,_) priority pattern ~depth:_ {env;options} _ -> grab_global_env "coq.hints.add-resolve" (fun state ->
3558 let locality = hint_locality options in
3559 let hint_priority = unspec2opt priority in
3560 let sigma = get_sigma state in
3561 let hint_pattern = unspec2opt pattern |> Option.map (Rocq_elpi_utils.detype_to_pattern env sigma) in
3562 let info = { Typeclasses.hint_priority; hint_pattern } in
3563 Hints.add_hints ~locality [db] Hints.(Hints.HintsResolveEntry[info, true, hint_globref gr]);
3564 Univ.ContextSet.empty, state, (), []
3565 ))),
3566 DocAbove);
3567
3568
3569 LPDoc "-- Coq's notational mechanisms -------------------------------------";
3570
3571 MLData implicit_kind;
3572
3573 MLCode(Pred("coq.arguments.implicit",
3574 In(gref,"GR",
3575 Out(list (list implicit_kind),"Imps",
3576 Easy "reads the implicit arguments declarations associated to a global reference. See also the [] and {} flags for the Arguments command.")),
3577 (fun gref _ ~depth ->
3578 !: (List.map (fun (_,x) -> List.map implicit_kind_of_status x)
3579 (Impargs.extract_impargs_data (Impargs.implicits_of_global gref))))),
3580 DocAbove);
3581
3582 MLCode(Pred("coq.arguments.set-implicit",
3583 In(gref,"GR",
3584 In(list (list (B.unspec implicit_kind)),"Imps",
3585 Full(global,
3586 {|sets the implicit arguments declarations associated to a global reference.
3587 Unspecified means explicit.
3588 See also the [] and {} flags for the Arguments command.
3589 Supported attributes:
3590 - @global! (default: false)|}))),
3591 (fun gref imps ~depth {options} _ -> grab_global_env "coq.arguments.set-implicit" (fun state ->
3592 let local = options.local <> Some false in
3593 let imps = imps |> List.(map (map (function
3594 | B.Unspec -> Anonymous, Glob_term.Explicit
3595 | B.Given x -> Anonymous, x))) in
3596 Impargs.set_implicits local gref imps;
3597 Univ.ContextSet.empty, state, (), []))),
3598 DocAbove);
3599
3600 MLCode(Pred("coq.arguments.set-default-implicit",
3601 In(gref,"GR",
3602 Full(global,
3603 {|sets the default implicit arguments declarations associated to a global reference.
3604 See also the "default implicits" flag to the Arguments command.
3605 Supported attributes:
3606 - @global! (default: false)|})),
3607 (fun gref ~depth { options } _ -> grab_global_env "coq.arguments.set-default-implicit" (fun state ->
3608 let local = options.local <> Some false in
3609 Impargs.declare_implicits local gref;
3610 Univ.ContextSet.empty, state, (), []))),
3611 DocAbove);
3612
3613 MLCode(Pred("coq.arguments.name",
3614 In(gref,"GR",
3615 Out(list (option id),"Names",
3616 Read (global, "reads the Names of the arguments of a global reference. See also the (f (A := v)) syntax."))),
3617 (fun gref _ ~depth { env } _ _ ->
3618 let open Name in
3619 !: (try arguments_names env gref
3620 |> List.map (function Name x -> Some (Id.to_string x) | _ -> None)
3621 with Not_found -> []))),
3622 DocAbove);
3623
3624 MLCode(Pred("coq.arguments.set-name",
3625 In(gref,"GR",
3626 In(list (option id),"Names",
3627 Full(global,
3628 {|sets the Names of the arguments of a global reference.
3629 See also the :rename flag to the Arguments command.
3630 Supported attributes:
3631 - @global! (default: false)|}))),
3632 (fun gref names ~depth { options } _ -> grab_global_env "coq.arguments.set-name" (fun state ->
3633 let local = options.local <> Some false in
3634 let names = names |> List.map (function
3635 | None -> Names.Name.Anonymous
3636 | Some x -> Names.(Name.Name (Id.of_string x))) in
3637 Arguments_renaming.rename_arguments local gref names;
3638 Univ.ContextSet.empty, state, (), []))),
3639 DocAbove);
3640
3641 MLCode(Pred("coq.arguments.scope",
3642 In(gref,"GR",
3643 Out(list (list id),"Scopes",
3644 Read (global, "reads the notation scope of the arguments of a global reference. See also the %scope modifier for the Arguments command"))),
3645 (fun gref _ ~depth { env } _ _ -> !: (find_arguments_scope env gref))),
3646 DocAbove);
3647
3648 MLCode(Pred("coq.arguments.set-scope",
3649 In(gref,"GR",
3650 In(list (list id),"Scopes",
3651 Full(global,
3652 {|sets the notation scope of the arguments of a global reference.
3653 Scope can be a scope name or its delimiter.
3654 See also the %scope modifier for the Arguments command.
3655 Supported attributes:
3656 - @global! (default: false)|}))),
3657 (fun gref scopes ~depth { options } _ -> grab_global_env "coq.arguments.set-scope" (fun state ->
3658 let local = options.local <> Some false in
3659 let scopes = scopes |> List.map (List.map (fun k ->
3660 try ignore (CNotation.find_scope k); k
3661 with CErrors.UserError _ -> CNotation.find_delimiters_scope k)) in
3662 CNotation.declare_arguments_scope local gref scopes;
3663 Univ.ContextSet.empty, state, (), []))),
3664 DocAbove);
3665
3666 MLData simplification_strategy;
3667
3668 MLCode(Pred("coq.arguments.simplification",
3669 In(gref,"GR",
3670 Out(option simplification_strategy,"Strategy",
3671 Easy "reads the behavior of the simplification tactics. Positions are 0 based. See also the ! and / modifiers for the Arguments command")),
3672 (fun gref _ ~depth ->
3673 let flags = match gref with
3674 | ConstRef c -> Reductionops.ReductionBehaviour.get c
3675 | _ -> None
3676 in
3677 !: flags)),
3678 DocAbove);
3679
3680 MLCode(Pred("coq.arguments.set-simplification",
3681 In(gref,"GR",
3682 In(simplification_strategy, "Strategy",
3683 Full(global,
3684 {|sets the behavior of the simplification tactics.
3685 Positions are 0 based.
3686 See also the ! and / modifiers for the Arguments command.
3687 Supported attributes:
3688 - @global! (default: false)|}))),
3689 (fun gref strategy ~depth { options } _ -> grab_global_env "coq.arguments.set-simplification" (fun state ->
3690 match gref with
3691 | ConstRef gref ->
3692 let local = options.local <> Some false in
3693 compat_reduction_behavior_set ~local gref strategy;
3694 Univ.ContextSet.empty, state, (), []
3695 | _ -> err Pp.(str "set-simplification must be called on constant")))),
3696 DocAbove)
3697
3698 ] @ compat_reset_simplification @ [
3699
3700 MLCode(Pred("coq.locate-abbreviation",
3701 In(id, "Name",
3702 Out(abbreviation, "Abbreviation",
3703 Easy "locates an abbreviation. It's a fatal error if Name cannot be located.")),
3704 (fun s _ ~depth ->
3705 let qualid = Libnames.qualid_of_string s in
3706 let sd =
3707 try Nametab.locate_abbreviation qualid
3708 with Not_found -> err Pp.(str "Abbreviation not found: " ++ Libnames.pr_qualid qualid) in
3709 !:sd)),
3710 DocAbove);
3711
3712 MLData abbreviation;
3713
3714 MLCode(Pred("coq.notation.add-abbreviation",
3715 In(id,"Name",
3716 In(int,"Nargs",
3717 CIn(closed_term,"Body",
3718 In(flag "bool","OnlyParsing",
3719 Out(abbreviation, "Abbreviation",
3720 Full(global, {|Declares an abbreviation Name with Nargs arguments.
3721 The term must begin with at least Nargs "fun" nodes whose domain is ignored, eg (fun _ _ x\ fun _ _ y\ app[global "add",x,y]).
3722 Supported attributes:
3723 - @deprecated! (default: not deprecated)
3724 - @warn! (default: no warning)
3725 - @global! (default: false)|})))))),
3726 (fun name nargs term onlyparsing _ ~depth { env; options } _ -> grab_global_env "coq.notation.add-abbreviation" (fun state ->
3727 let sigma = get_sigma state in
3728 let strip_n_lambas nargs env term =
3729 let rec aux vars nenv env n t =
3730 if n = 0 then List.rev vars, nenv, env, t
3731 else match EConstr.kind sigma t with
3732 | Constr.Lambda(name,ty,t) ->
3733 let name, id =
3734 match name with
3735 | { Context.binder_name = Names.Name.Name id; _ } ->
3736 let id = Id.of_string_soft (Printf.sprintf "_elpi_ctx_entry_%d_was_%s_" n (Id.to_string id)) in
3737 { name with Context.binder_name = Names.Name.Name id }, id
3738 | _ ->
3739 let id = Id.of_string_soft (Printf.sprintf "_elpi_ctx_entry_%d_" n) in
3740 { name with Context.binder_name = Names.Name.Name id }, id
3741 in
3742 let nenv, vars =
3743 { nenv with Notation_term.ninterp_var_type =
3744 Id.Map.add id (Notation_term.NtnInternTypeAny None)
3745 nenv.Notation_term.ninterp_var_type },
3746 (id, ((Notation_ops.constr_some_level,([],[])),Id.Set.empty,Notation_term.NtnTypeConstr)) :: vars in
3747 let env = EConstr.push_rel (Context.Rel.Declaration.LocalAssum(name,ty)) env in
3748 aux vars nenv env (n-1) t
3749 | _ ->
3750 U.type_error
3751 (Printf.sprintf "coq.notation.add-abbreviation: term with %d more lambdas expected" n)
3752 in
3753 let vars = [] in
3754 let nenv =
3755 {
3756 Notation_term.ninterp_var_type = Id.Map.empty;
3757 ninterp_rec_vars = Id.Map.empty;
3758 } in
3759 aux vars nenv env nargs term
3760 in
3761 let local = locality_of_options options in
3762 let onlyparsing = (onlyparsing = B.Given true) in
3763 let name = Id.of_string name in
3764 let vars, nenv, env, body = strip_n_lambas nargs env term in
3765 let gbody = Rocq_elpi_utils.detype env sigma body in
3766 let pat, _ = Notation_ops.notation_constr_of_glob_constr nenv gbody in
3767 let warns = warns_of_options options in
3768 abbreviation_declare ~local ~onlyparsing warns name (vars,pat);
3769 let loc = to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state in
3770 Dumpglob.dump_definition (CAst.make ~loc name) false "abbrev";
3771 let qname = Libnames.qualid_of_string (Id.to_string name) in
3772 match Nametab.locate_extended qname with
3773 | Globnames.TrueGlobal _ -> assert false
3774 | Globnames.Abbrev sd -> Univ.ContextSet.empty, state, !: sd, []))),
3775 DocAbove);
3776
3777 MLCode(Pred("coq.notation.abbreviation",
3778 In(abbreviation,"Abbreviation",
3779 In(B.list (B.poly "term"),"Args",
3780 Out(B.poly "term","Body",
3781 Full(global, "Unfolds an abbreviation")))),
3782 (fun sd arglist _ ~depth {env} _ state ->
3783 let args, _ = abbreviation_find_interp sd in
3784 let nargs = List.length args in
3785 let argno = List.length arglist in
3786 if nargs > argno then
3787 err Pp.(str"coq.notation.abbreviation: abbreviation " ++
3788 Names.Label.print (Names.KerName.label sd) ++ str " expects " ++
3789 int nargs ++ str " arguments but was given " ++ int argno);
3790 let open Constrexpr in
3791 let binders, vars = List.split (CList.init nargs (fun i ->
3792 let name = Rocq_elpi_glob_quotation.mk_restricted_name i in
3793 let lname = CAst.make @@ Name.Name (Id.of_string name) in
3794 mkCLocalAssum [lname] (Default Glob_term.Explicit) (CAst.make @@ CHole(None)),
3795 (CAst.make @@ CRef(Libnames.qualid_of_string name,None), None))) in
3796 let eta = CAst.(make @@ CLambdaN(binders,make @@ CApp(make @@ CRef(Libnames.qualid_of_string (KerName.to_string sd),None),vars))) in
3797 let sigma = get_sigma state in
3798 let geta = Constrintern.intern_constr env sigma eta in
3799 let base = Option.get @@ State.get base state in
3800 let loc = to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state in
3801 let teta = Rocq_elpi_glob_quotation.runtime_gterm2lp ~loc ~base ~depth geta state in
3802 let t =
3803 let rec aux ~depth n t =
3804 if n = 0 then t
3805 else match Rocq_elpi_HOAS.is_lam ~depth t with
3806 | Some(_,bo) -> E.mkLam (aux ~depth:(depth+1) (n-1) bo)
3807 | None -> CErrors.anomaly Pp.(str"coq.notation.abbreviation")
3808 in
3809 aux ~depth nargs teta in
3810 state, !: (U.beta ~depth t arglist), []
3811 )),
3812 DocAbove);
3813
3814 MLCode(Pred("coq.notation.abbreviation-body",
3815 In(abbreviation,"Abbreviation",
3816 Out(B.int,"Nargs",
3817 Out(B.poly "term","Body",
3818 Full(global, "Retrieves the body of an abbreviation")))),
3819 (fun sd _ _ ~depth {env} _ state ->
3820 let args, _ = abbreviation_find_interp sd in
3821 let nargs = List.length args in
3822 let open Constrexpr in
3823 let binders, vars = List.split (CList.init nargs (fun i ->
3824 let name = Rocq_elpi_glob_quotation.mk_restricted_name i in
3825 let lname = CAst.make @@ Name.Name (Id.of_string name) in
3826 mkCLocalAssum [lname] (Default Glob_term.Explicit) (CAst.make @@ CHole(None)),
3827 (CAst.make @@ CRef(Libnames.qualid_of_string name,None), None))) in
3828 let eta = CAst.(make @@ CLambdaN(binders,make @@ CApp(make @@ CRef(Libnames.qualid_of_string (KerName.to_string sd),None),vars))) in
3829 let sigma = get_sigma state in
3830 let geta = Constrintern.intern_constr env sigma eta in
3831 let base = Option.get @@ State.get base state in
3832 let loc = to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state in
3833 let teta = Rocq_elpi_glob_quotation.runtime_gterm2lp ~loc ~base ~depth geta state in
3834 state, !: nargs +! teta, []
3835 )),
3836 DocAbove);
3837
3838 MLCode(Pred("coq.notation.add-abbreviation-for-tactic",
3839 In(B.string,"Name",
3840 In(B.string,"TacticName",
3841 CIn(CConv.(!>>) B.list tactic_arg,"FixedArgs",
3842 Full(proof_context, {|Declares a parsing rule similar to
3843 Notation Name X1..Xn := ltac:(elpi TacticName FixedArgs (X1)..(Xn))
3844 so that Name can be used in the middle of a term to invoke an
3845 elpi tactic. While FixedArgs can contain str, int, and trm all
3846 other arguments will necessarily be terms, and their number is
3847 not fixed (the user can pass as many as he likes).
3848 The tactic receives as the elpi.loc attribute the precise location
3849 at which the term is written (unlike if a regular abbreviation was
3850 declared by hand).
3851 A call to coq.notation.add-abbreviation-for-tactic TacName TacName []
3852 is equivalent to Elpi Export TacName.|})))),
3853 (fun name tacname more_args ~depth { options} _ -> grab_global_env "coq.notation.add-abbreviation-for-tactic" (fun state ->
3854 let sigma = get_sigma state in
3855 let env = get_global_env state in
3856 let tac_fixed_args = more_args |> List.map (function
3857 | Rocq_elpi_arg_HOAS.Cint n -> Rocq_elpi_arg_HOAS.Tac.Int n
3858 | Rocq_elpi_arg_HOAS.Cstr s -> Rocq_elpi_arg_HOAS.Tac.String s
3859 | Rocq_elpi_arg_HOAS.Ctrm t -> Rocq_elpi_arg_HOAS.Tac.Term (Rocq_elpi_utils.detype env sigma t,None)
3860 | Rocq_elpi_arg_HOAS.CLtac1 _ -> nYI "tactic notation with LTac1 argument") in
3861 let abbrev_name = Rocq_elpi_utils.string_split_on_char '.' name in
3862 let tac_name = Rocq_elpi_utils.string_split_on_char '.' tacname in
3863 Lib.add_leaf @@ inAbbreviationForTactic { abbrev_name; tac_name; tac_fixed_args};
3864 Univ.ContextSet.empty, state, (), []))),
3865 DocAbove);
3866
3867 MLData Rocq_elpi_builtins_synterp.attribute_value;
3868 MLData Rocq_elpi_builtins_synterp.attribute;
3869
3870 LPDoc "-- Coq's pretyper ---------------------------------------------------";
3871
3872 MLCode(Pred("coq.sigma.print",
3873 Read(raw_ctx, "Prints Coq's Evarmap and the mapping to/from Elpi's unification variables"),
3874 (fun ~depth hyps constraints state ->
3875 let state, _, _, _ = get_current_env_sigma ~depth hyps constraints state in
3876 Feedback.msg_notice Pp.(
3877 str (Format.asprintf "%a" API.RawPp.constraints constraints));
3878 Feedback.msg_notice Pp.(str (show_coq_engine ~with_univs:false state));
3879 Feedback.msg_notice Pp.(str (show_coq_elpi_engine_mapping state));
3880 ())),
3881 DocAbove);
3882
3883 MLCode(Pred("coq.typecheck",
3884 CIn(term, "T",
3885 CInOut(B.ioargC term, "Ty",
3886 InOut(B.ioarg B.diagnostic, "Diagnostic",
3887 Full (proof_context,
3888 {|typchecks a term T returning its type Ty. If Ty is provided, then
3889 the inferred type is unified (see unify-leq) with it.
3890 Universe constraints are put in the constraint store.|})))),
3891 (fun t ety diag ~depth proof_context _ state ->
3892 try
3893 let sigma = get_sigma state in
3894 let (sigma, conv_pbs) = Evd.extract_all_conv_pbs sigma in
3895 let sigma, ty = Typing.type_of proof_context.env sigma t in
3896 let sigma, r = match ety with
3897 | Data ety ->
3898 let sigma = Evarconv.unify proof_context.env sigma ~with_ho:true Conversion.CUMUL ty ety in
3899 sigma, ?: None +! B.mkOK
3900 | NoData ->
3901 let flags = Evarconv.default_flags_of TransparentState.full in
3902 let sigma = Evarconv.solve_unif_constraints_with_heuristics ~flags ~with_ho:true proof_context.env sigma in
3903 sigma, !: ty +! B.mkOK
3904 in let sigma = List.fold_left (fun sigma conv_pb -> Evd.add_conv_pb conv_pb sigma) sigma conv_pbs in
3905 let state, assignments = set_current_sigma ~depth state sigma in
3906 state, r, assignments
3907 with Pretype_errors.PretypeError (env, sigma, err) ->
3908 match diag with
3909 | Data B.OK ->
3910 (* optimization: don't print the error if caller wants OK *)
3911 raise No_clause
3912 | _ ->
3913 let error = string_of_ppcmds proof_context.options @@ Himsg.explain_pretype_error env sigma err in
3914 state, ?: None +! B.mkERROR error, [])),
3915 DocAbove);
3916
3917 MLCode(Pred("coq.typecheck-ty",
3918 CIn(term, "Ty",
3919 CInOut(B.ioargC sort, "U",
3920 InOut(B.ioarg B.diagnostic, "Diagnostic",
3921 Full (proof_context,
3922 {|typchecks a type Ty returning its universe U. If U is provided, then
3923 the inferred universe is unified (see unify-leq) with it.
3924 Universe constraints are put in the constraint store.|})))),
3925 (fun ty es diag ~depth proof_context _ state ->
3926 try
3927 let sigma = get_sigma state in
3928 let (sigma, conv_pbs) = Evd.extract_all_conv_pbs sigma in
3929 let sigma, s = Typing.sort_of proof_context.env sigma ty in
3930 let sigma, r = match es with
3931 | Data es ->
3932 let sigma = Evarconv.unify proof_context.env sigma ~with_ho:true Conversion.CUMUL (EConstr.mkSort s) (EConstr.mkSort (EConstr.ESorts.make es)) in
3933 sigma, !: es +! B.mkOK
3934 | NoData ->
3935 let flags = Evarconv.default_flags_of TransparentState.full in
3936 let sigma = Evarconv.solve_unif_constraints_with_heuristics ~flags ~with_ho:true proof_context.env sigma in
3937 sigma, !: (EConstr.ESorts.kind sigma s) +! B.mkOK
3938 in let sigma = List.fold_left (fun sigma conv_pb -> Evd.add_conv_pb conv_pb sigma) sigma conv_pbs in
3939 let state, assignments = set_current_sigma ~depth state sigma in
3940 state, r, assignments
3941 with Pretype_errors.PretypeError (env, sigma, err) ->
3942 match diag with
3943 | Data B.OK ->
3944 (* optimization: don't print the error if caller wants OK *)
3945 raise No_clause
3946 | _ ->
3947 let error = string_of_ppcmds proof_context.options @@ Himsg.explain_pretype_error env sigma err in
3948 state, ?: None +! B.mkERROR error, [])),
3949 DocAbove);
3950
3951 MLCode(Pred("coq.unify-eq",
3952 CIn(term, "A",
3953 CIn(term, "B",
3954 InOut(B.ioarg B.diagnostic, "Diagnostic",
3955 Full (proof_context, "unifies the two terms")))),
3956 (fun a b diag ~depth proof_context _ state ->
3957 let sigma = get_sigma state in
3958 try
3959 let sigma = Evarconv.unify proof_context.env sigma ~with_ho:true Conversion.CONV a b in
3960 let state, assignments = set_current_sigma ~depth state sigma in
3961 state, !: B.mkOK, assignments
3962 with Pretype_errors.PretypeError (env, sigma, err) ->
3963 match diag with
3964 | Data B.OK ->
3965 (* optimization: don't print the error if caller wants OK *)
3966 raise No_clause
3967 | _ ->
3968 let error = string_of_ppcmds proof_context.options @@ Himsg.explain_pretype_error env sigma err in
3969 state, !: (B.mkERROR error), [])),
3970 DocAbove);
3971
3972 MLCode(Pred("coq.unify-leq",
3973 CIn(term, "A",
3974 CIn(term, "B",
3975 InOut(B.ioarg B.diagnostic, "Diagnostic",
3976 Full (proof_context, "unifies the two terms (with cumulativity, if they are types)")))),
3977 (fun a b diag ~depth proof_context _ state ->
3978 let sigma = get_sigma state in
3979 try
3980 let sigma = Evarconv.unify proof_context.env sigma ~with_ho:true Conversion.CUMUL a b in
3981 let state, assignments = set_current_sigma ~depth state sigma in
3982 state, !: B.mkOK, assignments
3983 with Pretype_errors.PretypeError (env, sigma, err) ->
3984 match diag with
3985 | Data B.OK ->
3986 (* optimization: don't print the error if caller wants OK *)
3987 raise No_clause
3988 | _ ->
3989 let error = string_of_ppcmds proof_context.options @@ Himsg.explain_pretype_error env sigma err in
3990 state, !: (B.mkERROR error), [])),
3991 DocAbove);
3992
3993 MLCode(Pred("coq.elaborate-skeleton",
3994 CIn(term_skeleton, "T",
3995 CInOut(B.ioargC_flex term, "ETy",
3996 COut(term, "E",
3997 InOut(B.ioarg B.diagnostic, "Diagnostic",
3998 Full (proof_context,{|elaborates T against the expected type ETy.
3999 T is allowed to contain holes (unification variables) but these are
4000 not assigned even if the elaborated term has a term in place of the
4001 hole. Similarly universe levels present in T are disregarded.
4002 Supported attributes:
4003 - @keepunivs! (default false, do not disregard universe levels)
4004 - @no-tc! (default false, do not infer typeclasses) |}))))),
4005 (fun gt ety _ diag ~depth proof_context _ state ->
4006 let flags = if proof_context.options.no_tc = Some true then {(Pretyping.default_inference_flags false) with use_typeclasses = NoUseTC} else Pretyping.default_inference_flags false in
4007 try
4008 let sigma = get_sigma state in
4009 let ety_given, expected_type =
4010 match ety with
4011 | NoData -> `No, Pretyping.WithoutTypeConstraint
4012 | Data ety ->
4013 match EConstr.kind sigma ety with
4014 | Constr.Evar _ -> `NoUnify ety, Pretyping.WithoutTypeConstraint
4015 | _ -> `Yes, Pretyping.OfType ety
4016 in
4017 let sigma = Evd.push_future_goals sigma in
4018 let sigma, uj_val, uj_type =
4019 Pretyping.understand_tcc_ty ~flags proof_context.env sigma ~expected_type gt in
4020 let _, sigma = Evd.pop_future_goals sigma in
4021 match ety_given with
4022 | `No ->
4023 let state, assignments = set_current_sigma ~depth state sigma in
4024 state, !: uj_type +! uj_val +! B.mkOK, assignments
4025 | `Yes ->
4026 let state, assignments = set_current_sigma ~depth state sigma in
4027 state, ?: None +! uj_val +! B.mkOK, assignments
4028 | `NoUnify ety ->
4029 let sigma = Evarconv.unify proof_context.env sigma ~with_ho:true Conversion.CUMUL uj_type ety in
4030 let state, assignments = set_current_sigma ~depth state sigma in
4031 state, ?: None +! uj_val +! B.mkOK, assignments
4032 with Pretype_errors.PretypeError (env, sigma, err) ->
4033 match diag with
4034 | Data B.OK ->
4035 (* optimization: don't print the error if caller wants OK *)
4036 raise No_clause
4037 | _ ->
4038 let error = string_of_ppcmds proof_context.options @@ Himsg.explain_pretype_error env sigma err in
4039 state, ?: None +? None +! B.mkERROR error, [])),
4040 DocAbove);
4041
4042 MLCode(Pred("coq.elaborate-ty-skeleton",
4043 CIn(term_skeleton, "T",
4044 COut(sort, "U",
4045 COut(term, "E",
4046 InOut(B.ioarg B.diagnostic, "Diagnostic",
4047 Full (proof_context,{|elaborates T expecting it to be a type of sort U.
4048 T is allowed to contain holes (unification variables) but these are
4049 not assigned even if the elaborated term has a term in place of the
4050 hole. Similarly universe levels present in T are disregarded.
4051 Supported attributes:
4052 - @keepunivs! (default false, do not disregard universe levels)
4053 - @no-tc! (default false, do not infer typeclasses)|}))))),
4054 (fun gt es _ diag ~depth proof_context _ state ->
4055 try
4056 let sigma = get_sigma state in
4057 let flags = if proof_context.options.no_tc = Some true then {(Pretyping.default_inference_flags false) with use_typeclasses = NoUseTC} else Pretyping.default_inference_flags false in
4058 let expected_type = Pretyping.IsType in
4059 let sigma = Evd.push_future_goals sigma in
4060 let sigma, uj_val, uj_type =
4061 Pretyping.understand_tcc_ty ~flags proof_context.env sigma ~expected_type gt in
4062 let _, sigma = Evd.pop_future_goals sigma in
4063 let sort = EConstr.ESorts.kind sigma @@ EConstr.destSort sigma uj_type in
4064 let state, assignments = set_current_sigma ~depth state sigma in
4065 state, !: sort +! uj_val +! B.mkOK, assignments
4066 with Pretype_errors.PretypeError (env, sigma, err) ->
4067 match diag with
4068 | Data B.OK ->
4069 (* optimization: don't print the error if caller wants OK *)
4070 raise No_clause
4071 | _ ->
4072 let error = string_of_ppcmds proof_context.options @@ Himsg.explain_pretype_error env sigma err in
4073 state, ?: None +? None +! B.mkERROR error, [])),
4074 DocAbove);
4075
4076 LPDoc "-- Coq's reduction flags ------------------------------------";
4077
4078 MLData reduction_kind;
4079 MLData reduction_flags;
4080
4081 MLCode(Pred("coq.redflags.add",
4082 In(reduction_flags,"Flags",
4083 In(B.list reduction_kind,"Options",
4084 Out(reduction_flags,"NewFlags",
4085 Easy "Updates reduction Flags by adding Options"))),
4086 (fun f l _ ~depth ->
4087 let f = List.fold_left RedFlags.red_add f l in
4088 !: f)),
4089 DocAbove);
4090
4091 MLCode(Pred("coq.redflags.sub",
4092 In(reduction_flags,"Flags",
4093 In(B.list reduction_kind,"Options",
4094 Out(reduction_flags,"NewFlags",
4095 Easy "Updates reduction Flags by removing Options"))),
4096 (fun f l _ ~depth ->
4097 let f = List.fold_left RedFlags.red_sub f l in
4098 !: f)),
4099 DocAbove);
4100
4101 LPDoc "-- Coq's reduction machines ------------------------------------";
4102
4103 MLCode(Pred("coq.reduction.lazy.whd",
4104 CIn(term,"T",
4105 COut(term,"Tred",
4106 Read(proof_context, {|Puts T in weak head normal form.
4107 Supported attributes:
4108 - @redflags! (default coq.redflags.all)|}))),
4109 (fun t _ ~depth proof_context constraints state ->
4110 let sigma = get_sigma state in
4111 let flags = Option.default RedFlags.all proof_context.options.redflags in
4112 let t = Reductionops.clos_whd_flags flags proof_context.env sigma t in
4113 !: t)),
4114 DocAbove);
4115
4116 MLCode(Pred("coq.reduction.lazy.norm",
4117 CIn(term,"T",
4118 COut(term,"Tred",
4119 Read(proof_context, {|Puts T in normal form.
4120 Supported attributes:
4121 - @redflags! (default coq.redflags.all)|}))),
4122 (fun t _ ~depth proof_context constraints state ->
4123 let sigma = get_sigma state in
4124 let flags = Option.default RedFlags.all proof_context.options.redflags in
4125 let t = Reductionops.clos_norm_flags flags proof_context.env sigma t in
4126 !: t)),
4127 DocAbove);
4128
4129 MLCode(Pred("coq.reduction.lazy.bi-norm",
4130 CIn(term,"T",
4131 COut(term,"Tred",
4132 Read(proof_context, "Puts T in normal form only reducing beta and iota redexes"))),
4133 (fun t _ ~depth proof_context constraints state ->
4134 let sigma = get_sigma state in
4135 let t = Reductionops.nf_betaiota proof_context.env sigma t in
4136 !: t)),
4137 DocAbove);
4138
4139 MLCode(Pred("coq.reduction.cbv.norm",
4140 CIn(term,"T",
4141 COut(term,"Tred",
4142 Read(proof_context, {|Puts T in normal form using the call by value strategy.
4143 Supported attributes:
4144 - @redflags! (default coq.redflags.all)|}))),
4145 (fun t _ ~depth proof_context constraints state ->
4146 let sigma = get_sigma state in
4147 let flags = Option.default RedFlags.all proof_context.options.redflags in
4148 let t = Tacred.cbv_norm_flags flags ~strong:true proof_context.env sigma t in
4149 !: t)),
4150 DocAbove);
4151
4152 MLCode(Pred("coq.reduction.vm.norm",
4153 CIn(term,"T",
4154 CIn(B.unspecC term,"Ty",
4155 COut(term,"Tred",
4156 Read(proof_context, "Puts T in normal form using [vm_compute]'s machinery. Its type Ty can be omitted (but is recomputed)")))),
4157 (fun t ty _ ~depth proof_context constraints state ->
4158 let sigma = get_sigma state in
4159 let sigma, ty =
4160 match ty with
4161 | B.Given ty -> sigma, ty
4162 | B.Unspec -> Typing.type_of proof_context.env sigma t in
4163 let t = Vnorm.cbv_vm proof_context.env sigma t ty in
4164 !: t)),
4165 DocAbove);
4166
4167 MLCode(Pred("coq.reduction.native.norm",
4168 CIn(term,"T",
4169 CIn(B.unspecC term,"Ty",
4170 COut(term,"Tred",
4171 Read(proof_context, "Puts T in normal form using [native_compute]'s machinery. Its type Ty can be omitted (but is recomputed). Falls back to vm.norm if native compilation is not available.")))),
4172 (fun t ty _ ~depth proof_context constraints state ->
4173 let sigma = get_sigma state in
4174 let sigma, ty =
4175 match ty with
4176 | B.Given ty -> sigma, ty
4177 | B.Unspec -> Typing.type_of proof_context.env sigma t in
4178 let t =
4179 if (Environ.typing_flags proof_context.env).enable_native_compiler then
4180 Nativenorm.native_norm proof_context.env sigma t ty
4181 else
4182 Vnorm.cbv_vm proof_context.env sigma t ty in
4183 !: t)),
4184 DocAbove);
4185
4186 MLCode(Pred("coq.reduction.native.available?",
4187 Easy "Is native compilation available on this system/configuration?",
4188 (fun ~depth:_ -> if not ((Global.typing_flags ()).enable_native_compiler) then raise No_clause)),
4189 DocAbove);
4190
4191 LPCode {|% Deprecated, use coq.reduction.cbv.norm
4192 pred coq.reduction.cbv.whd_all i:term, o:term.
4193 coq.reduction.cbv.whd_all T R :-
4194 coq.warning "elpi.deprecated" "elpi.cbv-whd-all" "use coq.reduction.cbv.norm in place of coq.reduction.cbv.whd_all",
4195 coq.reduction.cbv.norm T R.
4196 |};
4197
4198 LPCode {|% Deprecated, use coq.reduction.vm.norm
4199 pred coq.reduction.vm.whd_all i:term, i:term, o:term.
4200 coq.reduction.vm.whd_all T TY R :-
4201 coq.warning "elpi.deprecated" "elpi.vm-whd-all" "use coq.reduction.vm.norm in place of coq.reduction.vm.whd_all",
4202 coq.reduction.vm.norm T TY R.
4203 |};
4204
4205 LPCode {|
4206 func coq.reduction.lazy.whd_all term -> term.
4207 coq.reduction.lazy.whd_all X Y :-
4208 @redflags! coq.redflags.all => coq.reduction.lazy.whd X Y.
4209 |};
4210
4211 MLCode(Pred("coq.reduction.eta-contract",
4212 CIn(term,"T",
4213 COut(term,"Tred",
4214 Read(proof_context, {|Removes all eta expansions from T|}))),
4215 (fun t _ ~depth proof_context constraints state ->
4216 let sigma = get_sigma state in
4217 let t = eta_contract proof_context.env sigma t in
4218 !: t)),
4219 DocAbove);
4220
4221 LPDoc "-- Coq's conversion strategy tweaks --------------------------";
4222
4223 MLData conversion_strategy;
4224
4225 MLCode(Pred("coq.strategy.set",
4226 In(B.list constant, "CL",
4227 In(conversion_strategy, "Level",
4228 Full(global,"Sets the unfolding priority for all the constants in the list CL. See the command Strategy."))),
4229 (fun csts level ~depth:_ ctx _ -> grab_global_env "coq.strategy.set" (fun state ->
4230 let local = ctx.options.local = Some true in
4231 let csts = csts |> List.map eval_of_constant in
4232 Redexpr.set_strategy local [level, csts];
4233 Univ.ContextSet.empty, state, (), []))),
4234 DocAbove);
4235
4236 MLCode(Pred("coq.strategy.get",
4237 In(constant, "C",
4238 Out(conversion_strategy, "Level",
4239 Read(global, "Gets the unfolding priority for C"))),
4240 (fun c _ ~depth:_ _ _ state ->
4241 let env = get_global_env state in
4242 let oracle = Environ.oracle env in
4243 let k = eval_of_constant c in
4244 !: (Conv_oracle.get_strategy oracle (eval_to_oeval k)))),
4245 DocAbove);
4246
4247 LPDoc "-- Coq's tactics --------------------------------------------";
4248
4249 MLData Rocq_elpi_arg_HOAS.tac;
4250
4251 MLCode(Pred("coq.ltac.fail",
4252 In(B.unspec B.int,"Level",
4253 VariadicIn(unit_ctx, !> B.any, "Interrupts the Elpi program and calls Ltac's fail Level Msg, where Msg is the printing of the remaining arguments. Level can be left unspecified and defaults to 0")),
4254 (fun level args ~depth _hyps _constraints _state ->
4255 let pp = pp ~depth in
4256 let level = match level with B.Given x -> x | B.Unspec -> 0 in
4257 let msg =
4258 if args = [] then Pp.mt ()
4259 else Pp.(str (pp2string (P.list ~boxed:true pp " ") args)) in
4260 ltac_fail_err level msg)),
4261 DocAbove);
4262
4263 MLCode(Pred("coq.ltac.collect-sealed-goals",
4264 CIn(failsafe_term, "T",
4265 Out(list sealed_goal, "Goals",
4266 Out(list sealed_goal, "ShelvedGoals",
4267 Full(proof_context, {|
4268 Turns the holes in T into Goals.
4269 Goals are closed with nablas.
4270 ShelvedGoals are goals which can be solved by side effect (they occur
4271 in the type of the other goals).
4272 The order of Goals is given by the traversal order of EConstr.fold (a
4273 fold_left over the terms, letin body comes before the type).
4274 |})))),
4275 (fun proof _ shelved ~depth proof_context constraints state ->
4276 let shelved_subgoals, subgoals = goals_of_term state proof_context proof in
4277 let shelved =
4278 match shelved with
4279 | Keep -> Some shelved_subgoals
4280 | Discard -> None in
4281 state, !: subgoals +? shelved, []
4282 )),
4283 DocAbove);
4284
4285 LPCode {|
4286 func coq.ltac.collect-goals term -> list sealed-goal, list sealed-goal.
4287 coq.ltac.collect-goals T GA GB :- coq.ltac.collect-sealed-goals T GA GB.
4288 |};
4289
4290 MLCode(Pred("coq.ltac.collect-simple-goals",
4291 CIn(failsafe_term, "T",
4292 COut(B.listC goal', "Goals",
4293 Out(list sealed_goal, "ShelvedGoals",
4294 Full(proof_context, {|Like coq.ltac.collect-sealed-goals turns the holes in T into
4295 Goals but fails if the goals do not live in the current proof context.
4296 |})))),
4297 (fun proof _ shelved ~depth proof_context constraints state ->
4298 let shelved_subgoals, subgoals = goals_of_term state proof_context proof in
4299 let shelved =
4300 match shelved with
4301 | Keep -> Some shelved_subgoals
4302 | Discard -> None in
4303 (* TODO FIXME *)
4304 let subgoals = List.map (fun evar -> {
4305 caller = Some (API.RawOpaqueData.of_string "collect-simple-goals");
4306 proof_context; evar; tac_args = [] })
4307 subgoals in
4308 state, !: subgoals +? shelved, []
4309 )),
4310 DocAbove);
4311
4312
4313 MLCode(Pred("coq.ltac.call-mltac",
4314 In(B.string, "PluginName",
4315 In(B.string, "BlockName",
4316 In(B.int, "BlockIndex",
4317 CIn(goal, "G",
4318 Out(list sealed_goal,"GL",
4319 InOut(B.ioarg B.diagnostic, "Diagnostic",
4320 Full(raw_ctx, {|Calls OCaml code bound via TACTIC EXTEND. For example the
4321 OCaml code for lia looks like:
4322
4323 DECLARE PLUGIN "rocq-runtime.plugins.micromega"
4324 ...
4325 TACTIC EXTEND Lia
4326 | [ "xlia" tactic(t) ] -> { Coq_micromega.xlia (Tacinterp.tactic_of_value ist t) }
4327 END
4328
4329 In order to call the code between curly braces one has to run
4330
4331 coq.ltac.call-mltac "rocq-runtime.plugins.micromega" "Lia" 0 G GL
4332
4333 Note that each TACTIC EXTEND block can have many entries and their numbering
4334 starts from 0. Also, each block has a name, "Lia" in this case.
4335
4336 When the diagnostic is (error Msg), then GL is not set.
4337
4338 Supported attributes:
4339 - @no-tc! (default false, do not infer typeclasses)|}))))))),
4340 (fun plugin block index { proof_context; evar; tac_args } _ diag ~depth _ _ -> abstract__grab_global_env_keep_sigma "coq.ltac.call-mltac" (fun state ->
4341 let no_tc = if proof_context.options.no_tc = Some true then true else false in
4342 let open Ltac_plugin in
4343
4344 let tac_args = tac_args |> List.map (function
4345 | Rocq_elpi_arg_HOAS.Ctrm t -> Tacinterp.Value.of_constr t
4346 | Rocq_elpi_arg_HOAS.Cstr s -> Geninterp.(Val.inject (val_tag (Genarg.topwit Stdarg.wit_string))) s
4347 | Rocq_elpi_arg_HOAS.Cint i -> Tacinterp.Value.of_int i
4348 | Rocq_elpi_arg_HOAS.CLtac1 x -> Geninterp.(Val.inject (val_tag (Topwit Ltac_plugin.Tacarg.wit_tactic))) x) in
4349 let tactic =
4350 let tacname = Tacexpr.{ mltac_name = { mltac_plugin = plugin; mltac_tactic = block; }; mltac_index = index } in
4351 Tacenv.interp_ml_tactic tacname tac_args (Tacinterp.default_ist ()) in
4352
4353 match call_tactic ~depth state ~no_tc proof_context evar tactic with
4354 | Result.Ok (state, subgoals, assignments) ->
4355 (* universe constraints fixed by the code above*)
4356 Univ.ContextSet.empty, state, !: subgoals +! B.mkOK, assignments
4357 | Result.Error ie ->
4358 match diag with
4359 | Data B.OK -> raise No_clause (* optimization: don't print the error if caller wants OK *)
4360 | _ ->
4361 let error = string_of_ppcmds proof_context.options @@ CErrors.iprint_no_report ie in
4362 Univ.ContextSet.empty, state, ?: None +! B.mkERROR error, []
4363 ))),
4364 DocAbove);
4365
4366 MLCode(Pred("coq.ltac.call-simple-mltac",
4367 In(B.string, "PluginName",
4368 In(B.string, "BlockName",
4369 In(B.int, "BlockIndex",
4370 CIn(goal, "G",
4371 COut(B.listC goal,"GL",
4372 InOut(B.ioarg B.diagnostic, "Diagnostic",
4373 Full(raw_ctx, {|Like coq.ltac.call-mltac but Tac is not allowed to
4374 generate new goals GL in different contexts. For example "intro" does not
4375 obey this restriction.
4376
4377 Supported attributes:
4378 - @no-tc! (default false, do not infer typeclasses)|}))))))),
4379 (fun plugin block index { proof_context; evar; tac_args } _ diag ~depth _ _ -> abstract__grab_global_env_keep_sigma "coq.ltac.call-mltac" (fun state ->
4380 let no_tc = if proof_context.options.no_tc = Some true then true else false in
4381 let open Ltac_plugin in
4382
4383 let tac_args = tac_args |> List.map (function
4384 | Rocq_elpi_arg_HOAS.Ctrm t -> Tacinterp.Value.of_constr t
4385 | Rocq_elpi_arg_HOAS.Cstr s -> Geninterp.(Val.inject (val_tag (Genarg.topwit Stdarg.wit_string))) s
4386 | Rocq_elpi_arg_HOAS.Cint i -> Tacinterp.Value.of_int i
4387 | Rocq_elpi_arg_HOAS.CLtac1 x -> Geninterp.(Val.inject (val_tag (Topwit Ltac_plugin.Tacarg.wit_tactic))) x) in
4388 let tactic =
4389 let tacname = Tacexpr.{ mltac_name = { mltac_plugin = plugin; mltac_tactic = block; }; mltac_index = index } in
4390 Tacenv.interp_ml_tactic tacname tac_args (Tacinterp.default_ist ()) in
4391
4392 match call_tactic ~depth state ~no_tc proof_context evar tactic with
4393 | Result.Ok (state, subgoals, assignments) ->
4394 let subgoals = List.map (fun evar -> {
4395 caller = Some (API.RawOpaqueData.of_string (Format.asprintf "%s#%s(%d)" plugin block index));
4396 proof_context; evar; tac_args = [] })
4397 subgoals in
4398 (* universe constraints fixed by the code above*)
4399 Univ.ContextSet.empty, state, !: subgoals +! B.mkOK, assignments
4400 | Result.Error ie ->
4401 match diag with
4402 | Data B.OK -> raise No_clause (* optimization: don't print the error if caller wants OK *)
4403 | _ ->
4404 let error = string_of_ppcmds proof_context.options @@ CErrors.iprint_no_report ie in
4405 Univ.ContextSet.empty, state, ?: None +! B.mkERROR error, []
4406 ))),
4407 DocAbove);
4408
4409
4410 MLCode(Pred("coq.ltac.call-ltac1",
4411 In(B.any, "Tac",
4412 CIn(goal, "G",
4413 Out(list sealed_goal,"GL",
4414 VariadicInOut(raw_ctx,B.ioargC (CConv.(!>) B.diagnostic), {|Calls Ltac1 tactic Tac on goal G (passing the arguments of G, see coq.ltac.call for a handy wrapper).
4415 It accepts one diagnostic argument, defaults to ok if omitted.
4416 Tac can either be a string (the tactic name), or a value
4417 of type ltac1-tactic, see the tac argument constructor
4418 and the ltac_tactic:(...) syntax to pass arguments to
4419 an elpi tactic.
4420 Caveat:
4421 if Tac is a tactic name, then the tactic must be defined using
4422 "Ltac name := body", it cannot be a builtin one. For example
4423 "Ltac myapply x := apply x." lets one call apply by running
4424 coq.ltac.call-ltac1 "myapply" G GL.
4425
4426 When the diagnostic is (error Msg), then GL is not set.
4427
4428 Supported attributes:
4429 - @no-tc! (default false, do not infer typeclasses)|})))),
4430 (fun tac { proof_context; evar; tac_args } _ diags ~depth _ _ -> abstract__grab_global_env_keep_sigma "coq.ltac.call-ltac1" (fun state ->
4431 let no_tc = if proof_context.options.no_tc = Some true then true else false in
4432
4433 let tac_args = tac_args |> List.map Rocq_elpi_arg_HOAS.ltac1_of_arg in
4434 let tactic = apply_ltac1 ~depth tac tac_args in
4435
4436 match call_tactic ~depth state ~no_tc proof_context evar tactic with
4437 | Result.Ok (state, subgoals, assignments) ->
4438 (* universe constraints fixed by the code above*)
4439 let diags =
4440 match diags with
4441 | [] -> []
4442 | _ :: _ :: _ -> U.type_error "coq.ltac.call-ltac1: too many arguments"
4443 | _ -> [Some B.mkOK] in
4444 Univ.ContextSet.empty, state, !: subgoals +! diags, assignments
4445 | Result.Error ie ->
4446 match diags with
4447 | [] -> raise No_clause (* optimization: don't print the error if caller wants OK *)
4448 | _ :: _ :: _ -> U.type_error "coq.ltac.call-ltac1: too many arguments"
4449 | [Data B.OK] -> raise No_clause (* optimization: don't print the error if caller wants OK *)
4450 | _ ->
4451 let error = string_of_ppcmds proof_context.options @@ CErrors.iprint_no_report ie in
4452 Univ.ContextSet.empty, state, ?: None +! [Some(B.mkERROR error)], []
4453 ))),
4454 DocAbove);
4455
4456 MLCode(Pred("coq.ltac.call-simple-ltac1",
4457 In(B.any, "Tac",
4458 CIn(goal, "G",
4459 COut(B.listC goal,"GL",
4460 InOut(B.ioarg B.diagnostic, "Diagnostic",
4461 Full(raw_ctx, {|Like coq.ltac.call-ltac1 but Tac is not allowed to
4462 generate new goals GL in different contexts. For example "intro" does not
4463 obey this restriction.
4464
4465 Supported attributes:
4466 - @no-tc! (default false, do not infer typeclasses)|}))))),
4467 (fun tac { proof_context; evar; tac_args } _ diag ~depth _ _ -> abstract__grab_global_env_keep_sigma "coq.ltac.call-simple-ltac1" (fun state ->
4468 let no_tc = if proof_context.options.no_tc = Some true then true else false in
4469
4470 let tac_args = tac_args |> List.map Rocq_elpi_arg_HOAS.ltac1_of_arg in
4471 let tactic = apply_ltac1 ~depth tac tac_args in
4472
4473 match call_tactic ~depth state ~no_tc proof_context evar tactic with
4474 | Result.Ok (state, subgoals, assignments) ->
4475 let subgoals = List.map (fun evar -> {
4476 caller = Some tac; proof_context; evar; tac_args = [] })
4477 subgoals in
4478 (* universe constraints fixed by the code above*)
4479 Univ.ContextSet.empty, state, !: subgoals +! B.mkOK, assignments
4480 | Result.Error ie ->
4481 match diag with
4482 | Data B.OK -> raise No_clause (* optimization: don't print the error if caller wants OK *)
4483 | _ ->
4484 let error = string_of_ppcmds proof_context.options @@ CErrors.iprint_no_report ie in
4485 Univ.ContextSet.empty, state, ?: None +! B.mkERROR error, []
4486 ))),
4487 DocAbove);
4488
4489 MLCode(Pred("coq.ltac.id-free?",
4490 In(id, "ID",
4491 CIn(goal, "G",
4492 Read(raw_ctx, {|
4493 Fails if ID is already used in G. Note that ids which are taken are renamed
4494 on the fly (since in the HOAS of terms, names are just pretty printing
4495 hints), but for the ergonomy of a tactic it may help to know if an
4496 hypothesis name is already taken.
4497 |}))),
4498 (fun id { proof_context } ~depth _ _ _ ->
4499 if not @@ Id.Set.mem (Names.Id.of_string_soft id) proof_context.names then ()
4500 else raise No_clause)),
4501 DocAbove);
4502
4503 MLCode(Pred("coq.ltac.fresh-id",
4504 In(B.unspec id, "Default",
4505 CIn(B.unspecC term, "Ty",
4506 Out(id,"FreshID",
4507 Read(proof_context, "TODO")))),
4508 (fun id ty _ ~depth proof_context _ state ->
4509 let id = match id with Unspec -> "x" | Given x -> x in
4510 let id =
4511 match ty with
4512 | Unspec -> Namegen.next_ident_away (Names.Id.of_string_soft id) proof_context.names
4513 | Given ty ->
4514 let env = proof_context.env in
4515 let sigma = get_sigma state in
4516 next_name_away_with_default_using_types env sigma id Name.Anonymous proof_context.names ty in
4517 !: (Id.to_string id))),
4518 DocAbove);
4519
4520 LPDoc "-- Coq's options system --------------------------------------------";
4521
4522 MLData goption;
4523
4524 MLCode(Pred("coq.option.get",
4525 In(B.list B.string,"Option",
4526 Out(goption,"Value",
4527 Easy "reads Option. Reading a non existing option is a fatal error.")),
4528 (fun name _ ~depth ->
4529 let table = Goptions.get_tables () in
4530 match Goptions.OptionMap.find_opt name table with
4531 | Some { Goptions.opt_value = x; _ } -> !: x
4532 | None -> err Pp.(str "option " ++ str (String.concat " " name) ++ str" does not exist"))),
4533 DocAbove);
4534
4535 MLCode(Pred("coq.option.set",
4536 In(B.list B.string,"Option",
4537 In(goption,"Value",
4538 Easy "writes Option. Writing a non existing option is a fatal error.")),
4539 (fun name value ~depth -> goption_set name value)),
4540 DocAbove);
4541
4542 MLCode(Pred("coq.option.available?",
4543 In(B.list B.string,"Option",
4544 Out(B.bool,"Deprecated",
4545 Easy "checks if Option exists and tells if is deprecated (tt) or not (ff)")),
4546 (fun name _ ~depth ->
4547 match is_available_option name with
4548 | None -> raise No_clause
4549 | Some e -> !: e)
4550 ),
4551 DocAbove);
4552
4553 MLCode(Pred("coq.option.add",
4554 In(B.list B.string,"Option",
4555 In(goption,"Value",
4556 In(B.unspec B.bool,"Deprecated",
4557 Easy {|
4558 adds a new option to Coq setting its current value (and type).
4559 Deprecated can be left unspecified and defaults to ff.
4560 This call cannot be undone in a Coq interactive session, use it once
4561 and for all in a .v file which your clients will load. Eg.
4562
4563 Elpi Query lp:{{ coq.option.add ... }}.
4564
4565 |}))),
4566 (fun key value depr ~depth ->
4567 let depr = Option.default false @@ unspec2opt depr in
4568 Lib.add_leaf @@ inGoption (depr,key,value))),
4569 DocAbove);
4570
4571 LPDoc "-- Datatypes conversions --------------------------------------------";
4572
4573 MLData name;
4574
4575 MLCode(Pred("coq.name-suffix",
4576 In(name, "Name",
4577 In(B.any, "Suffix",
4578 Out(name,"NameSuffix",
4579 Easy "suffixes a Name with a string or an int or another name"))),
4580 (fun n suffix _ ~depth ->
4581 match E.look ~depth suffix with
4582 | E.CData i when API.RawOpaqueData.(is_string i || is_int i || isname i) ->
4583 let s = Pp.string_of_ppcmds (Name.print @@ Context.binder_name n) in
4584 let suffix =
4585 if API.RawOpaqueData.is_string i then API.RawOpaqueData.to_string i
4586 else if API.RawOpaqueData.is_int i then string_of_int (API.RawOpaqueData.to_int i)
4587 else Pp.string_of_ppcmds (Name.print (Context.binder_name @@ nameout i)) in
4588 let s = s ^ suffix in
4589 !: (Context.map_annot (fun _ -> Name.mk_name (Id.of_string s)) n)
4590 | _ -> err Pp.(str "coq.name-suffix: suffix is not int, nor string nor name"))),
4591 DocAbove);
4592
4593 MLCode(Pred("coq.string->name",
4594 In(B.string, "Hint",
4595 Out(name, "Name",
4596 Full(global, "creates a name hint using a relevance variable"))),
4597 (fun s _ ~depth _ _ state ->
4598 let state, s = mk_coq_name state (Id.of_string s) in
4599 state, !: s, [])),
4600 DocAbove);
4601
4602 MLCode(Pred("coq.string->name-relevant",
4603 In(B.string, "Hint",
4604 Out(name, "Name",
4605 Easy("creates a name hint with the relevant mark (see SProp)"))),
4606 (fun s _ ~depth ->
4607 let s = EConstr.nameR (Id.of_string s) in
4608 !: s)),
4609 DocAbove);
4610
4611 LPCode {|
4612 func coq.id->name id -> name.
4613 coq.id->name S N :- coq.string->name-relevant S N.
4614 |};
4615
4616 MLCode(Pred("coq.name->id",
4617 In(name, "Name",
4618 Out(id, "Id",
4619 Easy "tuns a pretty printing hint into a string. This API is for internal use, no guarantee on its behavior.")),
4620 (fun n _ ~depth ->
4621 match Context.binder_name n with
4622 | Name.Anonymous -> !: "_"
4623 | Name.Name s -> !: (Id.to_string s))),
4624 DocAbove);
4625
4626 MLCode(Pred("coq.name.relevant?",
4627 In(name, "Name",
4628 Out(option bool, "Relevance",
4629 Read(global, "Reads the relevance mark. none means unset, some tt means relevant."))),
4630 (fun n _ ~depth _ _ state ->
4631 let sigma = get_sigma state in
4632 match EConstr.ERelevance.kind sigma @@ Context.binder_relevance n with
4633 | Sorts.Irrelevant -> !: (Some false)
4634 | Sorts.Relevant -> !: (Some true)
4635 | Sorts.RelevanceVar _ -> !: None)),
4636 DocAbove);
4637
4638
4639 MLCode(Pred("coq.gref->id",
4640 In(gref, "GR",
4641 Out(id, "Id",
4642 Read (unit_ctx, "extracts the label (last component of a full kernel name)"))),
4643 (fun gr _ ~depth _ _ state ->
4644 !: (gr2id state gr))),
4645 DocAbove);
4646
4647 MLCode(Pred("coq.gref->string",
4648 In(gref, "GR",
4649 Out(B.string, "FullPath",
4650 Read(unit_ctx, "extract the full kernel name"))),
4651 (fun gr _ ~depth h c state ->
4652 let path = gr2path gr in
4653 let id = gr2id state gr in
4654 !: (String.concat "." (path @ [id])))),
4655 DocAbove);
4656
4657 MLCode(Pred("coq.gref->path",
4658 In(gref, "GR",
4659 Out(B.list B.string, "FullPath",
4660 Read(unit_ctx, "extract the full path (kernel name without final id), each component is a separate list item"))),
4661 (fun gr _ ~depth h c state -> !: (gr2path gr))),
4662 DocAbove);
4663
4664 Rocq_elpi_builtins_synterp.modpath_to_path;
4665 Rocq_elpi_builtins_synterp.modtypath_to_path;
4666 Rocq_elpi_builtins_synterp.modpath_to_library;
4667 Rocq_elpi_builtins_synterp.modtypath_to_library;
4668
4669 MLCode(Pred("coq.term->string",
4670 CIn(failsafe_term,"T",
4671 Out(B.string, "S",
4672 Full(proof_context, {|prints a term T to a string S using Coq's pretty printer
4673 Supported attributes:
4674 - @ppwidth! N (default 80, max line length)
4675 - @ppall! (default: false, prints all details)
4676 - @ppmost! (default: false, prints most details)
4677 - @pplevel! (default: _, prints parentheses to reach that level, 200 = off)
4678 - @holes! (default: false, prints evars as _)|}))),
4679 (fun t _ ~depth proof_context constraints state ->
4680 let sigma = get_sigma state in
4681 let s = string_of_ppcmds proof_context.options (pr_econstr_env proof_context.options proof_context.env sigma t) in
4682 state, !: s, [])),
4683 DocAbove);
4684
4685 MLCode(Pred("coq.term->pp",
4686 CIn(failsafe_term,"T",
4687 Out(ppboxes, "B",
4688 Full(proof_context, {|prints a term T to a pp.t B using Coq's pretty printer"
4689 Supported attributes:
4690 - @ppall! (default: false, prints all details)
4691 - @ppmost! (default: false, prints most details)
4692 - @pplevel! (default: _, prints parentheses to reach that level, 200 = off)
4693 - @holes! (default: false, prints evars as _)|}))),
4694 (fun t _ ~depth proof_context constraints state ->
4695 let sigma = get_sigma state in
4696 let s = Pp.repr @@ pr_econstr_env proof_context.options proof_context.env sigma t in
4697 state, !: s, [])),
4698 DocAbove);
4699
4700 MLCode(Pred("coq.goal->pp",
4701 CIn(goal,"G",
4702 Out(ppboxes, "B",
4703 Full(raw_ctx, {|prints a goal G to a pp.t B using Coq's pretty printer"
4704 Supported attributes:
4705 - @ppall! (default: false, prints all details)
4706 - @ppmost! (default: false, prints most details)
4707 - @pplevel! (default: _, prints parentheses to reach that level, 200 = off)
4708 - @holes! (default: false, prints evars as _)|}))),
4709 (fun { proof_context; evar } _ ~depth _ _ state ->
4710 let sigma = get_sigma state in
4711 let s = Pp.(repr @@ with_pp_options proof_context.options.pp (fun flags ->
4712 v 0 @@
4713 pr_named_context_of proof_context.options proof_context.env sigma ++ cut () ++
4714 str "======================" ++ cut () ++
4715 pr_econstr_env_flagged flags proof_context.env sigma
4716 Evd.(evar_concl @@ find_undefined sigma evar))) in
4717 state, !: s, [])),
4718 DocAbove);
4719
4720 LPDoc "-- Register -----------------------------------------------";
4721
4722 MLData scheme_kind;
4723 MLData register;
4724
4725 MLCode(Pred("coq.register",
4726 In(gref,"GR",
4727 In(register,"R",
4728 Full(global,"Registers GR as R (See Register Inline, Register Scheme)"))),
4729 (fun gr r ~depth ctx _ state ->
4730 let local = hint_locality ctx.options in
4731 match r with
4732 | Inline ->
4733 begin match gr with
4734 | GlobRef.ConstRef c -> Global.register_inline c
4735 | _ -> U.type_error "Register Inline: expecting a constant."
4736 end;
4737 state, (), []
4738 | Rocqlib x ->
4739 register_ref local x gr;
4740 state, (), []
4741 | Scheme(ref,k) ->
4742 let k = string_of_scheme_kind k in
4743 declare_scheme_for local k ref gr;
4744 state, (), []
4745 )),
4746 DocAbove);
4747
4748 MLCode(Pred("coq.scheme",
4749 In(scheme_kind, "Kind",
4750 In(gref, "GR",
4751 Out(option gref, "Scheme",
4752 Easy "looks up the scheme of the given kind for GR. Returns none if GR is not an inductive or no such scheme is registered."))),
4753 (fun k gr _ ~depth ->
4754 !: (lookup_scheme_opt (string_of_scheme_kind k) gr))),
4755 DocAbove);
4756
4757 LPDoc "-- Extra Dependencies -----------------------------------------------";
4758
4759 MLCode(Pred("coq.extra-dep",
4760 In(id, "Identifier",
4761 Out(option id, "FileName",
4762 Easy "Resolve the file name of an extra dependency. See also Coq's From xxx Extra Dependency yyy as zzz.")),
4763 (fun id _ ~depth ->
4764 !: (try Some (ComExtraDeps.query_extra_dep (Names.Id.of_string id))
4765 with Not_found -> None))),
4766 DocAbove);
4767
4768 LPDoc "-- Access to Elpi's data --------------------------------------------";
4769
4770 (* Self modification *)
4771 MLData Rocq_elpi_builtins_synterp.clause;
4772 MLData Rocq_elpi_builtins_synterp.grafting;
4773 MLData Rocq_elpi_builtins_synterp.scope;
4774
4775 LPCode {|
4776 % see coq.elpi.accumulate-clauses
4777 :index (1)
4778 func coq.elpi.accumulate scope, id, clause.
4779 coq.elpi.accumulate S N C :- coq.elpi.accumulate-clauses S N [C].
4780 |};
4781
4782 MLCode(Pred("coq.elpi.accumulate-clauses",
4783 In(B.unspec Rocq_elpi_builtins_synterp.scope, "Scope",
4784 In(id, "DbName",
4785 In(B.list Rocq_elpi_builtins_synterp.clause, "Clauses",
4786 Full (global, {|
4787 Declare that the given clauses have to be added to the given db (see Elpi Db).
4788 Clauses usually belong to Coq modules: the Scope argument lets one
4789 select which module:
4790 - execution site (default) is the module in which the program is
4791 invoked, the clauses will be accumulated when the execution of the program ends
4792 - current is the module currently being constructed (see
4793 begin/end-module), the clauses will be accumulated when the execution of the program ends
4794 or the start of another program (whichever comes first)
4795 - library is the current file (the module that is named after the file),
4796 the clauses will be accumulated when the execution of the program ends
4797 The clauses are visible as soon as the enclosing module is Imported.
4798 A clause that mentions a section variable is automatically discarded
4799 at the end of the section.
4800 Clauses cannot be accumulated inside functors.
4801 Supported attributes:
4802 - @local! (default: false, discard at the end of section or module)
4803 - @global! (default: false, always active, only if Scope is execution-site, discouraged)|} )))),
4804 (fun scope dbname clauses ~depth {options} _ state ->
4805 Rocq_elpi_builtins_synterp.accumulate_clauses
4806 ~clauses_for_later:clauses_for_later_interp
4807 ~accumulate_to_db:(get_accumulate_to_db_interp()) ~preprocess_clause
4808 ~scope ~dbname clauses ~depth ~options state)),
4809 DocAbove);
4810
4811 MLData argument_mode;
4812
4813 MLCode(Pred("coq.elpi.add-predicate",
4814 In(B.string,"Db",
4815 In(B.unspec B.string,"Indexing",
4816 In(B.string,"PredName",
4817 In(B.list (B.pair argument_mode B.string),"Spec",
4818 Full(global,{|Declares a new predicate PredName in the data base Db.
4819 Indexing can be left unspecified. Spec gathers a mode and a
4820 type for each argument. CAVEAT: types and indexing are strings
4821 instead of proper data types; beware parsing errors are fatal.
4822 Supported attributes:
4823 - @local! (default: false, discard at the end of section or module)
4824 - @global! (default: false, always active|}))))),
4825 (fun dbname indexing predname spec ~depth ctx _ state ->
4826 let dbname = Rocq_elpi_utils.string_split_on_char '.' dbname in
4827 let f = get_accumulate_text_to_db_interp () in
4828 let local = ctx.options.local = Some true in
4829 let super_global = ctx.options.local = Some false in
4830 if local && super_global then CErrors.user_err Pp.(str "coq.elpi.add-predicate: @global! incompatible with @local!");
4831 let indexing =
4832 match indexing with
4833 | B.Given str -> ":index ("^str^") "
4834 | B.Unspec -> "" in
4835 let spec = spec |> List.map (fun (mode,ty) ->
4836 let mode =
4837 match mode with
4838 | `Input -> "i:"
4839 | `Output -> "o:" in
4840 mode ^ "(" ^ ty ^ ")") in
4841 let spec = String.concat ", " spec in
4842 let text = indexing ^ "pred " ^ predname ^ " " ^ spec ^ "." in
4843 let scope = if local then Local else if super_global then SuperGlobal else Regular in
4844 let loc = to_coq_loc @@ State.get Rocq_elpi_builtins_synterp.invocation_site_loc state in
4845 f ~loc dbname text scope;
4846 state, (), []
4847 )),
4848 DocAbove);
4849
4850 MLCode(Pred("coq.elpi.predicate?",
4851 In(B.string,"PredName",
4852 Full(global,"Tells if a predicate called PredName exists")),
4853 (fun name ~depth _ _ state ->
4854 try
4855 Elpi.API.RawQuery.global_name_to_constant state name |> ignore;
4856 state, (), []
4857 with Elpi_compiler.Compiler_data.CompileError _ -> raise No_clause
4858 )),
4859 DocAbove);
4860
4861 MLCode(Pred("coq.elpi.predicate",
4862 In(B.string,"PredName",
4863 In(list B.any,"Args",
4864 Out(B.poly "prop","Pred",
4865 Full(global,"Pred is the application of PredName to Args")))),
4866 (fun name args _ ~depth _ _ state ->
4867 try
4868 let c = Elpi.API.RawQuery.global_name_to_constant state name in
4869 match args with
4870 | [] -> state, !: (E.mkGlobal c), []
4871 | x :: xs -> state, !: (E.mkApp c x xs), []
4872 with Not_found -> U.type_error ("predicate name expected, got " ^ name)
4873 )),
4874 DocAbove);
4875
4876
4877 ] @ Rocq_elpi_builtins_synterp.SynterpAction.builtins_interp @ [
4878
4879 LPDoc "-- Utils ------------------------------------------------------------";
4880 ] @
4881 gref_set_decl @
4882 B.ocaml_map ~name:"coq.gref.map" gref (module GRMap) @
4883 B.ocaml_set ~name:"coq.univ.set" univ (module UnivSet) @
4884 B.ocaml_map ~name:"coq.univ.map" univ (module UnivMap) @
4885 universe_level_set_decl @
4886 B.ocaml_map ~name:"coq.univ.variable.map" universe_level_variable (module UnivLevelMap) @
4887 [
4888 MLData ppbox;
4889 MLData ppboxes;
4890 MLCode(Pred("coq.pp->string",
4891 In(ppboxes, "B",
4892 Out(B.string, "S",
4893 Read(global, {|Prints a pp.t box expression B to a string S
4894 Supported attributes:
4895 - @ppwidth! N (default 80, max line length)|}))),
4896 (fun box _ ~depth ctx _ _ ->
4897 !: (string_of_ppcmds ctx.options (Pp.unrepr box))
4898 )),
4899 DocAbove)
4900
4901 ]
4902
4903 ;;