Debian Codegraph @

kernel/safe_typing.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 (* Created by Jean-Christophe Filliâtre as part of the rebuilding of
12 Coq around a purely functional abstract type-checker, Dec 1999 *)
13
14 (* This file provides the entry points to the kernel type-checker. It
15 defines the abstract type of well-formed environments and
16 implements the rules that build well-formed environments.
17
18 An environment is made of constants and inductive types (E), of
19 section declarations (Delta), of local bound-by-index declarations
20 (Gamma) and of universe constraints (C). Below E[Delta,Gamma] |-_C
21 means that the tuple E, Delta, Gamma, C is a well-formed
22 environment. Main rules are:
23
24 empty_environment:
25
26 ------
27 [,] |-
28
29 push_named_assum(a,T):
30
31 E[Delta,Gamma] |-_G
32 ------------------------
33 E[Delta,Gamma,a:T] |-_G'
34
35 push_named_def(a,t,T):
36
37 E[Delta,Gamma] |-_G
38 ---------------------------
39 E[Delta,Gamma,a:=t:T] |-_G'
40
41 add_constant(ConstantEntry(DefinitionEntry(c,t,T))):
42
43 E[Delta,Gamma] |-_G
44 ---------------------------
45 E,c:=t:T[Delta,Gamma] |-_G'
46
47 add_constant(ConstantEntry(ParameterEntry(c,T))):
48
49 E[Delta,Gamma] |-_G
50 ------------------------
51 E,c:T[Delta,Gamma] |-_G'
52 add_mind(Ind(Ind[Gamma_p](Gamma_I:=Gamma_C))):
53
54
55 E[Delta,Gamma] |-_G
56 ------------------------
57 E,Ind[Gamma_p](Gamma_I:=Gamma_C)[Delta,Gamma] |-_G'
58
59 etc.
60 *)
61
62 open Util
63 open Names
64 open Declarations
65 open Mod_declarations
66 open Constr
67 open Context.Named.Declaration
68
69 module NamedDecl = Context.Named.Declaration
70
71 (** {6 Safe environments }
72
73 Fields of [safe_environment] :
74
75 - [env] : the underlying environment (cf Environ)
76 - [modpath] : the current module name
77 - [modvariant] :
78 * NONE before coqtop initialization
79 * LIBRARY at toplevel of a compilation or a regular coqtop session
80 * STRUCT (params,oldsenv) : inside a local module, with
81 module parameters [params] and earlier environment [oldsenv]
82 * SIG (params,oldsenv) : same for a local module type
83 - [modresolver] : delta_resolver concerning the module content, that needs to
84 be marshalled on disk. Its root must be [modpath].
85 - [paramresolver] : delta_resolver in scope but not part of the library per
86 se, that is from functor parameters and required libraries
87 - [revstruct] : current module content, most recent declarations first
88 - [modlabels] and [objlabels] : names defined in the current module,
89 either for modules/modtypes or for constants/inductives.
90 These fields could be deduced from [revstruct], but they allow faster
91 name freshness checks.
92 - [univ] : current universe constraints
93 - [future_cst] : delayed opaque constants yet to be checked
94 - [required] : names and digests of Require'd libraries since big-bang.
95 This field will only grow
96 - [loads] : list of libraries Require'd inside the current module.
97 They will be propagated to the upper module level when
98 the current module ends.
99 - [local_retroknowledge]
100
101 *)
102
103 type vodigest =
104 | Dvo_or_vi of Digest.t (* The digest of the seg_lib part *)
105
106 let digest_match ~actual ~required =
107 match actual, required with
108 | Dvo_or_vi d1, Dvo_or_vi d2 -> String.equal d1 d2
109
110 type library_info = DirPath.t * vodigest
111
112 (** Functor and funsig parameters, most recent first *)
113 type module_parameters = (MBId.t * module_type_body) list
114
115 type permanent_flags = {
116 rewrite_rules_allowed : bool;
117 }
118
119 module ParamResolver :
120 sig
121 type t
122 val empty : DirPath.t -> t
123 val add_delta_resolver : ModPath.t -> Mod_subst.delta_resolver -> t -> t
124 val constant_of_delta_kn : t -> KerName.t -> Constant.t
125 val mind_of_delta_kn : t -> KerName.t -> MutInd.t
126 end =
127 struct
128 type t = {
129 root : DirPath.t;
130 data : Mod_subst.delta_resolver ModPath.Map.t;
131 (** Invariant: No [MPdot] in data *)
132 }
133
134 let empty root = {
135 root = root;
136 data = ModPath.Map.empty;
137 }
138
139 let rec head mp = match mp with
140 | MPfile _ | MPbound _ -> mp
141 | MPdot (mp, _) -> head mp
142
143 let add_delta_resolver mp delta preso =
144 let self = MPfile preso.root in
145 let data =
146 if ModPath.subpath self mp then
147 match ModPath.Map.find_opt self preso.data with
148 | None ->
149 (* we were at toplevel *)
150 ModPath.Map.add self delta preso.data
151 | Some reso ->
152 ModPath.Map.add self (Mod_subst.add_delta_resolver delta reso) preso.data
153 else
154 let () = match mp with
155 | MPfile _ | MPbound _ -> ()
156 | MPdot _ -> assert false
157 in
158 let () = assert (not (ModPath.Map.mem mp preso.data)) in
159 ModPath.Map.add mp delta preso.data
160 in
161 { preso with data }
162
163 let kn_of_delta preso kn =
164 let head = head (KerName.modpath kn) in
165 match ModPath.Map.find_opt head preso.data with
166 | None -> kn
167 | Some delta -> Mod_subst.kn_of_delta delta kn
168
169 let constant_of_delta_kn preso kn = Constant.make kn (kn_of_delta preso kn)
170
171 let mind_of_delta_kn preso kn = MutInd.make kn (kn_of_delta preso kn)
172
173 end
174
175 type compiled_library = {
176 comp_name : DirPath.t;
177 comp_mod : module_body;
178 comp_univs : Univ.ContextSet.t;
179 comp_sorts : Sorts.QContextSet.t;
180 comp_deps : library_info array;
181 comp_flags : permanent_flags;
182 }
183
184 type reimport = compiled_library * Vmlibrary.on_disk * vodigest
185
186 type required_lib = {
187 req_root : bool; (* true if a root of the dependency DAG *)
188 req_digest : vodigest;
189 }
190
191 (** Part of the safe_env at a section opening time to be backtracked *)
192 type section_data = {
193 rev_env : Environ.env;
194 rev_univ : Univ.ContextSet.t;
195 rev_qualities : Sorts.QVar.Set.t * Sorts.ElimConstraints.t;
196 rev_objlabels : Id.Set.t;
197 rev_reimport : reimport list;
198 rev_revstruct : structure_body;
199 rev_paramresolver : ParamResolver.t;
200 }
201
202 module HandleMap = Opaqueproof.HandleMap
203
204 (** We rely on uniqueness of pointers to provide a simple implementation of
205 kernel certificates. For this to work across processes, one needs the
206 safe environments to be marshaled at the same time as their corresponding
207 certificates and sharing to be preserved. *)
208 module Nonce :
209 sig
210 type t
211 val create : unit -> t
212 val equal : t -> t -> bool
213 end =
214 struct
215 type t = unit ref
216 let create () = ref ()
217 let equal x y = x == y
218 end
219
220 type safe_environment =
221 { env : Environ.env;
222 sections : section_data Section.t option;
223 modpath : ModPath.t;
224 modvariant : modvariant;
225 modresolver : Mod_subst.delta_resolver;
226 paramresolver : ParamResolver.t;
227 revstruct : structure_body;
228 modlabels : Id.Set.t;
229 objlabels : Id.Set.t;
230 univ : Univ.ContextSet.t;
231 (* maybe should be a qglobal set? *)
232 qualities : Sorts.QVar.Set.t * Sorts.ElimConstraints.t;
233 future_cst : (Constant_typing.typing_context * safe_environment * Nonce.t) HandleMap.t;
234 required : required_lib DirPath.Map.t;
235 loads : (ModPath.t * module_body) list;
236 local_retroknowledge : Retroknowledge.action list;
237 opaquetab : Opaqueproof.opaquetab;
238 }
239
240 and modvariant =
241 | NONE
242 | LIBRARY
243 | SIG of module_parameters * safe_environment (** saved env *)
244 | STRUCT of module_parameters * safe_environment (** saved env *)
245
246 let rec library_dp_of_senv senv =
247 match senv.modvariant with
248 | NONE | LIBRARY -> ModPath.dp senv.modpath
249 | SIG(_,senv) -> library_dp_of_senv senv
250 | STRUCT(_,senv) -> library_dp_of_senv senv
251
252 let empty_environment =
253 { env = Environ.empty_env;
254 modpath = ModPath.dummy;
255 modvariant = NONE;
256 modresolver = Mod_subst.empty_delta_resolver ModPath.dummy;
257 paramresolver = ParamResolver.empty DirPath.dummy;
258 revstruct = [];
259 modlabels = Id.Set.empty;
260 objlabels = Id.Set.empty;
261 sections = None;
262 future_cst = HandleMap.empty;
263 univ = Univ.ContextSet.empty;
264 qualities = Sorts.QVar.Set.empty, Sorts.ElimConstraints.empty;
265 required = DirPath.Map.empty;
266 loads = [];
267 local_retroknowledge = [];
268 opaquetab = Opaqueproof.empty_opaquetab;
269 }
270
271 let is_initial senv =
272 match senv.revstruct, senv.modvariant with
273 | [], NONE -> ModPath.equal senv.modpath ModPath.dummy
274 | _ -> false
275
276 let sections_are_opened senv = not (Option.is_empty senv.sections)
277
278 let delta_of_senv senv = senv.modresolver
279
280 let constant_of_delta_kn_senv senv kn =
281 let mp = KerName.modpath kn in
282 if ModPath.subpath senv.modpath mp then Mod_subst.constant_of_delta_kn senv.modresolver kn
283 else ParamResolver.constant_of_delta_kn senv.paramresolver kn
284
285 let mind_of_delta_kn_senv senv kn =
286 let mp = KerName.modpath kn in
287 if ModPath.subpath senv.modpath mp then Mod_subst.mind_of_delta_kn senv.modresolver kn
288 else ParamResolver.mind_of_delta_kn senv.paramresolver kn
289
290 (** The safe_environment state monad *)
291
292 type safe_transformer0 = safe_environment -> safe_environment
293 type 'a safe_transformer = safe_environment -> 'a * safe_environment
294
295
296 (** {6 Typing flags } *)
297
298 let set_typing_flags c senv =
299 let env = Environ.set_typing_flags c senv.env in
300 if env == senv.env then senv
301 else { senv with env }
302
303 let set_typing_flags flags senv =
304 (* NB: we allow changing the conv_oracle inside sections because it
305 doesn't matter for consistency. *)
306 if Option.has_some senv.sections
307 && not (Environ.same_flags flags
308 {(Environ.typing_flags senv.env) with
309 conv_oracle = flags.conv_oracle;
310 share_reduction = flags.share_reduction;
311 })
312 then CErrors.user_err Pp.(str "Changing typing flags inside sections is not allowed.");
313 set_typing_flags flags senv
314
315 let set_impredicative_set b senv =
316 let flags = Environ.typing_flags senv.env in
317 set_typing_flags { flags with impredicative_set = b } senv
318
319 let set_check_guarded b senv =
320 let flags = Environ.typing_flags senv.env in
321 set_typing_flags { flags with check_guarded = b } senv
322
323 let set_check_positive b senv =
324 let flags = Environ.typing_flags senv.env in
325 set_typing_flags { flags with check_positive = b } senv
326
327 let set_check_universes b senv =
328 let flags = Environ.typing_flags senv.env in
329 set_typing_flags { flags with check_universes = b } senv
330
331 let set_indices_matter indices_matter senv =
332 set_typing_flags { (Environ.typing_flags senv.env) with indices_matter } senv
333
334 let set_share_reduction b senv =
335 let flags = Environ.typing_flags senv.env in
336 set_typing_flags { flags with share_reduction = b } senv
337
338 let set_VM b senv =
339 let flags = Environ.typing_flags senv.env in
340 set_typing_flags { flags with enable_VM = b } senv
341
342 let set_native_compiler b senv =
343 let flags = Environ.typing_flags senv.env in
344 set_typing_flags { flags with enable_native_compiler = b } senv
345
346 let set_allow_sprop b senv = { senv with env = Environ.set_allow_sprop b senv.env }
347
348 let set_rewrite_rules_allowed b senv =
349 if b then { senv with env = Environ.allow_rewrite_rules senv.env }
350 else senv
351
352 (* Temporary sets custom typing flags *)
353 let with_typing_flags ?typing_flags senv ~f =
354 match typing_flags with
355 | None -> f senv
356 | Some typing_flags ->
357 let orig_typing_flags = Environ.typing_flags senv.env in
358 let res, senv = f (set_typing_flags typing_flags senv) in
359 res, set_typing_flags orig_typing_flags senv
360
361 (** {6 Stm machinery } *)
362
363 module Certificate :
364 sig
365 type t
366
367 val make : safe_environment -> t
368
369 val universes : t -> Univ.ContextSet.t
370
371 (** Checks whether [dst] is a valid extension of [src] by 1 declaration,
372 possibly adding universes and constraints. *)
373 val safe_extend : src:t -> dst:t -> t option
374
375 (** [compatible src dst] checks whether [dst] adds exactly 1 declaration
376 to an ancestor of [src].
377 If it does, the declaration is also valid in [src] (up to universes). *)
378 val compatible : safe_environment -> t -> bool
379 end =
380 struct
381
382 type t = {
383 certif_struc : Mod_declarations.structure_body;
384 certif_univs : Univ.ContextSet.t;
385 }
386
387 let make senv = {
388 certif_struc = senv.revstruct;
389 certif_univs = senv.univ;
390 }
391
392 let is_suffix l suf = match l with
393 | [] -> false
394 | _ :: l -> l == suf
395
396 let safe_extend ~src ~dst =
397 if is_suffix dst.certif_struc src.certif_struc then
398 Some { certif_struc = dst.certif_struc;
399 certif_univs = Univ.ContextSet.union src.certif_univs dst.certif_univs }
400 else None
401
402 let compatible src dst =
403 let dst = dst.certif_struc in
404 let src = src.revstruct in
405 match dst with
406 | [] -> false
407 | _ :: dst_base ->
408 let rec aux src =
409 src == dst_base || match src with
410 | [] -> false
411 | _ :: src -> aux src
412 in
413 aux src
414
415 let universes c = c.certif_univs
416
417 end
418
419 type side_effect = {
420 seff_certif : Certificate.t CEphemeron.key;
421 seff_constant : Constant.t;
422 seff_body : HConstr.t option * (Constr.t, Vmemitcodes.body_code option) Declarations.pconstant_body;
423 seff_univs : Univ.ContextSet.t;
424 }
425 (* Invariant: For any senv, if [Certificate.safe_extend senv seff_certif] returns [Some certif'] then
426 [senv + Certificate.universes certif' + (c.seff_constant -> seff_body)] is well-formed
427 (if no univ inconsistency). *)
428
429 module SideEffects :
430 sig
431 type t
432 val repr : t -> side_effect list
433 val empty : t
434 val is_empty : t -> bool
435 val add : side_effect -> t -> t
436 val concat : t -> t -> t
437 val length : t -> int
438 val pop : t -> int -> t * t
439 end =
440 struct
441
442 module SeffOrd = struct
443 type t = side_effect
444 let compare e1 e2 =
445 Constant.UserOrd.compare e1.seff_constant e2.seff_constant
446 end
447
448 module SeffSet = Set.Make(SeffOrd)
449
450 type t = { seff : side_effect list; elts : SeffSet.t; len : int }
451 (** Invariant: [seff] is a permutation of the elements of [elts] *)
452
453 let repr eff = eff.seff
454 let empty = { seff = []; elts = SeffSet.empty; len = 0 }
455 let is_empty { seff; elts; _ } = List.is_empty seff && SeffSet.is_empty elts
456 let add x es =
457 if SeffSet.mem x es.elts then es
458 else { seff = x :: es.seff; elts = SeffSet.add x es.elts; len = es.len + 1 }
459 let concat xes yes =
460 List.fold_right add xes.seff yes
461
462 let length eff = eff.len
463
464 let pop eff n =
465 let () = assert (n <= eff.len) in
466 let top, rem = List.chop n eff.seff in
467 let fold accu x = SeffSet.remove x accu in
468 let elts = List.fold_left fold eff.elts top in
469 { seff = top; len = n; elts = SeffSet.of_list top }, { seff = rem; len = eff.len - n; elts }
470
471 end
472
473 type private_constants = SideEffects.t
474
475 let debug_print_private_constants seff =
476 let open Pp in
477 prlist_with_sep spc (fun seff -> Constant.print seff.seff_constant) (SideEffects.repr seff)
478
479 let side_effects_of_private_constants l =
480 List.rev (SideEffects.repr l)
481
482 let length_private = SideEffects.length
483 let pop_private = SideEffects.pop
484
485 (* Only used to push in an Environ.env. *)
486 let lift_constant c =
487 let body = match c.const_body with
488 | OpaqueDef _ -> Undef None
489 | Def _ | Undef _ | Primitive _ | Symbol _ as body -> body
490 in
491 { c with const_body = body }
492
493 let push_bytecode vmtab code =
494 let open Vmemitcodes in
495 let vmtab, code = match code with
496 | None -> vmtab, None
497 | Some (BCdefined (mask, code, patches)) ->
498 let vmtab, index = Vmlibrary.add code vmtab in
499 vmtab, Some (BCdefined (mask, index, patches))
500 | Some BCconstant -> vmtab, Some BCconstant
501 | Some (BCalias kn) -> vmtab, Some (BCalias kn)
502 in
503 vmtab, code
504
505 let push_private_constants env eff =
506 let eff = side_effects_of_private_constants eff in
507 let add_if_undefined env eff =
508 if Environ.mem_constant eff.seff_constant env then env
509 else
510 let (_hbody, cb) = eff.seff_body in
511 let vmtab, code = push_bytecode (Environ.vm_library env) cb.const_body_code in
512 let cb = { cb with const_body_code = code } in
513 let env = Environ.set_vm_library vmtab env in
514 Environ.add_constant eff.seff_constant (lift_constant cb) env
515 in
516 List.fold_left add_if_undefined env eff
517
518 let empty_private_constants = SideEffects.empty
519 let is_empty_private_constants c = SideEffects.is_empty c
520 let concat_private = SideEffects.concat
521
522 let universes_of_private eff =
523 let fold acc eff = Univ.ContextSet.union eff.seff_univs acc in
524 List.fold_left fold Univ.ContextSet.empty (side_effects_of_private_constants eff)
525
526 let constants_of_private eff =
527 let fold acc eff = eff.seff_constant :: acc in
528 List.fold_left fold [] (side_effects_of_private_constants eff)
529
530 let env_of_safe_env senv = senv.env
531 let env_of_senv = env_of_safe_env
532
533 let structure_body_of_safe_env env = env.revstruct
534
535 let sections_of_safe_env senv = senv.sections
536
537 let rec is_modtype senv =
538 match senv.modvariant with
539 | STRUCT (_,senv) -> is_modtype senv
540 | SIG _ -> true
541 | NONE | LIBRARY -> false
542
543 let get_section = function
544 | None -> CErrors.user_err Pp.(str "No open section.")
545 | Some s -> s
546
547 let push_context_set ~strict cst senv =
548 if Univ.ContextSet.is_empty cst then senv
549 else
550 let sections = Option.map (Section.push_level_constraints cst) senv.sections
551 in
552 { senv with
553 env = Environ.push_context_set ~strict cst senv.env;
554 univ = Univ.ContextSet.union cst senv.univ;
555 sections }
556
557 let push_qualities ~rigid qs senv =
558 if Sorts.QVar.Set.is_empty (fst qs) && Sorts.ElimConstraints.is_empty (snd qs) then
559 senv
560 else if is_modtype senv then
561 CErrors.user_err (Pp.str "Cannot declare global sort qualities inside module types.")
562 else if Option.has_some senv.sections then
563 CErrors.user_err (Pp.str "Cannot declare global sort qualities inside sections")
564 else
565 let check_local qv = match Sorts.QVar.repr qv with
566 | Sorts.QVar.Global gv ->
567 let (dp, _) = Sorts.QGlobal.repr gv in
568 let () = assert (DirPath.equal dp (ModPath.dp senv.modpath)) in
569 assert (not @@ QGraph.is_declared (Sorts.Quality.QVar qv) (Environ.qualities senv.env))
570 | Sorts.QVar.Unif _ | Sorts.QVar.Var _ -> assert false
571 in
572 let () = Sorts.QVar.Set.iter check_local (fst qs) in
573 { senv with
574 env = Environ.push_qualities ~rigid qs senv.env ;
575 qualities = Sorts.QContextSet.union qs senv.qualities ;
576 }
577
578 let is_curmod_library senv =
579 match senv.modvariant with LIBRARY -> true | _ -> false
580
581 let is_joined_environment e = HandleMap.is_empty e.future_cst
582
583 (** {6 Various checks } *)
584
585 let exists_modlabel l senv = Id.Set.mem l senv.modlabels
586 let exists_objlabel l senv = Id.Set.mem l senv.objlabels
587
588 let check_modlabel l senv =
589 if exists_modlabel l senv then Modops.error_existing_label l
590
591 let check_objlabel l senv =
592 if exists_objlabel l senv then Modops.error_existing_label l
593
594 let check_objlabels ls senv =
595 Id.Set.iter (fun l -> check_objlabel l senv) ls
596
597 (** Are we closing the right module / modtype ?
598 No user error here, since the opening/ending coherence
599 is now verified in [vernac_end_segment] *)
600
601 let check_current_label lab = function
602 | MPdot (_,l) -> assert (Id.equal lab l)
603 | _ -> assert false
604
605 let check_struct = function
606 | STRUCT (params,oldsenv) -> params, oldsenv
607 | NONE | LIBRARY | SIG _ -> assert false
608
609 let check_sig = function
610 | SIG (params,oldsenv) -> params, oldsenv
611 | NONE | LIBRARY | STRUCT _ -> assert false
612
613 let check_current_library dir senv = match senv.modvariant with
614 | LIBRARY -> assert (ModPath.equal senv.modpath (MPfile dir))
615 | NONE | STRUCT _ | SIG _ -> assert false (* cf Lib.end_compilation *)
616
617 (** When operating on modules, we're normally outside sections *)
618
619 let check_empty_context senv =
620 assert (Environ.empty_context senv.env && Option.is_empty senv.sections)
621
622 (** When adding a parameter to the current module/modtype,
623 it must have been freshly started *)
624
625 let check_empty_struct senv =
626 assert (List.is_empty senv.revstruct
627 && List.is_empty senv.loads)
628
629 (** When loading a library, its dependencies should be already there,
630 with the correct digests. *)
631
632 let check_required current_libs needed =
633 let check current (id, required) = match DirPath.Map.find_opt id current with
634 | None ->
635 CErrors.user_err Pp.(pr_sequence str ["Reference to unknown module"; DirPath.to_string id; "."])
636 | Some { req_root; req_digest = actual } ->
637 if not (digest_match ~actual ~required) then
638 CErrors.user_err Pp.(pr_sequence str
639 ["Inconsistent assumptions over module"; DirPath.to_string id; "."])
640 else if req_root then
641 (* the library is being transitively required, not a root anymore *)
642 DirPath.Map.set id { req_root = false; req_digest = actual } current
643 else
644 (* nothing to do *)
645 current
646 in
647 Array.fold_left check current_libs needed
648
649 (** When loading a library, the current flags should match
650 those needed for the library *)
651
652 let check_flags_for_library lib senv =
653 let { rewrite_rules_allowed } = lib.comp_flags in
654 set_rewrite_rules_allowed rewrite_rules_allowed senv
655
656 (** {6 Insertion of section variables} *)
657
658 (** They are now typed before being added to the environment.
659 Same as push_named, but check that the variable is not already
660 there. Should *not* be done in Environ because tactics add temporary
661 hypothesis many many times, and the check performed here would
662 cost too much. *)
663
664 let safe_push_named d env =
665 let id = NamedDecl.get_id d in
666 let _ =
667 try
668 let _ = Environ.lookup_named id env in
669 CErrors.user_err Pp.(pr_sequence str ["Identifier"; Id.to_string id; "already defined."])
670 with Not_found -> () in
671 Environ.push_named d env
672
673 let push_named_def (id,de) senv =
674 let sections = get_section senv.sections in
675 let c, r, typ = Constant_typing.infer_local_def senv.env id de in
676 let d = LocalDef (Context.make_annot id r, c, typ) in
677 let env'' = safe_push_named d senv.env in
678 let sections = Section.push_local d sections in
679 { senv with sections=Some sections; env = env'' }
680
681 let push_named_assum (x,t) senv =
682 let sections = get_section senv.sections in
683 let t, r = Constant_typing.infer_local_assum senv.env t in
684 let d = LocalAssum (Context.make_annot x r, t) in
685 let sections = Section.push_local d sections in
686 let env'' = safe_push_named d senv.env in
687 { senv with sections=Some sections; env = env'' }
688
689 let push_section_context uctx senv =
690 let sections = get_section senv.sections in
691 let sections = Section.push_local_universe_context uctx sections in
692 let senv = { senv with sections=Some sections } in
693 let qctx, ctx = UVars.UContext.to_context_set uctx in
694 let check_quality q =
695 Sorts.QVar.is_global q &&
696 not (QGraph.is_declared (Sorts.Quality.QVar q) (Environ.qualities senv.env))
697 in
698 let () = assert (Sorts.QVar.Set.for_all check_quality (fst qctx)) in
699 let check_fresh u = match UGraph.check_declared_universes (Environ.universes senv.env) (Univ.Level.Set.singleton u) with
700 | Result.Ok _ -> assert false
701 | Result.Error _ -> ()
702 in
703 let () = Univ.Level.Set.iter check_fresh (fst ctx) in
704 let env = Environ.push_context_set ~strict:false ctx senv.env in
705 (* FIXME: check validity of the sort context *)
706 (* FIXME: marking the section-local sorts as rigid makes little sense *)
707 let env = Environ.push_qualities ~rigid:true qctx env in
708 { senv with
709 env;
710 univ = Univ.ContextSet.union ctx senv.univ ;
711 qualities = Sorts.QContextSet.union qctx senv.qualities }
712
713 (** {6 Insertion of new declarations to current environment } *)
714
715 let labels_of_mib mib =
716 let add,get =
717 let labels = ref Id.Set.empty in
718 (fun id -> labels := Id.Set.add id !labels),
719 (fun () -> !labels)
720 in
721 let visit_mip mip =
722 add mip.mind_typename;
723 Array.iter add mip.mind_consnames
724 in
725 Array.iter visit_mip mib.mind_packets;
726 get ()
727
728 let add_retroknowledge pttc senv =
729 { senv with
730 env = Primred.add_retroknowledge senv.env pttc;
731 local_retroknowledge = pttc::senv.local_retroknowledge }
732
733 (** A generic function for adding a new field in a same environment.
734 It also performs the corresponding [add_constraints]. *)
735
736 type generic_name =
737 | C of Constant.t
738 | I of MutInd.t
739 | R
740 | M of ModPath.t
741 | MT of ModPath.t
742
743 let add_field ((l,sfb) as field) gn senv =
744 let mlabs,olabs = match sfb with
745 | SFBmind mib ->
746 let l = labels_of_mib mib in
747 check_objlabels l senv; (Id.Set.empty,l)
748 | SFBconst _ | SFBrules _ ->
749 check_objlabel l senv; (Id.Set.empty, Id.Set.singleton l)
750 | SFBmodule _ | SFBmodtype _ ->
751 check_modlabel l senv; (Id.Set.singleton l, Id.Set.empty)
752 in
753 let env' = match sfb, gn with
754 | SFBconst cb, C con -> Environ.add_constant con cb senv.env
755 | SFBmind mib, I mind -> Environ.add_mind mind mib senv.env
756 | SFBmodtype mtb, MT mp -> Environ.add_modtype mp mtb senv.env
757 | SFBmodule mb, M mp -> Modops.add_module mp mb senv.env
758 | SFBrules r, R -> Environ.add_rewrite_rules r.rewrules_rules senv.env
759 | _ -> assert false
760 in
761 let sections = match senv.sections with
762 | None -> None
763 | Some sections ->
764 match sfb, gn with
765 | SFBconst cb, C con ->
766 let poly = Declareops.constant_is_polymorphic cb in
767 Some Section.(push_global ~poly env' (SecDefinition con) sections)
768 | SFBmind mib, I mind ->
769 let poly = Declareops.inductive_is_polymorphic mib in
770 Some Section.(push_global ~poly env' (SecInductive mind) sections)
771 | _, (M _ | MT _) -> Some sections
772 | _ -> assert false
773 in
774 { senv with
775 env = env';
776 sections;
777 revstruct = field :: senv.revstruct;
778 modlabels = Id.Set.union mlabs senv.modlabels;
779 objlabels = Id.Set.union olabs senv.objlabels }
780
781 (** Applying a certain function to the resolver of a safe environment *)
782
783 let update_resolver f senv = { senv with modresolver = f senv.modresolver }
784
785 type exported_opaque = {
786 exp_handle : Opaqueproof.opaque_handle;
787 exp_body : Constr.t;
788 exp_univs : (int * int) option;
789 (* Minimal amount of data needed to rebuild the private universes. We enforce
790 in the API that private constants have no internal constraints. *)
791 }
792 type exported_private_constant = Constant.t * exported_opaque option
793
794 let repr_exported_opaque o =
795 let priv = match o .exp_univs with
796 | None -> Opaqueproof.PrivateMonomorphic ()
797 | Some _ -> Opaqueproof.PrivatePolymorphic Univ.ContextSet.empty
798 in
799 (o.exp_handle, (o.exp_body, priv))
800
801 let set_vm_library lib senv =
802 { senv with env = Environ.set_vm_library lib senv.env }
803
804 let push_const_bytecode senv cb =
805 let vmtab, code = push_bytecode (Environ.vm_library senv.env) cb.const_body_code in
806 let cb = { cb with const_body_code = code } in
807 let senv = set_vm_library vmtab senv in
808 senv, cb
809
810 let make_hbody = function
811 | None -> None
812 | Some hc -> Some (fun c ->
813 assert (c == HConstr.self hc);
814 snd @@ HConstr.hcons hc)
815
816 let add_constant_aux senv ?hbody (kn, cb) =
817 let l = Constant.label kn in
818 (* This is the only place where we hashcons the contents of a constant body *)
819 let senv, cb = push_const_bytecode senv cb in
820 let cb = if sections_are_opened senv then cb else
821 Declareops.hcons_const_body ?hbody:(make_hbody hbody) cb
822 in
823 let senv' = add_field (l,SFBconst cb) (C kn) senv in
824 let senv'' = match cb.const_body with
825 | Undef (Some lev) ->
826 update_resolver
827 (Mod_subst.add_inline_delta_resolver (Constant.user kn) (lev,None)) senv'
828 | _ -> senv'
829 in
830 senv''
831
832 let inline_side_effects env body side_eff =
833 let open Constr in
834 (** First step: remove the constants that are still in the environment *)
835 let filter e =
836 if Environ.mem_constant e.seff_constant env then None
837 else Some e
838 in
839 (* CAVEAT: we assure that most recent effects come first *)
840 let side_eff = List.map_filter filter (SideEffects.repr side_eff) in
841 let sigs = List.rev_map (fun e -> e.seff_constant, e.seff_certif) side_eff in
842 (** Most recent side-effects first in side_eff *)
843 if List.is_empty side_eff then (body, Univ.ContextSet.empty, sigs, 0)
844 else
845 (** Second step: compute the lifts and substitutions to apply *)
846 let cname c r = Context.make_annot (Name (Constant.label c)) r in
847 let fold (subst, var, ctx, args) { seff_constant = c; seff_body = (_hbody, cb); seff_univs = univs; _ } =
848 let (b, opaque) = match cb.const_body with
849 | Def b -> (b, false)
850 | OpaqueDef b -> (b, true)
851 | _ -> assert false
852 in
853 match cb.const_universes with
854 | Monomorphic ->
855 (** Abstract over the term at the top of the proof *)
856 let ty = cb.const_type in
857 let subst = Cmap_env.add c (Inr var) subst in
858 let ctx = Univ.ContextSet.union ctx univs in
859 (subst, var + 1, ctx, (cname c cb.const_relevance, b, ty, opaque) :: args)
860 | Polymorphic _ ->
861 let () = assert (Univ.ContextSet.is_empty univs) in
862 (** Inline the term to emulate universe polymorphism *)
863 let subst = Cmap_env.add c (Inl b) subst in
864 (subst, var, ctx, args)
865 in
866 let (subst, len, ctx, args) = List.fold_left fold (Cmap_env.empty, 1, Univ.ContextSet.empty, []) side_eff in
867 (** Third step: inline the definitions *)
868 let rec subst_const i k t = match Constr.kind t with
869 | Const (c, u) ->
870 let data = try Some (Cmap_env.find c subst) with Not_found -> None in
871 begin match data with
872 | None -> t
873 | Some (Inl b) ->
874 (** [b] is closed but may refer to other constants *)
875 subst_const i k (Vars.subst_instance_constr u b)
876 | Some (Inr n) ->
877 mkRel (k + n - i)
878 end
879 | Rel n ->
880 (** Lift free rel variables *)
881 if n <= k then t
882 else mkRel (n + len - i - 1)
883 | _ -> Constr.map_with_binders ((+) 1) (fun k t -> subst_const i k t) k t
884 in
885 let map_args i (na, b, ty, opaque) =
886 (** Both the type and the body may mention other constants *)
887 let ty = subst_const (len - i - 1) 0 ty in
888 let b = subst_const (len - i - 1) 0 b in
889 (na, b, ty, opaque)
890 in
891 let args = List.mapi map_args args in
892 let body = subst_const 0 0 body in
893 let fold_arg (na, b, ty, opaque) accu =
894 if opaque then mkApp (mkLambda (na, ty, accu), [|b|])
895 else mkLetIn (na, b, ty, accu)
896 in
897 let body = List.fold_right fold_arg args body in
898 (body, ctx, sigs, len - 1)
899
900 let inline_private_constants env ((body, ctx), side_eff) =
901 let body, ctx', _, _ = inline_side_effects env body side_eff in
902 let ctx' = Univ.ContextSet.union ctx ctx' in
903 (body, ctx')
904
905 let warn_failed_cert = CWarnings.create ~name:"failed-abstract-certificate"
906 ~category:CWarnings.CoreCategories.tactics ~default:CWarnings.AsError
907 Pp.(fun kn ->
908 str "Certificate for private constant " ++
909 Id.print (Constant.label kn) ++
910 str " failed.")
911
912 (* Given the list of signatures of side effects, checks if they match.
913 * I.e. if they are ordered descendants of an ancestor of the current revstruct.
914 Returns the universes needed to trust the side effects (None if they can't be trusted). *)
915 let check_signatures senv sl =
916 match sl with
917 | [] -> Ok Univ.ContextSet.empty
918 | (firstkn,first) :: rest ->
919 match CEphemeron.get first with
920 | exception CEphemeron.InvalidKey -> Error None
921 | first ->
922 if not (Certificate.compatible senv first) then Error (Some firstkn)
923 else
924 let is_direct_ancestor curmb (kn, mb) =
925 match CEphemeron.get mb with
926 | exception CEphemeron.InvalidKey -> Error None
927 | mb ->
928 let mb = Certificate.safe_extend ~src:curmb ~dst:mb in
929 match mb with
930 | None -> Error (Some kn)
931 | Some mb -> Ok mb
932 in
933 let accu = List.fold_left_error is_direct_ancestor first rest in
934 match accu with
935 | Error _ as e -> e
936 | Ok mb ->
937 let univs = Certificate.universes mb in
938 Ok (Univ.ContextSet.diff univs senv.univ)
939
940 let check_signatures senv sl =
941 match check_signatures senv sl with
942 | Ok univs -> Some univs
943 | Error None ->
944 (* don't warn when the issue is an invalid ephemeron *)
945 None
946 | Error (Some kn) -> warn_failed_cert kn; None
947
948 type side_effect_declaration =
949 | DefinitionEff : Entries.definition_entry -> side_effect_declaration
950 | OpaqueEff : Constr.constr Entries.opaque_entry -> side_effect_declaration
951
952 let constant_entry_of_side_effect eff =
953 let (_hbody, cb) = eff.seff_body in
954 let open Entries in
955 let univs =
956 match cb.const_universes with
957 | Monomorphic ->
958 Monomorphic_entry
959 | Polymorphic auctx ->
960 Polymorphic_entry (UVars.AbstractContext.repr auctx)
961 in
962 let p =
963 match cb.const_body with
964 | OpaqueDef b -> b
965 | Def b -> b
966 | _ -> assert false in
967 if Declareops.is_opaque cb then
968 OpaqueEff {
969 opaque_entry_body = p;
970 opaque_entry_secctx = Context.Named.to_vars cb.const_hyps;
971 opaque_entry_type = cb.const_type;
972 opaque_entry_universes = univs;
973 }
974 else
975 DefinitionEff {
976 definition_entry_body = p;
977 definition_entry_secctx = Some (Context.Named.to_vars cb.const_hyps);
978 definition_entry_type = Some cb.const_type;
979 definition_entry_universes = univs;
980 definition_entry_inline_code = cb.const_inline_code }
981
982 let export_eff eff =
983 (eff.seff_constant, eff.seff_body)
984
985 let is_empty_private = function
986 | Opaqueproof.PrivateMonomorphic ctx -> Univ.ContextSet.is_empty ctx
987 | Opaqueproof.PrivatePolymorphic ctx -> Univ.ContextSet.is_empty ctx
988
989 let compile_bytecode env cb =
990 let code = Vmbytegen.compile_constant_body ~fail_on_error:false env cb.const_universes cb.const_body in
991 { cb with const_body_code = code }
992
993 (* Special function to call when the body of an opaque definition is provided.
994 It performs the type-checking of the body immediately. *)
995 let infer_direct_opaque ~sec_univs env ce =
996 let cb, ctx = Constant_typing.infer_opaque ~sec_univs env ce in
997 let body = ce.Entries.opaque_entry_body, Univ.ContextSet.empty in
998 let handle _env c () = (c, Univ.ContextSet.empty, 0) in
999 let (hbody, c, u) = Constant_typing.check_delayed handle ctx (body, ()) in
1000 (* No constraints can be generated, we set it empty everywhere *)
1001 let () = assert (is_empty_private u) in
1002 hbody, { cb with const_body = OpaqueDef c }
1003
1004 let export_side_effects senv eff =
1005 let sec_univs = Option.map Section.all_poly_univs senv.sections in
1006 let env = senv.env in
1007 let not_exists e = not (Environ.mem_constant e.seff_constant env) in
1008 let aux (acc,sl) e =
1009 if not (not_exists e) then acc, sl
1010 else e :: acc, (e.seff_constant, e.seff_certif) :: sl in
1011 let seff, signatures = List.fold_left aux ([],[]) (SideEffects.repr eff) in
1012 let trusted = check_signatures senv signatures in
1013 let push_seff env eff =
1014 let { seff_constant = kn; seff_body = (_hbody, cb); _ } = eff in
1015 let vmtab, code = push_bytecode (Environ.vm_library env) cb.const_body_code in
1016 let env = Environ.set_vm_library vmtab env in
1017 let cb = { cb with const_body_code = code } in
1018 let env = Environ.add_constant kn (lift_constant cb) env in
1019 env
1020 in
1021 match trusted with
1022 | Some univs ->
1023 univs, List.map export_eff seff
1024 | None ->
1025 let rec recheck_seff seff univs acc env = match seff with
1026 | [] -> univs, List.rev acc
1027 | eff :: rest ->
1028 let uctx = eff.seff_univs in
1029 let env = Environ.push_context_set ~strict:true uctx env in
1030 let univs = Univ.ContextSet.union uctx univs in
1031 let env, cb =
1032 let ce = constant_entry_of_side_effect eff in
1033 let hbody, cb = match ce with
1034 | DefinitionEff ce ->
1035 Constant_typing.infer_definition ~sec_univs env ce
1036 | OpaqueEff ce ->
1037 infer_direct_opaque ~sec_univs env ce
1038 in
1039 let cb = compile_bytecode env cb in
1040 let eff = { eff with seff_body = (hbody, cb) } in
1041 (push_seff env eff, export_eff eff)
1042 in
1043 recheck_seff rest univs (cb :: acc) env
1044 in
1045 recheck_seff seff Univ.ContextSet.empty [] env
1046
1047 let push_opaque_proof senv =
1048 let o, otab = Opaqueproof.create (library_dp_of_senv senv) senv.opaquetab in
1049 let senv = { senv with opaquetab = otab } in
1050 senv, o
1051
1052 let export_private_constants eff senv =
1053 let uctx, exported = export_side_effects senv eff in
1054 let senv = push_context_set ~strict:true uctx senv in
1055 let map senv (kn, (hbody, c)) = match c.const_body with
1056 | OpaqueDef body ->
1057 (* Don't care about the body, it has been checked by {!infer_direct_opaque} *)
1058 let senv, o = push_opaque_proof senv in
1059 let (_, _, _, h) = Opaqueproof.repr o in
1060 let univs = match c.const_universes with
1061 | Monomorphic -> None
1062 | Polymorphic auctx -> Some (UVars.AbstractContext.size auctx)
1063 in
1064 (* Hashcons now, before storing in the opaque table *)
1065 let _, body = match hbody with
1066 | None -> Constr.hcons body
1067 | Some hbody ->
1068 let () = assert (HConstr.self hbody == body) in
1069 HConstr.hcons hbody
1070 in
1071 let opaque = { exp_body = body; exp_handle = h; exp_univs = univs } in
1072 senv, (kn, { c with const_body = OpaqueDef o }, Some opaque, None)
1073 | Def _ | Undef _ | Primitive _ | Symbol _ as body ->
1074 (* Hashconsing is handled by {!add_constant_aux}, propagate hbody *)
1075 senv, (kn, { c with const_body = body }, None, hbody)
1076 in
1077 let senv, bodies = List.fold_left_map map senv exported in
1078 let exported = List.map (fun (kn, _, opaque, _) -> kn, opaque) bodies in
1079 (* No delayed constants to declare *)
1080 let fold senv (kn, cb, _, hbody) = add_constant_aux ?hbody senv (kn, cb) in
1081 let senv = List.fold_left fold senv bodies in
1082 exported, senv
1083
1084 let add_constant l decl senv =
1085 let kn = Constant.make2 senv.modpath l in
1086 let senv, (hbody, cb) =
1087 let sec_univs = Option.map Section.all_poly_univs senv.sections in
1088 match decl with
1089 | Entries.OpaqueEntry ce ->
1090 let senv, o = push_opaque_proof senv in
1091 let cb, ctx = Constant_typing.infer_opaque ~sec_univs senv.env ce in
1092 (* Push the delayed data in the environment *)
1093 let (_, _, _, i) = Opaqueproof.repr o in
1094 let nonce = Nonce.create () in
1095 let future_cst = HandleMap.add i (ctx, senv, nonce) senv.future_cst in
1096 let senv = { senv with future_cst } in
1097 senv, (None, { cb with const_body = OpaqueDef o })
1098 | Entries.DefinitionEntry entry ->
1099 senv, Constant_typing.infer_definition ~sec_univs senv.env entry
1100 | Entries.ParameterEntry entry ->
1101 senv, (None, Constant_typing.infer_parameter ~sec_univs senv.env entry)
1102 | Entries.PrimitiveEntry entry ->
1103 let senv = match entry with
1104 | { Entries.prim_entry_content = CPrimitives.OT_type t; _ } ->
1105 if sections_are_opened senv then CErrors.anomaly (Pp.str "Primitive type not allowed in sections");
1106 add_retroknowledge (Retroknowledge.Register_type(t,kn)) senv
1107 | _ -> senv in
1108 senv, (None, Constant_typing.infer_primitive senv.env entry)
1109 | Entries.SymbolEntry entry ->
1110 senv, (None, Constant_typing.infer_symbol senv.env entry)
1111 in
1112 let cb = compile_bytecode senv.env cb in
1113 let senv = add_constant_aux senv ?hbody (kn, cb) in
1114 kn, senv
1115
1116 let add_constant ?typing_flags l decl senv =
1117 with_typing_flags ?typing_flags senv ~f:(add_constant l decl)
1118
1119 type opaque_certificate = {
1120 opq_body : Constr.t;
1121 opq_univs : Univ.ContextSet.t Opaqueproof.delayed_universes;
1122 opq_handle : Opaqueproof.opaque_handle;
1123 opq_nonce : Nonce.t;
1124 }
1125
1126 let check_opaque senv (i : Opaqueproof.opaque_handle) pf =
1127 let ty_ctx, trust, nonce =
1128 try HandleMap.find i senv.future_cst
1129 with Not_found ->
1130 CErrors.anomaly Pp.(str "Missing opaque with identifier " ++ int (Opaqueproof.repr_handle i))
1131 in
1132 let handle env body eff =
1133 let body, uctx, signatures, skip = inline_side_effects env body eff in
1134 let trusted = check_signatures trust signatures in
1135 let trusted, uctx = match trusted with
1136 | None -> 0, uctx
1137 | Some univs -> skip, Univ.ContextSet.union univs uctx
1138 in
1139 body, uctx, trusted
1140 in
1141 let (hbody, c, ctx) = Constant_typing.check_delayed handle ty_ctx pf in
1142 let _, c = match hbody with
1143 | Some hbody -> assert (c == HConstr.self hbody); HConstr.hcons hbody
1144 | None -> Constr.hcons c
1145 in
1146 let ctx = match ctx with
1147 | Opaqueproof.PrivateMonomorphic u ->
1148 Opaqueproof.PrivateMonomorphic (snd @@ Univ.ContextSet.hcons u)
1149 | Opaqueproof.PrivatePolymorphic u ->
1150 Opaqueproof.PrivatePolymorphic (snd @@ Univ.ContextSet.hcons u)
1151 in
1152 { opq_body = c; opq_univs = ctx; opq_handle = i; opq_nonce = nonce }
1153
1154 let fill_opaque { opq_univs = ctx; opq_handle = i; opq_nonce = n; _ } senv =
1155 let () = if not @@ HandleMap.mem i senv.future_cst then
1156 CErrors.anomaly Pp.(str "Missing opaque handle" ++ spc () ++ int (Opaqueproof.repr_handle i))
1157 in
1158 let _, _, nonce = HandleMap.find i senv.future_cst in
1159 let () =
1160 if not (Nonce.equal n nonce) then
1161 CErrors.anomaly Pp.(str "Invalid opaque certificate")
1162 in
1163 (* TODO: Drop the the monomorphic constraints, they should really be internal
1164 but the higher levels use them haphazardly. *)
1165 let senv = match ctx with
1166 | Opaqueproof.PrivateMonomorphic ctx -> push_context_set ~strict:true ctx senv
1167 | Opaqueproof.PrivatePolymorphic _ -> senv
1168 in
1169 (* Mark the constant as having been checked *)
1170 { senv with future_cst = HandleMap.remove i senv.future_cst }
1171
1172 let is_filled_opaque i senv =
1173 let () = assert (Opaqueproof.mem_handle i senv.opaquetab) in
1174 not (HandleMap.mem i senv.future_cst)
1175
1176 let repr_certificate { opq_body = body; opq_univs = ctx; _ } =
1177 body, ctx
1178
1179 let check_constraints uctx = function
1180 | Entries.Polymorphic_entry _ -> Univ.ContextSet.is_empty uctx
1181 | Entries.Monomorphic_entry -> true
1182
1183 let add_private_constant l uctx decl senv : (Constant.t * private_constants) * safe_environment =
1184 let kn = Constant.make2 senv.modpath l in
1185 let senv = push_context_set ~strict:true uctx senv in
1186 let hbody, cb =
1187 let sec_univs = Option.map Section.all_poly_univs senv.sections in
1188 match decl with
1189 | OpaqueEff ce ->
1190 let () = assert (check_constraints uctx ce.Entries.opaque_entry_universes) in
1191 infer_direct_opaque ~sec_univs senv.env ce
1192 | DefinitionEff ce ->
1193 let () = assert (check_constraints uctx ce.Entries.definition_entry_universes) in
1194 Constant_typing.infer_definition ~sec_univs senv.env ce
1195 in
1196 let cb = compile_bytecode senv.env cb in
1197 let dcb = match cb.const_body with
1198 | Def _ as const_body -> { cb with const_body }
1199 | OpaqueDef _ ->
1200 (* We drop the body, to save the definition of an opaque and thus its
1201 hashconsing. It does not matter since this only happens inside a proof,
1202 and depending of the opaque status of the latter, this proof term will be
1203 either inlined or reexported. *)
1204 { cb with const_body = Undef None }
1205 | Undef _ | Primitive _ | Symbol _ -> assert false
1206 in
1207 let senv = add_constant_aux senv ?hbody (kn, dcb) in
1208 let eff =
1209 let from_env = CEphemeron.create (Certificate.make senv) in
1210 let eff = {
1211 seff_certif = from_env;
1212 seff_constant = kn;
1213 seff_body = (hbody, cb);
1214 seff_univs = uctx;
1215 } in
1216 SideEffects.add eff empty_private_constants
1217 in
1218 (kn, eff), senv
1219
1220 (** Rewrite rules *)
1221
1222 let add_rewrite_rules l rules senv =
1223 if Option.has_some senv.sections
1224 then CErrors.user_err Pp.(str "Adding rewrite rules not supported in sections.");
1225 (* TODO: Hashconsing? *)
1226 add_field (l, SFBrules rules) R senv
1227
1228 (** Insertion of inductive types *)
1229
1230 let check_mind mie lab =
1231 let open Entries in
1232 match mie.mind_entry_inds with
1233 | [] -> assert false (* empty inductive entry *)
1234 | oie::_ ->
1235 (* The label and the first inductive type name should match *)
1236 assert (Id.equal lab oie.mind_entry_typename)
1237
1238 let add_checked_mind kn mib senv =
1239 let mib =
1240 match mib.mind_hyps with [] -> Declareops.hcons_mind mib | _ -> mib
1241 in
1242 add_field (MutInd.label kn,SFBmind mib) (I kn) senv
1243
1244 let add_mind l mie senv =
1245 let () = check_mind mie l in
1246 let kn = MutInd.make2 senv.modpath l in
1247 let sec_univs = Option.map Section.all_poly_univs senv.sections in
1248 let mib, why_not_prim_record = Indtypes.check_inductive senv.env ~sec_univs kn mie in
1249 (* We still have to add the template monomorphic constraints, and only those
1250 ones. In all other cases, they are already part of the environment at this
1251 point. *)
1252 let senv = match mib.mind_template with
1253 | None -> senv
1254 | Some { template_context = ctx; template_defaults = u; _ } ->
1255 let qs, levels = UVars.Instance.levels u in
1256 let () = assert (Sorts.Quality.Set.for_all (fun q -> Sorts.Quality.equal Sorts.Quality.qtype q) qs) in
1257 let (qctx, uctx) = UVars.AbstractContext.instantiate u ctx in
1258 let () = assert (Sorts.ElimConstraints.is_empty qctx) in
1259 (* Eliminiation constraints used to be pushed with QGraph.Static *)
1260 let senv = push_context_set ~strict:true (levels, uctx) senv in
1261 senv
1262 in
1263 (kn, why_not_prim_record), add_checked_mind kn mib senv
1264
1265 let add_mind ?typing_flags l mie senv =
1266 with_typing_flags ?typing_flags senv ~f:(add_mind l mie)
1267
1268 (** Insertion of module types *)
1269
1270 let check_state senv =
1271 (Environ.universes senv.env, Conversion.checked_universes)
1272
1273 let vm_handler env univs c vmtab =
1274 let env = Environ.set_vm_library vmtab env in
1275 let code = Vmbytegen.compile_constant_body ~fail_on_error:false env univs (Def c) in
1276 let vmtab, code = push_bytecode vmtab code in
1277 vmtab, code
1278
1279 let vm_state senv =
1280 (Environ.vm_library senv.env, { Mod_typing.vm_handler })
1281
1282 let add_modtype l params_mte inl senv =
1283 let mp = MPdot(senv.modpath, l) in
1284 let state = check_state senv in
1285 let vmstate = vm_state senv in
1286 let mtb, _, vmtab = Mod_typing.translate_modtype state vmstate senv.env mp inl params_mte in
1287 let senv = set_vm_library vmtab senv in
1288 let mtb = Mod_declarations.hcons_module_type mtb in
1289 let senv = add_field (l,SFBmodtype mtb) (MT mp) senv in
1290 mp, senv
1291
1292 (** full_add_module adds module with universes and constraints *)
1293
1294 let full_add_module mp mb senv =
1295 let dp = ModPath.dp mp in
1296 let linkinfo = Nativecode.link_info_of_dirpath dp in
1297 { senv with env = Modops.add_linked_module mp mb linkinfo senv.env }
1298
1299 (** Insertion of modules *)
1300
1301 let add_module l me inl senv =
1302 let mp = MPdot(senv.modpath, l) in
1303 let state = check_state senv in
1304 let vmstate = vm_state senv in
1305 let mb, _, vmtab = Mod_typing.translate_module state vmstate senv.env mp inl me in
1306 let senv = set_vm_library vmtab senv in
1307 let mb = Mod_declarations.hcons_module_body mb in
1308 let senv = add_field (l,SFBmodule mb) (M mp) senv in
1309 let senv = match mod_global_delta mb with
1310 | None -> senv
1311 | Some delta -> update_resolver (Mod_subst.add_delta_resolver delta) senv
1312 in
1313 (mp, mod_delta mb), senv
1314
1315 (** {6 Starting / ending interactive modules and module types } *)
1316
1317 let start_mod_modtype ~istype l senv =
1318 let () = check_modlabel l senv in
1319 let () = check_empty_context senv in
1320 let mp = MPdot(senv.modpath, l) in
1321 mp,
1322 {
1323 (* modified fields *)
1324 modpath = mp;
1325 modvariant = if istype then SIG ([], senv) else STRUCT ([],senv);
1326
1327 (* carried over fields *)
1328 env = senv.env;
1329 future_cst = senv.future_cst;
1330 modresolver = Mod_subst.empty_delta_resolver mp;
1331 paramresolver = ParamResolver.add_delta_resolver senv.modpath senv.modresolver senv.paramresolver;
1332 univ = senv.univ;
1333 qualities = senv.qualities;
1334 required = senv.required;
1335 opaquetab = senv.opaquetab;
1336 sections = None; (* checked in check_empty_context *)
1337
1338 (* module local fields *)
1339 revstruct = [];
1340 modlabels = Id.Set.empty;
1341 objlabels = Id.Set.empty;
1342 loads = [];
1343 local_retroknowledge = [];
1344 }
1345
1346 let start_module l senv = start_mod_modtype ~istype:false l senv
1347
1348 let start_modtype l senv = start_mod_modtype ~istype:true l senv
1349
1350 (** Adding parameters to the current module or module type.
1351 This module should have been freshly started. *)
1352
1353 let add_module_parameter mbid mte inl senv =
1354 let () = check_empty_struct senv in
1355 let mp = MPbound mbid in
1356 let state = check_state senv in
1357 let vmstate = vm_state senv in
1358 let mtb, _, vmtab = Mod_typing.translate_modtype state vmstate senv.env mp inl ([],mte) in
1359 let senv = set_vm_library vmtab senv in
1360 let senv = { senv with env = Modops.add_module_parameter mbid mtb senv.env } in
1361 let new_variant = match senv.modvariant with
1362 | STRUCT (params,oldenv) -> STRUCT ((mbid,mtb) :: params, oldenv)
1363 | SIG (params,oldenv) -> SIG ((mbid,mtb) :: params, oldenv)
1364 | _ -> assert false
1365 in
1366 let new_paramresolver = match mod_global_delta mtb with
1367 | None -> senv.paramresolver
1368 | Some delta -> ParamResolver.add_delta_resolver mp delta senv.paramresolver
1369 in
1370 mtb,
1371 { senv with
1372 modvariant = new_variant;
1373 paramresolver = new_paramresolver }
1374
1375 let rec module_num_parameters senv =
1376 match senv.modvariant with
1377 | STRUCT (params,senv) -> List.length params :: module_num_parameters senv
1378 | SIG (params,senv) -> List.length params :: module_num_parameters senv
1379 | _ -> []
1380
1381 let rec module_is_modtype senv =
1382 match senv.modvariant with
1383 | STRUCT (_,senv) -> false :: module_is_modtype senv
1384 | SIG (_,senv) -> true :: module_is_modtype senv
1385 | _ -> []
1386
1387 let functorize params init =
1388 List.fold_left (fun e (mbid,mt) -> MoreFunctor(mbid,mt,e)) init params
1389
1390 let propagate_loads senv =
1391 List.fold_left
1392 (fun env (mp, mb) -> full_add_module mp mb env)
1393 senv
1394 (List.rev senv.loads)
1395
1396 (** Build the module body of the current module, taking in account
1397 a possible return type (_:T) *)
1398
1399 let build_module_body params restype senv =
1400 let struc = NoFunctor (List.rev senv.revstruct) in
1401 let restype' = Option.map (fun (ty,inl) -> (([],ty),inl)) restype in
1402 let state = check_state senv in
1403 let vmstate = vm_state senv in
1404 let mb, _, vmtab =
1405 Mod_typing.finalize_module state vmstate senv.env senv.modpath
1406 (struc, senv.modresolver) restype'
1407 in
1408 let senv = set_vm_library vmtab senv in
1409 let mb' = functorize_module params mb in
1410 set_retroknowledge mb' senv.local_retroknowledge
1411
1412 (** Returning back to the old pre-interactive-module environment,
1413 with one extra component and some updated fields
1414 (constraints, required, etc) *)
1415
1416 let allow_delayed_constants = ref false
1417
1418 let propagate_senv newdef newenv newresolver senv oldsenv =
1419 (* This asserts that after Paral-ITP, standard vo compilation is behaving
1420 * exctly as before: the same universe constraints are added to modules *)
1421 if not !allow_delayed_constants && not (HandleMap.is_empty senv.future_cst) then
1422 CErrors.anomaly ~label:"safe_typing"
1423 Pp.(str "True Future.t were created for opaque constants even if -async-proofs is off");
1424 { oldsenv with
1425 env = newenv;
1426 modresolver = newresolver;
1427 revstruct = newdef::oldsenv.revstruct;
1428 modlabels = Id.Set.add (fst newdef) oldsenv.modlabels;
1429 univ = senv.univ;
1430 qualities = senv.qualities ;
1431 future_cst = senv.future_cst;
1432 required = senv.required;
1433 loads = senv.loads@oldsenv.loads;
1434 local_retroknowledge =
1435 senv.local_retroknowledge@oldsenv.local_retroknowledge;
1436 opaquetab = senv.opaquetab;
1437 }
1438
1439 let end_module l restype senv =
1440 let mp = senv.modpath in
1441 let params, oldsenv = check_struct senv.modvariant in
1442 let () = check_current_label l mp in
1443 let () = check_empty_context senv in
1444 let mbids = List.rev_map fst params in
1445 let mb = build_module_body params restype senv in
1446 let newenv = Environ.set_universes (Environ.universes senv.env) oldsenv.env in
1447 let newenv = Environ.set_qualities (Environ.qualities senv.env) newenv in
1448 let newenv = if Environ.rewrite_rules_allowed senv.env then Environ.allow_rewrite_rules newenv else newenv in
1449 let newenv = Environ.set_vm_library (Environ.vm_library senv.env) newenv in
1450 let senv' = propagate_loads { senv with env = newenv } in
1451 let newenv = Modops.add_module mp mb senv'.env in
1452 let newresolver = match mod_global_delta mb with
1453 | None -> oldsenv.modresolver
1454 | Some delta -> Mod_subst.add_delta_resolver delta oldsenv.modresolver
1455 in
1456 (mp, mbids, mod_delta mb),
1457 propagate_senv (l,SFBmodule mb) newenv newresolver senv' oldsenv
1458
1459 let build_mtb = Mod_declarations.make_module_type
1460
1461 let end_modtype l senv =
1462 let mp = senv.modpath in
1463 let params, oldsenv = check_sig senv.modvariant in
1464 let () = check_current_label l mp in
1465 let () = check_empty_context senv in
1466 let mbids = List.rev_map fst params in
1467 let newenv = Environ.set_universes (Environ.universes senv.env) oldsenv.env in
1468 let newenv = if Environ.rewrite_rules_allowed senv.env then Environ.allow_rewrite_rules newenv else newenv in
1469 let newenv = Environ.set_vm_library (Environ.vm_library senv.env) newenv in
1470 let senv' = propagate_loads {senv with env=newenv} in
1471 let auto_tb = functorize params (NoFunctor (List.rev senv.revstruct)) in
1472 let mtb = build_mtb auto_tb senv.modresolver in
1473 let newenv = Environ.add_modtype mp mtb senv'.env in
1474 let newresolver = oldsenv.modresolver in
1475 (mp,mbids),
1476 propagate_senv (l,SFBmodtype mtb) newenv newresolver senv' oldsenv
1477
1478 (** {6 Inclusion of module or module type } *)
1479
1480 let add_include me is_module inl senv =
1481 let open Mod_typing in
1482 let mp_sup = senv.modpath in
1483 let state = check_state senv in
1484 let vmstate = vm_state senv in
1485 let sign,(),resolver, _, vmtab =
1486 translate_mse_include is_module state vmstate senv.env mp_sup inl me
1487 in
1488 let senv = set_vm_library vmtab senv in
1489 (* Include Self support *)
1490 let struc = NoFunctor (List.rev senv.revstruct) in
1491 let mb = Mod_declarations.make_module_body struc senv.modresolver [] in
1492 let rec compute_sign sign resolver =
1493 match sign with
1494 | MoreFunctor(mbid,mtb,str) ->
1495 let state = check_state senv in
1496 (* Module subcomponents are already part of senv.env at this point *)
1497 let env = Environ.shallow_add_module mp_sup mb senv.env in
1498 let (_ : UGraph.t) = Subtyping.check_subtypes state env mp_sup (MPbound mbid) mtb in
1499 let mpsup_delta =
1500 Modops.inline_delta_resolver senv.env inl mp_sup mbid mtb senv.modresolver
1501 in
1502 let subst = Mod_subst.map_mbid mbid mp_sup mpsup_delta in
1503 let resolver = Mod_subst.subst_codom_delta_resolver subst resolver in
1504 compute_sign (Modops.subst_signature subst mp_sup str) resolver
1505 | NoFunctor str -> resolver, str
1506 in
1507 let resolver, str = compute_sign sign resolver in
1508 let senv = update_resolver (Mod_subst.add_delta_resolver resolver) senv in
1509 let add senv ((l,elem) as field) =
1510 let new_name = match elem with
1511 | SFBconst _ ->
1512 C (Mod_subst.constant_of_delta_kn resolver (KerName.make mp_sup l))
1513 | SFBmind _ ->
1514 I (Mod_subst.mind_of_delta_kn resolver (KerName.make mp_sup l))
1515 | SFBrules _ -> R
1516 | SFBmodule _ -> M (MPdot (mp_sup, l))
1517 | SFBmodtype _ -> MT (MPdot (mp_sup, l))
1518 in
1519 add_field field new_name senv
1520 in
1521 resolver, List.fold_left add senv str
1522
1523 (** {6 Libraries, i.e. compiled modules } *)
1524
1525 let dirpath_of_library lib = lib.comp_name
1526
1527 let module_of_library lib = lib.comp_mod
1528
1529 let univs_of_library lib = lib.comp_sorts, lib.comp_univs
1530
1531 (** FIXME: MS: remove?*)
1532 let current_modpath senv = senv.modpath
1533 let current_dirpath senv = Names.ModPath.dp (current_modpath senv)
1534
1535 let start_library dir senv =
1536 (* When starting a library, the current environment should be initial
1537 i.e. only composed of Require's *)
1538 (* XXX is it really possible / should be allowed to have nonempty Requires?
1539 especially if [dir] is in the [senv.required] *)
1540 assert (is_initial senv);
1541 assert (not (DirPath.is_empty dir));
1542 let mp = MPfile dir in
1543 let vmtab = Vmlibrary.set_path dir (Environ.vm_library senv.env) in
1544 let env = Environ.set_vm_library vmtab senv.env in
1545 mp,
1546 { env = env;
1547 modpath = mp;
1548 modvariant = LIBRARY;
1549 required = senv.required;
1550
1551 modresolver = Mod_subst.empty_delta_resolver mp;
1552 paramresolver = ParamResolver.empty dir;
1553 revstruct = [];
1554 modlabels = Id.Set.empty;
1555 objlabels = Id.Set.empty;
1556 sections = None;
1557 future_cst = HandleMap.empty;
1558 univ = Univ.ContextSet.empty;
1559 qualities = Sorts.QContextSet.empty;
1560 loads = [];
1561 local_retroknowledge = [];
1562 opaquetab = Opaqueproof.empty_opaquetab;
1563 }
1564
1565 let export ~output_native_objects senv dir =
1566 let () = check_current_library dir senv in
1567 let mp = senv.modpath in
1568 let str = NoFunctor (List.rev senv.revstruct) in
1569 let mb = Mod_declarations.make_module_body str senv.modresolver senv.local_retroknowledge in
1570 let ast, symbols =
1571 if output_native_objects then
1572 Nativelibrary.dump_library mp senv.env str
1573 else [], Nativevalues.empty_symbols
1574 in
1575 let permanent_flags = {
1576 rewrite_rules_allowed = Environ.rewrite_rules_allowed senv.env;
1577 } in
1578 let filter_dep (dp, { req_root; req_digest }) =
1579 if req_root then Some (dp, req_digest) else None
1580 in
1581 let comp_deps = List.map_filter filter_dep (DirPath.Map.bindings senv.required) in
1582 let lib = {
1583 comp_name = dir;
1584 comp_mod = mb;
1585 comp_univs = senv.univ;
1586 comp_sorts = senv.qualities;
1587 comp_deps = Array.of_list comp_deps;
1588 comp_flags = permanent_flags
1589 } in
1590 let vmlib = Vmlibrary.export @@ Environ.vm_library senv.env in
1591 mp, lib, vmlib, (ast, symbols)
1592
1593 let import lib vmtab vodigest senv =
1594 let senv = check_flags_for_library lib senv in
1595 let required = check_required senv.required lib.comp_deps in
1596 if DirPath.equal (ModPath.dp senv.modpath) lib.comp_name then
1597 CErrors.user_err
1598 Pp.(strbrk "Cannot load a library with the same name as the current one ("
1599 ++ DirPath.print lib.comp_name ++ str").");
1600 let mp = MPfile lib.comp_name in
1601 let mb = lib.comp_mod in
1602 let univs = lib.comp_univs in
1603 let qualities = lib.comp_sorts in
1604 let check_quality q =
1605 Sorts.QVar.is_global q &&
1606 not (QGraph.is_declared (Sorts.Quality.QVar q) (Environ.qualities senv.env))
1607 in
1608 let () = assert (Sorts.QVar.Set.for_all check_quality (fst qualities)) in
1609 let env = Environ.push_qualities ~rigid:true qualities senv.env in
1610 let env = Environ.push_context_set ~strict:true univs env in
1611 let env = Environ.link_vm_library vmtab env in
1612 let env =
1613 let linkinfo = Nativecode.link_info_of_dirpath lib.comp_name in
1614 Modops.add_linked_module mp mb linkinfo env
1615 in
1616 let sections =
1617 Option.map (Section.map_custom (fun custom ->
1618 {custom with rev_reimport = (lib,vmtab,vodigest) :: custom.rev_reimport}))
1619 senv.sections
1620 in
1621 let required =
1622 if DirPath.Map.mem lib.comp_name required then
1623 (* should probably be an error, we are requiring the same library twice *)
1624 required
1625 else DirPath.Map.add lib.comp_name { req_root = true; req_digest = vodigest } required
1626 in
1627 mp,
1628 { senv with
1629 env;
1630 (* Do NOT store the name quotient from the dependencies in the set of
1631 constraints that will be marshalled on disk. *)
1632 paramresolver = ParamResolver.add_delta_resolver mp (mod_delta mb) senv.paramresolver;
1633 required;
1634 loads = (mp,mb)::senv.loads;
1635 sections;
1636 }
1637
1638 (** {6 Interactive sections} *)
1639
1640 let open_section senv =
1641 let custom = {
1642 rev_env = senv.env;
1643 rev_univ = senv.univ;
1644 rev_qualities = senv.qualities;
1645 rev_objlabels = senv.objlabels;
1646 rev_reimport = [];
1647 rev_revstruct = senv.revstruct;
1648 rev_paramresolver = senv.paramresolver;
1649 } in
1650 let sections = Section.open_section ~custom senv.sections in
1651 { senv with sections=Some sections }
1652
1653 let close_section senv =
1654 let open Section in
1655 let sections0 = get_section senv.sections in
1656 let env0 = senv.env in
1657 (* First phase: revert the declarations added in the section *)
1658 let sections, entries, cstrs, revert = Section.close_section sections0 in
1659 (* Don't revert the delayed constraints (future_cst). If some delayed constraints
1660 were forced inside the section, they have been turned into global monomorphic
1661 that are going to be replayed. Those that are not forced are not readded
1662 by {!add_constant_aux}. *)
1663 let { rev_env = env; rev_univ = univ; rev_qualities = qualities; rev_objlabels = objlabels;
1664 rev_reimport; rev_revstruct = revstruct; rev_paramresolver = paramresolver } = revert in
1665 let env = if Environ.rewrite_rules_allowed env0 then Environ.allow_rewrite_rules env else env in
1666 let senv = { senv with env; revstruct; sections; univ; qualities; objlabels; paramresolver } in
1667 (* Second phase: replay Requires *)
1668 let senv = List.fold_left (fun senv (lib,vmtab,vodigest) -> snd (import lib vmtab vodigest senv))
1669 senv (List.rev rev_reimport)
1670 in
1671 (* Third phase: replay the discharged section contents *)
1672 let senv = push_context_set ~strict:true cstrs senv in
1673 let fold entry senv =
1674 match entry with
1675 | SecDefinition kn ->
1676 let cb = Environ.lookup_constant kn env0 in
1677 let info = Section.segment_of_constant kn sections0 in
1678 let cb = Discharge.cook_constant senv.env info cb in
1679 let cb = compile_bytecode senv.env cb in
1680 (* Delayed constants are already in the global environment *)
1681 add_constant_aux senv (kn, cb)
1682 | SecInductive ind ->
1683 let mib = Environ.lookup_mind ind env0 in
1684 let info = Section.segment_of_inductive ind sections0 in
1685 let mib = Discharge.cook_inductive info mib in
1686 add_checked_mind ind mib senv
1687 in
1688 List.fold_right fold entries senv
1689
1690 let flatten_env senv =
1691 let label = function MPdot (_,l) -> l | _ -> assert false in
1692 let rec close senv =
1693 match senv.modvariant with
1694 | STRUCT _ -> close (snd (end_module (label senv.modpath) None senv))
1695 | SIG (params,env) -> close (snd (end_module (label senv.modpath) None {senv with modvariant = STRUCT (params,env)}))
1696 | LIBRARY | NONE -> senv in
1697 let senv = close senv in
1698 (senv.modpath, senv.revstruct)
1699
1700 (** {6 Safe typing } *)
1701
1702 type judgment = {
1703 jdg_env : safe_environment;
1704 jdg_val : constr;
1705 jdg_type : types;
1706 }
1707
1708 let typing senv c =
1709 let j = Typeops.infer (env_of_senv senv) c in
1710 { jdg_env = senv;
1711 jdg_val = j.Environ.uj_val;
1712 jdg_type = j.Environ.uj_type;
1713 }
1714
1715 (** {6 Retroknowledge / native compiler } *)
1716
1717 let register_inline kn senv =
1718 let open Environ in
1719 if not (evaluable_constant kn senv.env) then
1720 CErrors.user_err Pp.(str "Register inline: an evaluable constant is expected");
1721 let env = senv.env in
1722 let cb = lookup_constant kn env in
1723 let cb = {cb with const_inline_code = true} in
1724 let env = add_constant kn cb env in { senv with env}
1725
1726 let check_register_ind (type t) ind (r : t CPrimitives.prim_ind) env =
1727 let (mb,ob as spec) = Inductive.lookup_mind_specif env ind in
1728 let ind = match mb.mind_universes with
1729 | Polymorphic _ -> CErrors.user_err Pp.(str "A universe monomorphic inductive type is expected.")
1730 | Monomorphic -> Constr.UnsafeMonomorphic.mkInd ind
1731 in
1732 let check_if b msg =
1733 if not b then
1734 CErrors.user_err msg in
1735 check_if (Int.equal (Array.length mb.mind_packets) 1) Pp.(str "A non mutual inductive is expected.");
1736 check_if (not @@ Inductive.is_private spec) Pp.(str "A non-private inductive type is expected");
1737 let check_nparams n =
1738 check_if (Int.equal mb.mind_nparams n) Pp.(str "An inductive type with " ++ int n ++ str " parameters is expected")
1739 in
1740 let check_nconstr n =
1741 check_if (Int.equal (Array.length ob.mind_consnames) n)
1742 Pp.(str "an inductive type with " ++ int n ++ str " constructors is expected")
1743 in
1744 let check_name pos s =
1745 check_if (Id.equal ob.mind_consnames.(pos) (Id.of_string s))
1746 Pp.(str"the " ++ int (pos + 1) ++ str
1747 "th constructor does not have the expected name: " ++ str s) in
1748 let check_type pos t =
1749 check_if (Constr.equal t ob.mind_user_lc.(pos))
1750 Pp.(str"the " ++ int (pos + 1) ++ str
1751 "th constructor does not have the expected type") in
1752 let check_type_cte pos = check_type pos ind in
1753 match r with
1754 | CPrimitives.PIT_bool ->
1755 check_nparams 0;
1756 check_nconstr 2;
1757 check_name 0 "true";
1758 check_type_cte 0;
1759 check_name 1 "false";
1760 check_type_cte 1
1761 | CPrimitives.PIT_carry ->
1762 check_nparams 1;
1763 check_nconstr 2;
1764 let test_type pos =
1765 let c = ob.mind_user_lc.(pos) in
1766 let s = Pp.(str"the " ++ int (pos + 1) ++ str
1767 "th constructor does not have the expected type") in
1768 check_if (Constr.isProd c) s;
1769 let (_,d,cd) = Constr.destProd c in
1770 check_if (Constr.is_Type d) s;
1771 check_if
1772 (Constr.equal
1773 (mkProd (Context.anonR,mkRel 1, mkApp (ind,[|mkRel 2|])))
1774 cd)
1775 s in
1776 check_name 0 "C0";
1777 test_type 0;
1778 check_name 1 "C1";
1779 test_type 1;
1780 | CPrimitives.PIT_pair ->
1781 check_nparams 2;
1782 check_nconstr 1;
1783 check_name 0 "pair";
1784 let c = ob.mind_user_lc.(0) in
1785 let s = Pp.str "the constructor does not have the expected type" in
1786 begin match Term.decompose_prod c with
1787 | ([_,b;_,a;_,_B;_,_A], codom) ->
1788 check_if (is_Type _A) s;
1789 check_if (is_Type _B) s;
1790 check_if (Constr.equal a (mkRel 2)) s;
1791 check_if (Constr.equal b (mkRel 2)) s;
1792 check_if (Constr.equal codom (mkApp (ind,[|mkRel 4; mkRel 3|]))) s
1793 | _ -> check_if false s
1794 end
1795 | CPrimitives.PIT_cmp ->
1796 check_nparams 0;
1797 check_nconstr 3;
1798 check_name 0 "Eq";
1799 check_type_cte 0;
1800 check_name 1 "Lt";
1801 check_type_cte 1;
1802 check_name 2 "Gt";
1803 check_type_cte 2
1804 | CPrimitives.PIT_f_cmp ->
1805 check_nconstr 4;
1806 check_name 0 "FEq";
1807 check_type_cte 0;
1808 check_name 1 "FLt";
1809 check_type_cte 1;
1810 check_name 2 "FGt";
1811 check_type_cte 2;
1812 check_name 3 "FNotComparable";
1813 check_type_cte 3
1814 | CPrimitives.PIT_f_class ->
1815 check_nconstr 9;
1816 check_name 0 "PNormal";
1817 check_type_cte 0;
1818 check_name 1 "NNormal";
1819 check_type_cte 1;
1820 check_name 2 "PSubn";
1821 check_type_cte 2;
1822 check_name 3 "NSubn";
1823 check_type_cte 3;
1824 check_name 4 "PZero";
1825 check_type_cte 4;
1826 check_name 5 "NZero";
1827 check_type_cte 5;
1828 check_name 6 "PInf";
1829 check_type_cte 6;
1830 check_name 7 "NInf";
1831 check_type_cte 7;
1832 check_name 8 "NaN";
1833 check_type_cte 8
1834
1835 let register_inductive ind prim senv =
1836 check_register_ind ind prim senv.env;
1837 let action = Retroknowledge.Register_ind(prim,ind) in
1838 add_retroknowledge action senv
1839
1840 (* NB: The next old comment probably refers to [propagate_loads] above.
1841 When a Require is done inside a module, we'll redo this require
1842 at the upper level after the module is ended, and so on.
1843 This is probably not a big deal anyway, since these Require's
1844 inside modules should be pretty rare. Maybe someday we could
1845 brutally forbid this tricky "feature"... *)
1846
1847 (* we have an inefficiency: Since loaded files are added to the
1848 environment every time a module is closed, their components are
1849 calculated many times. This could be avoided in several ways:
1850
1851 1 - for each file create a dummy environment containing only this
1852 file's components, merge this environment with the global
1853 environment, and store for the future (instead of just its type)
1854
1855 2 - create "persistent modules" environment table in Environ add put
1856 loaded by side-effect once and for all (like it is done in OCaml).
1857 Would this be correct with respect to undo's and stuff ?
1858 *)
1859
1860 let set_oracle ts e =
1861 { e with env = Environ.set_oracle e.env ts }
1862
1863 let set_strategy k l e = { e with env =
1864 (Environ.set_oracle e.env
1865 (Conv_oracle.set_strategy (Environ.oracle e.env) k l)) }