Debian Codegraph @

kernel/environ.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* Author: Jean-Christophe Filliâtre as part of the rebuilding of Coq
12 around a purely functional abstract type-checker, Aug 1999 *)
13 (* Cleaning and lightening of the kernel by Bruno Barras, Nov 2001 *)
14 (* Flag for predicativity of Set by Hugo Herbelin in Oct 2003 *)
15 (* Support for virtual machine by Benjamin Grégoire in Oct 2004 *)
16 (* Support for retroknowledge by Arnaud Spiwack in May 2007 *)
17 (* Support for assumption dependencies by Arnaud Spiwack in May 2007 *)
18
19 (* Miscellaneous maintenance by Bruno Barras, Hugo Herbelin, Jean-Marc
20 Notin, Matthieu Sozeau *)
21
22 (* This file defines the type of environments on which the
23 type-checker works, together with simple related functions *)
24
25 open CErrors
26 open Util
27 open Names
28 open Constr
29 open Vars
30 open Declarations
31 open Mod_declarations
32 open Context.Rel.Declaration
33
34 module NamedDecl = Context.Named.Declaration
35
36 (* The type of environments. *)
37
38 (* The key attached to each constant is used by the VM to retrieve previous *)
39 (* evaluations of the constant. It is essentially an index in the symbols table *)
40 (* used by the VM. *)
41 type key = int CEphemeron.key option ref
42
43 (** Linking information for the native compiler. *)
44
45 type link_info =
46 | Linked of string
47 | NotLinked
48
49 type constant_key = constant_body * (link_info ref * key) * KerName.t
50
51 type mind_key = mutual_inductive_body * link_info ref * KerName.t
52
53 type named_context_val = {
54 env_named_ctx : Constr.named_context;
55 env_named_map : Constr.named_declaration Id.Map.t;
56 env_named_idx : Constr.named_declaration Range.t;
57 }
58
59 type rel_context_val = {
60 env_rel_ctx : Constr.rel_context;
61 env_rel_map : Constr.rel_declaration Range.t;
62 }
63
64 type env = {
65 env_constants : constant_key Cmap_env.t;
66 env_inductives : mind_key Mindmap_env.t;
67 env_modules : module_body ModPath.Map.t;
68 env_modtypes : module_type_body ModPath.Map.t;
69 env_named_context : named_context_val; (* section variables *)
70 env_rel_context : rel_context_val;
71 env_universes : UGraph.t;
72 env_qualities : QGraph.t;
73 symb_pats : machine_rewrite_rule list Cmap_env.t;
74 env_typing_flags : typing_flags;
75 vm_library : Vmlibrary.t;
76 retroknowledge : Retroknowledge.retroknowledge;
77 rewrite_rules_allowed : bool;
78
79 (* caches *)
80 env_nb_rel : int;
81 irr_constants : Sorts.relevance Cmap_env.t;
82 irr_inds : Sorts.relevance Indmap_env.t;
83 constant_hyps : Id.Set.t Cmap_env.t;
84 inductive_hyps : Id.Set.t Mindmap_env.t;
85 }
86
87 type rewrule_not_allowed = Symb | Rule
88 exception RewriteRulesNotAllowed of rewrule_not_allowed
89
90 let empty_named_context_val = {
91 env_named_ctx = [];
92 env_named_map = Id.Map.empty;
93 env_named_idx = Range.empty;
94 }
95
96 let empty_rel_context_val = {
97 env_rel_ctx = [];
98 env_rel_map = Range.empty;
99 }
100
101 let empty_env = {
102 env_constants = Cmap_env.empty;
103 env_inductives = Mindmap_env.empty;
104 env_modules = ModPath.Map.empty;
105 env_modtypes = ModPath.Map.empty;
106 constant_hyps = Cmap_env.empty;
107 inductive_hyps = Mindmap_env.empty;
108 env_named_context = empty_named_context_val;
109 env_rel_context = empty_rel_context_val;
110 env_nb_rel = 0;
111 env_universes = UGraph.initial_universes;
112 env_qualities = QGraph.initial_graph;
113 irr_constants = Cmap_env.empty;
114 irr_inds = Indmap_env.empty;
115 symb_pats = Cmap_env.empty;
116 env_typing_flags = Declareops.safe_flags Conv_oracle.empty;
117 vm_library = Vmlibrary.empty;
118 retroknowledge = Retroknowledge.empty;
119 rewrite_rules_allowed = false;
120 }
121
122
123 (* Rel context *)
124
125 let push_rel_context_val d ctx = {
126 env_rel_ctx = Context.Rel.add d ctx.env_rel_ctx;
127 env_rel_map = Range.cons d ctx.env_rel_map;
128 }
129
130 let match_rel_context_val ctx = match ctx.env_rel_ctx with
131 | [] -> None
132 | decl :: rem ->
133 let ctx = { env_rel_ctx = rem; env_rel_map = Range.tl ctx.env_rel_map } in
134 Some (decl, ctx)
135
136 let push_rel d env =
137 { env with
138 env_rel_context = push_rel_context_val d env.env_rel_context;
139 env_nb_rel = env.env_nb_rel + 1 }
140
141 let lookup_rel n env =
142 try Range.get env.env_rel_context.env_rel_map (n - 1)
143 with Invalid_argument _ -> raise Not_found
144
145 let rel_skipn n ctx = {
146 env_rel_ctx = Util.List.skipn n ctx.env_rel_ctx;
147 env_rel_map = Range.skipn n ctx.env_rel_map;
148 }
149
150 let env_of_rel n env =
151 { env with
152 env_rel_context = rel_skipn n env.env_rel_context;
153 env_nb_rel = env.env_nb_rel - n
154 }
155
156 let set_rel_context_val v env =
157 { env with
158 env_rel_context = v;
159 env_nb_rel = Range.length v.env_rel_map; }
160
161 (* Named context *)
162
163 let push_named_context_val d ctxt =
164 (* assert (not (Id.Map.mem (NamedDecl.get_id d) ctxt.env_named_map)); *)
165 {
166 env_named_ctx = Context.Named.add d ctxt.env_named_ctx;
167 env_named_map = Id.Map.add (NamedDecl.get_id d) d ctxt.env_named_map;
168 env_named_idx = Range.cons d ctxt.env_named_idx;
169 }
170
171 let match_named_context_val c = match c.env_named_ctx with
172 | [] -> None
173 | decl :: ctx ->
174 let map = Id.Map.remove (NamedDecl.get_id decl) c.env_named_map in
175 let cval = { env_named_ctx = ctx; env_named_map = map; env_named_idx = Range.tl c.env_named_idx } in
176 Some (decl, cval)
177
178 let map_named_val f ctxt =
179 let open Context.Named.Declaration in
180 let fold accu d =
181 let d' = f d in
182 let accu =
183 if d == d' then accu
184 else Id.Map.set (get_id d) d' accu
185 in
186 (accu, d')
187 in
188 let map, ctx = List.Smart.fold_left_map fold ctxt.env_named_map ctxt.env_named_ctx in
189 if map == ctxt.env_named_map then ctxt
190 else
191 let idx = List.fold_right Range.cons ctx Range.empty in
192 { env_named_ctx = ctx; env_named_map = map; env_named_idx = idx }
193
194 let push_named d env =
195 {env with env_named_context = push_named_context_val d env.env_named_context}
196
197 let mem_named id env =
198 Id.Map.mem id env.env_named_context.env_named_map
199
200 let lookup_named id env =
201 Id.Map.find id env.env_named_context.env_named_map
202
203 let lookup_named_ctxt id ctxt =
204 Id.Map.find id ctxt.env_named_map
205
206 let record_global_hyps add kn hyps acc =
207 if CList.is_empty hyps then acc
208 else add kn (Context.Named.to_vars hyps) acc
209
210 let fold_constants f env acc =
211 Cmap_env.fold (fun c (body,_,_) acc -> f c body acc) env.env_constants acc
212
213 let fold_inductives f env acc =
214 Mindmap_env.fold (fun c (body,_,_) acc -> f c body acc) env.env_inductives acc
215
216 (* Global constants *)
217
218 let lookup_constant_opt kn env =
219 match Cmap_env.find_opt kn env.env_constants with
220 | None -> None
221 | Some (cb, _, _) -> Some cb
222
223 let lookup_constant_key kn env =
224 match Cmap_env.find_opt kn env.env_constants with
225 | Some v -> v
226 | None ->
227 anomaly Pp.(str "Constant " ++ Constant.print kn ++ str" does not appear in the environment.")
228
229 let lookup_constant kn env =
230 pi1 (lookup_constant_key kn env)
231
232 let mem_constant kn env = Cmap_env.mem kn env.env_constants
233
234 let add_rewrite_rules l env =
235 if not env.rewrite_rules_allowed then raise (RewriteRulesNotAllowed Rule);
236 let add c r = function
237 | None -> anomaly Pp.(str "Trying to add a rule to non-symbol " ++ Constant.print c ++ str".")
238 | Some rs -> Some (r::rs)
239 in
240 { env with
241 symb_pats = List.fold_left (fun symb_pats (c, r) -> Cmap_env.update c (add c r) symb_pats) env.symb_pats l
242 }
243
244 let lookup_rewrite_rules cst env =
245 Cmap_env.find cst env.symb_pats
246
247 (* Mutual Inductives *)
248 let lookup_mind_key kn env =
249 match Mindmap_env.find_opt kn env.env_inductives with
250 | Some v -> v
251 | None ->
252 anomaly Pp.(str "Inductive " ++ MutInd.print kn ++ str" does not appear in the environment.")
253
254 let lookup_mind kn env =
255 pi1 (lookup_mind_key kn env)
256
257 let ind_relevance kn env = match Indmap_env.find_opt kn env.irr_inds with
258 | None -> Sorts.Relevant
259 | Some r -> r
260
261 (** {6 Changes of representation of Case nodes} *)
262
263 (** Provided:
264 - a universe instance [u]
265 - a term substitution [subst]
266 - name replacements [nas]
267 [instantiate_context u subst nas ctx] applies both [u] and [subst] to [ctx]
268 while replacing names using [nas] (order reversed)
269 *)
270 let instantiate_context u subst nas ctx =
271 let open Context.Rel.Declaration in
272 let get_binder i na =
273 Context.
274 { binder_name = nas.(i).binder_name;
275 binder_relevance = UVars.subst_instance_relevance u na.binder_relevance }
276 in
277 let rec instantiate i ctx = match ctx with
278 | [] -> assert (Int.equal i (-1)); []
279 | LocalAssum (na, ty) :: ctx ->
280 let ctx = instantiate (pred i) ctx in
281 let ty = substnl subst i (subst_instance_constr u ty) in
282 let na = get_binder i na in
283 LocalAssum (na, ty) :: ctx
284 | LocalDef (na, ty, bdy) :: ctx ->
285 let ctx = instantiate (pred i) ctx in
286 let ty = substnl subst i (subst_instance_constr u ty) in
287 let bdy = substnl subst i (subst_instance_constr u bdy) in
288 let na = get_binder i na in
289 LocalDef (na, ty, bdy) :: ctx
290 in
291 instantiate (Array.length nas - 1) ctx
292
293 let expand_arity (mib, mip) (ind, u) params nas =
294 let open Context.Rel.Declaration in
295 let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
296 let params = Vars.subst_of_rel_context_instance paramdecl params in
297 let realdecls, _ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
298 let self =
299 let u = UVars.Instance.abstract_instance (UVars.Instance.length u) in
300 let args = Context.Rel.instance mkRel 0 mip.mind_arity_ctxt in
301 mkApp (mkIndU (ind, u), args)
302 in
303 let na = Context.make_annot Anonymous mip.mind_relevance in
304 let realdecls = LocalAssum (na, self) :: realdecls in
305 instantiate_context u params nas realdecls
306
307 let expand_branch_contexts (mib, mip) u params br =
308 let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
309 let paramsubst = Vars.subst_of_rel_context_instance paramdecl params in
310 let build_one_branch i (nas, _) (ctx, _) =
311 let ctx, _ = List.chop mip.mind_consnrealdecls.(i) ctx in
312 let ctx = instantiate_context u paramsubst nas ctx in
313 ctx
314 in
315 Array.map2_i build_one_branch br mip.mind_nf_lc
316
317
318 let mem_mind kn env = Mindmap_env.mem kn env.env_inductives
319
320 let mind_context env mind =
321 let mib = lookup_mind mind env in
322 Declareops.inductive_polymorphic_context mib
323
324 let oracle env = env.env_typing_flags.conv_oracle
325 let set_oracle env o =
326 let env_typing_flags = { env.env_typing_flags with conv_oracle = o } in
327 { env with env_typing_flags }
328
329 let typing_flags env = env.env_typing_flags
330
331 let is_impredicative_set env = env.env_typing_flags.impredicative_set
332
333 let is_impredicative_sort env = function
334 | Sorts.SProp | Sorts.Prop -> true
335 | Sorts.Set -> is_impredicative_set env
336 | Sorts.Type _ | Sorts.QSort _ -> false
337
338 let type_in_type env = not (typing_flags env).check_universes
339 let deactivated_guard env = not (typing_flags env).check_guarded
340
341 let indices_matter env = env.env_typing_flags.indices_matter
342
343 let universes env = env.env_universes
344
345 let set_universes g env =
346 {env with env_universes=g}
347
348 let qualities env = env.env_qualities
349 let qvars env = QGraph.qvar_domain @@ qualities env
350
351 let set_qualities g env =
352 {env with env_qualities=g}
353
354 let named_context env = env.env_named_context.env_named_ctx
355 let named_context_val env = env.env_named_context
356 let rel_context env = env.env_rel_context.env_rel_ctx
357 let rel_context_val env = env.env_rel_context
358
359 let empty_context env =
360 match env.env_rel_context.env_rel_ctx, env.env_named_context.env_named_ctx with
361 | [], [] -> true
362 | _ -> false
363
364 (* Rel context *)
365 let evaluable_rel n env =
366 is_local_def (lookup_rel n env)
367
368 let nb_rel env = env.env_nb_rel
369
370 let push_rel_context ctxt x = Context.Rel.fold_outside push_rel ctxt ~init:x
371
372 let push_rec_types (lna,typarray,_) env =
373 let ctxt = Array.map2_i (fun i na t -> LocalAssum (na, lift i t)) lna typarray in
374 Array.fold_left (fun e assum -> push_rel assum e) env ctxt
375
376 let fold_rel_context f env ~init =
377 let rec fold_right env =
378 match match_rel_context_val env.env_rel_context with
379 | None -> init
380 | Some (rd, rc) ->
381 let env =
382 { env with
383 env_rel_context = rc;
384 env_nb_rel = env.env_nb_rel - 1 } in
385 f env rd (fold_right env)
386 in fold_right env
387
388 (* Named context *)
389
390 let named_context_of_val c = c.env_named_ctx
391
392 let ids_of_named_context_val c = Id.Map.domain c.env_named_map
393
394 let empty_named_context = Context.Named.empty
395
396 let push_named_context = List.fold_right push_named
397
398 let val_of_named_context ctxt =
399 List.fold_right push_named_context_val ctxt empty_named_context_val
400
401
402 let eq_named_context_val c1 c2 =
403 c1 == c2 || Context.Named.equal Sorts.relevance_equal Constr.equal (named_context_of_val c1) (named_context_of_val c2)
404
405 (* A local const is evaluable if it is defined *)
406
407 let named_type id env =
408 let open Context.Named.Declaration in
409 get_type (lookup_named id env)
410
411 let named_body id env =
412 let open Context.Named.Declaration in
413 get_value (lookup_named id env)
414
415 let evaluable_named id env =
416 match named_body id env with
417 | Some _ -> true
418 | _ -> false
419
420 let reset_with_named_context ctxt env =
421 { env with
422 env_named_context = ctxt;
423 env_rel_context = empty_rel_context_val;
424 env_nb_rel = 0 }
425
426 let reset_context = reset_with_named_context empty_named_context_val
427
428 let pop_rel_context n env =
429 let rec skip n ctx =
430 if Int.equal n 0 then ctx
431 else match match_rel_context_val ctx with
432 | None -> invalid_arg "List.skipn"
433 | Some (_, ctx) -> skip (pred n) ctx
434 in
435 let ctxt = env.env_rel_context in
436 { env with
437 env_rel_context = skip n ctxt;
438 env_nb_rel = env.env_nb_rel - n }
439
440 let fold_named_context f env ~init =
441 let rec fold_right env =
442 match match_named_context_val env.env_named_context with
443 | None -> init
444 | Some (d, rem) ->
445 let env =
446 reset_with_named_context rem env in
447 f env d (fold_right env)
448 in fold_right env
449
450 let fold_named_context_reverse f ~init env =
451 Context.Named.fold_inside f ~init:init (named_context env)
452
453
454 (* Universe constraints *)
455
456 let map_universes f env = set_universes (f env.env_universes) env
457
458 let map_qualities f env = set_qualities (f env.env_qualities) env
459
460 let check_univ_constraints univ_csts env =
461 UGraph.check_constraints univ_csts env.env_universes
462
463 let check_constraints (elim_csts,univ_csts) env =
464 check_univ_constraints univ_csts env &&
465 QGraph.check_constraints elim_csts env.env_qualities
466
467 let add_universes ~strict ctx g =
468 let _, us = UVars.Instance.to_array (UVars.UContext.instance ctx) in
469 let g = Array.fold_left
470 (fun g v -> UGraph.add_universe ~strict v g)
471 g us
472 in
473 UGraph.merge_constraints (UVars.UContext.univ_constraints ctx) g
474
475 let set_qualities g env = {env with env_qualities = g}
476
477 let add_qualities ctx g =
478 let qs, _ = UVars.Instance.to_array (UVars.UContext.instance ctx) in
479 let g = Array.fold_right QGraph.add_quality qs g in
480 QGraph.merge_constraints (UVars.UContext.elim_constraints ctx) g
481
482 let push_context ?(strict=false) ctx env =
483 let env = map_qualities (add_qualities ctx) env in
484 map_universes (add_universes ~strict ctx) env
485
486 (* TODO: a bit wasteful, we typically call this before pushing the sort context *)
487 let check_ucontext ctx env =
488 let qgraph = add_qualities ctx (qualities env) in
489 if not (Sorts.ElimConstraints.is_empty @@ UVars.UContext.elim_constraints ctx) then
490 QGraph.check_rigid_paths qgraph
491
492 let add_universes_set ~strict (lvl, cstr) g =
493 let g = Univ.Level.Set.fold
494 (* Be lenient, module typing reintroduces universes and constraints due to includes *)
495 (fun v g -> try UGraph.add_universe ~strict v g with UGraph.AlreadyDeclared -> g)
496 lvl g
497 in
498 UGraph.merge_constraints cstr g
499
500 let push_context_set ?(strict=false) ctx env =
501 map_universes (add_universes_set ~strict ctx) env
502
503 let push_qualities ~rigid (qs, qcsts) env =
504 let () = assert Sorts.QVar.Set.(is_empty @@ inter qs (QGraph.qvar_domain env.env_qualities)) in
505 let fold v = QGraph.add_quality (Sorts.Quality.QVar v) in
506 let g = Sorts.QVar.Set.fold fold qs env.env_qualities in
507 let merge g =
508 let g = QGraph.merge_constraints qcsts g in
509 if rigid then
510 let fold (q1, _, q2) accu = QGraph.add_rigid_path q1 q2 accu in
511 Sorts.ElimConstraints.fold fold qcsts g
512 else g
513 in
514 map_qualities merge @@ set_qualities g env
515
516 let push_subgraph (levels, univ_csts) env =
517 let add_subgraph g =
518 let newg = Univ.Level.Set.fold (fun v g -> UGraph.add_universe ~strict:false v g) levels g in
519 let newg = UGraph.merge_constraints univ_csts newg in
520 (if not (Univ.UnivConstraints.is_empty univ_csts) then
521 let restricted = UGraph.constraints_for ~kept:(UGraph.domain g) newg in
522 (if not (UGraph.check_constraints restricted g) then
523 CErrors.anomaly Pp.(str "Local constraints imply new transitive constraints.")));
524 newg
525 in
526 map_universes add_subgraph env
527
528 (* It's convenient to use [{flags with foo = bar}] so we're smart wrt to it. *)
529 let same_flags {
530 check_guarded;
531 check_positive;
532 check_universes;
533 conv_oracle;
534 indices_matter;
535 share_reduction;
536 enable_VM;
537 enable_native_compiler;
538 impredicative_set;
539 sprop_allowed;
540 allow_uip;
541 } alt =
542 check_guarded == alt.check_guarded &&
543 check_positive == alt.check_positive &&
544 check_universes == alt.check_universes &&
545 conv_oracle == alt.conv_oracle &&
546 indices_matter == alt.indices_matter &&
547 share_reduction == alt.share_reduction &&
548 enable_VM == alt.enable_VM &&
549 enable_native_compiler == alt.enable_native_compiler &&
550 impredicative_set == alt.impredicative_set &&
551 sprop_allowed == alt.sprop_allowed &&
552 allow_uip == alt.allow_uip
553 [@warning "+9"]
554
555 let set_type_in_type b = map_universes (UGraph.set_type_in_type b)
556
557 let set_typing_flags c env =
558 if same_flags env.env_typing_flags c then env
559 else
560 let env = { env with env_typing_flags = c } in
561 let env = set_type_in_type (not c.check_universes) env in
562 env
563
564 let update_typing_flags ?typing_flags env =
565 Option.cata (fun flags -> set_typing_flags flags env) env typing_flags
566
567 let set_impredicative_set b env =
568 set_typing_flags {env.env_typing_flags with impredicative_set=b} env
569
570 let set_type_in_type b env =
571 set_typing_flags {env.env_typing_flags with check_universes=not b} env
572
573 let set_allow_sprop b env =
574 set_typing_flags {env.env_typing_flags with sprop_allowed=b} env
575
576 let sprop_allowed env = env.env_typing_flags.sprop_allowed
577
578 let allow_rewrite_rules env =
579 (* We need to be safe with reduction machines *)
580 let flags = typing_flags env in
581 let env = set_typing_flags
582 { flags with
583 enable_VM = false;
584 enable_native_compiler = false }
585 env
586 in
587 { env with rewrite_rules_allowed = true }
588
589 let rewrite_rules_allowed env = env.rewrite_rules_allowed
590
591 (* Global constants *)
592
593 let no_link_info = NotLinked
594
595 let add_constant_key kn cb linkinfo env =
596 let new_constants =
597 Cmap_env.add kn (cb,(ref linkinfo, ref None), Constant.canonical kn) env.env_constants in
598 let irr_constants = if cb.const_relevance != Sorts.Relevant
599 then Cmap_env.add kn cb.const_relevance env.irr_constants
600 else env.irr_constants
601 in
602 let constant_hyps = record_global_hyps Cmap_env.add kn cb.const_hyps env.constant_hyps in
603 let symb_pats =
604 match cb.const_body with
605 | Symbol _ ->
606 if not env.rewrite_rules_allowed then raise (RewriteRulesNotAllowed Symb);
607 Cmap_env.add kn [] env.symb_pats
608 | _ -> env.symb_pats
609 in
610 { env with constant_hyps; irr_constants; symb_pats; env_constants = new_constants }
611
612 let add_constant kn cb env =
613 add_constant_key kn cb no_link_info env
614
615 (* constant_type gives the type of a constant *)
616 let constant_type env (kn,u) =
617 let cb = lookup_constant kn env in
618 let uctx = Declareops.constant_polymorphic_context cb in
619 let csts = UVars.AbstractContext.instantiate u uctx in
620 (subst_instance_constr u cb.const_type, csts)
621
622 type const_evaluation_result =
623 | NoBody
624 | Opaque
625 | IsPrimitive of UVars.Instance.t * CPrimitives.t
626 | HasRules of UVars.Instance.t * bool * machine_rewrite_rule list
627
628 exception NotEvaluableConst of const_evaluation_result
629
630 let constant_value_and_type env (kn, u) =
631 let cb = lookup_constant kn env in
632 let uctx = Declareops.constant_polymorphic_context cb in
633 let cst = UVars.AbstractContext.instantiate u uctx in
634 let b' = match cb.const_body with
635 | Def l_body -> Some (subst_instance_constr u l_body)
636 | OpaqueDef _ -> None
637 | Undef _ | Primitive _ | Symbol _ -> None
638 in
639 b', subst_instance_constr u cb.const_type, cst
640
641 (* These functions should be called under the invariant that [env]
642 already contains the constraints corresponding to the constant
643 application. *)
644
645 (* constant_type gives the type of a constant *)
646 let constant_type_in env (kn,u) =
647 let cb = lookup_constant kn env in
648 subst_instance_constr u cb.const_type
649
650 let constant_value_in env (kn,u) =
651 let cb = lookup_constant kn env in
652 match cb.const_body with
653 | Def l_body ->
654 subst_instance_constr u l_body
655 | OpaqueDef _ -> raise (NotEvaluableConst Opaque)
656 | Undef _ -> raise (NotEvaluableConst NoBody)
657 | Primitive p -> raise (NotEvaluableConst (IsPrimitive (u,p)))
658 | Symbol b ->
659 match Cmap_env.find_opt kn env.symb_pats with
660 | Some r -> raise (NotEvaluableConst (HasRules (u, b, r)))
661 | None -> assert false
662
663 let constant_opt_value_in env cst =
664 try Some (constant_value_in env cst)
665 with NotEvaluableConst _ -> None
666
667 (* A global const is evaluable if it is defined and not opaque *)
668 let evaluable_constant kn env =
669 let cb = lookup_constant kn env in
670 match cb.const_body with
671 | Def _ -> true
672 | OpaqueDef _ -> false
673 | Undef _ | Primitive _ | Symbol _ -> false
674
675 let constant_relevance kn env = match Cmap_env.find_opt kn env.irr_constants with
676 | None -> Sorts.Relevant
677 | Some r -> r
678
679 let is_primitive env c =
680 let cb = lookup_constant c env in
681 match cb.Declarations.const_body with
682 | Declarations.Primitive _ -> true
683 | _ -> false
684
685 let is_symbol env c =
686 let cb = lookup_constant c env in
687 match cb.Declarations.const_body with
688 | Declarations.Symbol _ -> true
689 | _ -> false
690
691 let get_primitive env c =
692 let cb = lookup_constant c env in
693 match cb.Declarations.const_body with
694 | Declarations.Primitive p -> Some p
695 | _ -> None
696
697 let is_int63_type env c =
698 match env.retroknowledge.Retroknowledge.retro_int63 with
699 | None -> false
700 | Some c' -> Constant.CanOrd.equal c c'
701
702 let is_float64_type env c =
703 match env.retroknowledge.Retroknowledge.retro_float64 with
704 | None -> false
705 | Some c' -> Constant.CanOrd.equal c c'
706
707 let is_string_type env c =
708 match env.retroknowledge.Retroknowledge.retro_string with
709 | None -> false
710 | Some c' -> Constant.CanOrd.equal c c'
711
712 let is_array_type env c =
713 match env.retroknowledge.Retroknowledge.retro_array with
714 | None -> false
715 | Some c' -> Constant.CanOrd.equal c c'
716
717 let is_primitive_type env c =
718 (* dummy match to force an update if we add a primitive type *)
719 let _ =
720 function
721 | CPrimitives.(PTE(PT_int63))
722 | CPrimitives.(PTE(PT_float64))
723 | CPrimitives.(PTE(PT_string))
724 | CPrimitives.(PTE(PT_array)) -> ()
725 in
726 is_int63_type env c || is_float64_type env c || is_array_type env c ||
727 is_string_type env c
728
729 let polymorphic_constant cst env =
730 Declareops.constant_is_polymorphic (lookup_constant cst env)
731
732 let polymorphic_pconstant (cst,u) env =
733 if UVars.Instance.is_empty u then false
734 else polymorphic_constant cst env
735
736 let type_in_type_constant cst env =
737 not (lookup_constant cst env).const_typing_flags.check_universes
738
739 let lookup_projection p env =
740 let mind,i = Projection.inductive p in
741 let mib = lookup_mind mind env in
742 (if not (Int.equal mib.mind_nparams (Projection.npars p))
743 then anomaly ~label:"lookup_projection" Pp.(str "Bad number of parameters on projection."));
744 match mib.mind_packets.(i).mind_record with
745 | NotRecord | FakeRecord -> anomaly ~label:"lookup_projection" Pp.(str "not a projection")
746 | PrimRecord { relevances; tys; _ } ->
747 let arg = Projection.arg p in
748 relevances.(arg), tys.(arg)
749
750 let get_projection env ind ~proj_arg =
751 let mib = lookup_mind (fst ind) env in
752 Declareops.inductive_make_projection ind mib ~proj_arg
753
754 let get_projections env ind =
755 let mib = lookup_mind (fst ind) env in
756 Option.map fst @@ Declareops.inductive_make_projections ind mib
757
758 (* Mutual Inductives *)
759 let polymorphic_ind (mind,_i) env =
760 Declareops.inductive_is_polymorphic (lookup_mind mind env)
761
762 let polymorphic_pind (ind,u) env =
763 if UVars.Instance.is_empty u then false
764 else polymorphic_ind ind env
765
766 let type_in_type_ind (mind,_i) env =
767 not (lookup_mind mind env).mind_typing_flags.check_universes
768
769 let template_polymorphic_ind (mind,_) env =
770 match (lookup_mind mind env).mind_template with
771 | Some _ -> true
772 | None -> false
773
774 let template_polymorphic_pind (ind,u) env =
775 if not (UVars.Instance.is_empty u) then false
776 else template_polymorphic_ind ind env
777
778 let add_mind_key kn mind link env =
779 let mind_key = (mind, ref link, MutInd.canonical kn) in
780 let new_inds = Mindmap_env.add kn mind_key env.env_inductives in
781 let irr_inds = Array.fold_left_i (fun i irr_inds mip ->
782 if mip.mind_relevance != Sorts.Relevant
783 then Indmap_env.add (kn, i) mip.mind_relevance irr_inds
784 else irr_inds) env.irr_inds mind.mind_packets
785 in
786 let inductive_hyps = record_global_hyps Mindmap_env.add kn mind.mind_hyps env.inductive_hyps in
787 { env with inductive_hyps; irr_inds; env_inductives = new_inds }
788
789 let add_mind kn mib env =
790 let li = no_link_info in add_mind_key kn mib li env
791
792 (* Lookup of section variables *)
793
794 let lookup_constant_variables c env =
795 Option.default Id.Set.empty (Cmap_env.find_opt c env.constant_hyps)
796
797 let lookup_inductive_variables (kn,_i) env =
798 Option.default Id.Set.empty (Mindmap_env.find_opt kn env.inductive_hyps)
799
800 let lookup_constructor_variables (ind,_) env =
801 lookup_inductive_variables ind env
802
803 (* Universes *)
804 let constant_context env c =
805 let cb = lookup_constant c env in
806 Declareops.constant_polymorphic_context cb
807
808 let universes_of_global env r =
809 let open GlobRef in
810 match r with
811 | VarRef _ -> UVars.AbstractContext.empty
812 | ConstRef c -> constant_context env c
813 | IndRef (mind,_) | ConstructRef ((mind,_),_) ->
814 let mib = lookup_mind mind env in
815 Declareops.inductive_polymorphic_context mib
816
817 (* Returns the list of global variables in a term *)
818
819 let vars_of_global env gr =
820 let open GlobRef in
821 match gr with
822 | VarRef id -> Id.Set.singleton id
823 | ConstRef kn -> lookup_constant_variables kn env
824 | IndRef ind -> lookup_inductive_variables ind env
825 | ConstructRef cstr -> lookup_constructor_variables cstr env
826
827 let global_vars_set env constr =
828 let rec filtrec acc c =
829 match destRef c with
830 | gr, _ ->
831 Id.Set.union (vars_of_global env gr) acc
832 | exception DestKO -> Constr.fold filtrec acc c
833 in
834 filtrec Id.Set.empty constr
835
836
837 (* [keep_hyps env ids] keeps the part of the section context of [env] which
838 contains the variables of the set [ids], and recursively the variables
839 contained in the types of the needed variables. *)
840
841 let really_needed env needed =
842 let open! Context.Named.Declaration in
843 Context.Named.fold_inside
844 (fun need decl ->
845 if Id.Set.mem (get_id decl) need then
846 let globc =
847 match decl with
848 | LocalAssum _ -> Id.Set.empty
849 | LocalDef (_,c,_) -> global_vars_set env c in
850 Id.Set.union
851 (global_vars_set env (get_type decl))
852 (Id.Set.union globc need)
853 else need)
854 ~init:needed
855 (named_context env)
856
857 let keep_hyps env needed =
858 let open Context.Named.Declaration in
859 let really_needed = really_needed env needed in
860 Context.Named.fold_outside
861 (fun d nsign ->
862 if Id.Set.mem (get_id d) really_needed then Context.Named.add d nsign
863 else nsign)
864 (named_context env)
865 ~init:empty_named_context
866
867 (* Modules *)
868
869 let add_modtype mp mtb env =
870 let new_modtypes = ModPath.Map.add mp mtb env.env_modtypes in
871 { env with env_modtypes = new_modtypes }
872
873 let shallow_add_module mp mb env =
874 let () = assert (not @@ ModPath.Map.mem mp env.env_modules) in
875 let new_mods = ModPath.Map.add mp mb env.env_modules in
876 { env with env_modules = new_mods }
877
878 let lookup_module mp env =
879 ModPath.Map.find mp env.env_modules
880
881
882 let lookup_modtype mp env =
883 ModPath.Map.find mp env.env_modtypes
884
885 (*s Judgments. *)
886
887 type ('constr, 'types) punsafe_judgment = {
888 uj_val : 'constr;
889 uj_type : 'types }
890
891 let on_judgment f j = { uj_val = f j.uj_val; uj_type = f j.uj_type }
892 let on_judgment_value f j = { j with uj_val = f j.uj_val }
893 let on_judgment_type f j = { j with uj_type = f j.uj_type }
894
895 type unsafe_judgment = (constr, types) punsafe_judgment
896
897 let make_judge v tj =
898 { uj_val = v;
899 uj_type = tj }
900
901 let j_val j = j.uj_val
902 let j_type j = j.uj_type
903
904 type ('types, 'sorts) punsafe_type_judgment = {
905 utj_val : 'types;
906 utj_type : 'sorts }
907
908 type unsafe_type_judgment = (types, Sorts.t) punsafe_type_judgment
909
910 exception Hyp_not_found
911
912 let apply_to_hyp ctxt id f =
913 let open Context.Named.Declaration in
914 let rec aux rtail ctxt =
915 match match_named_context_val ctxt with
916 | Some (d, ctxt) ->
917 if Id.equal (get_id d) id then
918 push_named_context_val (f ctxt.env_named_ctx d rtail) ctxt
919 else
920 let ctxt' = aux (d::rtail) ctxt in
921 push_named_context_val d ctxt'
922 | None -> raise Hyp_not_found
923 in aux [] ctxt
924
925 (* To be used in Logic.clear_hyps *)
926 let remove_hyps ids check_context ctxt =
927 let rec remove_hyps ids ctxt =
928 if Id.Set.is_empty ids then ctxt, false
929 else match match_named_context_val ctxt with
930 | None -> empty_named_context_val, false
931 | Some (d, rctxt) ->
932 let id0 = Context.Named.Declaration.get_id d in
933 let removed = Id.Set.mem id0 ids in
934 let ids = if removed then Id.Set.remove id0 ids else ids in
935 let (ans, seen) = remove_hyps ids rctxt in
936 if removed then (ans, true)
937 else if not seen then ctxt, false
938 else
939 let rctxt' = ans in
940 let d' = check_context d in
941 if d == d' && rctxt == rctxt' then
942 ctxt, true
943 else push_named_context_val d' rctxt', true
944 in
945 fst (remove_hyps ids ctxt)
946
947 (* A general request *)
948
949 let is_polymorphic env r =
950 let open Names.GlobRef in
951 match r with
952 | VarRef _id -> false
953 | ConstRef c -> polymorphic_constant c env
954 | IndRef ind -> polymorphic_ind ind env
955 | ConstructRef cstr -> polymorphic_ind (inductive_of_constructor cstr) env
956
957 let is_template_polymorphic env r =
958 let open Names.GlobRef in
959 match r with
960 | VarRef _id -> false
961 | ConstRef _c -> false
962 | IndRef ind -> template_polymorphic_ind ind env
963 | ConstructRef cstr -> template_polymorphic_ind (inductive_of_constructor cstr) env
964
965 let is_type_in_type env r =
966 let open Names.GlobRef in
967 match r with
968 | VarRef _id -> false
969 | ConstRef c -> type_in_type_constant c env
970 | IndRef ind -> type_in_type_ind ind env
971 | ConstructRef cstr -> type_in_type_ind (inductive_of_constructor cstr) env
972
973 let vm_library env = env.vm_library
974
975 let set_vm_library lib env =
976 { env with vm_library = lib }
977
978 let link_vm_library lib env =
979 let vm_library = Vmlibrary.link lib env.vm_library in
980 { env with vm_library }
981
982 let lookup_vm_code idx env =
983 Vmlibrary.resolve idx env.vm_library
984
985 let set_retroknowledge env r = { env with retroknowledge = r }
986 let retroknowledge env = env.retroknowledge
987
988 module type QS =
989 sig
990 type t
991 val canonize : env -> t -> t
992 end
993
994 module type QMapS =
995 sig
996 type key
997 type (+'a) t
998 val empty: 'a t
999 val is_empty: 'a t -> bool
1000 val mem: env -> key -> 'a t -> bool
1001 val add: env -> key -> 'a -> 'a t -> 'a t
1002 val remove: env -> key -> 'a t -> 'a t
1003 val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
1004 val merge: (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
1005 val find: env -> key -> 'a t -> 'a
1006 val find_opt : env -> key -> 'a t -> 'a option
1007 end
1008
1009 module QMap (M : CSig.UMapS) (Q : QS with type t = M.key) : QMapS with type key = M.key =
1010 struct
1011 type key = M.key
1012 type 'a t = 'a M.t
1013 let empty = M.empty
1014 let is_empty = M.is_empty
1015 let mem env key m = M.mem (Q.canonize env key) m
1016 let add env key v m = M.add (Q.canonize env key) v m
1017 let remove env key m = M.remove (Q.canonize env key) m
1018 let fold = M.fold
1019 let merge = M.merge
1020 let find env key m = M.find (Q.canonize env key) m
1021 let find_opt env key m = M.find_opt (Q.canonize env key) m
1022 end
1023
1024 module type QNameS =
1025 sig
1026 type t
1027 val equal : env -> t -> t -> bool
1028 val compare : env -> t -> t -> int
1029 val hash : env -> t -> int
1030 val canonize : env -> t -> t
1031 end
1032
1033 module type HackQS = sig
1034 (** A type with canonical information separate from the env *)
1035 type t
1036
1037 val canonize : t -> t
1038 module CanOrd : sig
1039 val equal : t -> t -> bool
1040 val compare : t -> t -> int
1041 val hash : t -> int
1042 end
1043 end
1044
1045 module HackQ (X:HackQS) (UserMap:CSig.UMapS with type key = X.t) = struct
1046 module Self = struct
1047 type t = X.t
1048 let canonize _env x = X.canonize x
1049 end
1050 include Self
1051 let equal _env c1 c2 = X.CanOrd.equal c1 c2
1052 let compare _env c1 c2 = X.CanOrd.compare c1 c2
1053 let hash _env c = X.CanOrd.hash c
1054
1055 module Map = QMap(UserMap)(Self)
1056 end
1057
1058 module QConstant = HackQ(Constant)(Cmap_env)
1059
1060 module QMutInd = HackQ(MutInd)(Mindmap_env)
1061
1062 module QInd = HackQ(Ind)(Indmap_env)
1063
1064 module QConstruct = HackQ(Construct)(Constrmap_env)
1065
1066 module QProjection =
1067 struct
1068 include HackQ(Projection)(HMap.Make(Projection.UserOrd))
1069 module Repr = HackQ(Projection.Repr)(HMap.Make(Projection.Repr.UserOrd))
1070 end
1071
1072 module QGlobRef = HackQ(GlobRef)(GlobRef.Map_env)
1073
1074 module Internal = struct
1075 let push_template_context uctx env =
1076 let () = check_ucontext uctx env in
1077 let env = push_context ~strict:false uctx env in
1078 let (qvars, _), _ = UVars.UContext.to_context_set uctx in
1079 let env = map_universes (UGraph.Internal.add_template_qvars qvars) env in
1080 env
1081
1082 let is_above_prop env = UGraph.Internal.is_above_prop (universes env)
1083
1084 module View =
1085 struct
1086 type t = {
1087 env_constants : constant_key Cmap_env.t;
1088 env_inductives : mind_key Mindmap_env.t;
1089 env_modules : module_body ModPath.Map.t;
1090 env_modtypes : module_type_body ModPath.Map.t;
1091 env_named_context : named_context_val;
1092 env_rel_context : rel_context_val;
1093 env_universes : UGraph.t;
1094 env_qualities : Sorts.QVar.Set.t;
1095 env_symb_pats : machine_rewrite_rule list Cmap_env.t;
1096 env_typing_flags : typing_flags;
1097 }
1098
1099 let view (env : env) = {
1100 env_constants = env.env_constants;
1101 env_inductives = env.env_inductives;
1102 env_modtypes = env.env_modtypes;
1103 env_modules = env.env_modules;
1104 env_named_context = env.env_named_context;
1105 env_rel_context = env.env_rel_context;
1106 env_universes = env.env_universes;
1107 env_qualities = QGraph.qvar_domain env.env_qualities;
1108 env_symb_pats = env.symb_pats;
1109 env_typing_flags = env.env_typing_flags;
1110 } [@@ocaml.warning "-42"]
1111
1112 end
1113
1114 let shallow_overwrite_module mp mb env =
1115 let new_mods = ModPath.Map.add mp mb env.env_modules in
1116 { env with env_modules = new_mods }
1117
1118 let rec overwrite_structure mp sign resolver env =
1119 let add_field env (l,elem) = match elem with
1120 | SFBconst cb ->
1121 let c = Mod_subst.constant_of_delta_kn resolver (KerName.make mp l) in
1122 add_constant c cb env
1123 | SFBmind mib ->
1124 let mind = Mod_subst.mind_of_delta_kn resolver (KerName.make mp l) in
1125 add_mind mind mib env
1126 | SFBmodule mb -> overwrite_module (MPdot (mp, l)) mb env
1127 | SFBmodtype mtb -> add_modtype (MPdot (mp, l)) mtb env
1128 | SFBrules r -> add_rewrite_rules r.rewrules_rules env
1129 in
1130 List.fold_left add_field env sign
1131
1132 and overwrite_module mp mb env =
1133 let env = shallow_overwrite_module mp mb env in
1134 match mod_type mb with
1135 | NoFunctor struc ->
1136 let delta = Option.get (Mod_declarations.mod_global_delta mb) in
1137 overwrite_structure mp struc delta env
1138 | MoreFunctor _ -> env
1139
1140 let overwrite_module_parameter mbid mtb env =
1141 overwrite_module (MPbound mbid) (module_body_of_type mtb) env
1142
1143 end