Source file rewrite.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
(** Implementation of the rewrite tactic. *)
open Lplib
open Common open Pos open Error open Debug
open Core open Term open Print
open Goal
(** Logging function for the rewrite tactic. *)
let log = Logger.make 'r' "rtac" "rewrite tactic"
let log = log.pp
(** Equality configuration. *)
type eq_config =
{ symb_P : sym (** Encoding of propositions. *)
; symb_T : sym (** Encoding of types. *)
; symb_eq : sym (** Equality proposition. *)
; symb_eqind : sym (** Induction principle on equality. *)
; symb_refl : sym (** Reflexivity of equality. *) }
(** Additional configuration needed only when rewrite has to lift an equality
over a binder. *)
type binder_rewrite_config =
{ symb_arr : sym (** HOL non-dependent function type constructor. *)
; symb_funext : sym (** Functional extensionality principle. *) }
(** [get_eq_config ss pos] returns the current configuration for
equality, used by tactics such as “rewrite” or “reflexivity”. *)
let get_eq_config : Sig_state.t -> popt -> eq_config = fun ss pos ->
let builtin = Builtin.get ss pos [] in
{ symb_P = builtin "Prf"
; symb_T = builtin "El"
; symb_eq = builtin "eq"
; symb_eqind = builtin "eqind"
; symb_refl = builtin "refl" }
(** [get_binder_rewrite_config ss pos] returns the configuration needed for
binder-dependent rewrite occurrences. *)
let get_binder_rewrite_config :
Sig_state.t -> popt -> binder_rewrite_config = fun ss pos ->
let builtin = Builtin.get ss pos [] in
{ symb_arr = builtin "arr"
; symb_funext = builtin "funExt" }
(** [get_eq_data pos cfg a] returns [((a,l,r),[v1;..;vn])] if [a ≡ Π v1:A1,
.., Π vn:An, P (eq a l r)] and fails otherwise. *)
let get_eq_data :
eq_config -> popt -> term -> (term * term * term) * var list = fun cfg ->
let exception Not_eq of term in
let get_eq_args u =
if Logger.log_enabled () then log "get_eq_args %a" term u;
match get_args u with
| eq, [a;l;r] when is_symb cfg.symb_eq eq -> a, l, r
| _ -> raise (Not_eq u)
in
let exception Not_P of term in
let return vs r = r, List.rev vs in
let rec get_eq vs t notin_whnf =
if Logger.log_enabled () then log "get_eq %a" term t;
match get_args t with
| Prod(_,t), _ ->
let v,t = unbind ~name:("$"^binder_name t) t in get_eq (v::vs) t true
| p, [u] when is_symb cfg.symb_P p ->
begin
let u = Eval.whnf ~tags:[NoRw;NoExpand] [] u in
try return vs (get_eq_args u)
with Not_eq _ ->
(try return vs (get_eq_args (Eval.whnf [] u))
with Not_eq _ when notin_whnf -> get_eq vs (Eval.whnf [] t) false)
end
| _ ->
if notin_whnf then get_eq vs (Eval.whnf [] t) false
else raise (Not_P t)
in
fun pos t ->
if Logger.log_enabled () then log "get_eq_data %a" term t;
try get_eq [] t true with
| Not_P u ->
fatal pos "Expected %a _ but found %a." sym cfg.symb_P term u
| Not_eq u ->
fatal pos "Expected %a _ _ but found %a." sym cfg.symb_eq term u
(** Type of a term with the free variables that need to be substituted. It is
usually used to store the LHS of a proof of equality, together with the
variables that were quantified over. *)
type to_subst = var array * term
(** [matches p t] instantiates the [TRef]s of [p] so that [p] becomes equal
to [t] and returns [true] if all [TRef]s of [p] could be instantiated, and
[false] otherwise. With [allow_binder_holes], a [TRef] belonging to a
selection pattern may match a term containing a variable bound inside
[p]. Callers must preserve the scope of those variables when using the
assignments, or discard them. *)
let matches ?(allow_binder_holes=false) : term -> term -> bool =
let exception Not_equal in
let add_eqs xs = List.fold_left2 (fun l pi ti -> (xs,pi,ti)::l) in
let rec eq l =
match l with
| [] -> ()
| (xs,p,t)::l ->
if LibTerm.eq_alpha p t then eq l else begin
let hp, ps, kp = get_args_len p and ht, ts, kt = get_args_len t in
if Logger.log_enabled() then
log "%a %a \nmatches? %a %a"
term hp (D.list term) ps term ht (D.list term) ts;
match hp with
| Wild -> assert false
| Patt _ -> assert false
| Plac _ -> assert false
| Appl _ -> assert false
| Type -> assert false
| Kind -> assert false
| Bvar _ -> assert false
| TRef r ->
if kp > kt then raise Not_equal;
let ts1, ts2 = List.cut ts (kt-kp) in
let u = add_args ht ts1 in
if not allow_binder_holes && List.exists (fun x -> occur x u) xs
then raise Not_equal;
if Logger.log_enabled() then log (Color.red "<TRef> ≔ %a") term u;
Timed.(r := Some u);
eq (add_eqs xs l ps ts2)
| Meta _ -> eq l
| Prod _
| Abst _
| LLet _
| Symb _
| Vari _ ->
if kp <> kt then raise Not_equal;
match hp, ht with
| Vari x, Vari y when eq_vars x y -> eq (add_eqs xs l ps ts)
| Symb f, Symb g when f == g -> eq (add_eqs xs l ps ts)
| Abst(a,b), Abst(a',b')
| Prod(a,b), Prod(a',b') ->
let x,b,b' = unbind2 b b' in
eq ((xs,a,a')::(x::xs,b,b')::add_eqs xs l ps ts)
| LLet(a,c,b), LLet(a',c',b') ->
let x,b,b' = unbind2 b b' in
eq ((xs,a,a')::(xs,c,c')::(x::xs,b,b')
::add_eqs xs l ps ts)
| _ ->
if Logger.log_enabled() then log "distinct heads";
raise Not_equal
end
in
fun p t ->
let r = try eq [[],p,t]; true with Not_equal -> false in
if Logger.log_enabled() then log "matches result: %b" r; r
let no_match ?(subterm=false) pos p t =
if subterm then fatal pos "No subterm of [%a] matches [%a]." term t term p
else fatal pos "[%a] doesn't match [%a]." term t term p
(** [matching_subs (xs,p) t] attempts to match the pattern [p] containing the
variables [xs] with the term [t]. If successful, it returns [Some ts]
where [ts] is an array of terms such that substituting [xs] by the
corresponding elements of [ts] in [p] yields [t].
WARNING: Some elements of [ts] may be uninstantiated TRefs. This happens if
not all [xs] are in [LibTerm.free_vars p], for instance when some [xs] are
type variables not occurring in [p], for instance when trying to apply an
equation of the form [x = ...] with [x] of polymorphic type. This could be
improved by generating p_terms instead of terms. Indeed, in this case, we
could replace uninstantiated TRefs by underscores. *)
let matching_subs : to_subst -> term -> term array option = fun (xs,p) t ->
let ts = Array.map (fun _ -> mk_TRef(Timed.ref None)) xs in
let p = msubst (bind_mvar xs p) ts in
if matches p t then Some ts else None
(** [check_subs vars ts] checks that no element of [ts] is an uninstantiated
TRef. *)
let check_subs pos vars ts =
let f i ti =
match unfold ti with
| TRef _ ->
fatal pos "Don't know how to instantiate the argument \"%a\" \
of the equation." var vars.(i)
| _ -> ()
in
Array.iteri f ts
let matching_subs_check_TRef pos ((vars,p) as xsp) t =
match matching_subs xsp t with
| Some ts -> check_subs pos vars ts; ts
| None -> no_match pos p t
(** Binder frame enclosing a subterm. [binder_path] identifies the original
binder by the path to its body, storing child indices in reverse order.
Application children are 0 for the function and 1 for the argument;
abstraction/product children are 0 for the domain and 1 for the body;
let children are 0 for the type, 1 for the definition and 2 for the body.
The path recognises the same binder across traversals even when unbinding
creates fresh variables. [binder_var] is the variable opened in this
traversal, with type [binder_typ]. *)
type binder_frame =
{ binder_var : var
; binder_typ : term
; binder_path : int list }
(** [abstract_over_frame frame t] abstracts [t] over the variable recorded in
[frame], using the frame's binder type. *)
let abstract_over_frame : binder_frame -> term -> term =
fun frame t ->
mk_Abst(frame.binder_typ, bind_var frame.binder_var t)
(** [abstract_over_frames frames t] abstracts [t] over all [frames]. The frame
list must be ordered from innermost to outermost binder, and the returned
abstractions are nested from outermost to innermost binder. *)
let abstract_over_frames : binder_frame list -> term -> term =
fun frames t ->
List.fold_left
(fun t frame -> abstract_over_frame frame t)
t frames
(** [same_binder_paths frames frames'] tells whether [frames] and [frames']
identify the same original enclosing binders across independent
traversals of the goal. *)
let same_binder_paths : binder_frame list -> binder_frame list -> bool =
List.equal (fun f f' -> f.binder_path = f'.binder_path)
(** [apply_to_frames t frames] applies [t] to the variables in [frames]. The
frame list must be ordered from innermost to outermost binder. *)
let apply_to_frames : term -> binder_frame list -> term =
fun t frames ->
List.fold_right
(fun frame t -> mk_Appl(t, mk_Vari frame.binder_var))
frames t
(** [adapt_to_frames frames frames' t] adapts references in [t] to variables
bound by [frames] so that they refer to the corresponding
variables bound by [frames']. *)
let adapt_to_frames :
binder_frame list -> binder_frame list -> term -> term =
fun frames frames' t ->
apply_to_frames (abstract_over_frames frames t) frames'
(** [same_under_binders first_frames frames first t] tells whether [t] is the
same term as [first], modulo the fresh variables generated when unbinding
the same original enclosing binders. *)
let same_under_binders :
binder_frame list -> binder_frame list -> term -> term -> bool =
fun first_frames frames first t ->
same_binder_paths first_frames frames
&& LibTerm.eq_alpha
(abstract_over_frames first_frames first)
(abstract_over_frames frames t)
(** [find_subterm_from binders path try_match t] searches [t], trying each
candidate before its children. [try_match] receives its enclosing frames
and term, and returns [Some result] on success. Failed attempts are
rolled back before descending. Children are searched in application order,
with binder domains and let definitions before bodies. Initial frames are
ordered from innermost to outermost; paths store child indices in reverse.
A successful result retains the state established by [try_match]. *)
let find_subterm_from :
binder_frame list -> int list ->
(binder_frame list -> term -> 'a option) ->
term -> 'a option =
fun initial_binders initial_path try_match t ->
let time = Timed.Time.save () in
let rec find binders path t =
match try_match binders t with
| Some _ as r -> r
| None ->
Timed.Time.restore time;
match unfold t with
| Appl(a,b) -> find_app binders path a b
| Abst(a,b) | Prod(a,b) -> find_binder binders path a b
| LLet(a,c,b) -> find_let binders path a c b
| _ -> None
and find_app binders path a b =
match find binders (0::path) a with
| None -> Timed.Time.restore time; find binders (1::path) b
| r -> r
and find_let binders path a c b =
match find binders (0::path) a with
| Some _ as r -> r
| None ->
Timed.Time.restore time;
match find binders (1::path) c with
| None ->
Timed.Time.restore time;
let x,b = unbind b in
let frame =
{ binder_var = x; binder_typ = a; binder_path = 2::path }
in
find (frame::binders) (2::path) b
| r -> r
and find_binder binders path a b =
match find binders (0::path) a with
| None ->
Timed.Time.restore time;
let x,b = unbind b in
let frame =
{ binder_var = x; binder_typ = a; binder_path = 1::path }
in
find (frame::binders) (1::path) b
| r -> r
in find initial_binders initial_path t
(** Result of a successful binder-aware rewrite occurrence search. *)
type subst_under_binders =
{ subst : term array
; redex : term
; binders : binder_frame list }
(** [find_subst_from binders path (xs,p) t] searches for the first subterm of
[t] matching [p]. It returns the substitution for [xs], the matched term
and its enclosing binder frames. [binders] and [path] are the known
enclosing context of [t], ordered as in [find_subterm_from]. *)
let find_subst_from :
binder_frame list -> int list -> to_subst -> term ->
subst_under_binders option = fun initial_binders initial_path xsp t ->
let try_match binders t =
if Logger.log_enabled() then
log "find_subst %a ≡ %a" term (snd xsp) term t;
match matching_subs xsp t with
| None -> None
| Some subst -> Some { subst; redex = t; binders }
in
find_subterm_from initial_binders initial_path try_match t
(** [find_subst_in_region pos binders (vars,p) t] searches for
[p] in an already-selected region [t], preserving the binder context
enclosing the region. *)
let find_subst_in_region :
popt -> binder_frame list -> to_subst -> term -> subst_under_binders =
fun pos binders (vars,p) t ->
match find_subst_from binders [] (vars,p) t with
| None -> no_match ~subterm:true pos p t
| Some r -> check_subs pos vars r.subst; r
(** [find_subst pos (vars,p) t] returns the search result for the first
occurrence of [p] in [t], or fails if no subterm matches. It also
checks that all variables in [vars] have been instantiated. *)
let find_subst : popt -> to_subst -> term -> subst_under_binders =
fun pos -> find_subst_in_region pos []
(** [replace_wild_by_tref t] substitutes every wildcard of [t] by a distinct
fresh [TRef]. *)
let rec replace_wild_by_tref : term -> term = fun t ->
match unfold t with
| Wild -> mk_TRef(Timed.ref None)
| Appl(t,u) ->
mk_Appl_not_canonical(replace_wild_by_tref t, replace_wild_by_tref u)
| Abst(a,b) ->
let x,b = unbind b in
mk_Abst(replace_wild_by_tref a,
bind_var x (replace_wild_by_tref b))
| Prod(a,b) ->
let x,b = unbind b in
mk_Prod(replace_wild_by_tref a,
bind_var x (replace_wild_by_tref b))
| LLet(a,c,b) ->
let x,b = unbind b in
mk_LLet(replace_wild_by_tref a, replace_wild_by_tref c,
bind_var x (replace_wild_by_tref b))
| _ -> t
(** Result of matching a rewrite selector pattern. [term] is the actual
matched goal subterm; [binders] records its enclosing binder frames. *)
type selected_term_under_binders =
{ term : term
; binders : binder_frame list }
(** [find_subterm_matching_from binders path p t] tries to find
a subterm of [t] that matches [p] by instantiating the [TRef]s of [p]
and records the binders enclosing the selected subterm. [binders] and
[path] are the already-known enclosing binder context of [t]. The binder
list is ordered from innermost to outermost binder. *)
let find_subterm_matching_from :
binder_frame list -> int list -> term -> term ->
selected_term_under_binders option =
fun initial_binders initial_path p t ->
let p_refs = replace_wild_by_tref p in
let try_match binders t =
if matches ~allow_binder_holes:true p_refs t then Some
{ term = t; binders }
else None
in
find_subterm_from initial_binders initial_path try_match t
(** [find_subterm_matching pos p t] returns the first selected
subterm matching [p] in [t], or fails if no subterm matches. *)
let find_subterm_matching :
popt -> term -> term -> selected_term_under_binders = fun pos p t ->
match find_subterm_matching_from [] [] p t with
| None -> no_match ~subterm:true pos p t
| Some r -> r
(** Result of matching a contextual pattern such as [id in p]. [pat_l] is
the actual matched goal context before rewriting, retained directly rather
than reconstructed from [p]. [id_val] is the term denoted by [id] inside
it. Both terms retain their enclosing binder frames in [pat_l_binders]
and [id_val_binders], respectively. [id_path] is the first occurrence of
[id], and [id_paths] records every occurrence. These paths are relative
to [pat_l] and are stored in reverse order, as in the rewrite
traversal. *)
type contextual_selection =
{ pat_l : term
; pat_l_binders : binder_frame list
; id_val : term
; id_val_binders : binder_frame list
; id_path : int list
; id_paths : int list list }
(** [match_contextual_pattern selector p binders t] matches one
candidate [t] against [p], collecting all occurrences of [selector]. The
selected paths are relative to [t]; [binders] records its enclosing
context. *)
let match_contextual_pattern :
var -> term -> binder_frame list -> term ->
contextual_selection option =
fun selector p binders t ->
let same fs fs' u t =
let fs = List.filter (fun f -> occur f.binder_var u) fs in
let fs' = List.filter (fun f -> occur f.binder_var t) fs' in
same_under_binders fs fs' u t
in
let selected = ref None in
let rec match_pattern binders path p t =
match unfold p, unfold t with
| Vari x, _ when eq_vars x selector ->
begin match !selected with
| None -> selected := Some(t,binders,[path]); true
| Some(u,fs,paths) ->
if same fs binders u t then
(selected := Some(u,fs,path::paths); true)
else false
end
| Wild, _ -> true
| Vari x, Vari y -> eq_vars x y
| Symb f, Symb g -> f == g
| Type, Type | Kind, Kind -> true
| Appl(p,q), Appl(t,u) ->
match_pattern binders (0::path) p t
&& match_pattern binders (1::path) q u
| Abst(a,b), Abst(a',b')
| Prod(a,b), Prod(a',b') ->
let x,b,b' = unbind2 b b' in
match_pattern binders (0::path) a a'
&& let frame =
{ binder_var = x; binder_typ = a'; binder_path = 1::path }
in
match_pattern (frame::binders) (1::path) b b'
| LLet(a,c,b), LLet(a',c',b') ->
let x,b,b' = unbind2 b b' in
match_pattern binders (0::path) a a'
&& match_pattern binders (1::path) c c'
&& let frame =
{ binder_var = x; binder_typ = a'; binder_path = 2::path }
in
match_pattern (frame::binders) (2::path) b b'
| _ -> false
in
if match_pattern binders [] p t then
match !selected with
| Some(u,fs,id_paths) ->
let id_path = List.hd (List.rev id_paths) in
Some { pat_l = t; pat_l_binders = binders
; id_val = u; id_val_binders = fs
; id_path; id_paths }
| _ -> None
else None
(** [find_contextual_selection pos p goal] finds the first subterm of
[goal] matching the contextual pattern [p]. It matches the context and
identifies the selector occurrence together. *)
let find_contextual_selection :
popt -> binder -> term -> contextual_selection = fun pos p goal ->
let selector,p = unbind p in
let match_context = match_contextual_pattern selector p in
match find_subterm_from [] [] match_context goal with
| Some r -> r
| None -> no_match ~subterm:true pos p goal
(** [replace_under_binders_from binders path f goal] traverses [goal] while
recording enclosing binder frames. [binders] and [path] are the
already-known enclosing binder context of [goal]. At each subterm [t],
[f binders path t] may return a replacement. The path is relative to the
initial [goal] unless [path] is supplied by a containing search. If [f]
returns a replacement, traversal does not descend below [t]. *)
let replace_under_binders_from :
binder_frame list -> int list ->
(binder_frame list -> int list -> term -> term option) -> term -> term =
fun initial_binders initial_path f goal ->
let rec replace : binder_frame list -> int list -> term -> term =
fun binders path t ->
match f binders path t with
| Some t -> t
| None ->
match unfold t with
| Appl(t,u) ->
mk_Appl (replace binders (0::path) t,
replace binders (1::path) u)
| Prod(a,b) ->
let x,b = unbind b in
let frame =
{ binder_var = x; binder_typ = a; binder_path = 1::path }
in
mk_Prod (replace binders (0::path) a,
bind_var x (replace (frame::binders) (1::path) b))
| Abst(a,b) ->
let x,b = unbind b in
let frame =
{ binder_var = x; binder_typ = a; binder_path = 1::path }
in
mk_Abst (replace binders (0::path) a,
bind_var x (replace (frame::binders) (1::path) b))
| LLet(typ, def, body) ->
let x, body = unbind body in
let frame =
{ binder_var = x; binder_typ = typ; binder_path = 2::path }
in
mk_LLet (replace binders (0::path) typ,
replace binders (1::path) def,
bind_var x
(replace (frame::binders) (2::path) body))
| Meta(m,ts) -> mk_Meta (m, Array.map (replace binders path) ts)
| Bvar _ -> assert false
| Wild -> assert false
| TRef _ -> assert false
| Patt _ -> assert false
| Plac _ -> assert false
| _ -> t
in
replace initial_binders initial_path goal
(** [replace_under_binders f goal] traverses [goal] while recording enclosing
binder frames. At each subterm [t], [f binders t] may return a
replacement. If it does, traversal does not descend below [t]. *)
let replace_under_binders :
(binder_frame list -> term -> term option) -> term -> term =
fun f -> replace_under_binders_from [] [] (fun fs _ t -> f fs t)
(** [bind_pattern ~at binders z lhs relevant goal]
replaces occurrences matching the instantiated [lhs] in [goal] by [z]
applied to the relevant bound variables. [relevant] is the list of binder
frames that the equality is lifted over. [lhs] is already abstracted over
these frames. Candidates must use the same original binders and
match after abstraction over their local frames. [binders] is the
already-known enclosing context of [goal]; [at] optionally restricts
replacement to selected paths. *)
let bind_pattern ?(at=fun _ -> true) :
binder_frame list -> var -> term -> binder_frame list -> term -> term =
fun initial_binders z lhs relevant goal ->
let replace binders path t =
if not (at path) then None else
let current_relevant =
if relevant = [] then [] else
List.filter (fun frame -> occur frame.binder_var t) binders in
if same_binder_paths relevant current_relevant
&& matches lhs (abstract_over_frames current_relevant t)
then Some (apply_to_frames (mk_Vari z) current_relevant)
else None
in
replace_under_binders_from initial_binders [] replace goal
(** [replace_selected_under_binders selected_binders selected replacement
goal] replaces every occurrence of [selected] in [goal] by
[replacement], adapting references from the variables recorded in
[selected_binders] to the corresponding fresh variables when the same
original binders are unbound again while traversing [goal]. *)
let replace_selected_under_binders :
binder_frame list -> term -> term -> term -> term =
fun selected_binders selected replacement goal ->
let selected_binders =
List.filter (fun frame -> occur frame.binder_var selected)
selected_binders
in
let replace binders t =
let current_binders =
List.filter (fun frame -> occur frame.binder_var t) binders
in
if same_under_binders selected_binders current_binders selected t then
Some (adapt_to_frames selected_binders current_binders replacement)
else None
in
replace_under_binders replace goal
(** Data prepared for the final equality-induction rewrite step. *)
type prepared_rewrite =
{ eq_type : term
; lhs : term
; rhs : term
; proof : term
; pred_bind : binder
; new_term : term }
(** Equality data being lifted over one or more binders. *)
type eq_data = term * term * term * term
(** [hol_domain_of_binder cfg pos typ] returns [a] when [typ] is convertible
to [T a], and fails otherwise. *)
let hol_domain_of_binder : eq_config -> popt -> term -> term =
fun cfg pos typ ->
match get_args (Eval.whnf ~tags:[NoRw] [] typ) with
| t, [a] when is_symb cfg.symb_T t -> a
| _ -> fatal pos
"Expected a non-dependent HOL binder type of the form %a _."
sym cfg.symb_T
(** [lift_over_frame cfg binder_cfg pos frame (a,l,r,p)] lifts the equality
data [p : P (eq a l r)] over [frame] using [funExt]. *)
let lift_over_frame : eq_config -> binder_rewrite_config -> popt ->
binder_frame -> eq_data -> eq_data =
fun cfg binder_cfg pos frame (eq_type, lhs, rhs, proof) ->
let dom = hol_domain_of_binder cfg pos frame.binder_typ in
let cod = eq_type in
let eq_type = add_args (mk_Symb binder_cfg.symb_arr) [dom; cod] in
let lhs = abstract_over_frame frame lhs in
let rhs = abstract_over_frame frame rhs in
let proof = abstract_over_frame frame proof in
let proof =
add_args (mk_Symb binder_cfg.symb_funext) [dom; cod; lhs; rhs; proof]
in
eq_type, lhs, rhs, proof
(** [prepare_eq_data_under_binders ss cfg pos binders redex data] lifts
[data] over every enclosing binder on which [redex] depends. It returns
the lifted equality data and the relevant binders. *)
let prepare_eq_data_under_binders :
Sig_state.t -> eq_config -> popt -> binder_frame list -> term ->
eq_data -> eq_data * binder_frame list =
fun ss cfg pos binders redex (eq_type, lhs, rhs, proof) ->
let relevant =
List.filter (fun frame -> occur frame.binder_var redex) binders
in
match relevant with
| [] -> (eq_type, lhs, rhs, proof), relevant
| _ ->
let binder_cfg = get_binder_rewrite_config ss pos in
let data =
List.fold_left
(fun acc frame -> lift_over_frame cfg binder_cfg pos frame acc)
(eq_type, lhs, rhs, proof) relevant
in
data, relevant
(** [prepare_rewrite_from ~at binders ss cfg pos goal eq_data
found] prepares the equality data, predicate and rewritten term for a
rewrite occurrence. [binders] is the already-known enclosing binder
context of [goal]. If the redex depends on enclosing binders,
the equality is lifted over the relevant ones and the context abstracts
the resulting function-level occurrence. [at] optionally restricts
replacement to selected paths. *)
let prepare_rewrite_from ?(at=fun _ -> true) :
binder_frame list -> Sig_state.t -> eq_config -> popt ->
term -> eq_data -> subst_under_binders -> prepared_rewrite =
fun initial_binders ss cfg pos goal (eq_type, lhs, rhs, proof) found ->
let (eq_type, lhs, rhs, proof), relevant =
prepare_eq_data_under_binders ss cfg pos found.binders found.redex
(eq_type, lhs, rhs, proof)
in
let z = new_var "z" in
let pred =
bind_pattern ~at initial_binders z lhs relevant goal
in
let pred_bind = bind_var z pred in
{ eq_type; lhs; rhs; proof; pred_bind; new_term = subst pred_bind rhs }
(** [prepare_rewrite ss cfg pos goal eq_data found] is
[prepare_rewrite_from] with no initial enclosing binders. *)
let prepare_rewrite :
Sig_state.t -> eq_config -> popt -> term -> eq_data ->
subst_under_binders -> prepared_rewrite =
prepare_rewrite_from []
(** [swap cfg a r l t] returns a term of type [P (eq a l r)] from a term [t]
of type [P (eq a r l)]. *)
let swap : eq_config -> term -> term -> term -> term -> term =
fun cfg a r l t ->
let pred =
let x = new_var "x" in
let pred = add_args (mk_Symb cfg.symb_eq) [a; l; mk_Vari x] in
mk_Abst(mk_Appl(mk_Symb cfg.symb_T, a), bind_var x pred)
in
let refl_a_l = add_args (mk_Symb cfg.symb_refl) [a; l] in
add_args (mk_Symb cfg.symb_eqind) [a; r; l; t; pred; refl_a_l]
(** [at_selector selected path] tells whether [path] names an occurrence
of the contextual selector identifier. Paths are relative to
[selected.pat_l]; repeated uses of the identifier are all included. *)
let at_selector : contextual_selection -> int list -> bool =
fun selected path -> List.mem path selected.id_paths
(** [within_selector selected path] tells whether [path] is at or below a
region named by the contextual selector identifier. Paths are relative
to [selected.pat_l] and store child indices in reverse order, so a
descendant path ends with its region's path. *)
let within_selector : contextual_selection -> int list -> bool =
fun selected path ->
List.exists (fun root ->
let delta = List.length path - List.length root in
delta >= 0 && List.drop delta path = root)
selected.id_paths
(** [rewrite_in_context ss cfg pos goal data at selected found] prepares a
rewrite inside the matched [selected.pat_l], then reinserts the
rewritten context and predicate into [goal]. [data] is the instantiated
equality (type, LHS, RHS, proof); [found] records the first redex and its
enclosing binders. [at] restricts replacement to paths relative to the
matched context. The result contains the prepared equality type,
whole-goal predicate binder, rewritten goal, equality proof and sides. *)
let rewrite_in_context :
Sig_state.t -> eq_config -> popt -> term -> eq_data ->
(int list -> bool) -> contextual_selection -> subst_under_binders ->
term * binder * term * term * term * term =
fun ss cfg pos goal data at selected found ->
let prepared =
prepare_rewrite_from ~at
selected.pat_l_binders ss cfg pos selected.pat_l data found
in
let z,region_pred = unbind prepared.pred_bind in
let new_term =
replace_selected_under_binders selected.pat_l_binders
selected.pat_l prepared.new_term goal
in
let pred =
replace_selected_under_binders selected.pat_l_binders
selected.pat_l region_pred goal
in
( prepared.eq_type, bind_var z pred, new_term
, prepared.proof, prepared.lhs, prepared.rhs )
(** [rewrite ss p pos gt l2r pat t] generates a term for the refine tactic
representing the application of the rewrite tactic to the goal type
[gt]. Every occurrence of the first instance of the left-hand side is
replaced by the right-hand side of the obtained proof (or the reverse if
l2r is false). [pat] is an optional SSReflect pattern. [t] is the
equational lemma that is applied. It handles the full set of SSReflect
patterns. *)
let rewrite : Sig_state.t -> problem -> popt -> goal_typ -> bool ->
(term, binder) Parsing.Syntax.rwpatt option -> term -> term =
fun ss p pos {goal_hyps=g_env; goal_type=g_type; _} l2r pat t ->
let cfg = get_eq_config ss pos in
let g_term =
match get_args g_type with
| t, [u] when is_symb cfg.symb_P t -> u
| _ -> fatal pos "Goal not of the form (%a _)." sym cfg.symb_P
in
let g_ctxt = Env.to_ctxt g_env in
let (t, t_type) = Query.infer pos p g_ctxt t in
let (a, l, r), vars = get_eq_data cfg pos t_type in
let vars = Array.of_list vars in
let t = Array.fold_left (fun t x -> mk_Appl(t, mk_Vari x)) t vars in
let (t, l, r) = if l2r then (t, l, r) else (swap cfg a l r t, r, l) in
let bound = let bind = bind_mvar vars in bind t, bind l, bind r in
let msubst3 (b1, b2, b3) ts = msubst b1 ts, msubst b2 ts, msubst b3 ts in
let (a, pred_bind, new_term, t, l, r) =
match pat with
| None ->
let found = find_subst pos (vars, l) g_term in
let (t, l, r) = msubst3 bound found.subst in
let prepared = prepare_rewrite
ss cfg pos g_term (a, l, r, t) found
in
( prepared.eq_type, prepared.pred_bind, prepared.new_term
, prepared.proof, prepared.lhs, prepared.rhs )
| Some(Rw_Term(p)) ->
let match_p = find_subterm_matching pos p g_term in
let sigma = matching_subs_check_TRef pos (vars,l) match_p.term in
let (t, l, r) = msubst3 bound sigma in
let found =
{ subst = sigma; redex = match_p.term
; binders = match_p.binders }
in
let prepared = prepare_rewrite
ss cfg pos g_term (a, l, r, t) found
in
( prepared.eq_type, prepared.pred_bind, prepared.new_term
, prepared.proof, prepared.lhs, prepared.rhs )
| Some(Rw_InTerm(p)) ->
let match_p = find_subterm_matching pos p g_term in
let sigma =
find_subst_in_region
pos match_p.binders (vars,l) match_p.term
in
let (t, l, r) = msubst3 bound sigma.subst in
let prepared =
prepare_rewrite_from
match_p.binders ss cfg pos
match_p.term (a, l, r, t) sigma
in
let x, p_x = unbind prepared.pred_bind in
let new_term =
replace_selected_under_binders
match_p.binders match_p.term
prepared.new_term g_term
in
let pred =
replace_selected_under_binders
match_p.binders match_p.term
p_x g_term
in
( prepared.eq_type, bind_var x pred, new_term
, prepared.proof, prepared.lhs, prepared.rhs )
| Some(Rw_IdInTerm(p)) ->
let selected = find_contextual_selection pos p g_term in
let redex = selected.id_val in
let sigma = matching_subs_check_TRef pos (vars,l) redex in
let found =
{ subst = sigma; redex
; binders = selected.id_val_binders }
in
let (t,l,r) = msubst3 bound found.subst in
rewrite_in_context ss cfg pos g_term (a,l,r,t)
(at_selector selected) selected found
| Some(Rw_TermInIdInTerm(s,p)) ->
let selected = find_contextual_selection pos p g_term in
let found_s =
match find_subterm_matching_from
selected.id_val_binders selected.id_path
s selected.id_val with
| Some r -> r
| None -> no_match ~subterm:true pos s selected.id_val
in
let sigma = matching_subs_check_TRef pos (vars,l) found_s.term in
let found =
{ subst = sigma; redex = found_s.term
; binders = found_s.binders }
in
let (t,l,r) = msubst3 bound found.subst in
rewrite_in_context ss cfg pos g_term (a,l,r,t)
(within_selector selected) selected found
| Some(Rw_TermAsIdInTerm(s,p)) ->
let id,pat = unbind p in
let p_s = subst p s in
let p_refs = replace_wild_by_tref p_s in
let try_match binders t =
let time = Timed.Time.save () in
let result = matches ~allow_binder_holes:true p_refs t in
Timed.Time.restore time;
if result then match_contextual_pattern id pat binders t
else None
in
let selected =
match find_subterm_from [] [] try_match g_term with
| Some r -> r
| None -> no_match ~subterm:true pos p_s g_term
in
let redex = selected.id_val in
let sigma = matching_subs_check_TRef pos (vars,l) redex in
let found =
{ subst = sigma; redex
; binders = selected.id_val_binders }
in
let (t,l,r) = msubst3 bound found.subst in
rewrite_in_context ss cfg pos g_term (a,l,r,t)
(at_selector selected) selected found
| Some(Rw_InIdInTerm(q)) ->
let selected = find_contextual_selection pos q g_term in
let found =
match find_subst_from
selected.id_val_binders selected.id_path
(vars,l) selected.id_val with
| Some r -> check_subs pos vars r.subst; r
| None -> no_match ~subterm:true pos l selected.id_val
in
let (t,l,r) = msubst3 bound found.subst in
rewrite_in_context ss cfg pos g_term (a,l,r,t)
(within_selector selected) selected found
in
let pred = mk_Abst(mk_Appl(mk_Symb cfg.symb_T, a), pred_bind) in
let goal_type = mk_Appl(mk_Symb cfg.symb_P, new_term) in
let goal_term = LibMeta.make p g_ctxt goal_type in
let eqind = mk_Symb cfg.symb_eqind in
let result = add_args eqind [a; l; r; t; pred; goal_term] in
if Logger.log_enabled () then
begin
log "Rewriting with:";
log " goal = [%a]" term g_type;
log " equality proof = [%a]" term t;
log " equality LHS = [%a]" term l;
log " equality RHS = [%a]" term r;
log " pred = [%a]" term pred;
log " new goal = [%a]" term goal_type;
log " produced term = [%a]" term result;
end;
result