forked from coq/coq
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cClosure.ml
1667 lines (1468 loc) · 58.9 KB
/
cClosure.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 Bruno Barras with Benjamin Werner's account to implement
a call-by-value conversion algorithm and a lazy reduction machine
with sharing, Nov 1996 *)
(* Addition of zeta-reduction (let-in contraction) by Hugo Herbelin, Oct 2000 *)
(* Call-by-value machine moved to cbv.ml, Mar 01 *)
(* Additional tools for module subtyping by Jacek Chrzaszcz, Aug 2002 *)
(* Extension with closure optimization by Bruno Barras, Aug 2003 *)
(* Support for evar reduction by Bruno Barras, Feb 2009 *)
(* Miscellaneous other improvements by Bruno Barras, 1997-2009 *)
(* This file implements a lazy reduction for the Calculus of Inductive
Constructions *)
[@@@ocaml.warning "+4"]
open CErrors
open Util
open Names
open Constr
open Declarations
open Context
open Environ
open Vars
open Esubst
open RedFlags
module RelDecl = Context.Rel.Declaration
module NamedDecl = Context.Named.Declaration
type mode = Conversion | Reduction
(* In conversion mode we can introduce FIrrelevant terms.
Invariants of the conversion mode:
- the only irrelevant terms as returned by [knr] are either [FIrrelevant],
[FLambda], [FFlex] or [FRel].
- the stack never contains irrelevant-producing nodes i.e. [Zproj], [ZFix]
and [ZcaseT] are all relevant
*)
(**********************************************************************)
(* Lazy reduction: the one used in kernel operations *)
(* type of shared terms. fconstr and frterm are mutually recursive.
* Clone of the constr structure, but completely mutable, and
* annotated with reduction state (reducible or not).
* - FLIFT is a delayed shift; allows sharing between 2 lifted copies
* of a given term.
* - FCLOS is a delayed substitution applied to a constr
* - FLOCKED is used to erase the content of a reference that must
* be updated. This is to allow the garbage collector to work
* before the term is computed.
*)
(* Ntrl means the term is in βιδζ head normal form and cannot create a redex
when substituted
Cstr means the term is in βιδζ head normal form and that it can
create a redex when substituted (i.e. constructor, fix, lambda)
Red is used for terms that might be reduced
*)
type red_state = Ntrl | Cstr | Red
let neutr = function Ntrl -> Ntrl | Red | Cstr -> Red
let is_red = function Red -> true | Ntrl | Cstr -> false
type table_key = Constant.t UVars.puniverses tableKey
type evar_repack = Evar.t * constr list -> constr
type fconstr = {
mutable mark : red_state;
mutable term: fterm;
}
and fterm =
| FRel of int
| FAtom of constr (* Metas and Sorts *)
| FFlex of table_key
| FInd of pinductive
| FConstruct of pconstructor
| FApp of fconstr * fconstr array
| FProj of Projection.t * Sorts.relevance * fconstr
| FFix of fixpoint * usubs
| FCoFix of cofixpoint * usubs
| FCaseT of case_info * UVars.Instance.t * constr array * case_return * fconstr * case_branch array * usubs (* predicate and branches are closures *)
| FCaseInvert of case_info * UVars.Instance.t * constr array * case_return * finvert * fconstr * case_branch array * usubs
| FLambda of int * (Name.t Context.binder_annot * constr) list * constr * usubs
| FProd of Name.t Context.binder_annot * fconstr * constr * usubs
| FLetIn of Name.t Context.binder_annot * fconstr * fconstr * constr * usubs
| FEvar of Evar.t * constr list * usubs * evar_repack
| FInt of Uint63.t
| FFloat of Float64.t
| FArray of UVars.Instance.t * fconstr Parray.t * fconstr
| FLIFT of int * fconstr
| FCLOS of constr * usubs
| FIrrelevant
| FLOCKED
and usubs = fconstr subs UVars.puniverses
and finvert = fconstr array
let fterm_of v = v.term
let set_ntrl v = v.mark <- Ntrl
let mk_atom c = {mark=Ntrl;term=FAtom c}
let mk_red f = {mark=Red;term=f}
(* Could issue a warning if no is still Red, pointing out that we loose
sharing. *)
let update v1 mark t =
v1.mark <- mark; v1.term <- t
type 'a evar_expansion =
| EvarDefined of 'a
| EvarUndefined of Evar.t * 'a list
type 'constr evar_handler = {
evar_expand : 'constr pexistential -> 'constr evar_expansion;
evar_repack : Evar.t * 'constr list -> 'constr;
evar_irrelevant : 'constr pexistential -> bool;
qvar_irrelevant : Sorts.QVar.t -> bool;
}
let default_evar_handler env = {
evar_expand = (fun _ -> assert false);
evar_repack = (fun _ -> assert false);
evar_irrelevant = (fun _ -> assert false);
qvar_irrelevant = (fun q ->
assert (Sorts.QVar.Set.mem q env.env_qualities);
false);
}
(** Reduction cache *)
type infos_cache = {
i_env : env;
i_sigma : constr evar_handler;
i_share : bool;
i_univs : UGraph.t;
i_mode : mode;
}
type clos_infos = {
i_flags : reds;
i_relevances : Sorts.relevance Range.t;
i_cache : infos_cache }
let info_flags info = info.i_flags
let info_env info = info.i_cache.i_env
let info_univs info = info.i_cache.i_univs
let push_relevance infos x =
{ infos with i_relevances = Range.cons x.binder_relevance infos.i_relevances }
let push_relevances infos nas =
{ infos with
i_relevances =
Array.fold_left (fun l x -> Range.cons x.binder_relevance l)
infos.i_relevances nas }
let set_info_relevances info r = { info with i_relevances = r }
let info_relevances info = info.i_relevances
(**********************************************************************)
(* The type of (machine) stacks (= lambda-bar-calculus' contexts) *)
type 'a next_native_args = (CPrimitives.arg_kind * 'a) list
type stack_member =
| Zapp of fconstr array
| ZcaseT of case_info * UVars.Instance.t * constr array * case_return * case_branch array * usubs
| Zproj of Projection.Repr.t * Sorts.relevance
| Zfix of fconstr * stack
| Zprimitive of CPrimitives.t * pconstant * fconstr list * fconstr next_native_args
(* operator, constr def, arguments already seen (in rev order), next arguments *)
| Zshift of int
| Zupdate of fconstr
and stack = stack_member list
let empty_stack = []
let append_stack v s =
if Int.equal (Array.length v) 0 then s else
match s with
| Zapp l :: s -> Zapp (Array.append v l) :: s
| (ZcaseT _ | Zproj _ | Zfix _ | Zshift _ | Zupdate _ | Zprimitive _) :: _ | [] ->
Zapp v :: s
(* Collapse the shifts in the stack *)
let zshift n s =
match (n,s) with
(0,_) -> s
| (_,Zshift(k)::s) -> Zshift(n+k)::s
| (_,(ZcaseT _ | Zproj _ | Zfix _ | Zapp _ | Zupdate _ | Zprimitive _) :: _) | _,[] -> Zshift(n)::s
let rec stack_args_size = function
| Zapp v :: s -> Array.length v + stack_args_size s
| Zshift(_)::s -> stack_args_size s
| Zupdate(_)::s -> stack_args_size s
| (ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | [] -> 0
let usubs_shft (n,(e,u)) = subs_shft (n, e), u
(* Lifting. Preserves sharing (useful only for cell with norm=Red).
lft_fconstr always create a new cell, while lift_fconstr avoids it
when the lift is 0. *)
let rec lft_fconstr n ft =
match ft.term with
| (FInd _|FConstruct _|FFlex(ConstKey _|VarKey _)|FInt _|FFloat _|FIrrelevant) -> ft
| FRel i -> {mark=ft.mark;term=FRel(i+n)}
| FLambda(k,tys,f,e) -> {mark=Cstr; term=FLambda(k,tys,f,usubs_shft(n,e))}
| FFix(fx,e) ->
{mark=Cstr; term=FFix(fx,usubs_shft(n,e))}
| FCoFix(cfx,e) ->
{mark=Cstr; term=FCoFix(cfx,usubs_shft(n,e))}
| FLIFT(k,m) -> lft_fconstr (n+k) m
| FLOCKED -> assert false
| FFlex (RelKey _) | FAtom _ | FApp _ | FProj _ | FCaseT _ | FCaseInvert _ | FProd _
| FLetIn _ | FEvar _ | FCLOS _ | FArray _ -> {mark=ft.mark; term=FLIFT(n,ft)}
let lift_fconstr k f =
if Int.equal k 0 then f else lft_fconstr k f
let lift_fconstr_vect k v =
if Int.equal k 0 then v else Array.Fun1.map lft_fconstr k v
let clos_rel e i =
match expand_rel i e with
| Inl(n,mt) -> lift_fconstr n mt
| Inr(k,None) -> {mark=Ntrl; term= FRel k}
| Inr(k,Some p) ->
lift_fconstr (k-p) {mark=Red;term=FFlex(RelKey p)}
(* since the head may be reducible, we might introduce lifts of 0 *)
let compact_stack head stk =
let rec strip_rec depth = function
| Zshift(k)::s -> strip_rec (depth+k) s
| Zupdate(m)::s ->
(* Be sure to create a new cell otherwise sharing would be
lost by the update operation *)
let h' = lft_fconstr depth head in
(** The stack contains [Zupdate] marks only if in sharing mode *)
let () = update m h'.mark h'.term in
strip_rec depth s
| ((ZcaseT _ | Zproj _ | Zfix _ | Zapp _ | Zprimitive _) :: _ | []) as stk -> zshift depth stk
in
strip_rec 0 stk
(* Put an update mark in the stack, only if needed *)
let zupdate info m s =
let share = info.i_cache.i_share in
if share && is_red m.mark then
let s' = compact_stack m s in
let _ = m.term <- FLOCKED in
Zupdate(m)::s'
else s
(* We use empty as a special identity value, if we don't check
subst_instance_instance will raise array out of bounds. *)
let usubst_instance (_,u) u' =
if UVars.Instance.is_empty u then u'
else UVars.subst_instance_instance u u'
let usubst_punivs (_,u) (v,u' as orig) =
if UVars.Instance.is_empty u then orig
else v, UVars.subst_instance_instance u u'
let usubst_sort (_,u) s =
if UVars.Instance.is_empty u then s
else UVars.subst_instance_sort u s
let usubst_relevance (_,u) r =
if UVars.Instance.is_empty u then r
else UVars.subst_instance_relevance u r
let usubst_binder e x =
let r = x.binder_relevance in
let r' = usubst_relevance e r in
if r == r' then x else { x with binder_relevance = r' }
let mk_lambda env t =
let (rvars,t') = Term.decompose_lambda t in
FLambda(List.length rvars, List.rev rvars, t', env)
let usubs_lift (e,u) = subs_lift e, u
let usubs_liftn n (e,u) = subs_liftn n e, u
(* t must be a FLambda and binding list cannot be empty *)
let destFLambda clos_fun t =
match [@ocaml.warning "-4"] t.term with
| FLambda(_,[(na,ty)],b,e) ->
(usubst_binder e na,clos_fun e ty,clos_fun (usubs_lift e) b)
| FLambda(n,(na,ty)::tys,b,e) ->
(usubst_binder e na,clos_fun e ty,{mark=t.mark;term=FLambda(n-1,tys,b,usubs_lift e)})
| _ -> assert false
(* Optimization: do not enclose variables in a closure.
Makes variable access much faster *)
let mk_clos (e:usubs) t =
match kind t with
| Rel i -> clos_rel (fst e) i
| Var x -> {mark = Red; term = FFlex (VarKey x) }
| Const c -> {mark = Red; term = FFlex (ConstKey (usubst_punivs e c)) }
| Sort s ->
let s = usubst_sort e s in
{mark = Ntrl; term = FAtom (mkSort s) }
| Meta _ -> {mark = Ntrl; term = FAtom t }
| Ind kn -> {mark = Ntrl; term = FInd (usubst_punivs e kn) }
| Construct kn -> {mark = Cstr; term = FConstruct (usubst_punivs e kn) }
| Int i -> {mark = Cstr; term = FInt i}
| Float f -> {mark = Cstr; term = FFloat f}
| (CoFix _|Lambda _|Fix _|Prod _|Evar _|App _|Case _|Cast _|LetIn _|Proj _|Array _) ->
{mark = Red; term = FCLOS(t,e)}
let injectu c u = mk_clos (subs_id 0, u) c
let inject c = injectu c UVars.Instance.empty
let mk_irrelevant = { mark = Cstr; term = FIrrelevant }
let is_irrelevant info r = match info.i_cache.i_mode with
| Reduction -> false
| Conversion -> match r with
| Sorts.Irrelevant -> true
| Sorts.RelevanceVar q -> info.i_cache.i_sigma.qvar_irrelevant q
| Sorts.Relevant -> false
(************************************************************************)
type table_val = (fconstr, Empty.t) constant_def
module Table : sig
type t
val create : unit -> t
val lookup : clos_infos -> t -> table_key -> table_val
end = struct
module Table = Hashtbl.Make(struct
type t = table_key
let equal = eq_table_key (eq_pair eq_constant_key UVars.Instance.equal)
let hash = hash_table_key (fun (c, _) -> Constant.UserOrd.hash c)
end)
type t = table_val Table.t
let create () = Table.create 17
exception Irrelevant
let shortcut_irrelevant info r =
if is_irrelevant info r then raise Irrelevant
let assoc_defined d =
match d with
| NamedDecl.LocalDef (_, c, _) -> inject c
| NamedDecl.LocalAssum (_, _) -> raise Not_found
let constant_value_in u = function
| Def b -> injectu b u
| OpaqueDef _ -> raise (NotEvaluableConst Opaque)
| Undef _ -> raise (NotEvaluableConst NoBody)
| Primitive p -> raise (NotEvaluableConst (IsPrimitive (u,p)))
let value_of info ref =
try
let env = info.i_cache.i_env in
match ref with
| RelKey n ->
let i = n - 1 in
let d =
try Range.get env.env_rel_context.env_rel_map i
with Invalid_argument _ -> raise Not_found
in
shortcut_irrelevant info (RelDecl.get_relevance d);
let body =
match d with
| RelDecl.LocalAssum _ -> raise Not_found
| RelDecl.LocalDef (_, t, _) -> lift n t
in
Def (inject body)
| VarKey id ->
let def = Environ.lookup_named id env in
shortcut_irrelevant info
(binder_relevance (NamedDecl.get_annot def));
let ts = RedFlags.red_transparent info.i_flags in
if TransparentState.is_transparent_variable ts id then
Def (assoc_defined def)
else
raise Not_found
| ConstKey (cst,u) ->
let cb = lookup_constant cst env in
shortcut_irrelevant info (UVars.subst_instance_relevance u cb.const_relevance);
let ts = RedFlags.red_transparent info.i_flags in
if TransparentState.is_transparent_constant ts cst then
Def (constant_value_in u cb.const_body)
else
raise Not_found
with
| Irrelevant -> Def mk_irrelevant
| NotEvaluableConst (IsPrimitive (_u,op)) (* Const *) -> Primitive op
| Not_found (* List.assoc *)
| NotEvaluableConst _ (* Const *) -> Undef None
let lookup info tab ref =
try Table.find tab ref with Not_found ->
let v = value_of info ref in
Table.add tab ref v; v
end
type clos_tab = Table.t
let create_tab = Table.create
(************************************************************************)
(** Hand-unrolling of the map function to bypass the call to the generic array
allocation *)
let mk_clos_vect env v = match v with
| [||] -> [||]
| [|v0|] -> [|mk_clos env v0|]
| [|v0; v1|] -> [|mk_clos env v0; mk_clos env v1|]
| [|v0; v1; v2|] -> [|mk_clos env v0; mk_clos env v1; mk_clos env v2|]
| [|v0; v1; v2; v3|] ->
[|mk_clos env v0; mk_clos env v1; mk_clos env v2; mk_clos env v3|]
| v -> Array.Fun1.map mk_clos env v
let rec subst_constr (subst,usubst as e) c =
let c = Vars.map_constr_relevance (usubst_relevance e) c in
match [@ocaml.warning "-4"] Constr.kind c with
| Rel i ->
begin match expand_rel i subst with
| Inl (k, lazy v) -> Vars.lift k v
| Inr (m, _) -> mkRel m
end
| Const _ | Ind _ | Construct _ | Sort _ -> subst_instance_constr usubst c
| Case (ci, u, pms, p, iv, discr, br) ->
let u' = usubst_instance e u in
let c = if u == u' then c else mkCase (ci, u', pms, p, iv, discr, br) in
Constr.map_with_binders usubs_lift subst_constr e c
| Array (u,elems,def,ty) ->
let u' = usubst_instance e u in
let c = if u == u' then c else mkArray (u',elems,def,ty) in
Constr.map_with_binders usubs_lift subst_constr e c
| _ ->
Constr.map_with_binders usubs_lift subst_constr e c
(* The inverse of mk_clos: move back to constr *)
(* XXX should there be universes in lfts???? *)
let rec to_constr (lfts, usubst as ulfts) v =
let subst_us c = subst_instance_constr usubst c in
match v.term with
| FRel i -> mkRel (reloc_rel i lfts)
| FFlex (RelKey p) -> mkRel (reloc_rel p lfts)
| FFlex (VarKey x) -> mkVar x
| FAtom c -> subst_us (exliftn lfts c)
| FFlex (ConstKey op) -> subst_us (mkConstU op)
| FInd op -> subst_us (mkIndU op)
| FConstruct op -> subst_us (mkConstructU op)
| FCaseT (ci, u, pms, p, c, ve, env) ->
to_constr_case ulfts ci u pms p NoInvert c ve env
| FCaseInvert (ci, u, pms, p, indices, c, ve, env) ->
let iv = CaseInvert {indices=Array.Fun1.map to_constr ulfts indices} in
to_constr_case ulfts ci u pms p iv c ve env
| FFix ((op,(lna,tys,bds)) as fx, e) ->
if is_subs_id (fst e) && is_lift_id lfts then
subst_instance_constr (usubst_instance ulfts (snd e)) (mkFix fx)
else
let n = Array.length bds in
let subs_ty = comp_subs ulfts e in
let subs_bd = comp_subs (on_fst (el_liftn n) ulfts) (on_fst (subs_liftn n) e) in
let lna = Array.Fun1.map usubst_binder subs_ty lna in
let tys = Array.Fun1.map subst_constr subs_ty tys in
let bds = Array.Fun1.map subst_constr subs_bd bds in
mkFix (op, (lna, tys, bds))
| FCoFix ((op,(lna,tys,bds)) as cfx, e) ->
if is_subs_id (fst e) && is_lift_id lfts then
subst_instance_constr (usubst_instance ulfts (snd e)) (mkCoFix cfx)
else
let n = Array.length bds in
let subs_ty = comp_subs ulfts e in
let subs_bd = comp_subs (on_fst (el_liftn n) ulfts) (on_fst (subs_liftn n) e) in
let lna = Array.Fun1.map usubst_binder subs_ty lna in
let tys = Array.Fun1.map subst_constr subs_ty tys in
let bds = Array.Fun1.map subst_constr subs_bd bds in
mkCoFix (op, (lna, tys, bds))
| FApp (f,ve) ->
mkApp (to_constr ulfts f,
Array.Fun1.map to_constr ulfts ve)
| FProj (p,r,c) ->
mkProj (p,usubst_relevance ulfts r,to_constr ulfts c)
| FLambda (len, tys, f, e) ->
if is_subs_id (fst e) && is_lift_id lfts then
subst_instance_constr (usubst_instance ulfts (snd e)) (Term.compose_lam (List.rev tys) f)
else
let subs = comp_subs ulfts e in
let tys = List.mapi (fun i (na, c) ->
usubst_binder subs na, subst_constr (usubs_liftn i subs) c)
tys
in
let f = subst_constr (usubs_liftn len subs) f in
Term.compose_lam (List.rev tys) f
| FProd (n, t, c, e) ->
if is_subs_id (fst e) && is_lift_id lfts then
mkProd (n, to_constr ulfts t, subst_instance_constr (usubst_instance ulfts (snd e)) c)
else
let subs' = comp_subs ulfts e in
mkProd (usubst_binder subs' n,
to_constr ulfts t,
subst_constr (usubs_lift subs') c)
| FLetIn (n,b,t,f,e) ->
let subs = comp_subs (on_fst el_lift ulfts) (usubs_lift e) in
mkLetIn (usubst_binder subs n,
to_constr ulfts b,
to_constr ulfts t,
subst_constr subs f)
| FEvar (ev, args, env, repack) ->
let subs = comp_subs ulfts env in
repack (ev, List.map (fun a -> subst_constr subs a) args)
| FLIFT (k,a) -> to_constr (el_shft k lfts, usubst) a
| FInt i ->
Constr.mkInt i
| FFloat f ->
Constr.mkFloat f
| FArray (u,t,ty) ->
let u = usubst_instance ((),usubst) u in
let def = to_constr ulfts (Parray.default t) in
let t = Array.init (Parray.length_int t) (fun i ->
to_constr ulfts (Parray.get t (Uint63.of_int i)))
in
let ty = to_constr ulfts ty in
mkArray(u, t, def,ty)
| FCLOS (t,env) ->
if is_subs_id (fst env) && is_lift_id lfts then
subst_instance_constr (usubst_instance ulfts (snd env)) t
else
let subs = comp_subs ulfts env in
subst_constr subs t
| FIrrelevant -> assert (!Flags.in_debugger); mkVar(Id.of_string"_IRRELEVANT_")
| FLOCKED -> assert (!Flags.in_debugger); mkVar(Id.of_string"_LOCKED_")
and to_constr_case (lfts,_ as ulfts) ci u pms (p,r) iv c ve env =
let subs = comp_subs ulfts env in
let r = usubst_relevance subs r in
if is_subs_id (fst env) && is_lift_id lfts then
mkCase (ci, usubst_instance subs u, pms, (p,r), iv, to_constr ulfts c, ve)
else
let f_ctx (nas, c) =
let nas = Array.map (usubst_binder subs) nas in
let c = subst_constr (usubs_liftn (Array.length nas) subs) c in
(nas, c)
in
mkCase (ci,
usubst_instance subs u,
Array.map (fun c -> subst_constr subs c) pms,
(f_ctx p,r),
iv,
to_constr ulfts c,
Array.map f_ctx ve)
and comp_subs (el,u) (s,u') =
Esubst.lift_subst (fun el c -> lazy (to_constr (el,u) c)) el s, u'
(* This function defines the correspondence between constr and
fconstr. When we find a closure whose substitution is the identity,
then we directly return the constr to avoid possibly huge
reallocation. *)
let term_of_fconstr c = to_constr (el_id, UVars.Instance.empty) c
(* fstrong applies unfreeze_fun recursively on the (freeze) term and
* yields a term. Assumes that the unfreeze_fun never returns a
* FCLOS term.
let rec fstrong unfreeze_fun lfts v =
to_constr (fstrong unfreeze_fun) lfts (unfreeze_fun v)
*)
let rec zip m stk =
match stk with
| [] -> m
| Zapp args :: s -> zip {mark=neutr m.mark; term=FApp(m, args)} s
| ZcaseT(ci, u, pms, p, br, e)::s ->
let t = FCaseT(ci, u, pms, p, m, br, e) in
let mark = (neutr m.mark) in
zip {mark; term=t} s
| Zproj (p,r) :: s ->
let mark = (neutr m.mark) in
zip {mark; term=FProj(Projection.make p true,r,m)} s
| Zfix(fx,par)::s ->
zip fx (par @ append_stack [|m|] s)
| Zshift(n)::s ->
zip (lift_fconstr n m) s
| Zupdate(rf)::s ->
(** The stack contains [Zupdate] marks only if in sharing mode *)
let () = update rf m.mark m.term in
zip rf s
| Zprimitive(_op,c,rargs,kargs)::s ->
let args = List.rev_append rargs (m::List.map snd kargs) in
let f = {mark = Red; term = FFlex (ConstKey c)} in
zip {mark=(neutr m.mark); term = FApp (f, Array.of_list args)} s
let fapp_stack (m,stk) = zip m stk
let term_of_process c stk = term_of_fconstr (zip c stk)
(*********************************************************************)
(* The assertions in the functions below are granted because they are
called only when m is a constructor, a cofix
(strip_update_shift_app), a fix (get_nth_arg) or an abstraction
(strip_update_shift, through get_arg). *)
(* optimised for the case where there are no shifts... *)
let strip_update_shift_app_red head stk =
let rec strip_rec rstk h depth = function
| Zshift(k) as e :: s ->
strip_rec (e::rstk) (lift_fconstr k h) (depth+k) s
| (Zapp args :: s) ->
strip_rec (Zapp args :: rstk)
{mark=h.mark;term=FApp(h,args)} depth s
| Zupdate(m)::s ->
(** The stack contains [Zupdate] marks only if in sharing mode *)
let () = update m h.mark h.term in
strip_rec rstk m depth s
| ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as stk ->
(depth,List.rev rstk, stk)
in
strip_rec [] head 0 stk
let strip_update_shift_app head stack =
assert (not (is_red head.mark));
strip_update_shift_app_red head stack
let get_nth_arg head n stk =
assert (not (is_red head.mark));
let rec strip_rec rstk h n = function
| Zshift(k) as e :: s ->
strip_rec (e::rstk) (lift_fconstr k h) n s
| Zapp args::s' ->
let q = Array.length args in
if n >= q
then
strip_rec (Zapp args::rstk) {mark=h.mark;term=FApp(h,args)} (n-q) s'
else
let bef = Array.sub args 0 n in
let aft = Array.sub args (n+1) (q-n-1) in
let stk' =
List.rev (if Int.equal n 0 then rstk else (Zapp bef :: rstk)) in
(Some (stk', args.(n)), append_stack aft s')
| Zupdate(m)::s ->
(** The stack contains [Zupdate] mark only if in sharing mode *)
let () = update m h.mark h.term in
strip_rec rstk m n s
| ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as s -> (None, List.rev rstk @ s) in
strip_rec [] head n stk
let usubs_cons x (s,u) = subs_cons x s, u
let rec subs_consn v i n s =
if Int.equal i n then s
else subs_consn v (i + 1) n (subs_cons v.(i) s)
let usubs_consn v i n s = on_fst (subs_consn v i n) s
let usubs_consv v s =
usubs_consn v 0 (Array.length v) s
(* Beta reduction: look for an applied argument in the stack.
Since the encountered update marks are removed, h must be a whnf *)
let rec get_args n tys f e = function
| Zupdate r :: s ->
(** The stack contains [Zupdate] mark only if in sharing mode *)
let () = update r Cstr (FLambda(n,tys,f,e)) in
get_args n tys f e s
| Zshift k :: s ->
get_args n tys f (usubs_shft (k,e)) s
| Zapp l :: s ->
let na = Array.length l in
if n == na then (Inl (usubs_consn l 0 na e), s)
else if n < na then (* more arguments *)
let eargs = Array.sub l n (na-n) in
(Inl (usubs_consn l 0 n e), Zapp eargs :: s)
else (* more lambdas *)
let etys = List.skipn na tys in
get_args (n-na) etys f (usubs_consn l 0 na e) s
| ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as stk ->
(Inr {mark=Cstr; term=FLambda(n,tys,f,e)}, stk)
(* Eta expansion: add a reference to implicit surrounding lambda at end of stack *)
let rec eta_expand_stack info na = function
| (Zapp _ | Zfix _ | ZcaseT _ | Zproj _
| Zshift _ | Zupdate _ | Zprimitive _ as e) :: s ->
e :: eta_expand_stack info na s
| [] ->
let arg =
if is_irrelevant info na.binder_relevance then mk_irrelevant
else {mark = Ntrl; term = FRel 1}
in
[Zshift 1; Zapp [|arg|]]
(* Get the arguments of a native operator *)
let rec skip_native_args rargs nargs =
match nargs with
| (kd, a) :: nargs' ->
if kd = CPrimitives.Kwhnf then rargs, nargs
else skip_native_args (a::rargs) nargs'
| [] -> rargs, []
let get_native_args op c stk =
let kargs = CPrimitives.kind op in
let rec get_args rnargs kargs args =
match kargs, args with
| kd::kargs, a::args -> get_args ((kd,a)::rnargs) kargs args
| _, _ -> rnargs, kargs, args in
let rec strip_rec rnargs h depth kargs = function
| Zshift k :: s ->
strip_rec (List.map (fun (kd,f) -> kd,lift_fconstr k f) rnargs)
(lift_fconstr k h) (depth+k) kargs s
| Zapp args :: s' ->
begin match get_args rnargs kargs (Array.to_list args) with
| rnargs, [], [] ->
(skip_native_args [] (List.rev rnargs), s')
| rnargs, [], eargs ->
(skip_native_args [] (List.rev rnargs),
Zapp (Array.of_list eargs) :: s')
| rnargs, kargs, _ ->
strip_rec rnargs {mark = h.mark;term=FApp(h, args)} depth kargs s'
end
| Zupdate(m) :: s ->
let () = update m h.mark h.term in
strip_rec rnargs m depth kargs s
| (Zprimitive _ | ZcaseT _ | Zproj _ | Zfix _) :: _ | [] -> assert false
in strip_rec [] {mark = Red; term = FFlex(ConstKey c)} 0 kargs stk
let get_native_args1 op c stk =
match get_native_args op c stk with
| ((rargs, (kd,a):: nargs), stk) ->
assert (kd = CPrimitives.Kwhnf);
(rargs, a, nargs, stk)
| _ -> assert false
let check_native_args op stk =
let nargs = CPrimitives.arity op in
let rargs = stack_args_size stk in
nargs <= rargs
(* Iota reduction: extract the arguments to be passed to the Case
branches *)
let rec reloc_rargs_rec depth = function
| Zapp args :: s ->
Zapp (lift_fconstr_vect depth args) :: reloc_rargs_rec depth s
| Zshift(k)::s -> if Int.equal k depth then s else reloc_rargs_rec (depth-k) s
| ((ZcaseT _ | Zproj _ | Zfix _ | Zupdate _ | Zprimitive _) :: _ | []) as stk -> stk
let reloc_rargs depth stk =
if Int.equal depth 0 then stk else reloc_rargs_rec depth stk
let rec try_drop_parameters depth n = function
| Zapp args::s ->
let q = Array.length args in
if n > q then try_drop_parameters depth (n-q) s
else if Int.equal n q then reloc_rargs depth s
else
let aft = Array.sub args n (q-n) in
reloc_rargs depth (append_stack aft s)
| Zshift(k)::s -> try_drop_parameters (depth-k) n s
| [] ->
if Int.equal n 0 then []
else raise Not_found
| (ZcaseT _ | Zproj _ | Zfix _ | Zupdate _ | Zprimitive _) :: _ -> assert false
(* strip_update_shift_app only produces Zapp and Zshift items *)
let drop_parameters depth n argstk =
try try_drop_parameters depth n argstk
with Not_found ->
(* we know that n < stack_args_size(argstk) (if well-typed term) *)
anomaly (Pp.str "ill-typed term: found a match on a partially applied constructor.")
let inductive_subst mib u pms =
let rec mk_pms i ctx = match ctx with
| [] -> subs_id 0
| RelDecl.LocalAssum _ :: ctx ->
let subs = mk_pms (i - 1) ctx in
subs_cons pms.(i) subs
| RelDecl.LocalDef (_, c, _) :: ctx ->
let subs = mk_pms i ctx in
subs_cons (mk_clos (subs,u) c) subs
in
mk_pms (Array.length pms - 1) mib.mind_params_ctxt, u
(* Iota-reduction: feed the arguments of the constructor to the branch *)
let get_branch infos depth ci pms ((ind, c), u) br e args =
let i = c - 1 in
let args = drop_parameters depth ci.ci_npar args in
let (_nas, br) = br.(i) in
if Int.equal ci.ci_cstr_ndecls.(i) ci.ci_cstr_nargs.(i) then
(* No let-bindings in the constructor, we don't have to fetch the
environment to know the value of the branch. *)
let rec push e stk = match stk with
| [] -> e
| Zapp v :: stk -> push (usubs_consv v e) stk
| (Zshift _ | ZcaseT _ | Zproj _ | Zfix _ | Zupdate _ | Zprimitive _) :: _ ->
assert false
in
let e = push e args in
(br, e)
else
(* The constructor contains let-bindings, but they are not physically
present in the match, so we fetch them in the environment. *)
let env = info_env infos in
let mib = Environ.lookup_mind (fst ind) env in
let mip = mib.mind_packets.(snd ind) in
let (ctx, _) = mip.mind_nf_lc.(i) in
let ctx, _ = List.chop mip.mind_consnrealdecls.(i) ctx in
let map = function
| Zapp args -> args
| Zshift _ | ZcaseT _ | Zproj _ | Zfix _ | Zupdate _ | Zprimitive _ ->
assert false
in
let ind_subst = inductive_subst mib u (Array.map (mk_clos e) pms) in
let args = Array.concat (List.map map args) in
let rec push i e = function
| [] -> []
| RelDecl.LocalAssum _ :: ctx ->
let ans = push (pred i) e ctx in
args.(i) :: ans
| RelDecl.LocalDef (_, b, _) :: ctx ->
let ans = push i e ctx in
let b = subst_instance_constr u b in
let s = Array.rev_of_list ans in
let e = usubs_consv s ind_subst in
let v = mk_clos e b in
v :: ans
in
let ext = push (Array.length args - 1) [] ctx in
(br, usubs_consv (Array.rev_of_list ext) e)
(** [eta_expand_ind_stack env ind c s t] computes stacks corresponding
to the conversion of the eta expansion of t, considered as an inhabitant
of ind, and the Constructor c of this inductive type applied to arguments
s.
@assumes [t] is an irreducible term, and not a constructor. [ind] is the inductive
of the constructor term [c]
@raise Not_found if the inductive is not a primitive record, or if the
constructor is partially applied.
*)
let eta_expand_ind_stack env (ind,u) m s (f, s') =
let open Declarations in
let mib = lookup_mind (fst ind) env in
(* disallow eta-exp for non-primitive records *)
if not (mib.mind_finite == BiFinite) then raise Not_found;
match Declareops.inductive_make_projections ind mib with
| Some projs ->
(* (Construct, pars1 .. parsm :: arg1...argn :: []) ~= (f, s') ->
arg1..argn ~= (proj1 t...projn t) where t = zip (f,s') *)
let pars = mib.Declarations.mind_nparams in
let right = fapp_stack (f, s') in
let (depth, args, _s) = strip_update_shift_app m s in
(** Try to drop the params, might fail on partially applied constructors. *)
let argss = try_drop_parameters depth pars args in
let hstack = Array.map (fun (p,r) ->
{ mark = Red; (* right can't be a constructor though *)
term = FProj (Projection.make p true, UVars.subst_instance_relevance u r, right) })
projs
in
argss, [Zapp hstack]
| None -> raise Not_found (* disallow eta-exp for non-primitive records *)
let rec project_nth_arg n = function
| Zapp args :: s ->
let q = Array.length args in
if n >= q then project_nth_arg (n - q) s
else (* n < q *) args.(n)
| (ZcaseT _ | Zproj _ | Zfix _ | Zupdate _ | Zshift _ | Zprimitive _) :: _ | [] -> assert false
(* After drop_parameters we have a purely applicative stack *)
(* Iota reduction: expansion of a fixpoint.
* Given a fixpoint and a substitution, returns the corresponding
* fixpoint body, and the substitution in which it should be
* evaluated: its first variables are the fixpoint bodies
*
* FCLOS(fix Fi {F0 := T0 .. Fn-1 := Tn-1}, S)
* -> (S. FCLOS(F0,S) . ... . FCLOS(Fn-1,S), Ti)
*)
(* does not deal with FLIFT *)
let contract_fix_vect fix =
let (thisbody, make_body, env, nfix) =
match [@ocaml.warning "-4"] fix with
| FFix (((reci,i),(_,_,bds as rdcl)),env) ->
(bds.(i),
(fun j -> { mark = Cstr;
term = FFix (((reci,j),rdcl),env) }),
env, Array.length bds)
| FCoFix ((i,(_,_,bds as rdcl)),env) ->
(bds.(i),
(fun j -> { mark = Cstr;
term = FCoFix ((j,rdcl),env) }),
env, Array.length bds)
| _ -> assert false
in
let rec mk_subs env i =
if Int.equal i nfix then env
else mk_subs (subs_cons (make_body i) env) (i + 1)
in
(on_fst (fun env -> mk_subs env 0) env, thisbody)
let unfold_projection info p r =
if red_projection info.i_flags p
then
Some (Zproj (Projection.repr p, r))
else None
(************************************************************************)
(* Reduction of Native operators *)
open Primred
module FNativeEntries =
struct
type elem = fconstr
type args = fconstr array
type evd = unit
type uinstance = UVars.Instance.t
let mk_construct c =
(* All constructors used in primitive functions are relevant *)
{ mark = Cstr; term = FConstruct (UVars.in_punivs c) }
let get = Array.get
let get_int () e =
match [@ocaml.warning "-4"] e.term with
| FInt i -> i
| _ -> assert false
let get_float () e =
match [@ocaml.warning "-4"] e.term with
| FFloat f -> f
| _ -> assert false
let get_parray () e =
match [@ocaml.warning "-4"] e.term with
| FArray (_u,t,_ty) -> t
| _ -> assert false
let dummy = {mark = Ntrl; term = FRel 0}
let current_retro = ref Retroknowledge.empty
let defined_int = ref false
let fint = ref dummy
let init_int retro =
match retro.Retroknowledge.retro_int63 with
| Some c ->
defined_int := true;
fint := { mark = Ntrl; term = FFlex (ConstKey (UVars.in_punivs c)) }
| None -> defined_int := false
let defined_float = ref false
let ffloat = ref dummy
let init_float retro =
match retro.Retroknowledge.retro_float64 with
| Some c ->
defined_float := true;
ffloat := { mark = Ntrl; term = FFlex (ConstKey (UVars.in_punivs c)) }
| None -> defined_float := false
let defined_bool = ref false
let ftrue = ref dummy
let ffalse = ref dummy
let init_bool retro =
match retro.Retroknowledge.retro_bool with
| Some (ct,cf) ->
defined_bool := true;
ftrue := mk_construct ct;
ffalse := mk_construct cf;
| None -> defined_bool :=false
let defined_carry = ref false
let fC0 = ref dummy
let fC1 = ref dummy
let init_carry retro =
match retro.Retroknowledge.retro_carry with
| Some(c0,c1) ->
defined_carry := true;
fC0 := mk_construct c0;
fC1 := mk_construct c1;