forked from LPCIC/coq-elpi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoq_elpi_HOAS.ml
2713 lines (2399 loc) · 111 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))
(* 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 options = {
hoas_holes : hole_mapping option;
local : bool option;
deprecation : Deprecation.t option;
primitive : bool option;
failsafe : bool; (* don't fail, e.g. we are trying to print a term *)
ppwidth : int;
pp : ppoption;
pplevel : Constrexpr.entry_relative_level;
using : string option;
inline : Declaremods.inline;
}
let default_options = {
hoas_holes = Some Verbatim;
local = None;
deprecation = None;
primitive = None;
failsafe = false;
ppwidth = 80;
pp = Normal;
pplevel = Constrexpr.LevelSome;
using = None;
inline = Declaremods.NoInline;
}
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 ~coq_ctx:{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 in_coq_annot ~depth t = Context.make_annot (in_coq_name ~depth t) Sorts.Relevant
let in_coq_fresh_annot_name ~depth ~coq_ctx dbl t =
Context.make_annot (in_coq_fresh ~id_only:false ~depth ~coq_ctx dbl t) Sorts.Relevant
let in_coq_fresh_annot_id ~depth ~coq_ctx 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 ~coq_ctx dbl t |> get_name) Sorts.Relevant
(* universes *)
let univin, isuniv, univout, univ_to_be_patched =
let { CD.cin; isc; cout }, univ = CD.declare {
CD.name = "univ";
doc = "Univ.Universe.t";
pp = (fun fmt x ->
let s = Pp.string_of_ppcmds (Univ.Universe.pr x) in
let l = string_split_on_char '.' s in
let s = match List.rev l with
| x :: y :: _ -> y ^ "." ^ x
| _ -> s in
Format.fprintf fmt "«%s»" s);
compare = Univ.Universe.compare;
hash = Univ.Universe.hash;
hconsed = false;
constants = [];
} in
cin, isc, cout, univ
;;
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 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"
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 in_elpi_gr ~depth s 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_coq_gref ~depth ~origin ~failsafe s t =
try
let s, t, gls = gref.API.Conversion.readback ~depth s t in
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 primitive_value =
| Uint63 of Uint63.t
| Float64 of Float64.t
| 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 "Type"
| Float64 f -> Format.fprintf fmt "Set"
| Projection p -> Format.fprintf fmt "");
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("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 []
(* ********************************* }}} ********************************** *)
(* {{{ HOAS : Evd.evar_map -> elpi *************************************** *)
let command_mode =
S.declare ~name:"coq-elpi:command-mode"
~init:(fun () -> true)
~start:(fun x -> x)
~pp:(fun fmt b -> Format.fprintf fmt "%b" b)
module CoqEngine_HOAS : sig
type coq_engine = {
global_env : Environ.env;
sigma : Evd.evar_map; (* includes universe constraints *)
}
val show_coq_engine : ?with_univs:bool -> coq_engine -> string
val engine : coq_engine S.component
val from_env_keep_univ_of_sigma : Environ.env -> Evd.evar_map -> coq_engine
val from_env_sigma : Environ.env -> Evd.evar_map -> coq_engine
end = struct
type coq_engine = {
global_env : Environ.env [@printer (fun _ _ -> ())];
sigma : Evd.evar_map [@printer (fun fmt m ->
Format.fprintf fmt "%a" Pp.pp_with (Termops.pr_evar_map None (Global.env()) m))];
}
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)
let from_env_keep_univ_of_sigma env sigma0 =
let uctx = UState.update_sigma_univs (Evd.evar_universe_context sigma0) (Environ.universes env) in
let sigma = Evd.from_ctx (UState.demote_global_univs env uctx) in
from_env_sigma env sigma
let init () = from_env (Global.env ())
let engine : coq_engine S.component =
S.declare ~name:"coq-elpi:evmap-constraint-type"
~pp:pp_coq_engine ~init ~start:(fun _ -> init())
end
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
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
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
(* 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 x
let pp fmt x = Format.fprintf fmt "%a" Pp.pp_with (Univ.Universe.pr x)
end)
let um = S.declare ~name:"coq-elpi:evar-univ-map"
~pp:UM.pp ~init:(fun () -> UM.empty) ~start:(fun x -> x)
let new_univ state =
S.update_return engine state (fun ({ sigma } as x) ->
let sigma, v = Evd.new_univ_level_variable UState.UnivRigid sigma in
let u = Univ.Universe.make v in
let sigma = Evd.add_universe_constraints sigma
(UnivProblem.Set.singleton (UnivProblem.ULe (Univ.type1_univ,u))) in
{ x with sigma }, 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 univ =
(* turn UVars into fresh universes *)
{ 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 ->
let state, u = new_univ 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 universe =
let open API.AlgebraicData in declare {
ty = API.Conversion.TyName "universe";
doc = "Universes (for the sort term former)";
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");
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 level)",A(univ,N),
B Sorts.sort_of_univ,
M (fun ~ok ~ko -> function
| Sorts.Type x -> ok x
| Sorts.Set -> ok Univ.type0_univ
| _ -> ko ()));
]
} |> API.ContextualConversion.(!<)
let sortc = E.Constants.declare_global_symbol "sort"
let propc = E.Constants.declare_global_symbol "prop"
let spropc = E.Constants.declare_global_symbol "sprop"
let typc = E.Constants.declare_global_symbol "typ"
let in_elpi_sort s =
E.mkApp
sortc
(match s with
| Sorts.SProp -> E.mkGlobal spropc
| Sorts.Prop -> E.mkGlobal propc
| Sorts.Set -> E.mkApp typc (univin Univ.type0_univ) []
| Sorts.Type u -> E.mkApp typc (univin u) [])
[]
let in_elpi_flex_sort t = E.mkApp sortc (E.mkApp typc t []) []
(* ********************************* }}} ********************************** *)
(* {{{ HOAS : EConstr.t -> elpi ******************************************* *)
let check_univ_inst univ_inst =
if not (Univ.Instance.is_empty univ_inst) then
nYI "HOAS universe polymorphism"
let get_sigma s = (S.get engine s).sigma
let get_global_env s = (S.get engine s).global_env
let declare_evc = E.Constants.declare_global_symbol "declare-evar"
let rm_evarc = E.Constants.declare_global_symbol "rm-evar"
(* We extend extra_goal with two /delayed/ actions: declaring a new evear to
elpi and removing a previously declared one. When the actions happen in
the same FFI call, we cancel them out, see set_extra_goals_postprocessing *)
type API.Conversion.extra_goal +=
| DeclareEvar of Evar.t * int * F.Elpi.t * F.Elpi.t
| RmEvar of Evar.t * E.term * E.term
let rec cancel_opposites acc removals = function
| [] -> []
| DeclareEvar(e,_,_,_) :: rest when Evar.Set.mem e removals ->
debug Pp.(fun () -> str "cancelling extra_goal for " ++ Evar.print e);
cancel_opposites (Evar.Set.add e acc) removals rest
| RmEvar(e,_,_) :: rest when Evar.Set.mem e acc -> cancel_opposites acc removals rest
| x :: rest -> x :: cancel_opposites acc removals rest
let rec removals_of acc = function
| [] -> acc
| RmEvar(e,_,_) :: rest -> removals_of (Evar.Set.add e acc) rest
| _ :: rest -> removals_of acc rest
let pp_coq_ctx { env } state =
try
Printer.pr_named_context_of env (get_sigma state)
with e when CErrors.noncritical e ->
Pp.(str "error in printing: " ++ str (Printexc.to_string e))
let module_inline_core = let open API.AlgebraicData in let open Declaremods in declare {
ty = API.Conversion.TyName "coq.inline";
doc = "Coq Module inline directive";
pp = (fun fmt -> function
| NoInline -> Format.fprintf fmt "NoInline"
| DefaultInline -> Format.fprintf fmt "DefaultInline"
| InlineAt x -> Format.fprintf fmt "InlineAt %d" x);
constructors = [
K("coq.inline.no", "Coq's [no inline] (aka !)",N,
B NoInline,
M (fun ~ok ~ko -> function NoInline -> ok | _ -> ko ()));
K("coq.inline.default","The default, can be omitted",N,
B DefaultInline,
M (fun ~ok ~ko -> function DefaultInline -> ok | _ -> ko ()));
K("coq.inline.at","Coq's [inline at <num>]",A(API.BuiltInData.int,N),
B (fun x -> InlineAt x),
M (fun ~ok ~ko -> function InlineAt x -> ok x | _ -> ko ()));
]
} |> API.ContextualConversion.(!<)
let module_inline_unspec = Elpi.Builtin.unspec module_inline_core
let module_inline_default = { module_inline_unspec with
API.Conversion.pp = (fun fmt x ->
module_inline_unspec.API.Conversion.pp fmt (Elpi.Builtin.Given x));
API.Conversion.embed = (fun ~depth state x ->
module_inline_unspec.API.Conversion.embed ~depth state (Elpi.Builtin.Given x));
API.Conversion.readback = (fun ~depth state x ->
match module_inline_unspec.API.Conversion.readback ~depth state x with
| state, Elpi.Builtin.Given x, gls -> state,x,gls
| state, Elpi.Builtin.Unspec, gls -> state,Declaremods.DefaultInline,gls)
}
let get_optionc = E.Constants.declare_global_symbol "get-option"
let get_options ~depth hyps state =
let is_string ~depth t =
match E.look ~depth t with
| E.CData d -> CD.is_string d
| _ -> false in
let get_string ~depth t =
match E.look ~depth t with
| E.CData d -> CD.to_string d
| _ -> assert false in
let options =
E.of_hyps hyps |> CList.map_filter (fun { E.hdepth = depth; E.hsrc = t } ->
match E.look ~depth t with
| E.App(c,name,[p]) when c == get_optionc && is_string ~depth name ->
Some (get_string ~depth name, (p,depth))
| _ -> None) in
let map = List.fold_right (fun (k,v) m -> API.Data.StrMap.add k v m) options API.Data.StrMap.empty in
let get_bool_option name =
try
let t, depth = API.Data.StrMap.find name map in
let _, b, _ = Elpi.Builtin.bool.API.Conversion.readback ~depth state t in
Some b
with Not_found -> None in
let get_string_option name =
try
let t, depth = API.Data.StrMap.find name map in
let _, b, _ = API.BuiltInData.string.API.Conversion.readback ~depth state t in
Some b
with Not_found -> None in
let get_int_option name =
try
let t, depth = API.Data.StrMap.find name map in
let _, b, _ = API.BuiltInData.int.API.Conversion.readback ~depth state t in
Some b
with Not_found -> None in
let locality s =
if s = Some "default" then None
else if s = Some "local" then Some true
else if s = Some "global" then Some false
else if s = None then None
else err Pp.(str"Unknown locality attribute: " ++ str (Option.get s)) in
let pp s =
if s = Some "all" then All
else if s = Some "most" then Most
else Normal in
let ppwidth = function Some i -> i | None -> 80 in
let pplevel = function None -> Constrexpr.LevelSome | Some i -> Constrexpr.LevelLe i in
let get_module_inline_option name =
try
let t, depth = API.Data.StrMap.find name map in
let _, b, _ = module_inline_core.API.Conversion.readback ~depth state t in
b
with Not_found -> Declaremods.NoInline in
let get_pair_option fst snd name =
try
let t, depth = API.Data.StrMap.find name map in
let _, b, _ = Elpi.Builtin.(pair (unspec fst) (unspec snd)).API.Conversion.readback ~depth state t in
Some b
with Not_found -> None in
let empty2none = function Some "" -> None | x -> x in
let deprecation = function
| None -> None
| Some(since,note) ->
let since = unspec2opt since |> empty2none in
let note = unspec2opt note |> empty2none in
Some { Deprecation.since; note } in
{
hoas_holes =
begin match get_bool_option "HOAS:holes" with
| None -> None
| Some true -> Some Heuristic
| Some false -> Some Verbatim end;
local = locality @@ get_string_option "coq:locality";
deprecation = deprecation @@ get_pair_option API.BuiltInData.string API.BuiltInData.string "coq:deprecation";
primitive = get_bool_option "coq:primitive";
failsafe = false;
ppwidth = ppwidth @@ get_int_option "coq:ppwidth";
pp = pp @@ get_string_option "coq:pp";
pplevel = pplevel @@ get_int_option "coq:pplevel";
using = get_string_option "coq:using";
inline = get_module_inline_option "coq:inline";
}
let mk_coq_context ~options state =
let env = get_global_env state in
let section = section_ids env in
{
section;
section_len = List.length section;
proof = [];
proof_len = 0;
local = [];
local_len = 0;
db2name = Int.Map.empty;
name2db = Names.Id.Map.empty;
db2rel = Int.Map.empty;
names = Environ.named_context env |> Context.Named.to_vars;
env;
options;
}
let push_coq_ctx_proof i e coq_ctx =
assert(coq_ctx.local = []);
let id = Context.Named.Declaration.get_id e in
{
coq_ctx with
proof = e :: coq_ctx.proof;
proof_len = 1 + coq_ctx.proof_len;
env = EConstr.push_named e coq_ctx.env;
db2name = Int.Map.add i id coq_ctx.db2name;
name2db = Names.Id.Map.add id i coq_ctx.name2db;
names = Id.Set.add id coq_ctx.names;
}
let push_coq_ctx_local i e coq_ctx =
let rel = 1 + coq_ctx.local_len in
{
coq_ctx with
local = (i,e) :: coq_ctx.local;
local_len = rel;
db2rel = Int.Map.add i rel coq_ctx.db2rel;
env = EConstr.push_rel e coq_ctx.env;
}
(* Not sure this is sufficient, eg we don't restrict evars, but elpi shuld... *)
let restrict_coq_context live_db state { proof; proof_len; local; name2db; env; options; } =
let named_ctx =
mk_coq_context ~options state |> List.fold_right (fun e ctx ->
let id = Context.Named.Declaration.get_id e in
let db = Names.Id.Map.find id name2db in
if List.mem db live_db
then push_coq_ctx_proof db e ctx
else ctx) proof in
debug Pp.(fun () ->
str "restrict_coq_context: named: " ++
Printer.pr_named_context_of named_ctx.env (get_sigma state));
let subst_rel_decl env k s = function
| Context.Rel.Declaration.LocalAssum(n,t) ->
debug Pp.(fun () ->
Printer.pr_econstr_env env (get_sigma state) t
++str "--"++ int k ++ str"->" ++
Printer.pr_econstr_env env (get_sigma state) (EConstr.Vars.substnl s k t));
Context.Rel.Declaration.LocalAssum(n,EConstr.Vars.substnl s k t)
| Context.Rel.Declaration.LocalDef(n,t,b) ->
Context.Rel.Declaration.LocalDef(n,EConstr.Vars.substnl s k t,EConstr.Vars.substnl s k b) in
(named_ctx,[]) |> List.fold_right (fun (db,e) (ctx,s) ->
debug Pp.(fun () ->
str"restrict_coq_context: cur rel ctx: " ++
Printer.pr_rel_context_of ctx.env (get_sigma state) ++ fnl() ++
str"restrict_coq_context: cur subst: " ++
prlist_with_sep spc (Printer.pr_econstr_env ctx.env (get_sigma state)) s ++ fnl() ++
str"restrict_coq_context: looking at " ++
Names.Name.print (Context.Rel.Declaration.get_name e)
++ str"(dbl " ++ int db ++ str")");
if List.mem db live_db
then push_coq_ctx_local db (subst_rel_decl ctx.env 0 s e) ctx, (EConstr.mkRel 1) :: List.map (EConstr.Vars.lift 1) s
else ctx, EConstr.mkProp :: s) local |>
fun (x,_) -> x
let info_of_evar ~env ~sigma ~section k =
let open Context.Named in
let { Evd.evar_concl } as info =
Evarutil.nf_evar_info sigma (Evd.find sigma k) in
let filtered_hyps = Evd.evar_filtered_hyps info in
let ctx = EC.named_context_of_val filtered_hyps in
let ctx = ctx |> CList.filter (fun x ->
not(CList.mem_f Id.equal (Declaration.get_id x) section)) in
evar_concl, ctx, Environ.reset_with_named_context filtered_hyps env
(* ******************************************* *)
(* <---- depth ----> *)
(* proof_ctx |- pis \ t *)
(* ******************************************* *)
type hyp = { ctx_entry : E.term; depth : int }
let declc = E.Constants.declare_global_symbol "decl"
let defc = E.Constants.declare_global_symbol "def"
let evarc = E.Constants.declare_global_symbol "evar"
let mk_pi rest =
E.mkApp E.Constants.pic (E.mkLam rest) []
let mk_pi_arrow hyp rest =
mk_pi (E.mkApp E.Constants.implc hyp [rest])
let mk_decl ~depth name ~ty =
E.mkApp declc E.(mkConst depth) [in_elpi_name name; ty]
let mk_def ~depth name ~bo ~ty =
E.mkApp defc E.(mkConst depth) [in_elpi_name name; ty; bo]
let rec constr2lp coq_ctx ~calldepth ~depth state t =
assert(depth >= coq_ctx.proof_len);
let { sigma } = S.get engine state in
let gls = ref [] in
let rec aux ~depth env state t = match EC.kind sigma t with
| C.Rel n -> state, E.mkConst (depth - n)
| C.Var n ->
begin
try state, E.mkConst @@ Names.Id.Map.find n coq_ctx.name2db
with Not_found ->
assert(List.mem n coq_ctx.section);
state, in_elpi_gr ~depth state (G.VarRef n)
end
| C.Meta _ -> nYI "constr2lp: Meta"
| C.Evar (k,args) ->
(* the evar is created at the depth the conversion is called, not at
the depth at which it is found *)
let state, elpi_uvk, _, gsl_t = in_elpi_evar ~calldepth k state in
gls := gsl_t @ !gls;
let args = CList.firstn (List.length args - coq_ctx.section_len) args in
let state, args = CList.fold_left_map (aux ~depth env) state args in
state, E.mkUnifVar elpi_uvk ~args:(List.rev args) state
| C.Sort s -> state, in_elpi_sort (EC.ESorts.kind sigma s)
| C.Cast (t,_,ty0) ->
let state, t = aux ~depth env state t in
let state, ty = aux ~depth env state ty0 in
let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(Context.make_annot Anonymous Sorts.Relevant,ty0)) env in
let state, self = aux ~depth:(depth+1) env state (EC.mkRel 1) in
state, in_elpi_let Names.Name.Anonymous t ty self
| C.Prod(n,s0,t) ->
let state, s = aux ~depth env state s0 in
let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(n,s0)) env in
let state, t = aux ~depth:(depth+1) env state t in
state, in_elpi_prod n.Context.binder_name s t
| C.Lambda(n,s0,t) ->
let state, s = aux ~depth env state s0 in
let env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum(n,s0)) env in
let state, t = aux ~depth:(depth+1) env state t in
state, in_elpi_lam n.Context.binder_name s t
| C.LetIn(n,b0,s0,t) ->
let state, b = aux ~depth env state b0 in
let state, s = aux ~depth env state s0 in
let env = EConstr.push_rel Context.Rel.Declaration.(LocalDef(n,b0,s0)) env in
let state, t = aux ~depth:(depth+1) env state t in
state, in_elpi_let n.Context.binder_name b s t
| C.App(hd,args) ->
let state, hd = aux ~depth env state hd in
let state, args = CArray.fold_left_map (aux ~depth env) state args in