-
Notifications
You must be signed in to change notification settings - Fork 51
/
coq_elpi_HOAS.ml
3662 lines (3260 loc) · 152 KB
/
coq_elpi_HOAS.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
(* coq-elpi: Coq terms as the object language of elpi *)
(* license: GNU Lesser General Public License Version 2.1 or later *)
(* ------------------------------------------------------------------------- *)
module API = Elpi.API
module E = API.RawData
module CD = API.RawOpaqueData
module U = API.Utils
module P = API.RawPp
module S = API.State
module F = API.FlexibleData
module C = Constr
module EC = EConstr
open Names
module G = GlobRef
open Coq_elpi_utils
(* ************************************************************************ *)
(* ****************** HOAS of Coq terms and goals ************************* *)
(* See also coq-HOAS.elpi (terms) *)
(* ************************************************************************ *)
(* {{{ CData ************************************************************** *)
(* names *)
let namein, isname, nameout, name =
let { CD.cin; isc; cout }, name = CD.declare {
CD.name = "name";
doc = "Name.Name.t: Name hints (in binders), can be input writing a name between backticks, e.g. `x` or `_` for anonymous. Important: these are just printing hints with no meaning, hence in elpi two name are always related: `x` = `y`";
pp = (fun fmt x ->
Format.fprintf fmt "`%a`" Pp.pp_with (Name.print x));
compare = (fun _ _ -> 0);
hash = (fun _ -> 0);
hconsed = false;
constants = [];
} in
cin, isc, cout, name
;;
let in_elpi_name x = namein x
let is_coq_name ~depth t =
match E.look ~depth t with
| E.CData n -> isname n || (CD.is_string n && Id.is_valid (CD.to_string n))
| _ -> false
let in_coq_name ~depth t =
match E.look ~depth t with
| E.CData n when isname n -> nameout n
| E.CData n when CD.is_string n ->
let s = CD.to_string n in
if s = "_" then Name.Anonymous
else Name.Name (Id.of_string s)
| E.UnifVar _ -> Name.Anonymous
| _ -> err Pp.(str"Not a name: " ++ str (API.RawPp.Debug.show_term t))
(* engine prologue, to break ciclicity *)
type coq_engine = {
global_env : Environ.env;
sigma : Evd.evar_map; (* includes universe constraints *)
}
let pre_engine : coq_engine S.component option ref = ref None
(* universes *)
module UnivOrd = struct
type t = Univ.Universe.t
let compare = Univ.Universe.compare
let show x = Pp.string_of_ppcmds (Univ.Universe.pr UnivNames.pr_level_with_global_universes x)
let pp fmt x = Format.fprintf fmt "%s" (show x)
end
module UnivSet = U.Set.Make(UnivOrd)
module UnivMap = U.Map.Make(UnivOrd)
module UnivLevelOrd = struct
type t = Univ.Level.t
let compare = Univ.Level.compare
let show x = Pp.string_of_ppcmds (UnivNames.pr_level_with_global_universes x)
let pp fmt x = Format.fprintf fmt "%s" (show x)
end
module UnivLevelSet = U.Set.Make(UnivLevelOrd)
module UnivLevelMap = U.Map.Make(UnivLevelOrd)
(* map from Elpi evars and Coq's universe levels *)
module UM = F.Map(struct
type t = Univ.Universe.t
let compare = Univ.Universe.compare
let show x = Pp.string_of_ppcmds @@ Univ.Universe.pr UnivNames.pr_level_with_global_universes x
let pp fmt x = Format.fprintf fmt "%a" Pp.pp_with (Univ.Universe.pr UnivNames.pr_level_with_global_universes x)
end)
let um = S.declare_component ~name:"coq-elpi:evar-univ-map" ~descriptor:interp_state
~pp:UM.pp ~init:(fun () -> UM.empty) ~start:(fun x -> x) ()
let constraint_leq u1 u2 =
let open UnivProblem in
ULe (u1, u2)
let constraint_eq u1 u2 =
let open UnivProblem in
ULe (u1, u2)
let add_constraints state c = S.update (Option.get !pre_engine) state (fun ({ sigma } as x) ->
{ x with sigma = Evd.add_universe_constraints sigma c })
let add_universe_constraint state c =
let open UnivProblem in
try add_constraints state (Set.singleton c)
with
| UGraph.UniverseInconsistency p ->
let sigma = (S.get (Option.get !pre_engine) state).sigma in
Feedback.msg_debug
(UGraph.explain_universe_inconsistency
(Termops.pr_evd_qvar sigma)
(Termops.pr_evd_level sigma)
p);
raise API.BuiltInPredicate.No_clause
| Evd.UniversesDiffer | UState.UniversesDiffer ->
Feedback.msg_debug Pp.(str"UniversesDiffer");
raise API.BuiltInPredicate.No_clause
let new_univ_level_variable ?(flexible=false) state =
S.update_return (Option.get !pre_engine) state (fun ({ sigma } as e) ->
(* ~name: really mean the universe level is a binder as in Definition f@{x} *)
let rigidity = if flexible then UState.univ_flexible_alg else UState.univ_rigid in
let sigma, v = Evd.new_univ_level_variable ?name:None rigidity sigma in
let u = Univ.Universe.make v in
(*
let sigma = Evd.add_universe_constraints sigma
(UnivProblem.Set.singleton (UnivProblem.ULe (Sorts.set,Sorts.sort_of_univ u))) in
*)
{ e with sigma }, (v, u))
(* We patch data_of_cdata by forcing all output universes that
* are unification variables to be a Coq universe variable, so that
* we can always call Coq's API *)
let isuniv, univout, (univ : Univ.Universe.t API.Conversion.t) =
let { CD.cin = univin; isc = isuniv; cout = univout }, univ_to_be_patched = CD.declare {
CD.name = "univ";
doc = "universe level (algebraic: max, +1, univ.variable)";
pp = (fun fmt x ->
let s = Pp.string_of_ppcmds (Univ.Universe.pr UnivNames.pr_level_with_global_universes x) in
Format.fprintf fmt "«%s»" s);
compare = Univ.Universe.compare;
hash = Univ.Universe.hash;
hconsed = false;
constants = [];
} in
(* turn UVars into fresh universes *)
isuniv, univout, { univ_to_be_patched with
API.Conversion.readback = begin fun ~depth state t ->
match E.look ~depth t with
| E.UnifVar (b,args) ->
let m = S.get um state in
begin try
let u = UM.host b m in
state, u, []
with Not_found ->
(* flexible makes {{ Type }} = {{ Set }} also true when coq.unify-eq {{ Type }} {{ Set }} *)
let state, (_,u) = new_univ_level_variable ~flexible:true state in
let state = S.update um state (UM.add b u) in
state, u, [ API.Conversion.Unify(E.mkUnifVar b ~args state,univin u) ]
end
| _ -> univ_to_be_patched.API.Conversion.readback ~depth state t
end
}
let sort =
let open API.AlgebraicData in declare {
ty = API.Conversion.TyName "sort";
doc = "Sorts (kinds of types)";
pp = (fun fmt -> function
| Sorts.Type _ -> Format.fprintf fmt "Type"
| Sorts.Set -> Format.fprintf fmt "Set"
| Sorts.Prop -> Format.fprintf fmt "Prop"
| Sorts.SProp -> Format.fprintf fmt "SProp"
| Sorts.QSort _ -> Format.fprintf fmt "Type");
constructors = [
K("prop","impredicative sort of propositions",N,
B Sorts.prop,
M (fun ~ok ~ko -> function Sorts.Prop -> ok | _ -> ko ()));
K("sprop","impredicative sort of propositions with definitional proof irrelevance",N,
B Sorts.sprop,
M (fun ~ok ~ko -> function Sorts.SProp -> ok | _ -> ko ()));
K("typ","predicative sort of data (carries a universe level)",A(univ,N),
B (fun x -> Sorts.sort_of_univ x),
M (fun ~ok ~ko -> function
| Sorts.Type x -> ok x
| Sorts.Set -> ok Univ.Universe.type0
| _ -> ko ()));
K("uvar","",A(F.uvar,N),
BS (fun (k,_) state ->
let m = S.get um state in
try
let u = UM.host k m in
state, Sorts.sort_of_univ u
with Not_found ->
let state, (_,u) = new_univ_level_variable state in
let state = S.update um state (UM.add k u) in
state, Sorts.sort_of_univ u),
M (fun ~ok ~ko _ -> ko ()));
]
} |> API.ContextualConversion.(!<)
let universe_level_variable =
let { CD.cin = levelin }, universe_level_variable_to_patch = CD.declare {
CD.name = "univ.variable";
doc = "universe level variable";
pp = (fun fmt x ->
let s = Pp.string_of_ppcmds (UnivNames.pr_level_with_global_universes x) in
Format.fprintf fmt "«%s»" s);
compare = Univ.Level.compare;
hash = Univ.Level.hash;
hconsed = false;
constants = [];
} in
{ universe_level_variable_to_patch with
API.Conversion.readback = begin fun ~depth state t ->
match E.look ~depth t with
| E.UnifVar (b,args) ->
let m = S.get um state in
begin try
let u = UM.host b m in
state, Option.get @@ Univ.Universe.level u, []
with Not_found ->
let state, (l,u) = new_univ_level_variable state in
let state = S.update um state (UM.add b u) in
state, l, [ API.Conversion.Unify(E.mkUnifVar b ~args state,levelin l) ]
end
| _ -> universe_level_variable_to_patch.API.Conversion.readback ~depth state t
end
}
let universe_constraint : Univ.univ_constraint API.Conversion.t =
let open API.Conversion in let open API.AlgebraicData in declare {
ty = TyName "univ-constraint";
doc = "Constraint between two universes level variables";
pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
constructors = [
K("lt","",A(universe_level_variable,A(universe_level_variable,N)),
B (fun u1 u2 -> (u1,Univ.Lt,u2)),
M (fun ~ok ~ko -> function (l1,Univ.Lt,l2) -> ok l1 l2 | _ -> ko ()));
K("le","",A(universe_level_variable,A(universe_level_variable,N)),
B (fun u1 u2 -> (u1,Univ.Le,u2)),
M (fun ~ok ~ko -> function (l1,Univ.Le,l2) -> ok l1 l2 | _ -> ko ()));
K("eq","",A(universe_level_variable,A(universe_level_variable,N)),
B (fun u1 u2 -> (u1,Univ.Eq,u2)),
M (fun ~ok ~ko -> function (l1,Univ.Eq,l2) -> ok l1 l2 | _ -> ko ()))
]
} |> API.ContextualConversion.(!<)
let universe_variance : (Univ.Level.t * UVars.Variance.t option) API.Conversion.t =
let open API.Conversion in let open API.AlgebraicData in declare {
ty = TyName "univ-variance";
doc = "Variance of a universe level variable";
pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
constructors = [
K("auto","",A(universe_level_variable,N),
B (fun u -> u,None),
M (fun ~ok ~ko -> function (u,None) -> ok u | _ -> ko ()));
K("covariant","",A(universe_level_variable,N),
B (fun u -> u,Some UVars.Variance.Covariant),
M (fun ~ok ~ko -> function (u,Some UVars.Variance.Covariant) -> ok u | _ -> ko ()));
K("invariant","",A(universe_level_variable,N),
B (fun u -> u,Some UVars.Variance.Invariant),
M (fun ~ok ~ko -> function (u,Some UVars.Variance.Invariant) -> ok u | _ -> ko ()));
K("irrelevant","",A(universe_level_variable,N),
B (fun u -> u,Some UVars.Variance.Invariant),
M (fun ~ok ~ko -> function (u,Some UVars.Variance.Irrelevant) -> ok u | _ -> ko ()));
]
} |> API.ContextualConversion.(!<)
type universe_decl = (Univ.Level.t list * bool) * (Univ.Constraints.t * bool)
let universe_decl : universe_decl API.Conversion.t =
let open API.Conversion in let open API.BuiltInData in let open API.AlgebraicData in let open Elpi.Builtin in declare {
ty = TyName "upoly-decl";
doc = "Constraints for a non-cumulative declaration. Boolean tt means loose (e.g. the '+' in f@{u v + | u < v +})";
pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
constructors = [
K("upoly-decl","",A(list universe_level_variable,A(bool,A(list universe_constraint,A(bool,N)))),
B (fun x sx y sy-> (x,sx),(Univ.Constraints.of_list y,sy)),
M (fun ~ok ~ko:_ ((x,sx),(y,sy)) -> ok x sx (Univ.Constraints.elements y) sy))
]
} |> API.ContextualConversion.(!<)
type universe_decl_cumul = ((Univ.Level.t * UVars.Variance.t option) list * bool) * (Univ.Constraints.t * bool)
let universe_decl_cumul : universe_decl_cumul API.Conversion.t =
let open API.Conversion in let open API.BuiltInData in let open API.AlgebraicData in let open Elpi.Builtin in declare {
ty = TyName "upoly-decl-cumul";
doc = "Constraints for a cumulative declaration. Boolean tt means loose (e.g. the '+' in f@{u v + | u < v +})";
pp = (fun fmt _ -> Format.fprintf fmt "<todo>");
constructors = [
K("upoly-decl-cumul","",A(list universe_variance,A(bool,A(list universe_constraint,A(bool,N)))),
B (fun x sx y sy -> ((x,sx),(Univ.Constraints.of_list y,sy))),
M (fun ~ok ~ko:_ ((x,sx),(y,sy)) -> ok x sx (Univ.Constraints.elements y) sy))
]
} |> API.ContextualConversion.(!<)
(* All in one data structure to represent the Coq context and its link with
the elpi one:
- section is not part of the elpi context, but Coq's evars are applied
also to that part
- proof is the named_context with proof variables only (no section part)
- local is the rel_context
- db2rel stores how many locally bound (rel) variables were there when
the binder for the given dbl is crossed: see lp2term
- env is a Coq environment corresponding to section + proof + local *)
type empty = [ `Options ]
type full = [ `Options | `Context ]
(* Readback of UVars into ... *)
type ppoption = All | Most | Normal
type hole_mapping =
| Verbatim (* 1:1 correspondence between UVar and Evar *)
| Heuristic (* new UVar outside Llam is pruned before being linked to Evar *)
| Implicit (* No link, UVar is intepreted as a "hole" constant *)
type uinstanceoption =
| NoInstance
(* the elpi command involved has to generate a fresh instance *)
| ConcreteInstance of UVars.Instance.t
(* a concrete instance was provided, the command will use it *)
| VarInstance of (F.Elpi.t * E.term list * inv_rel_key)
(* a variable was provided, the command will compute the instance to unify with it *)
type universe_decl_option =
| NotUniversePolymorphic
| Cumulative of universe_decl_cumul
| NonCumulative of universe_decl
type options = {
hoas_holes : hole_mapping option;
local : bool option;
user_warns : UserWarn.t option;
primitive : bool option;
failsafe : bool; (* readback is resilient to illformed terms *)
ppwidth : int;
pp : ppoption;
pplevel : Constrexpr.entry_relative_level;
using : string option;
inline : Declaremods.inline;
uinstance : uinstanceoption;
universe_decl : universe_decl_option;
reversible : bool option;
keepunivs : bool option;
redflags : RedFlags.reds option;
no_tc: bool option;
}
let default_options () = {
hoas_holes = Some Verbatim;
local = None;
user_warns = None;
primitive = None;
failsafe = false;
ppwidth = Option.default 80 (Topfmt.get_margin ());
pp = Normal;
pplevel = Constrexpr.LevelSome;
using = None;
inline = Declaremods.NoInline;
uinstance = NoInstance;
universe_decl = NotUniversePolymorphic;
reversible = None;
keepunivs = None;
redflags = None;
no_tc = None;
}
let make_options ~hoas_holes ~local ~warn ~depr ~primitive ~failsafe ~ppwidth
~pp ~pplevel ~using ~inline ~uinstance ~universe_decl ~reversible ~keepunivs
~redflags ~no_tc =
let user_warns = Some UserWarn.{ depr; warn } in
{ hoas_holes; local; user_warns; primitive; failsafe; ppwidth; pp;
pplevel; using; inline; uinstance; universe_decl; reversible; keepunivs;
redflags; no_tc; }
let make_warn = UserWarn.make_warn
type 'a coq_context = {
section : Names.Id.t list;
section_len : int;
proof : EConstr.named_context;
proof_len : int;
local : (int * EConstr.rel_declaration) list;
local_len : int;
env : Environ.env;
db2name : Names.Id.t Int.Map.t;
name2db : int Names.Id.Map.t;
db2rel : int Int.Map.t;
names : Id.Set.t;
options : options;
}
let upcast (x : [> `Options ] coq_context) : full coq_context = (x :> full coq_context)
let pr_coq_ctx { env; db2name; db2rel } sigma =
let open Pp in
v 0 (
str "Mapping from DBL:"++ cut () ++ str " " ++
v 0 (prlist_with_sep cut (fun (i,n) -> str(E.Constants.show i) ++ str " |-> " ++ Id.print n)
(Int.Map.bindings db2name)) ++ cut () ++
v 0 (prlist_with_sep cut (fun (i,n) -> str(E.Constants.show i) ++ str " |-> " ++ int n)
(Int.Map.bindings db2rel)) ++ cut () ++
str "Named:" ++ cut () ++ str " " ++
v 0 (Printer.pr_named_context_of env sigma) ++ cut () ++
str "Rel:" ++ cut () ++ str " " ++
v 0 (Printer.pr_rel_context_of env sigma) ++ cut ()
)
let in_coq_fresh ~id_only =
let mk_fresh dbl =
Id.of_string_soft
(Printf.sprintf "elpi_ctx_entry_%d_" dbl) in
fun ~depth dbl name ~names ->
match in_coq_name ~depth name with
| Name.Anonymous when id_only -> Name.Name (mk_fresh dbl)
| Name.Anonymous as x -> x
| Name.Name id when Id.Set.mem id names -> Name.Name (mk_fresh dbl)
| Name.Name id as x -> x
let relevant = EConstr.ERelevance.relevant
let anonR = Context.make_annot Names.Name.Anonymous EConstr.ERelevance.irrelevant
let nameR x = Context.make_annot (Names.Name.Name x) EConstr.ERelevance.irrelevant
let annotR x = Context.make_annot x EConstr.ERelevance.irrelevant
let in_coq_annot ~depth t = Context.make_annot (in_coq_name ~depth t) relevant
let in_coq_fresh_annot_name ~depth ~coq_ctx dbl t =
Context.make_annot (in_coq_fresh ~id_only:false ~depth ~names:coq_ctx.names dbl t) relevant
let in_coq_fresh_annot_id ~depth ~names dbl t =
let get_name = function Name.Name x -> x | Name.Anonymous -> assert false in
Context.make_annot (in_coq_fresh ~id_only:true ~depth ~names dbl t |> get_name) relevant
let unspec2opt = function Elpi.Builtin.Given x -> Some x | Elpi.Builtin.Unspec -> None
let opt2unspec = function Some x -> Elpi.Builtin.Given x | None -> Elpi.Builtin.Unspec
(* constants *)
type global_constant = Variable of Names.Id.t | Constant of Names.Constant.t
let hash_global_constant = function
| Variable id -> Names.Id.hash id
| Constant c -> Names.Constant.CanOrd.hash c
let compare_global_constant x y = match x,y with
| Variable v1, Variable v2 -> Names.Id.compare v1 v2
| Constant c1, Constant c2 -> Names.Constant.CanOrd.compare c1 c2
| Variable _, _ -> -1
| _ -> 1
let global_constant_of_globref = function
| GlobRef.VarRef x -> Variable x
| GlobRef.ConstRef x -> Constant x
| x -> CErrors.anomaly Pp.(str"not a global constant: " ++ (Printer.pr_global x))
let ({ CD.isc = isconstant; cout = constantout; cin = constantin },constant),
({ CD.isc = isinductive; cout = inductiveout; cin = inductivein },inductive),
({ CD.isc = isconstructor; cout = constructorout; cin = constructorin },constructor) =
let open API.RawOpaqueData in
declare {
name = "constant";
doc = "Global constant name";
pp = (fun fmt x ->
let x = match x with
| Variable x -> GlobRef.VarRef x
| Constant c -> GlobRef.ConstRef c in
Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global x));
compare = compare_global_constant;
hash = hash_global_constant;
hconsed = false;
constants = [];
},
declare {
name = "inductive";
doc = "Inductive type name";
pp = (fun fmt x -> Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global (GlobRef.IndRef x)));
compare = Names.Ind.CanOrd.compare;
hash = Names.Ind.CanOrd.hash;
hconsed = false;
constants = [];
},
declare {
name = "constructor";
doc = "Inductive constructor name";
pp = (fun fmt x -> Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global (GlobRef.ConstructRef x)));
compare = Names.Construct.CanOrd.compare;
hash = Names.Construct.CanOrd.hash;
hconsed = false;
constants = [];
}
;;
let compare_instances x y =
let qx, ux = UVars.Instance.to_array x
and qy, uy = UVars.Instance.to_array y in
Util.Compare.(compare [(CArray.compare Sorts.Quality.compare, qx, qy); (CArray.compare Univ.Level.compare, ux, uy)])
let uinstancein, isuinstance, uinstanceout, uinstance =
let { CD.cin; isc; cout }, uinstance = CD.declare {
CD.name = "univ-instance";
doc = "Universes level instance for a universe-polymorphic constant";
pp = (fun fmt x ->
let s = Pp.string_of_ppcmds (UVars.Instance.pr Sorts.QVar.raw_pr UnivNames.pr_level_with_global_universes x) in
Format.fprintf fmt "«%s»" s);
compare = compare_instances;
hash = UVars.Instance.hash;
hconsed = false;
constants = [];
} in
cin, isc, cout, uinstance
;;
let collect_term_variables ~depth t =
let rec aux ~depth acc t =
match E.look ~depth t with
| E.CData c when isconstant c ->
begin match constantout c with
| Variable id -> id :: acc
| _ -> acc
end
| x -> fold_elpi_term aux acc ~depth x
in
aux ~depth [] t
let constc = E.Constants.declare_global_symbol "const"
let indcc = E.Constants.declare_global_symbol "indc"
let indtc = E.Constants.declare_global_symbol "indt"
let gref : Names.GlobRef.t API.Conversion.t = {
API.Conversion.ty = API.Conversion.TyName "gref";
pp_doc = (fun fmt () ->
Format.fprintf fmt "%% Global objects: inductive types, inductive constructors, definitions@\n";
Format.fprintf fmt "kind gref type.@\n";
Format.fprintf fmt "type const constant -> gref. %% Nat.add, List.append, ...@\n";
Format.fprintf fmt "type indt inductive -> gref. %% nat, list, ...@\n";
Format.fprintf fmt "type indc constructor -> gref. %% O, S, nil, cons, ...@\n";
);
pp = (fun fmt x ->
Format.fprintf fmt "«%a»" Pp.pp_with (Printer.pr_global x));
embed = (fun ~depth state -> function
| GlobRef.IndRef i -> state, E.mkApp indtc (inductivein i) [], []
| GlobRef.ConstructRef c -> state, E.mkApp indcc (constructorin c) [], []
| GlobRef.VarRef v -> state, E.mkApp constc (constantin (Variable v)) [], []
| GlobRef.ConstRef c -> state, E.mkApp constc (constantin (Constant c)) [], []
);
readback = (fun ~depth state t ->
match E.look ~depth t with
| E.App(c,t,[]) when c == indtc ->
begin match E.look ~depth t with
| E.CData d when isinductive d -> state, GlobRef.IndRef (inductiveout d), []
| _ -> raise API.Conversion.(TypeErr(TyName"inductive",depth,t)); end
| E.App(c,t,[]) when c == indcc ->
begin match E.look ~depth t with
| E.CData d when isconstructor d -> state, GlobRef.ConstructRef (constructorout d), []
| _ -> raise API.Conversion.(TypeErr(TyName"constructor",depth,t)); end
| E.App(c,t,[]) when c == constc ->
begin match E.look ~depth t with
| E.CData d when isconstant d ->
begin match constantout d with
| Variable v -> state, GlobRef.VarRef v, []
| Constant v -> state, GlobRef.ConstRef v, [] end
| _ -> raise API.Conversion.(TypeErr(TyName"constant",depth,t)); end
| _ -> raise API.Conversion.(TypeErr(TyName"gref",depth,t));
);
}
let abbreviation =
let open API.OpaqueData in
declare {
name = "abbreviation";
doc = "Name of an abbreviation";
pp = (fun fmt x -> Format.fprintf fmt "«%s»" (KerName.to_string x));
compare = KerName.compare;
hash = KerName.hash;
hconsed = false;
constants = [];
}
module GROrd = struct
include Names.GlobRef.CanOrd
let show x = Pp.string_of_ppcmds (Printer.pr_global x)
let pp fmt x = Format.fprintf fmt "%a" Pp.pp_with (Printer.pr_global x)
end
module GRMap = U.Map.Make(GROrd)
module GRSet = U.Set.Make(GROrd)
let globalc = E.Constants.declare_global_symbol "global"
let pglobalc = E.Constants.declare_global_symbol "pglobal"
module GrefCache = Hashtbl.Make(struct
type t = GlobRef.t
let equal = GlobRef.SyntacticOrd.equal
let hash = GlobRef.SyntacticOrd.hash
end)
let cache = GrefCache.create 13
let assert_in_coq_gref_consistent ~poly gr =
match Global.is_polymorphic gr, poly with
| true, true -> ()
| false, false -> ()
| true, false ->
U.type_error Printf.(sprintf "Universe polymorphic gref %s used with the 'global' term constructor" (GROrd.show gr))
| false, true ->
U.type_error Printf.(sprintf "Non universe polymorphic gref %s used with the 'pglobal' term constructor" (GROrd.show gr))
;;
let assert_in_elpi_gref_consistent ~poly gr =
match Global.is_polymorphic gr, poly with
| true, true -> ()
| false, false -> ()
| true, false ->
U.anomaly Printf.(sprintf "Universe polymorphic gref %s used with the 'global' term constructor" (GROrd.show gr))
| false, true ->
U.anomaly Printf.(sprintf "Non universe polymorphic gref %s used with the 'pglobal' term constructor" (GROrd.show gr))
;;
let in_elpi_gr ~depth s r =
assert_in_elpi_gref_consistent ~poly:false r;
try
GrefCache.find cache r
with Not_found ->
let s, t, gl = gref.API.Conversion.embed ~depth s r in
assert (gl = []);
let x = E.mkApp globalc t [] in
GrefCache.add cache r x;
x
let in_elpi_poly_gr ~depth s r i =
assert_in_elpi_gref_consistent ~poly:true r;
let open API.Conversion in
let s, t, gl = gref.embed ~depth s r in
assert (gl = []);
E.mkApp pglobalc t [i]
let in_elpi_poly_gr_instance ~depth s r i =
assert_in_elpi_gref_consistent ~poly:true r;
let open API.Conversion in
let s, i, gl = uinstance.embed ~depth s i in
assert (gl = []);
in_elpi_poly_gr ~depth s r i
let in_coq_gref ~depth ~origin ~failsafe s t =
try
let s, t, gls = gref.API.Conversion.readback ~depth s t in
assert_in_coq_gref_consistent ~poly:false t;
assert(gls = []);
s, t
with API.Conversion.TypeErr _ ->
if failsafe then
s, Coqlib.lib_ref "elpi.unknown_gref"
else
err Pp.(str "The term " ++ str(pp2string (P.term depth) origin) ++
str " cannot be represented in Coq since its gref part is illformed")
let mpin, ismp, mpout, modpath =
let { CD.cin; isc; cout }, x = CD.declare {
CD.name = "modpath";
doc = "Name of a module /*E*/";
pp = (fun fmt x ->
Format.fprintf fmt "«%s»" (Names.ModPath.to_string x));
compare = Names.ModPath.compare;
hash = Names.ModPath.hash;
hconsed = false;
constants = [];
} in
cin, isc, cout, x
;;
let mptyin, istymp, mptyout, modtypath =
let { CD.cin; isc; cout }, x = CD.declare {
CD.name = "modtypath";
doc = "Name of a module type /*E*/";
pp = (fun fmt x ->
Format.fprintf fmt "«%s»" (Names.ModPath.to_string x));
compare = Names.ModPath.compare;
hash = Names.ModPath.hash;
hconsed = false;
constants =[];
} in
cin, isc, cout, x
;;
let in_elpi_modpath ~ty mp = if ty then mptyin mp else mpin mp
let is_modpath ~depth t =
match E.look ~depth t with E.CData x -> ismp x | _ -> false
let is_modtypath ~depth t =
match E.look ~depth t with E.CData x -> istymp x | _ -> false
let in_coq_modpath ~depth t =
match E.look ~depth t with
| E.CData x when ismp x -> mpout x
| E.CData x when istymp x -> mptyout x
| _ -> assert false
(* ********************************* }}} ********************************** *)
(* {{{ constants (app, fun, ...) ****************************************** *)
(* binders *)
let lamc = E.Constants.declare_global_symbol "fun"
let in_elpi_lam n s t = E.mkApp lamc (in_elpi_name n) [s;E.mkLam t]
let prodc = E.Constants.declare_global_symbol "prod"
let in_elpi_prod n s t = E.mkApp prodc (in_elpi_name n) [s;E.mkLam t]
let letc = E.Constants.declare_global_symbol "let"
let in_elpi_let n b s t = E.mkApp letc (in_elpi_name n) [s;b;E.mkLam t]
(* other *)
let appc = E.Constants.declare_global_symbol "app"
let in_elpi_app_Arg ~depth hd args =
match E.look ~depth hd, args with
| E.Const c, [] -> assert false
| E.Const c, x :: xs -> E.mkApp c x xs
| E.App(c,x,xs), _ -> E.mkApp c x (xs@args)
| _ -> assert false
let flatten_appc ~depth hd (args : E.term list) =
match E.look ~depth hd with
| E.App(c,x,[]) when c == appc ->
E.mkApp appc (U.list_to_lp_list (U.lp_list_to_list ~depth x @ args)) []
| _ -> E.mkApp appc (U.list_to_lp_list (hd :: args)) []
let in_elpi_appl ~depth hd (args : E.term list) =
if args = [] then hd
else flatten_appc ~depth hd args
let in_elpi_app ~depth hd (args : E.term array) =
in_elpi_appl ~depth hd (Array.to_list args)
let matchc = E.Constants.declare_global_symbol "match"
let in_elpi_match (*ci_ind ci_npar ci_cstr_ndecls ci_cstr_nargs*) t rt bs =
E.mkApp matchc t [rt; U.list_to_lp_list bs]
let fixc = E.Constants.declare_global_symbol "fix"
let in_elpi_fix name rno ty bo =
E.mkApp fixc (in_elpi_name name) [CD.of_int rno; ty; E.mkLam bo]
let primitivec = E.Constants.declare_global_symbol "primitive"
type pstring = Pstring.t
let pp_pstring = Pstring.to_string
let eC_mkString = EC.mkString
type primitive_value =
| Uint63 of Uint63.t
| Float64 of Float64.t
| Pstring of pstring
| Projection of Projection.t
let primitive_value : primitive_value API.Conversion.t =
let module B = Coq_elpi_utils in
let open API.AlgebraicData in declare {
ty = API.Conversion.TyName "primitive-value";
doc = "Primitive values";
pp = (fun fmt -> function
| Uint63 i -> Format.fprintf fmt "%s" (Uint63.to_string i)
| Float64 f -> Format.fprintf fmt "%s" (Float64.to_string f)
| Pstring s -> Format.fprintf fmt "%s" (pp_pstring s)
| Projection p -> Format.fprintf fmt "%s" (Projection.to_string p));
constructors = [
K("uint63","unsigned integers over 63 bits",A(B.uint63,N),
B (fun x -> Uint63 x),
M (fun ~ok ~ko -> function Uint63 x -> ok x | _ -> ko ()));
K("float64","double precision foalting points",A(B.float64,N),
B (fun x -> Float64 x),
M (fun ~ok ~ko -> function Float64 x -> ok x | _ -> ko ()));
K("pstring","primitive string",A(B.pstring,N),
B (fun x -> Pstring x),
M (fun ~ok ~ko -> function Pstring x -> ok x | _ -> ko ()));
K("proj","primitive projection",A(B.projection,A(API.BuiltInData.int,N)),
B (fun p n -> Projection p),
M (fun ~ok ~ko -> function Projection p -> ok p Names.Projection.(arg p + npars p) | _ -> ko ()));
]
} |> API.ContextualConversion.(!<)
let in_elpi_primitive ~depth state i =
let state, i, _ = primitive_value.API.Conversion.embed ~depth state i in
state, E.mkApp primitivec i []
let in_elpi_primitive_value ~depth state = function
| C.Int i -> in_elpi_primitive ~depth state (Uint63 i)
| C.Float f -> in_elpi_primitive ~depth state (Float64 f)
| C.String s -> in_elpi_primitive ~depth state (Pstring s)
| C.Array _ -> nYI "HOAS for persistent arrays"
| (C.Fix _ | C.CoFix _ | C.Lambda _ | C.App _ | C.Prod _ | C.Case _ | C.Cast _ | C.Construct _ | C.LetIn _ | C.Ind _ | C.Meta _ | C.Rel _ | C.Var _ | C.Proj _ | C.Evar _ | C.Sort _ | C.Const _) -> assert false
(* ********************************* }}} ********************************** *)
(* {{{ HOAS : Evd.evar_map -> elpi *************************************** *)
module CoqEngine_HOAS : sig
val show_coq_engine : ?with_univs:bool -> coq_engine -> string
val engine : coq_engine S.component
val from_env_sigma : Environ.env -> Evd.evar_map -> coq_engine
(* when the env changes under the hood, we can adapt sigma or drop it but keep
its constraints *)
val from_env_keep_univ_of_sigma : uctx:Univ.ContextSet.t -> env0:Environ.env -> env:Environ.env -> Evd.evar_map -> coq_engine
val from_env_keep_univ_and_sigma : uctx:Univ.ContextSet.t -> env0:Environ.env -> env:Environ.env -> Evd.evar_map -> coq_engine
end = struct
let pp_coq_engine ?with_univs fmt { sigma } =
Format.fprintf fmt "%a" Pp.pp_with (Termops.pr_evar_map ?with_univs None (Global.env()) sigma)
let show_coq_engine ?with_univs e = Format.asprintf "%a" (pp_coq_engine ?with_univs) e
let from_env_sigma global_env sigma =
{
global_env;
sigma;
}
let from_env env = from_env_sigma env (Evd.from_env env)
[%%if coq = "8.20"]
let demote uctx sigma0 env =
let uctx = UState.update_sigma_univs (Evd.evar_universe_context sigma0) (Environ.universes env) in
UState.demote_global_univs env uctx
[%%else]
let demote uctx sigma0 env =
UState.demote_global_univs uctx (Evd.evar_universe_context sigma0)
[%%endif]
let from_env_keep_univ_and_sigma ~uctx ~env0 ~env sigma0 =
assert(env0 != env);
let uctx = demote uctx sigma0 env in
from_env_sigma env (Evd.set_universe_context sigma0 uctx)
let from_env_keep_univ_of_sigma ~uctx ~env0 ~env sigma0 =
assert(env0 != env);
let uctx = demote uctx sigma0 env in
from_env_sigma env (Evd.from_ctx uctx)
let init () =
from_env (Global.env ())
let engine : coq_engine S.component =
S.declare_component ~name:"coq-elpi:evmap-constraint-type" ~descriptor:interp_state
~pp:pp_coq_engine ~init ~start:(fun _ -> init()) ()
end
let () = pre_engine := Some CoqEngine_HOAS.engine
open CoqEngine_HOAS
(* Bidirectional mapping between Elpi's UVars and Coq's Evars.
Coq evar E is represented by a constraint
evar X1 ty X2
and eventually a goal
goal ctx X1 ty attrs
and the bidirectional mapping
E <-> X2 \in UVElabMap
E <-> X1 \in UVRawMap
*)
module CoqEvarKey = struct
type t = Evar.t
let compare = Evar.compare
let pp fmt t = Format.fprintf fmt "%a" Pp.pp_with (Evar.print t)
let show t = Format.asprintf "%a" pp t
end
module UVElabMap = F.Map(CoqEvarKey)
module UVRawMap = F.Map(CoqEvarKey)
module UVMap = struct
let elpi k s =
UVRawMap.elpi k (S.get UVRawMap.uvmap s),
UVElabMap.elpi k (S.get UVElabMap.uvmap s)
let add k raw elab s =
let s = S.update UVRawMap.uvmap s (UVRawMap.add raw k) in
let s = S.update UVElabMap.uvmap s (UVElabMap.add elab k) in
s
(* should we remove this "unsafe" API? *)
let host elab s =
try
UVElabMap.host elab (S.get UVElabMap.uvmap s)
with Not_found ->
UVRawMap.host elab (S.get UVRawMap.uvmap s)
let mem_elpi x s =
try
let _ = UVElabMap.host x (S.get UVElabMap.uvmap s) in true
with Not_found -> try
let _ = UVRawMap.host x (S.get UVRawMap.uvmap s) in true
with Not_found ->
false
[@@ocaml.warning "-32"]
let mem_host x s =
try
let _ = UVElabMap.elpi x (S.get UVElabMap.uvmap s) in true
with Not_found -> try
let _ = UVRawMap.elpi x (S.get UVRawMap.uvmap s) in true
with Not_found ->
false
let show s =
"RAW:\n" ^ UVRawMap.show (S.get UVRawMap.uvmap s) ^
"ELAB:\n" ^ UVElabMap.show (S.get UVElabMap.uvmap s)
let empty s =
let s = S.set UVRawMap.uvmap s UVRawMap.empty in
let s = S.set UVElabMap.uvmap s UVElabMap.empty in
s
let fold f s acc =
UVElabMap.fold (fun ev uv sol acc ->
let ruv = UVRawMap.elpi ev (S.get UVRawMap.uvmap s) in
f ev ruv uv sol acc)
(S.get UVElabMap.uvmap s) acc
exception Return of Evar.t
let rec morally_same_uvar ~depth uv bo =
match E.look ~depth bo with
| E.Lam x -> morally_same_uvar ~depth:(depth+1) uv x
| E.UnifVar(ev,_) -> F.Elpi.equal ev uv
| _ -> false
let host_upto_assignment f s =
try
UVElabMap.fold (fun ev _ sol _ ->
match sol with
| None -> () (* the fast lookup can only fail if the uvar was instantiated (as is expanded or pruned)*)
| Some sol ->
if f ev sol then raise (Return ev) else ())
(S.get UVElabMap.uvmap s) ();
raise Not_found
with Return a -> a
let host_failsafe elab s =
try
UVElabMap.host elab (S.get UVElabMap.uvmap s)
with Not_found ->
try
UVRawMap.host elab (S.get UVRawMap.uvmap s)
with Not_found ->
host_upto_assignment (fun evar bo -> morally_same_uvar ~depth:0 elab bo) s
let remove_host evar s =
let s = S.update UVRawMap.uvmap s (UVRawMap.remove_host evar) in
let s = S.update UVElabMap.uvmap s (UVElabMap.remove_host evar) in
s
let filter_host f s =
let s = S.update UVRawMap.uvmap s (UVRawMap.filter (fun evar _ -> f evar)) in
let s = S.update UVElabMap.uvmap s (UVElabMap.filter (fun evar _ -> f evar)) in
s
end
let section_ids env =
let named_ctx = Environ.named_context env in
Context.Named.fold_inside
(fun acc x -> Context.Named.Declaration.get_id x :: acc)
~init:[] named_ctx
let sortc = E.Constants.declare_global_symbol "sort"
let typc = E.Constants.declare_global_symbol "typ"
let force_level_of_universe state u =
match Univ.Universe.level u with
| Some lvl -> state, lvl, u, Sorts.sort_of_univ u
| None ->
let state, (l,v) = new_univ_level_variable state in
let w = Sorts.sort_of_univ v in
add_universe_constraint state (constraint_eq (Sorts.sort_of_univ u) w), l, v, w
let purge_algebraic_univs_sort state s =
let sigma = (S.get engine state).sigma in
match EConstr.ESorts.kind sigma s with
| Sorts.Type u | Sorts.QSort (_ , u) ->
let state, _, _, s = force_level_of_universe state u in
state, s
| x -> state, x
let in_elpi_flex_sort t = E.mkApp sortc (E.mkApp typc t []) []
let sort = { sort with API.Conversion.embed = (fun ~depth state s ->
let state, s = purge_algebraic_univs_sort state (EConstr.ESorts.make s) in
sort.API.Conversion.embed ~depth state s) }
let in_elpi_sort ~depth state s =
let state, s, gl = sort.API.Conversion.embed ~depth state s in
assert(gl=[]);
state, E.mkApp sortc s []