forked from coq/coq
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tacinterp.ml
2208 lines (1998 loc) · 83.3 KB
/
tacinterp.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) *)
(************************************************************************)
open Constrintern
open Patternops
open Pp
open CAst
open Namegen
open Genredexpr
open Glob_term
open Glob_ops
open Tacred
open CErrors
open Util
open Names
open Nameops
open Libnames
open Tacmach
open Tactic_debug
open Constrexpr
open Termops
open Tacexpr
open Genarg
open Geninterp
open Stdarg
open Tacarg
open Printer
open Pretyping
open Tactypes
open Tactics
open Locus
open Tacintern
open Taccoerce
open Proofview.Notations
open Context.Named.Declaration
open Ltac_pretype
let ltac_trace_info = Tactic_debug.ltac_trace_info
let has_type : type a. Val.t -> a typed_abstract_argument_type -> bool = fun v wit ->
let Val.Dyn (t, _) = v in
let t' = match val_tag wit with
| Val.Base t' -> t'
| _ -> assert false (* not used in this module *)
in
match Val.eq t t' with
| None -> false
| Some Refl -> true
let prj : type a. a Val.typ -> Val.t -> a option = fun t v ->
let Val.Dyn (t', x) = v in
match Val.eq t t' with
| None -> None
| Some Refl -> Some x
let in_list tag v =
let tag = match tag with Val.Base tag -> tag | _ -> assert false in
Val.Dyn (Val.typ_list, List.map (fun x -> Val.Dyn (tag, x)) v)
let in_gen wit v =
let t = match val_tag wit with
| Val.Base t -> t
| _ -> assert false (* not used in this module *)
in
Val.Dyn (t, v)
let out_gen wit v =
let t = match val_tag wit with
| Val.Base t -> t
| _ -> assert false (* not used in this module *)
in
match prj t v with None -> assert false | Some x -> x
let val_tag wit = val_tag (topwit wit)
let pr_argument_type arg =
let Val.Dyn (tag, _) = arg in
Val.pr tag
type value = Val.t
let push_appl appl args =
match appl with
| UnnamedAppl -> UnnamedAppl
| GlbAppl l -> GlbAppl (List.map (fun (h,vs) -> (h,vs@args)) l)
let pr_generic arg =
let Val.Dyn (tag, _) = arg in
str"<" ++ Val.pr tag ++ str ":(" ++ Pptactic.pr_value Pptactic.ltop arg ++ str ")>"
let pr_appl h vs =
Pptactic.pr_ltac_constant h ++ spc () ++
Pp.prlist_with_sep spc pr_generic vs
let rec name_with_list appl t =
match appl with
| [] -> t
| (h,vs)::l -> Proofview.Trace.name_tactic (fun () -> pr_appl h vs) (name_with_list l t)
let name_if_glob appl t =
match appl with
| UnnamedAppl -> t
| GlbAppl l -> name_with_list l t
let combine_appl appl1 appl2 =
match appl1,appl2 with
| UnnamedAppl,a | a,UnnamedAppl -> a
| GlbAppl l1 , GlbAppl l2 -> GlbAppl (l2@l1)
let of_tacvalue v = in_gen (topwit wit_tacvalue) v
let to_tacvalue v = out_gen (topwit wit_tacvalue) v
(* Debug reference *)
let debug = ref DebugOff
(* Sets the debugger on or off *)
let set_debug pos = debug := pos
(* Gives the state of debug; disabled in worker processes *)
let get_debug () = if Flags.async_proofs_is_worker () then DebugOff else !debug
let log_trace = ref false
let is_traced () =
!log_trace || !debug <> DebugOff || !Flags.profile_ltac
(** More naming applications *)
let name_vfun appl vle =
if is_traced () && has_type vle (topwit wit_tacvalue) then
match to_tacvalue vle with
| VFun (appl0,trace,loc,lfun,vars,t) -> of_tacvalue (VFun (combine_appl appl0 appl,trace,loc,lfun,vars,t))
| _ -> vle
else vle
module TacStore = Geninterp.TacStore
let f_avoid_ids : Id.Set.t TacStore.field = TacStore.field ()
(* ids inherited from the call context (needed to get fresh ids) *)
let f_debug : debug_info TacStore.field = TacStore.field ()
let f_trace : ltac_trace TacStore.field = TacStore.field ()
let f_loc : Loc.t TacStore.field = TacStore.field ()
(* Signature for interpretation: val_interp and interpretation functions *)
type interp_sign = Geninterp.interp_sign =
{ lfun : value Id.Map.t
; poly : bool
; extra : TacStore.t }
let add_extra_trace trace extra = TacStore.set extra f_trace trace
let extract_trace ist =
if is_traced () then match TacStore.get ist.extra f_trace with
| None -> [],[]
| Some trace -> trace
else [],[]
let add_extra_loc loc extra =
match loc with
| None -> extra
| Some loc -> TacStore.set extra f_loc loc
let extract_loc ist = TacStore.get ist.extra f_loc
let ensure_loc loc ist =
match loc with
| None -> ist
| Some loc ->
match extract_loc ist with
| None -> { ist with extra = TacStore.set ist.extra f_loc loc }
| Some _ -> ist
let print_top_val env v = Pptactic.pr_value Pptactic.ltop v
let catching_error call_trace fail (e, info) =
let inner_trace =
Option.default [] (Exninfo.get info ltac_trace_info)
in
if List.is_empty call_trace && List.is_empty inner_trace then fail (e, info)
else begin
assert (CErrors.noncritical e); (* preserved invariant *)
let inner_trace = List.filter (fun i -> not (List.memq i call_trace)) inner_trace in
let new_trace = inner_trace @ call_trace in
let located_exc = (e, Exninfo.add info ltac_trace_info new_trace) in
fail located_exc
end
let update_loc loc (e, info as e') =
let eloc = Loc.get_loc info in
if Loc.finer eloc (Some loc) then e'
else (* eloc missing or refers to inside of Ltac function *)
(e, Loc.add_loc info loc)
let catch_error_with_trace_loc loc call_trace f x =
try f x
with e when CErrors.noncritical e ->
let e = Exninfo.capture e in
let e = Option.cata (fun loc -> update_loc loc e) e loc in
catching_error call_trace Exninfo.iraise e
let catch_error_loc loc tac =
match loc with
| None -> tac
| Some loc ->
Proofview.tclORELSE tac (fun exn ->
let (e, info) = update_loc loc exn in
Proofview.tclZERO ~info e)
let wrap_error tac k =
if is_traced () then Proofview.tclORELSE tac k else tac
let wrap_error_loc loc tac k =
if is_traced () then
let k = match loc with
| None -> k
| Some loc -> fun e -> k (update_loc loc e)
in
Proofview.tclORELSE tac k
else catch_error_loc loc tac
let catch_error_tac call_trace tac =
wrap_error
tac
(catching_error call_trace (fun (e, info) -> Proofview.tclZERO ~info e))
let catch_error_tac_loc loc call_trace tac =
wrap_error_loc loc
tac
(catching_error call_trace (fun (e, info) -> Proofview.tclZERO ~info e))
let curr_debug ist = match TacStore.get ist.extra f_debug with
| None -> DebugOff
| Some level -> level
let pr_closure env ist body =
let pp_body = Pptactic.pr_glob_tactic env body in
let pr_sep () = fnl () in
let pr_iarg (id, arg) =
let arg = pr_argument_type arg in
hov 0 (Id.print id ++ spc () ++ str ":" ++ spc () ++ arg)
in
let pp_iargs = v 0 (prlist_with_sep pr_sep pr_iarg (Id.Map.bindings ist)) in
pp_body ++ fnl() ++ str "in environment " ++ fnl() ++ pp_iargs
let pr_inspect env expr result =
let pp_expr = Pptactic.pr_glob_tactic env expr in
let pp_result =
if has_type result (topwit wit_tacvalue) then
match to_tacvalue result with
| VFun (_, _, _, ist, ul, b) ->
let body = if List.is_empty ul then b else CAst.make (TacFun (ul, b)) in
str "a closure with body " ++ fnl() ++ pr_closure env ist body
| VRec (ist, body) ->
str "a recursive closure" ++ fnl () ++ pr_closure env !ist body
else
let pp_type = pr_argument_type result in
str "an object of type" ++ spc () ++ pp_type
in
pp_expr ++ fnl() ++ str "this is " ++ pp_result
(* Transforms an id into a constr if possible, or fails with Not_found *)
let constr_of_id env id =
EConstr.mkVar (let _ = Environ.lookup_named id env in id)
(** Generic arguments : table of interpretation functions *)
let push_trace call ist =
if is_traced () then match TacStore.get ist.extra f_trace with
| None -> [call], [ist.lfun]
| Some (trace, varmaps) -> call :: trace, ist.lfun :: varmaps
else [],[]
let propagate_trace ist loc id v =
if has_type v (topwit wit_tacvalue) then
let tacv = to_tacvalue v in
match tacv with
| VFun (appl,_,_,lfun,it,b) ->
let kn =
match appl with
| GlbAppl ((kn, _) :: _) -> Some kn
| _ -> None
in
let t = if List.is_empty it then b else CAst.make (TacFun (it,b)) in
let trace = push_trace(loc,LtacVarCall (kn,id,t)) ist in
let ans = VFun (appl,trace,loc,lfun,it,b) in
Proofview.tclUNIT (of_tacvalue ans)
| _ -> Proofview.tclUNIT v
else Proofview.tclUNIT v
let append_trace trace v =
if has_type v (topwit wit_tacvalue) then
match to_tacvalue v with
| VFun (appl,trace',loc,lfun,it,b) -> of_tacvalue (VFun (appl,trace',loc,lfun,it,b))
| _ -> v
else v
(* Dynamically check that an argument is a tactic *)
let coerce_to_tactic loc id v =
let fail () = user_err ?loc
(str "Variable " ++ Id.print id ++ str " should be bound to a tactic.")
in
if has_type v (topwit wit_tacvalue) then
let tacv = to_tacvalue v in
match tacv with
| VFun (appl,trace,_,lfun,it,b) -> of_tacvalue (VFun (appl,trace,loc,lfun,it,b))
| _ -> fail ()
else fail ()
let intro_pattern_of_ident id = CAst.make @@ IntroNaming (IntroIdentifier id)
let value_of_ident id =
in_gen (topwit wit_intro_pattern) (intro_pattern_of_ident id)
let (+++) lfun1 lfun2 = Id.Map.fold Id.Map.add lfun1 lfun2
let extend_values_with_bindings (ln,lm) lfun =
let of_cub c = match c with
| [], c -> Value.of_constr c
| _ -> in_gen (topwit wit_constr_under_binders) c
in
(* For compatibility, bound variables are visible only if no other
binding of the same name exists *)
let accu = Id.Map.map value_of_ident ln in
let accu = lfun +++ accu in
Id.Map.fold (fun id c accu -> Id.Map.add id (of_cub c) accu) lm accu
(***************************************************************************)
(* Evaluation/interpretation *)
let is_variable env id =
Id.List.mem id (ids_of_named_context (Environ.named_context env))
let debugging_step ist pp =
match curr_debug ist with
| DebugOn lev -> Tactic_debug.defer_output
(fun _ -> (str "Level " ++ int lev ++ str": " ++ pp () ++ fnl()))
| _ -> Proofview.NonLogical.return ()
let debugging_exception_step ist signal_anomaly e pp =
let explain_exc =
if signal_anomaly then explain_logic_error
else explain_logic_error_no_anomaly in
debugging_step ist (fun () ->
pp() ++ spc() ++ str "raised the exception" ++ fnl() ++ explain_exc e)
let ensure_freshness env =
(* We anonymize declarations which we know will not be used *)
(* This assumes that the original context had no rels *)
process_rel_context
(fun d e -> EConstr.push_rel (Context.Rel.Declaration.set_name Anonymous d) e) env
(* Raise Not_found if not in interpretation sign *)
let try_interp_ltac_var coerce ist env {loc;v=id} =
let v = Id.Map.find id ist.lfun in
try coerce v with CannotCoerceTo s ->
Taccoerce.error_ltac_variable ?loc id env v s
let interp_ltac_var coerce ist env locid =
try try_interp_ltac_var coerce ist env locid
with Not_found -> anomaly (str "Detected '" ++ Id.print locid.v ++ str "' as ltac var at interning time.")
let interp_ident ist env sigma id =
try try_interp_ltac_var (coerce_var_to_ident false env sigma) ist (Some (env,sigma)) (CAst.make id)
with Not_found -> id
(* Interprets an optional identifier, bound or fresh *)
let interp_name ist env sigma = function
| Anonymous -> Anonymous
| Name id -> Name (interp_ident ist env sigma id)
let interp_intro_pattern_var loc ist env sigma id =
try try_interp_ltac_var (coerce_to_intro_pattern sigma) ist (Some (env,sigma)) (CAst.make ?loc id)
with Not_found -> IntroNaming (IntroIdentifier id)
let interp_intro_pattern_naming_var loc ist env sigma id =
try try_interp_ltac_var (coerce_to_intro_pattern_naming sigma) ist (Some (env,sigma)) (CAst.make ?loc id)
with Not_found -> IntroIdentifier id
let interp_int ist ({loc;v=id} as locid) =
try try_interp_ltac_var coerce_to_int ist None locid
with Not_found ->
user_err ?loc
(str "Unbound variable " ++ Id.print id ++ str".")
let interp_int_or_var ist = function
| ArgVar locid -> interp_int ist locid
| ArgArg n -> n
let interp_int_or_var_as_list ist = function
| ArgVar ({v=id} as locid) ->
(try coerce_to_int_or_var_list (Id.Map.find id ist.lfun)
with Not_found | CannotCoerceTo _ -> [ArgArg (interp_int ist locid)])
| ArgArg n as x -> [x]
let interp_int_or_var_list ist l =
List.flatten (List.map (interp_int_or_var_as_list ist) l)
(* Interprets a bound variable (especially an existing hypothesis) *)
let interp_hyp ist env sigma ({loc;v=id} as locid) =
(* Look first in lfun for a value coercible to a variable *)
try try_interp_ltac_var (coerce_to_hyp env sigma) ist (Some (env,sigma)) locid
with Not_found ->
(* Then look if bound in the proof context at calling time *)
if is_variable env id then id
else Loc.raise ?loc (Logic.RefinerError (env, sigma, Logic.NoSuchHyp id))
let interp_hyp_list_as_list ist env sigma ({loc;v=id} as x) =
try coerce_to_hyp_list env sigma (Id.Map.find id ist.lfun)
with Not_found | CannotCoerceTo _ -> [interp_hyp ist env sigma x]
let interp_hyp_list ist env sigma l =
List.flatten (List.map (interp_hyp_list_as_list ist env sigma) l)
let interp_reference ist env sigma = function
| ArgArg (_,r) -> r
| ArgVar {loc;v=id} ->
try try_interp_ltac_var (coerce_to_reference sigma) ist (Some (env,sigma)) (CAst.make ?loc id)
with Not_found ->
try
GlobRef.VarRef (get_id (Environ.lookup_named id env))
with Not_found as exn ->
let _, info = Exninfo.capture exn in
Nametab.error_global_not_found ~info (qualid_of_ident ?loc id)
let try_interp_evaluable env (loc, id) =
let v = Environ.lookup_named id env in
match v with
| LocalDef _ -> EvalVarRef id
| _ -> error_not_evaluable (GlobRef.VarRef id)
let interp_evaluable ist env sigma = function
| ArgArg (r,Some {loc;v=id}) ->
(* Maybe [id] has been introduced by Intro-like tactics *)
begin
try try_interp_evaluable env (loc, id)
with Not_found as exn ->
match r with
| EvalConstRef _ -> r
| _ ->
let _, info = Exninfo.capture exn in
Nametab.error_global_not_found ~info (qualid_of_ident ?loc id)
end
| ArgArg (r,None) -> r
| ArgVar {loc;v=id} ->
try try_interp_ltac_var (coerce_to_evaluable_ref env sigma) ist (Some (env,sigma)) (CAst.make ?loc id)
with Not_found ->
try try_interp_evaluable env (loc, id)
with Not_found as exn ->
let _, info = Exninfo.capture exn in
Nametab.error_global_not_found ~info (qualid_of_ident ?loc id)
(* Interprets an hypothesis name *)
let interp_occurrences ist occs =
Locusops.occurrences_map (interp_int_or_var_list ist) occs
let interp_hyp_location ist env sigma ((occs,id),hl) =
((interp_occurrences ist occs,interp_hyp ist env sigma id),hl)
let interp_hyp_location_list_as_list ist env sigma ((occs,id),hl as x) =
match occs,hl with
| AllOccurrences,InHyp ->
List.map (fun id -> ((AllOccurrences,id),InHyp))
(interp_hyp_list_as_list ist env sigma id)
| _,_ -> [interp_hyp_location ist env sigma x]
let interp_hyp_location_list ist env sigma l =
List.flatten (List.map (interp_hyp_location_list_as_list ist env sigma) l)
let interp_clause ist env sigma { onhyps=ol; concl_occs=occs } : clause =
{ onhyps=Option.map (interp_hyp_location_list ist env sigma) ol;
concl_occs=interp_occurrences ist occs }
(* Interpretation of constructions *)
(* Extract the constr list from lfun *)
let extract_ltac_constr_values ist env =
let fold id v accu =
try
let c = coerce_to_constr env v in
Id.Map.add id c accu
with CannotCoerceTo _ -> accu
in
Id.Map.fold fold ist.lfun Id.Map.empty
(** ppedrot: I have changed the semantics here. Before this patch, closure was
implemented as a list and a variable could be bound several times with
different types, resulting in its possible appearance on both sides. This
could barely be defined as a feature... *)
(* Extract the identifier list from lfun: join all branches (what to do else?)*)
let rec intropattern_ids accu {loc;v=pat} = match pat with
| IntroNaming (IntroIdentifier id) -> Id.Set.add id accu
| IntroAction (IntroOrAndPattern (IntroAndPattern l)) ->
List.fold_left intropattern_ids accu l
| IntroAction (IntroOrAndPattern (IntroOrPattern ll)) ->
List.fold_left intropattern_ids accu (List.flatten ll)
| IntroAction (IntroInjection l) ->
List.fold_left intropattern_ids accu l
| IntroAction (IntroApplyOn ({v=c},pat)) -> intropattern_ids accu pat
| IntroNaming (IntroAnonymous | IntroFresh _)
| IntroAction (IntroWildcard | IntroRewrite _)
| IntroForthcoming _ -> accu
let extract_ids ids lfun accu =
let fold id v accu =
if has_type v (topwit wit_intro_pattern) then
let {v=ipat} = out_gen (topwit wit_intro_pattern) v in
if Id.List.mem id ids then accu
else intropattern_ids accu (CAst.make ipat)
else accu
in
Id.Map.fold fold lfun accu
let default_fresh_id = Id.of_string "H"
let interp_fresh_id ist env sigma l =
let extract_ident ist env sigma id =
try try_interp_ltac_var (coerce_to_ident_not_fresh sigma)
ist (Some (env,sigma)) (CAst.make id)
with Not_found -> id in
let ids = List.map_filter (function ArgVar {v=id} -> Some id | _ -> None) l in
let avoid = match TacStore.get ist.extra f_avoid_ids with
| None -> Id.Set.empty
| Some l -> l
in
let avoid = extract_ids ids ist.lfun avoid in
let id =
if List.is_empty l then default_fresh_id
else
let s =
String.concat "" (List.map (function
| ArgArg s -> s
| ArgVar {v=id} -> Id.to_string (extract_ident ist env sigma id)) l) in
let s = if CLexer.is_keyword (Pcoq.get_keyword_state()) s then s^"0" else s in
Id.of_string s in
Tactics.fresh_id_in_env avoid id env
(* Extract the uconstr list from lfun *)
let extract_ltac_constr_context ist env sigma =
let add_uconstr id v map =
try Id.Map.add id (coerce_to_uconstr v) map
with CannotCoerceTo _ -> map
in
let add_constr id v map =
try Id.Map.add id (coerce_to_constr env v) map
with CannotCoerceTo _ -> map
in
let add_ident id v map =
try Id.Map.add id (coerce_var_to_ident false env sigma v) map
with CannotCoerceTo _ -> map
in
let fold id v {idents;typed;untyped;genargs} =
let idents = add_ident id v idents in
let typed = add_constr id v typed in
let untyped = add_uconstr id v untyped in
{ idents ; typed ; untyped; genargs }
in
let empty = { idents = Id.Map.empty ;typed = Id.Map.empty ; untyped = Id.Map.empty; genargs = ist.lfun } in
Id.Map.fold fold ist.lfun empty
(** Significantly simpler than [interp_constr], to interpret an
untyped constr, it suffices to adjoin a closure environment. *)
let interp_glob_closure ist env sigma ?(kind=WithoutTypeConstraint) ?(pattern_mode=false) (term,term_expr_opt) =
let closure = extract_ltac_constr_context ist env sigma in
match term_expr_opt with
| None -> { closure ; term }
| Some term_expr ->
(* If at toplevel (term_expr_opt<>None), the error can be due to
an incorrect context at globalization time: we retype with the
now known intros/lettac/inversion hypothesis names *)
let constr_context =
Id.Set.union
(Id.Map.domain closure.typed)
(Id.Map.domain closure.untyped)
in
let ltacvars = {
ltac_vars = constr_context;
ltac_bound = Id.Map.domain ist.lfun;
ltac_extra = Genintern.Store.empty;
} in
{ closure ; term = intern_gen kind ~strict_check:false ~pattern_mode ~ltacvars env sigma term_expr }
let interp_uconstr ist env sigma c = interp_glob_closure ist env sigma c
let interp_gen kind ist pattern_mode flags env sigma c =
let kind_for_intern = match kind with OfType _ -> WithoutTypeConstraint | _ -> kind in
let { closure = constrvars ; term } =
interp_glob_closure ist env sigma ~kind:kind_for_intern ~pattern_mode c in
let vars = {
ltac_constrs = constrvars.typed;
ltac_uconstrs = constrvars.untyped;
ltac_idents = constrvars.idents;
ltac_genargs = ist.lfun;
} in
let loc = loc_of_glob_constr term in
let trace = push_trace (loc,LtacConstrInterp (env,sigma,term,vars)) ist in
let (stack, _) = trace in
(* save and restore the current trace info because the called routine later starts
with an empty trace *)
Tactic_debug.push_chunk trace;
try
let (evd,c) =
catch_error_with_trace_loc loc stack (understand_ltac flags env sigma vars kind) term
in
(* spiwack: to avoid unnecessary modifications of tacinterp, as this
function already use effect, I call [run] hoping it doesn't mess
up with any assumption. *)
Proofview.NonLogical.run (db_constr (curr_debug ist) env evd c);
Tactic_debug.pop_chunk ();
(evd,c)
with reraise ->
let reraise = Exninfo.capture reraise in
Tactic_debug.pop_chunk ();
Exninfo.iraise reraise
let constr_flags () = {
use_coercions = true;
use_typeclasses = UseTC;
solve_unification_constraints = true;
fail_evar = true;
expand_evars = true;
program_mode = false;
polymorphic = false;
}
(* Interprets a constr; expects evars to be solved *)
let interp_constr_gen kind ist env sigma c =
let flags = { (constr_flags ()) with polymorphic = ist.Geninterp.poly } in
interp_gen kind ist false flags env sigma c
let interp_constr = interp_constr_gen WithoutTypeConstraint
let interp_type = interp_constr_gen IsType
let open_constr_use_classes_flags () = {
use_coercions = true;
use_typeclasses = UseTC;
solve_unification_constraints = true;
fail_evar = false;
expand_evars = false;
program_mode = false;
polymorphic = false;
}
let open_constr_no_classes_flags () = {
use_coercions = true;
use_typeclasses = NoUseTC;
solve_unification_constraints = true;
fail_evar = false;
expand_evars = false;
program_mode = false;
polymorphic = false;
}
let pure_open_constr_flags = {
use_coercions = true;
use_typeclasses = NoUseTC;
solve_unification_constraints = true;
fail_evar = false;
expand_evars = false;
program_mode = false;
polymorphic = false;
}
(* Interprets an open constr *)
let interp_open_constr ?(expected_type=WithoutTypeConstraint) ?(flags=open_constr_no_classes_flags ()) ist env sigma c =
interp_gen expected_type ist false flags env sigma c
let interp_open_constr_with_classes ?(expected_type=WithoutTypeConstraint) ist env sigma c =
interp_gen expected_type ist false (open_constr_use_classes_flags ()) env sigma c
let interp_pure_open_constr ist =
interp_gen WithoutTypeConstraint ist false pure_open_constr_flags
let interp_typed_pattern ist env sigma (_,c,_) =
let sigma, c =
interp_gen WithoutTypeConstraint ist true pure_open_constr_flags env sigma c in
(* FIXME: it is necessary to be unsafe here because of the way we handle
evars in the pretyper. Sometimes they get solved eagerly. *)
legacy_bad_pattern_of_constr env sigma c
(* Interprets a constr expression *)
let interp_constr_in_compound_list inj_fun dest_fun interp_fun ist env sigma l =
let try_expand_ltac_var sigma x =
try match DAst.get (fst (dest_fun x)) with
| GVar id ->
let v = Id.Map.find id ist.lfun in
sigma, List.map inj_fun (coerce_to_constr_list env v)
| _ ->
raise Not_found
with CannotCoerceTo _ | Not_found ->
(* dest_fun, List.assoc may raise Not_found *)
let sigma, c = interp_fun ist env sigma x in
sigma, [c] in
let sigma, l = List.fold_left_map try_expand_ltac_var sigma l in
sigma, List.flatten l
let interp_constr_list ist env sigma c =
interp_constr_in_compound_list (fun x -> x) (fun x -> x) interp_constr ist env sigma c
let interp_open_constr_list =
interp_constr_in_compound_list (fun x -> x) (fun x -> x) interp_open_constr
(* Interprets a reduction expression *)
let interp_unfold ist env sigma (occs,qid) =
(interp_occurrences ist occs,interp_evaluable ist env sigma qid)
let interp_flag ist env sigma red =
{ red with rConst = List.map (interp_evaluable ist env sigma) red.rConst }
let interp_constr_with_occurrences ist env sigma (occs,c) =
let (sigma,c_interp) = interp_constr ist env sigma c in
sigma , (interp_occurrences ist occs, c_interp)
let interp_closed_typed_pattern_with_occurrences ist env sigma (occs, a) =
let p = match a with
| Inl (ArgVar {loc;v=id}) ->
(* This is the encoding of an ltac var supposed to be bound
prioritary to an evaluable reference and otherwise to a constr
(it is an encoding to satisfy the "union" type given to Simpl) *)
let coerce_eval_ref_or_constr x =
try Inl (coerce_to_evaluable_ref env sigma x)
with CannotCoerceTo _ ->
let c = coerce_to_closed_constr env x in
Inr (legacy_bad_pattern_of_constr env sigma c) in
(try try_interp_ltac_var coerce_eval_ref_or_constr ist (Some (env,sigma)) (CAst.make ?loc id)
with Not_found as exn ->
let _, info = Exninfo.capture exn in
Nametab.error_global_not_found ~info (qualid_of_ident ?loc id))
| Inl (ArgArg _ as b) -> Inl (interp_evaluable ist env sigma b)
| Inr c -> Inr (interp_typed_pattern ist env sigma c) in
interp_occurrences ist occs, p
let interp_constr_with_occurrences_and_name_as_list =
interp_constr_in_compound_list
(fun c -> ((AllOccurrences,c),Anonymous))
(function ((occs,c),Anonymous) when occs == AllOccurrences -> c
| _ -> raise Not_found)
(fun ist env sigma (occ_c,na) ->
let (sigma,c_interp) = interp_constr_with_occurrences ist env sigma occ_c in
sigma, (c_interp,
interp_name ist env sigma na))
let interp_red_expr ist env sigma = function
| Unfold l -> sigma , Unfold (List.map (interp_unfold ist env sigma) l)
| Fold l ->
let (sigma,l_interp) = interp_constr_list ist env sigma l in
sigma , Fold l_interp
| Cbv f -> sigma , Cbv (interp_flag ist env sigma f)
| Cbn f -> sigma , Cbn (interp_flag ist env sigma f)
| Lazy f -> sigma , Lazy (interp_flag ist env sigma f)
| Pattern l ->
let (sigma,l_interp) =
Evd.MonadR.List.map_right
(fun c sigma -> interp_constr_with_occurrences ist env sigma c) l sigma
in
sigma , Pattern l_interp
| Simpl (f,o) ->
sigma , Simpl (interp_flag ist env sigma f,
Option.map (interp_closed_typed_pattern_with_occurrences ist env sigma) o)
| CbvVm o ->
sigma , CbvVm (Option.map (interp_closed_typed_pattern_with_occurrences ist env sigma) o)
| CbvNative o ->
sigma , CbvNative (Option.map (interp_closed_typed_pattern_with_occurrences ist env sigma) o)
| (Red _ | Hnf | ExtraRedExpr _ as r) -> sigma , r
let interp_may_eval f ist env sigma = function
| ConstrEval (r,c) ->
let (sigma,redexp) = interp_red_expr ist env sigma r in
let (sigma,c_interp) = f ist env sigma c in
let (redfun, _) = Redexpr.reduction_of_red_expr env redexp in
redfun env sigma c_interp
| ConstrContext ({loc;v=s},c) ->
let (sigma,ic) = f ist env sigma c in
let ctxt =
try try_interp_ltac_var coerce_to_constr_context ist (Some (env, sigma)) (CAst.make ?loc s)
with Not_found ->
user_err ?loc (str "Unbound context identifier" ++ Id.print s ++ str".")
in
let c = Constr_matching.instantiate_context ctxt ic in
Typing.solve_evars env sigma c
| ConstrTypeOf c ->
let (sigma,c_interp) = f ist env sigma c in
let (sigma, t) = Typing.type_of ~refresh:true env sigma c_interp in
(sigma, t)
| ConstrTerm c ->
try
f ist env sigma c
with reraise ->
let reraise = Exninfo.capture reraise in
(* spiwack: to avoid unnecessary modifications of tacinterp, as this
function already use effect, I call [run] hoping it doesn't mess
up with any assumption. *)
Proofview.NonLogical.run (debugging_exception_step ist false (fst reraise) (fun () ->
str"interpretation of term " ++ pr_glob_constr_env env sigma (fst c)));
Exninfo.iraise reraise
(* Interprets a constr expression possibly to first evaluate *)
let interp_constr_may_eval ist env sigma c =
let (sigma,csr) =
try
interp_may_eval interp_constr ist env sigma c
with reraise ->
let reraise = Exninfo.capture reraise in
(* spiwack: to avoid unnecessary modifications of tacinterp, as this
function already use effect, I call [run] hoping it doesn't mess
up with any assumption. *)
Proofview.NonLogical.run (debugging_exception_step ist false (fst reraise) (fun () -> str"evaluation of term"));
Exninfo.iraise reraise
in
begin
(* spiwack: to avoid unnecessary modifications of tacinterp, as this
function already use effect, I call [run] hoping it doesn't mess
up with any assumption. *)
Proofview.NonLogical.run (db_constr (curr_debug ist) env sigma csr);
sigma , csr
end
(** TODO: should use dedicated printers *)
let message_of_value v =
let pr_with_env pr =
Ftactic.enter begin fun gl -> Ftactic.return (pr (pf_env gl) (project gl)) end in
let open Genprint in
match generic_val_print v with
| TopPrinterBasic pr -> Ftactic.return (pr ())
| TopPrinterNeedsContext pr -> pr_with_env pr
| TopPrinterNeedsContextAndLevel { default_ensure_surrounded; printer } ->
pr_with_env (fun env sigma -> printer env sigma default_ensure_surrounded)
let interp_message_token ist = function
| MsgString s -> Ftactic.return (str s)
| MsgInt n -> Ftactic.return (int n)
| MsgIdent {loc;v=id} ->
let v = try Some (Id.Map.find id ist.lfun) with Not_found -> None in
match v with
| None -> Ftactic.lift (
let info = Exninfo.reify () in
Tacticals.tclZEROMSG ~info (Id.print id ++ str" not found."))
| Some v -> message_of_value v
let interp_message ist l =
let open Ftactic in
Ftactic.List.map (interp_message_token ist) l >>= fun l ->
Ftactic.return (prlist_with_sep spc (fun x -> x) l)
let rec interp_intro_pattern ist env sigma = with_loc_val (fun ?loc -> function
| IntroAction pat ->
let pat = interp_intro_pattern_action ist env sigma pat in
CAst.make ?loc @@ IntroAction pat
| IntroNaming (IntroIdentifier id) ->
CAst.make ?loc @@ interp_intro_pattern_var loc ist env sigma id
| IntroNaming pat ->
CAst.make ?loc @@ IntroNaming (interp_intro_pattern_naming loc ist env sigma pat)
| IntroForthcoming _ as x -> CAst.make ?loc x)
and interp_intro_pattern_naming loc ist env sigma = function
| IntroFresh id -> IntroFresh (interp_ident ist env sigma id)
| IntroIdentifier id -> interp_intro_pattern_naming_var loc ist env sigma id
| IntroAnonymous as x -> x
and interp_intro_pattern_action ist env sigma = function
| IntroOrAndPattern l ->
let l = interp_or_and_intro_pattern ist env sigma l in
IntroOrAndPattern l
| IntroInjection l ->
let l = interp_intro_pattern_list_as_list ist env sigma l in
IntroInjection l
| IntroApplyOn ({loc;v=c},ipat) ->
let c env sigma = interp_open_constr ist env sigma c in
let ipat = interp_intro_pattern ist env sigma ipat in
IntroApplyOn (CAst.make ?loc c,ipat)
| IntroWildcard | IntroRewrite _ as x -> x
and interp_or_and_intro_pattern ist env sigma = function
| IntroAndPattern l ->
let l = List.map (interp_intro_pattern ist env sigma) l in
IntroAndPattern l
| IntroOrPattern ll ->
let ll = List.map (interp_intro_pattern_list_as_list ist env sigma) ll in
IntroOrPattern ll
and interp_intro_pattern_list_as_list ist env sigma = function
| [{loc;v=IntroNaming (IntroIdentifier id)}] as l ->
(try coerce_to_intro_pattern_list ?loc sigma (Id.Map.find id ist.lfun)
with Not_found | CannotCoerceTo _ ->
List.map (interp_intro_pattern ist env sigma) l)
| l -> List.map (interp_intro_pattern ist env sigma) l
let interp_intro_pattern_naming_option ist env sigma = function
| None -> None
| Some lpat -> Some (map_with_loc (fun ?loc pat -> interp_intro_pattern_naming loc ist env sigma pat) lpat)
let interp_or_and_intro_pattern_option ist env sigma = function
| None -> None
| Some (ArgVar {loc;v=id}) ->
(match interp_intro_pattern_var loc ist env sigma id with
| IntroAction (IntroOrAndPattern l) -> Some (CAst.make ?loc l)
| _ ->
user_err ?loc (str "Cannot coerce to a disjunctive/conjunctive pattern."))
| Some (ArgArg {loc;v=l}) ->
let l = interp_or_and_intro_pattern ist env sigma l in
Some (CAst.make ?loc l)
let interp_intro_pattern_option ist env sigma = function
| None -> None
| Some ipat ->
let ipat = interp_intro_pattern ist env sigma ipat in
Some ipat
let interp_in_hyp_as ist env sigma (id,ipat) =
let ipat = interp_intro_pattern_option ist env sigma ipat in
(interp_hyp ist env sigma id,ipat)
let interp_binding_name ist env sigma = function
| AnonHyp n -> AnonHyp n
| NamedHyp id ->
(* If a name is bound, it has to be a quantified hypothesis *)
(* user has to use other names for variables if these ones clash with *)
(* a name intended to be used as a (non-variable) identifier *)
try try_interp_ltac_var (coerce_to_quantified_hypothesis sigma) ist (Some (env,sigma)) id
with Not_found -> NamedHyp id
let interp_declared_or_quantified_hypothesis ist env sigma = function
| AnonHyp n -> AnonHyp n
| NamedHyp id ->
try try_interp_ltac_var
(coerce_to_decl_or_quant_hyp sigma) ist (Some (env,sigma)) id
with Not_found -> NamedHyp id
let interp_binding ist env sigma {loc;v=(b,c)} =
let sigma, c = interp_open_constr ist env sigma c in
sigma, (CAst.make ?loc (interp_binding_name ist env sigma b,c))
let interp_bindings ist env sigma = function
| NoBindings ->
sigma, NoBindings
| ImplicitBindings l ->
let sigma, l = interp_open_constr_list ist env sigma l in
sigma, ImplicitBindings l
| ExplicitBindings l ->
let sigma, l = List.fold_left_map (interp_binding ist env) sigma l in
sigma, ExplicitBindings l
let interp_constr_with_bindings ist env sigma (c,bl) =
let sigma, bl = interp_bindings ist env sigma bl in
let sigma, c = interp_constr ist env sigma c in
sigma, (c,bl)
let interp_open_constr_with_bindings ist env sigma (c,bl) =
let sigma, bl = interp_bindings ist env sigma bl in
let sigma, c = interp_open_constr ist env sigma c in
sigma, (c, bl)
let loc_of_bindings = function
| NoBindings -> None
| ImplicitBindings l -> loc_of_glob_constr (fst (List.last l))
| ExplicitBindings l -> (List.last l).loc
let interp_open_constr_with_bindings_loc ist ((c,_),bl as cb) =
let loc1 = loc_of_glob_constr c in
let loc2 = loc_of_bindings bl in
let loc = Loc.merge_opt loc1 loc2 in
let f env sigma = interp_open_constr_with_bindings ist env sigma cb in
(loc,f)
let interp_destruction_arg ist gl arg =
match arg with
| keep,ElimOnConstr c ->
keep,ElimOnConstr begin fun env sigma ->
interp_open_constr_with_bindings ist env sigma c
end
| keep,ElimOnAnonHyp n as x -> x
| keep,ElimOnIdent {loc;v=id} ->
let error () = user_err ?loc
(strbrk "Cannot coerce " ++ Id.print id ++
strbrk " neither to a quantified hypothesis nor to a term.")
in
let try_cast_id id' =
if Tactics.is_quantified_hypothesis id' gl
then keep,ElimOnIdent (CAst.make ?loc id')
else
(keep, ElimOnConstr begin fun env sigma ->
try (sigma, (constr_of_id env id', NoBindings))
with Not_found ->
user_err ?loc (
Id.print id ++ strbrk " binds to " ++ Id.print id' ++ strbrk " which is neither a declared nor a quantified hypothesis.")
end)
in
try
(* FIXME: should be moved to taccoerce *)
let v = Id.Map.find id ist.lfun in
if has_type v (topwit wit_intro_pattern) then
let v = out_gen (topwit wit_intro_pattern) v in
match v with
| {v=IntroNaming (IntroIdentifier id)} -> try_cast_id id
| _ -> error ()
else if has_type v (topwit wit_hyp) then
let id = out_gen (topwit wit_hyp) v in
try_cast_id id
else if has_type v (topwit wit_int) then
keep,ElimOnAnonHyp (out_gen (topwit wit_int) v)
else match Value.to_constr v with
| None -> error ()
| Some c -> keep,ElimOnConstr (fun env sigma -> (sigma, (c,NoBindings)))
with Not_found ->