-
Notifications
You must be signed in to change notification settings - Fork 631
/
safe_typing.ml
1610 lines (1398 loc) · 55.3 KB
/
safe_typing.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * Copyright INRIA, CNRS and contributors *)
(* <O___,, * (see version control and CREDITS file for authors & dates) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(* Created by Jean-Christophe Filliâtre as part of the rebuilding of
Coq around a purely functional abstract type-checker, Dec 1999 *)
(* This file provides the entry points to the kernel type-checker. It
defines the abstract type of well-formed environments and
implements the rules that build well-formed environments.
An environment is made of constants and inductive types (E), of
section declarations (Delta), of local bound-by-index declarations
(Gamma) and of universe constraints (C). Below E[Delta,Gamma] |-_C
means that the tuple E, Delta, Gamma, C is a well-formed
environment. Main rules are:
empty_environment:
------
[,] |-
push_named_assum(a,T):
E[Delta,Gamma] |-_G
------------------------
E[Delta,Gamma,a:T] |-_G'
push_named_def(a,t,T):
E[Delta,Gamma] |-_G
---------------------------
E[Delta,Gamma,a:=t:T] |-_G'
add_constant(ConstantEntry(DefinitionEntry(c,t,T))):
E[Delta,Gamma] |-_G
---------------------------
E,c:=t:T[Delta,Gamma] |-_G'
add_constant(ConstantEntry(ParameterEntry(c,T))):
E[Delta,Gamma] |-_G
------------------------
E,c:T[Delta,Gamma] |-_G'
add_mind(Ind(Ind[Gamma_p](Gamma_I:=Gamma_C))):
E[Delta,Gamma] |-_G
------------------------
E,Ind[Gamma_p](Gamma_I:=Gamma_C)[Delta,Gamma] |-_G'
etc.
*)
open Util
open Names
open Declarations
open Constr
open Context.Named.Declaration
module NamedDecl = Context.Named.Declaration
(** {6 Safe environments }
Fields of [safe_environment] :
- [env] : the underlying environment (cf Environ)
- [modpath] : the current module name
- [modvariant] :
* NONE before coqtop initialization
* LIBRARY at toplevel of a compilation or a regular coqtop session
* STRUCT (params,oldsenv) : inside a local module, with
module parameters [params] and earlier environment [oldsenv]
* SIG (params,oldsenv) : same for a local module type
- [modresolver] : delta_resolver concerning the module content, that needs to
be marshalled on disk
- [paramresolver] : delta_resolver in scope but not part of the library per
se, that is from functor parameters and required libraries
- [revstruct] : current module content, most recent declarations first
- [modlabels] and [objlabels] : names defined in the current module,
either for modules/modtypes or for constants/inductives.
These fields could be deduced from [revstruct], but they allow faster
name freshness checks.
- [univ] : current universe constraints
- [future_cst] : delayed opaque constants yet to be checked
- [required] : names and digests of Require'd libraries since big-bang.
This field will only grow
- [loads] : list of libraries Require'd inside the current module.
They will be propagated to the upper module level when
the current module ends.
- [local_retroknowledge]
*)
type vodigest =
| Dvo_or_vi of Digest.t (* The digest of the seg_lib part *)
| Dvivo of Digest.t * Digest.t (* The digest of the seg_lib + seg_univ part *)
let digest_match ~actual ~required =
match actual, required with
| Dvo_or_vi d1, Dvo_or_vi d2
| Dvivo (d1,_), Dvo_or_vi d2 -> String.equal d1 d2
| Dvivo (d1,e1), Dvivo (d2,e2) -> String.equal d1 d2 && String.equal e1 e2
| Dvo_or_vi _, Dvivo _ -> false
type library_info = DirPath.t * vodigest
(** Functor and funsig parameters, most recent first *)
type module_parameters = (MBId.t * module_type_body) list
type permanent_flags = {
rewrite_rules_allowed : bool;
}
type compiled_library = {
comp_name : DirPath.t;
comp_mod : module_body;
comp_univs : Univ.ContextSet.t;
comp_deps : library_info array;
comp_flags : permanent_flags;
}
type reimport = compiled_library * Univ.ContextSet.t * vodigest
(** Part of the safe_env at a section opening time to be backtracked *)
type section_data = {
rev_env : Environ.env;
rev_univ : Univ.ContextSet.t;
rev_objlabels : Label.Set.t;
rev_reimport : reimport list;
rev_revstruct : structure_body;
}
module HandleMap = Opaqueproof.HandleMap
(** We rely on uniqueness of pointers to provide a simple implementation of
kernel certificates. For this to work across processes, one needs the
safe environments to be marshaled at the same time as their corresponding
certificates and sharing to be preserved. *)
module Nonce :
sig
type t
val create : unit -> t
val equal : t -> t -> bool
end =
struct
type t = unit ref
let create () = ref ()
let equal x y = x == y
end
type safe_environment =
{ env : Environ.env;
sections : section_data Section.t option;
modpath : ModPath.t;
modvariant : modvariant;
modresolver : Mod_subst.delta_resolver;
paramresolver : Mod_subst.delta_resolver;
revstruct : structure_body;
modlabels : Label.Set.t;
objlabels : Label.Set.t;
univ : Univ.ContextSet.t;
future_cst : (Constant_typing.typing_context * safe_environment * Nonce.t) HandleMap.t;
required : vodigest DPmap.t;
loads : (ModPath.t * module_body) list;
local_retroknowledge : Retroknowledge.action list;
opaquetab : Opaqueproof.opaquetab;
}
and modvariant =
| NONE
| LIBRARY
| SIG of module_parameters * safe_environment (** saved env *)
| STRUCT of module_parameters * safe_environment (** saved env *)
let rec library_dp_of_senv senv =
match senv.modvariant with
| NONE | LIBRARY -> ModPath.dp senv.modpath
| SIG(_,senv) -> library_dp_of_senv senv
| STRUCT(_,senv) -> library_dp_of_senv senv
let empty_environment =
{ env = Environ.empty_env;
modpath = ModPath.dummy;
modvariant = NONE;
modresolver = Mod_subst.empty_delta_resolver;
paramresolver = Mod_subst.empty_delta_resolver;
revstruct = [];
modlabels = Label.Set.empty;
objlabels = Label.Set.empty;
sections = None;
future_cst = HandleMap.empty;
univ = Univ.ContextSet.empty;
required = DPmap.empty;
loads = [];
local_retroknowledge = [];
opaquetab = Opaqueproof.empty_opaquetab;
}
let is_initial senv =
match senv.revstruct, senv.modvariant with
| [], NONE -> ModPath.equal senv.modpath ModPath.dummy
| _ -> false
let sections_are_opened senv = not (Option.is_empty senv.sections)
let delta_of_senv senv = senv.modresolver,senv.paramresolver
let constant_of_delta_kn_senv senv kn =
Mod_subst.constant_of_deltas_kn senv.paramresolver senv.modresolver kn
let mind_of_delta_kn_senv senv kn =
Mod_subst.mind_of_deltas_kn senv.paramresolver senv.modresolver kn
(** The safe_environment state monad *)
type safe_transformer0 = safe_environment -> safe_environment
type 'a safe_transformer = safe_environment -> 'a * safe_environment
(** {6 Typing flags } *)
let set_typing_flags c senv =
let env = Environ.set_typing_flags c senv.env in
if env == senv.env then senv
else { senv with env }
let set_typing_flags flags senv =
(* NB: we allow changing the conv_oracle inside sections because it
doesn't matter for consistency. *)
if Option.has_some senv.sections
&& not (Environ.same_flags flags
{(Environ.typing_flags senv.env) with
conv_oracle = flags.conv_oracle;
share_reduction = flags.share_reduction;
})
then CErrors.user_err Pp.(str "Changing typing flags inside sections is not allowed.");
set_typing_flags flags senv
let set_impredicative_set b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with impredicative_set = b } senv
let set_check_guarded b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with check_guarded = b } senv
let set_check_positive b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with check_positive = b } senv
let set_check_universes b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with check_universes = b } senv
let set_indices_matter indices_matter senv =
set_typing_flags { (Environ.typing_flags senv.env) with indices_matter } senv
let set_share_reduction b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with share_reduction = b } senv
let set_VM b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with enable_VM = b } senv
let set_native_compiler b senv =
let flags = Environ.typing_flags senv.env in
set_typing_flags { flags with enable_native_compiler = b } senv
let set_allow_sprop b senv = { senv with env = Environ.set_allow_sprop b senv.env }
let set_rewrite_rules_allowed b senv = { senv with env = Environ.set_rewrite_rules_allowed b senv.env }
(* Temporary sets custom typing flags *)
let with_typing_flags ?typing_flags senv ~f =
match typing_flags with
| None -> f senv
| Some typing_flags ->
let orig_typing_flags = Environ.typing_flags senv.env in
let res, senv = f (set_typing_flags typing_flags senv) in
res, set_typing_flags orig_typing_flags senv
(** {6 Stm machinery } *)
module Certificate :
sig
type t
val make : safe_environment -> t
val universes : t -> Univ.ContextSet.t
(** Checks whether [dst] is a valid extension of [src] *)
val check : src:t -> dst:t -> bool
end =
struct
type t = {
certif_struc : Declarations.structure_body;
certif_univs : Univ.ContextSet.t;
}
let make senv = {
certif_struc = senv.revstruct;
certif_univs = senv.univ;
}
let is_suffix l suf = match l with
| [] -> false
| _ :: l -> l == suf
let is_subset (s1, cst1) (s2, cst2) =
Univ.Level.Set.subset s1 s2 && Univ.Constraints.subset cst1 cst2
let check ~src ~dst =
is_suffix dst.certif_struc src.certif_struc &&
is_subset src.certif_univs dst.certif_univs
let universes c = c.certif_univs
end
type side_effect = {
seff_certif : Certificate.t CEphemeron.key;
seff_constant : Constant.t;
seff_body : Constr.t Declarations.pconstant_body;
seff_univs : Univ.ContextSet.t;
}
(* Invariant: For any senv, if [Certificate.check senv seff_certif] then
senv where univs := Certificate.universes seff_certif] +
(c.seff_constant -> seff_body) is well-formed. *)
module SideEffects :
sig
type t
val repr : t -> side_effect list
val empty : t
val is_empty : t -> bool
val add : side_effect -> t -> t
val concat : t -> t -> t
end =
struct
module SeffOrd = struct
type t = side_effect
let compare e1 e2 =
Constant.CanOrd.compare e1.seff_constant e2.seff_constant
end
module SeffSet = Set.Make(SeffOrd)
type t = { seff : side_effect list; elts : SeffSet.t }
(** Invariant: [seff] is a permutation of the elements of [elts] *)
let repr eff = eff.seff
let empty = { seff = []; elts = SeffSet.empty }
let is_empty { seff; elts } = List.is_empty seff && SeffSet.is_empty elts
let add x es =
if SeffSet.mem x es.elts then es
else { seff = x :: es.seff; elts = SeffSet.add x es.elts }
let concat xes yes =
List.fold_right add xes.seff yes
end
type private_constants = SideEffects.t
let side_effects_of_private_constants l =
List.rev (SideEffects.repr l)
(* Only used to push in an Environ.env. *)
let lift_constant c =
let body = match c.const_body with
| OpaqueDef _ -> Undef None
| Def _ | Undef _ | Primitive _ | Symbol _ as body -> body
in
{ c with const_body = body }
let push_private_constants env eff =
let eff = side_effects_of_private_constants eff in
let add_if_undefined env eff =
if Environ.mem_constant eff.seff_constant env then env
else Environ.add_constant eff.seff_constant (lift_constant eff.seff_body) env
in
List.fold_left add_if_undefined env eff
let empty_private_constants = SideEffects.empty
let is_empty_private_constants c = SideEffects.is_empty c
let concat_private = SideEffects.concat
let universes_of_private eff =
let fold acc eff = Univ.ContextSet.union eff.seff_univs acc in
List.fold_left fold Univ.ContextSet.empty (side_effects_of_private_constants eff)
let env_of_safe_env senv = senv.env
let env_of_senv = env_of_safe_env
let structure_body_of_safe_env env = env.revstruct
let sections_of_safe_env senv = senv.sections
let get_section = function
| None -> CErrors.user_err Pp.(str "No open section.")
| Some s -> s
let push_context_set ~strict cst senv =
if Univ.ContextSet.is_empty cst then senv
else
let sections = Option.map (Section.push_constraints cst) senv.sections
in
{ senv with
env = Environ.push_context_set ~strict cst senv.env;
univ = Univ.ContextSet.union cst senv.univ;
sections }
let add_constraints cst senv =
push_context_set ~strict:true cst senv
let is_curmod_library senv =
match senv.modvariant with LIBRARY -> true | _ -> false
let is_joined_environment e = HandleMap.is_empty e.future_cst
(** {6 Various checks } *)
let exists_modlabel l senv = Label.Set.mem l senv.modlabels
let exists_objlabel l senv = Label.Set.mem l senv.objlabels
let check_modlabel l senv =
if exists_modlabel l senv then Modops.error_existing_label l
let check_objlabel l senv =
if exists_objlabel l senv then Modops.error_existing_label l
let check_objlabels ls senv =
Label.Set.iter (fun l -> check_objlabel l senv) ls
(** Are we closing the right module / modtype ?
No user error here, since the opening/ending coherence
is now verified in [vernac_end_segment] *)
let check_current_label lab = function
| MPdot (_,l) -> assert (Label.equal lab l)
| _ -> assert false
let check_struct = function
| STRUCT (params,oldsenv) -> params, oldsenv
| NONE | LIBRARY | SIG _ -> assert false
let check_sig = function
| SIG (params,oldsenv) -> params, oldsenv
| NONE | LIBRARY | STRUCT _ -> assert false
let check_current_library dir senv = match senv.modvariant with
| LIBRARY -> assert (ModPath.equal senv.modpath (MPfile dir))
| NONE | STRUCT _ | SIG _ -> assert false (* cf Lib.end_compilation *)
(** When operating on modules, we're normally outside sections *)
let check_empty_context senv =
assert (Environ.empty_context senv.env && Option.is_empty senv.sections)
(** When adding a parameter to the current module/modtype,
it must have been freshly started *)
let check_empty_struct senv =
assert (List.is_empty senv.revstruct
&& List.is_empty senv.loads)
(** When loading a library, its dependencies should be already there,
with the correct digests. *)
let check_required current_libs needed =
let check (id,required) =
try
let actual = DPmap.find id current_libs in
if not(digest_match ~actual ~required) then
CErrors.user_err Pp.(pr_sequence str
["Inconsistent assumptions over module"; DirPath.to_string id; "."])
with Not_found ->
CErrors.user_err Pp.(pr_sequence str ["Reference to unknown module"; DirPath.to_string id; "."])
in
Array.iter check needed
(** When loading a library, the current flags should match
those needed for the library *)
let check_flags_for_library lib senv =
let { rewrite_rules_allowed } = lib.comp_flags in
set_rewrite_rules_allowed rewrite_rules_allowed senv
(** {6 Insertion of section variables} *)
(** They are now typed before being added to the environment.
Same as push_named, but check that the variable is not already
there. Should *not* be done in Environ because tactics add temporary
hypothesis many many times, and the check performed here would
cost too much. *)
let safe_push_named d env =
let id = NamedDecl.get_id d in
let _ =
try
let _ = Environ.lookup_named id env in
CErrors.user_err Pp.(pr_sequence str ["Identifier"; Id.to_string id; "already defined."])
with Not_found -> () in
Environ.push_named d env
let push_named_def (id,de) senv =
let sections = get_section senv.sections in
let c, r, typ = Constant_typing.infer_local_def senv.env id de in
let d = LocalDef (Context.make_annot id r, c, typ) in
let env'' = safe_push_named d senv.env in
let sections = Section.push_local d sections in
{ senv with sections=Some sections; env = env'' }
let push_named_assum (x,t) senv =
let sections = get_section senv.sections in
let t, r = Constant_typing.infer_local_assum senv.env t in
let d = LocalAssum (Context.make_annot x r, t) in
let sections = Section.push_local d sections in
let env'' = safe_push_named d senv.env in
{ senv with sections=Some sections; env = env'' }
let push_section_context uctx senv =
let sections = get_section senv.sections in
let sections = Section.push_local_universe_context uctx sections in
let senv = { senv with sections=Some sections } in
let ctx = Univ.ContextSet.of_context uctx in
(* We check that the universes are fresh. FIXME: This should be done
implicitly, but we have to work around the API. *)
let () = assert (Univ.Level.Set.for_all (fun u -> not (Univ.Level.Set.mem u (fst senv.univ))) (fst ctx)) in
{ senv with
env = Environ.push_context_set ~strict:false ctx senv.env;
univ = Univ.ContextSet.union ctx senv.univ }
(** {6 Insertion of new declarations to current environment } *)
let labels_of_mib mib =
let add,get =
let labels = ref Label.Set.empty in
(fun id -> labels := Label.Set.add (Label.of_id id) !labels),
(fun () -> !labels)
in
let visit_mip mip =
add mip.mind_typename;
Array.iter add mip.mind_consnames
in
Array.iter visit_mip mib.mind_packets;
get ()
let add_retroknowledge pttc senv =
{ senv with
env = Primred.add_retroknowledge senv.env pttc;
local_retroknowledge = pttc::senv.local_retroknowledge }
(** A generic function for adding a new field in a same environment.
It also performs the corresponding [add_constraints]. *)
type generic_name =
| C of Constant.t
| I of MutInd.t
| R
| M (** name already known, cf the mod_mp field *)
| MT (** name already known, cf the mod_mp field *)
let add_field ((l,sfb) as field) gn senv =
let mlabs,olabs = match sfb with
| SFBmind mib ->
let l = labels_of_mib mib in
check_objlabels l senv; (Label.Set.empty,l)
| SFBconst _ | SFBrules _ ->
check_objlabel l senv; (Label.Set.empty, Label.Set.singleton l)
| SFBmodule _ | SFBmodtype _ ->
check_modlabel l senv; (Label.Set.singleton l, Label.Set.empty)
in
let env' = match sfb, gn with
| SFBconst cb, C con -> Environ.add_constant con cb senv.env
| SFBmind mib, I mind -> Environ.add_mind mind mib senv.env
| SFBmodtype mtb, MT -> Environ.add_modtype mtb senv.env
| SFBmodule mb, M -> Modops.add_module mb senv.env
| SFBrules r, R -> Environ.add_rewrite_rules r.rewrules_rules senv.env
| _ -> assert false
in
let sections = match senv.sections with
| None -> None
| Some sections ->
match sfb, gn with
| SFBconst cb, C con ->
let poly = Declareops.constant_is_polymorphic cb in
Some Section.(push_global ~poly env' (SecDefinition con) sections)
| SFBmind mib, I mind ->
let poly = Declareops.inductive_is_polymorphic mib in
Some Section.(push_global ~poly env' (SecInductive mind) sections)
| _, (M | MT) -> Some sections
| _ -> assert false
in
{ senv with
env = env';
sections;
revstruct = field :: senv.revstruct;
modlabels = Label.Set.union mlabs senv.modlabels;
objlabels = Label.Set.union olabs senv.objlabels }
(** Applying a certain function to the resolver of a safe environment *)
let update_resolver f senv = { senv with modresolver = f senv.modresolver }
type global_declaration =
| ConstantEntry : Entries.constant_entry -> global_declaration
| OpaqueEntry : unit Entries.opaque_entry -> global_declaration
type exported_opaque = {
exp_handle : Opaqueproof.opaque_handle;
exp_body : Constr.t;
exp_univs : int option;
(* Minimal amount of data needed to rebuild the private universes. We enforce
in the API that private constants have no internal constraints. *)
}
type exported_private_constant = Constant.t * exported_opaque option
let repr_exported_opaque o =
let priv = match o .exp_univs with
| None -> Opaqueproof.PrivateMonomorphic ()
| Some _ -> Opaqueproof.PrivatePolymorphic Univ.ContextSet.empty
in
(o.exp_handle, (o.exp_body, priv))
let add_constant_aux senv (kn, cb) =
let l = Constant.label kn in
(* This is the only place where we hashcons the contents of a constant body *)
let cb = if sections_are_opened senv then cb else Declareops.hcons_const_body cb in
let senv' = add_field (l,SFBconst cb) (C kn) senv in
let senv'' = match cb.const_body with
| Undef (Some lev) ->
update_resolver
(Mod_subst.add_inline_delta_resolver (Constant.user kn) (lev,None)) senv'
| _ -> senv'
in
senv''
let inline_side_effects env body side_eff =
let open Constr in
(** First step: remove the constants that are still in the environment *)
let filter e =
if Environ.mem_constant e.seff_constant env then None
else Some e
in
(* CAVEAT: we assure that most recent effects come first *)
let side_eff = List.map_filter filter (SideEffects.repr side_eff) in
let sigs = List.rev_map (fun e -> e.seff_certif) side_eff in
(** Most recent side-effects first in side_eff *)
if List.is_empty side_eff then (body, Univ.ContextSet.empty, sigs, 0)
else
(** Second step: compute the lifts and substitutions to apply *)
let cname c r = Context.make_annot (Name (Label.to_id (Constant.label c))) r in
let fold (subst, var, ctx, args) { seff_constant = c; seff_body = cb; seff_univs = univs; _ } =
let (b, opaque) = match cb.const_body with
| Def b -> (b, false)
| OpaqueDef b -> (b, true)
| _ -> assert false
in
match cb.const_universes with
| Monomorphic ->
(** Abstract over the term at the top of the proof *)
let ty = cb.const_type in
let subst = Cmap_env.add c (Inr var) subst in
let ctx = Univ.ContextSet.union ctx univs in
(subst, var + 1, ctx, (cname c cb.const_relevance, b, ty, opaque) :: args)
| Polymorphic _ ->
let () = assert (Univ.ContextSet.is_empty univs) in
(** Inline the term to emulate universe polymorphism *)
let subst = Cmap_env.add c (Inl b) subst in
(subst, var, ctx, args)
in
let (subst, len, ctx, args) = List.fold_left fold (Cmap_env.empty, 1, Univ.ContextSet.empty, []) side_eff in
(** Third step: inline the definitions *)
let rec subst_const i k t = match Constr.kind t with
| Const (c, u) ->
let data = try Some (Cmap_env.find c subst) with Not_found -> None in
begin match data with
| None -> t
| Some (Inl b) ->
(** [b] is closed but may refer to other constants *)
subst_const i k (Vars.subst_instance_constr u b)
| Some (Inr n) ->
mkRel (k + n - i)
end
| Rel n ->
(** Lift free rel variables *)
if n <= k then t
else mkRel (n + len - i - 1)
| _ -> Constr.map_with_binders ((+) 1) (fun k t -> subst_const i k t) k t
in
let map_args i (na, b, ty, opaque) =
(** Both the type and the body may mention other constants *)
let ty = subst_const (len - i - 1) 0 ty in
let b = subst_const (len - i - 1) 0 b in
(na, b, ty, opaque)
in
let args = List.mapi map_args args in
let body = subst_const 0 0 body in
let fold_arg (na, b, ty, opaque) accu =
if opaque then mkApp (mkLambda (na, ty, accu), [|b|])
else mkLetIn (na, b, ty, accu)
in
let body = List.fold_right fold_arg args body in
(body, ctx, sigs, len - 1)
let inline_private_constants env ((body, ctx), side_eff) =
let body, ctx', _, _ = inline_side_effects env body side_eff in
let ctx' = Univ.ContextSet.union ctx ctx' in
(body, ctx')
(* Given the list of signatures of side effects, checks if they match.
* I.e. if they are ordered descendants of the current revstruct.
Returns the number of effects that can be trusted. *)
let check_signatures senv sl =
let curmb = Certificate.make senv in
let is_direct_ancestor accu mb =
match accu with
| None -> None
| Some curmb ->
try
let mb = CEphemeron.get mb in
if Certificate.check ~src:curmb ~dst:mb
then Some mb
else None
with CEphemeron.InvalidKey -> None in
let sl = List.fold_left is_direct_ancestor (Some curmb) sl in
match sl with
| None -> None
| Some mb ->
let univs = Certificate.universes mb in
Some (Univ.ContextSet.diff univs senv.univ)
type side_effect_declaration =
| DefinitionEff : Entries.definition_entry -> side_effect_declaration
| OpaqueEff : Constr.constr Entries.opaque_entry -> side_effect_declaration
let constant_entry_of_side_effect eff =
let cb = eff.seff_body in
let open Entries in
let univs =
match cb.const_universes with
| Monomorphic ->
Monomorphic_entry
| Polymorphic auctx ->
Polymorphic_entry (Univ.AbstractContext.repr auctx)
in
let p =
match cb.const_body with
| OpaqueDef b -> b
| Def b -> b
| _ -> assert false in
if Declareops.is_opaque cb then
OpaqueEff {
opaque_entry_body = p;
opaque_entry_secctx = Context.Named.to_vars cb.const_hyps;
opaque_entry_type = cb.const_type;
opaque_entry_universes = univs;
}
else
DefinitionEff {
const_entry_body = p;
const_entry_secctx = Some (Context.Named.to_vars cb.const_hyps);
const_entry_type = Some cb.const_type;
const_entry_universes = univs;
const_entry_inline_code = cb.const_inline_code }
let export_eff eff =
(eff.seff_constant, eff.seff_body)
let is_empty_private = function
| Opaqueproof.PrivateMonomorphic ctx -> Univ.ContextSet.is_empty ctx
| Opaqueproof.PrivatePolymorphic ctx -> Univ.ContextSet.is_empty ctx
(* Special function to call when the body of an opaque definition is provided.
It performs the type-checking of the body immediately. *)
let infer_direct_opaque ~sec_univs env ce =
let cb, ctx = Constant_typing.infer_opaque ~sec_univs env ce in
let body = ce.Entries.opaque_entry_body, Univ.ContextSet.empty in
let handle _env c () = (c, Univ.ContextSet.empty, 0) in
let (c, u) = Constant_typing.check_delayed handle ctx (body, ()) in
(* No constraints can be generated, we set it empty everywhere *)
let () = assert (is_empty_private u) in
{ cb with const_body = OpaqueDef c }
let export_side_effects senv eff =
let sec_univs = Option.map Section.all_poly_univs senv.sections in
let env = senv.env in
let not_exists e = not (Environ.mem_constant e.seff_constant env) in
let aux (acc,sl) e =
if not (not_exists e) then acc, sl
else e :: acc, e.seff_certif :: sl in
let seff, signatures = List.fold_left aux ([],[]) (SideEffects.repr eff) in
let trusted = check_signatures senv signatures in
let push_seff env eff =
let { seff_constant = kn; seff_body = cb ; _ } = eff in
let env = Environ.add_constant kn (lift_constant cb) env in
env
in
match trusted with
| Some univs ->
univs, List.map export_eff seff
| None ->
let rec recheck_seff seff univs acc env = match seff with
| [] -> univs, List.rev acc
| eff :: rest ->
let uctx = eff.seff_univs in
let env = Environ.push_context_set ~strict:true uctx env in
let univs = Univ.ContextSet.union uctx univs in
let env, cb =
let ce = constant_entry_of_side_effect eff in
let open Entries in
let cb = match ce with
| DefinitionEff ce ->
Constant_typing.infer_constant ~sec_univs env (DefinitionEntry ce)
| OpaqueEff ce ->
infer_direct_opaque ~sec_univs env ce
in
let eff = { eff with seff_body = cb } in
(push_seff env eff, export_eff eff)
in
recheck_seff rest univs (cb :: acc) env
in
recheck_seff seff Univ.ContextSet.empty [] env
let push_opaque_proof senv =
let o, otab = Opaqueproof.create (library_dp_of_senv senv) senv.opaquetab in
let senv = { senv with opaquetab = otab } in
senv, o
let export_private_constants eff senv =
let uctx, exported = export_side_effects senv eff in
let senv = push_context_set ~strict:true uctx senv in
let map senv (kn, c) = match c.const_body with
| OpaqueDef body ->
(* Don't care about the body, it has been checked by {!infer_direct_opaque} *)
let senv, o = push_opaque_proof senv in
let (_, _, _, h) = Opaqueproof.repr o in
let univs = match c.const_universes with
| Monomorphic -> None
| Polymorphic auctx -> Some (Univ.AbstractContext.size auctx)
in
let body = Constr.hcons body in
let opaque = { exp_body = body; exp_handle = h; exp_univs = univs } in
senv, (kn, { c with const_body = OpaqueDef o }, Some opaque)
| Def _ | Undef _ | Primitive _ | Symbol _ as body ->
senv, (kn, { c with const_body = body }, None)
in
let senv, bodies = List.fold_left_map map senv exported in
let exported = List.map (fun (kn, _, opaque) -> kn, opaque) bodies in
(* No delayed constants to declare *)
let fold senv (kn, cb, _) = add_constant_aux senv (kn, cb) in
let senv = List.fold_left fold senv bodies in
exported, senv
let add_constant l decl senv =
let kn = Constant.make2 senv.modpath l in
let senv, cb =
let sec_univs = Option.map Section.all_poly_univs senv.sections in
match decl with
| OpaqueEntry ce ->
let senv, o = push_opaque_proof senv in
let cb, ctx = Constant_typing.infer_opaque ~sec_univs senv.env ce in
(* Push the delayed data in the environment *)
let (_, _, _, i) = Opaqueproof.repr o in
let nonce = Nonce.create () in
let future_cst = HandleMap.add i (ctx, senv, nonce) senv.future_cst in
let senv = { senv with future_cst } in
senv, { cb with const_body = OpaqueDef o }
| ConstantEntry ce ->
senv, Constant_typing.infer_constant ~sec_univs senv.env ce
in
let senv = add_constant_aux senv (kn, cb) in
let senv =
match decl with
| ConstantEntry (Entries.PrimitiveEntry { Entries.prim_entry_content = CPrimitives.OT_type t; _ }) ->
if sections_are_opened senv then CErrors.anomaly (Pp.str "Primitive type not allowed in sections");
add_retroknowledge (Retroknowledge.Register_type(t,kn)) senv
| _ -> senv
in
kn, senv
let add_constant ?typing_flags l decl senv =
with_typing_flags ?typing_flags senv ~f:(add_constant l decl)
type opaque_certificate = {
opq_body : Constr.t;
opq_univs : Univ.ContextSet.t Opaqueproof.delayed_universes;
opq_handle : Opaqueproof.opaque_handle;
opq_nonce : Nonce.t;
}
let check_opaque senv (i : Opaqueproof.opaque_handle) pf =
let ty_ctx, trust, nonce =
try HandleMap.find i senv.future_cst
with Not_found ->
CErrors.anomaly Pp.(str "Missing opaque with identifier " ++ int (Opaqueproof.repr_handle i))
in
let handle env body eff =
let body, uctx, signatures, skip = inline_side_effects env body eff in
let trusted = check_signatures trust signatures in
let trusted, uctx = match trusted with
| None -> 0, uctx
| Some univs -> skip, Univ.ContextSet.union univs uctx
in
body, uctx, trusted
in
let (c, ctx) = Constant_typing.check_delayed handle ty_ctx pf in
let c = Constr.hcons c in
let ctx = match ctx with
| Opaqueproof.PrivateMonomorphic u ->
Opaqueproof.PrivateMonomorphic (Univ.hcons_universe_context_set u)
| Opaqueproof.PrivatePolymorphic u ->
Opaqueproof.PrivatePolymorphic (Univ.hcons_universe_context_set u)
in
{ opq_body = c; opq_univs = ctx; opq_handle = i; opq_nonce = nonce }
let fill_opaque { opq_univs = ctx; opq_handle = i; opq_nonce = n; _ } senv =
let () = if not @@ HandleMap.mem i senv.future_cst then
CErrors.anomaly Pp.(str "Missing opaque handle" ++ spc () ++ int (Opaqueproof.repr_handle i))
in
let _, _, nonce = HandleMap.find i senv.future_cst in
let () =
if not (Nonce.equal n nonce) then
CErrors.anomaly Pp.(str "Invalid opaque certificate")
in
(* TODO: Drop the the monomorphic constraints, they should really be internal
but the higher levels use them haphazardly. *)
let senv = match ctx with
| Opaqueproof.PrivateMonomorphic ctx -> add_constraints ctx senv
| Opaqueproof.PrivatePolymorphic _ -> senv
in
(* Mark the constant as having been checked *)
{ senv with future_cst = HandleMap.remove i senv.future_cst }
let is_filled_opaque i senv =
let () = assert (Opaqueproof.mem_handle i senv.opaquetab) in
not (HandleMap.mem i senv.future_cst)
let repr_certificate { opq_body = body; opq_univs = ctx; _ } =
body, ctx
let check_constraints uctx = function
| Entries.Polymorphic_entry _ -> Univ.ContextSet.is_empty uctx
| Entries.Monomorphic_entry -> true
let add_private_constant l uctx decl senv : (Constant.t * private_constants) * safe_environment =
let kn = Constant.make2 senv.modpath l in
let senv = push_context_set ~strict:true uctx senv in
let cb =
let sec_univs = Option.map Section.all_poly_univs senv.sections in
match decl with
| OpaqueEff ce ->
let () = assert (check_constraints uctx ce.Entries.opaque_entry_universes) in
infer_direct_opaque ~sec_univs senv.env ce
| DefinitionEff ce ->
let () = assert (check_constraints uctx ce.Entries.const_entry_universes) in
Constant_typing.infer_constant ~sec_univs senv.env (Entries.DefinitionEntry ce)
in
let dcb = match cb.const_body with
| Def _ as const_body -> { cb with const_body }
| OpaqueDef _ ->
(* We drop the body, to save the definition of an opaque and thus its
hashconsing. It does not matter since this only happens inside a proof,
and depending of the opaque status of the latter, this proof term will be
either inlined or reexported. *)
{ cb with const_body = Undef None }
| Undef _ | Primitive _ | Symbol _ -> assert false
in
let senv = add_constant_aux senv (kn, dcb) in
let eff =
let from_env = CEphemeron.create (Certificate.make senv) in
let eff = {
seff_certif = from_env;
seff_constant = kn;
seff_body = cb;
seff_univs = uctx;
} in
SideEffects.add eff empty_private_constants
in
(kn, eff), senv
(** Rewrite rules *)
let add_rewrite_rules l rules senv =
if Option.has_some senv.sections
then CErrors.user_err Pp.(str "Adding rewrite rules not supported in sections.");
(* TODO: Hashconsing? *)