This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 299
/
core.lean
2322 lines (1993 loc) · 90 KB
/
core.lean
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
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import logic.function.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.binder_matching
import tactic.lean_core_docs
import tactic.interactive_expr
import system.io
universe variable u
attribute [derive [has_reflect, decidable_eq]] tactic.transparency
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`
with `new`. The occurrences of `old` in `e` are determined using keyed matching
with transparency `md`; see `kabstract` for details. If `unify` is true,
we may assign metavariables in `e` as we match subterms of `e` against `old`. -/
meta def kreplace (e old new : expr) (md := semireducible) (unify := tt)
: tactic expr := do
e ← kabstract e old md unify,
pure $ e.instantiate_var new
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
/-- Format a list as a comma separated list, without any brackets. -/
meta def comma_separated {α : Type*} [has_to_format α] : list α → format
| [] := nil
| xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt)
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format :=
bracket "[" "]" (comma_separated l)
end format
namespace tactic
open function
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of `type`. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of `fn`'s type. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
private meta def get_app_fn_args_whnf_aux (md : transparency)
(unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) :=
λ args e, do
e ← whnf e md unfold_ginductive,
match e with
| (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t
| _ := pure (e, args)
end
/--
For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e`
is normalised as necessary; for example:
```
get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])
```
The returned expression is in whnf, but the arguments are generally not.
-/
meta def get_app_fn_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (expr × list expr) :=
get_app_fn_args_whnf_aux md unfold_ginductive [] e
/--
`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is
normalised as necessary (with transparency `md`). `unfold_ginductive` controls
whether constructors of generalised inductive types are unfolded. The returned
expression is in whnf.
-/
meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr
| e md unfold_ginductive := do
e ← whnf e md unfold_ginductive,
match e with
| (expr.app f _) := get_app_fn_whnf f md unfold_ginductive
| _ := pure e
end
/--
`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`,
where `C` is a constant, after normalisation with transparency `md`. If so, the
name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded.
-/
meta def get_app_fn_const_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic name := do
f ← get_app_fn_whnf e md unfold_ginductive,
match f with
| (expr.const n _) := pure n
| _ := fail format!
"expected a constant (possibly applied to some arguments), but got:\n{e}"
end
/--
`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`
is normalised as necessary (with transparency `md`). `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded. The
returned expressions are not necessarily in whnf.
-/
meta def get_app_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (list expr) :=
prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks
whether `decl_name` exists and has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- `get_decls_from` returns a dictionary mapping names to their
corresponding declarations. Covers all declarations the files listed
in `fs`, with the current file listed as `none`.
The path of the file names is expected to be relative to
the root of the project (i.e. the location of `leanpkg.toml` when it
is present); e.g. `"src/tactic/core.lean"`
Possible issue: `get_decls_from` uses `get_cwd`, the current working
directory, which may not always point at the root of the project.
It would work better if it searched for the root directory or,
better yet, if Lean exposed its path information.
-/
meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=
do root ← unsafe_run_io $ io.env.get_cwd,
let fs := fs.map (option.map $ λ path, root ++ "/" ++ path),
err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists,
guard (err = []) <|> fail format!"File not found: {err}",
e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s,
let source := e.decl_olean d.to_name in
if source ∈ fs ∧ (source = none → e.in_current_file d.to_name)
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/--
Update the type of a local constant or metavariable. For local constants and
metavariables obtained via, for example, `tactic.get_local`, the type stored in
the expression is not necessarily the same as the type returned by `infer_type`.
This tactic, given a local constant or metavariable, updates the stored type to
match the output of `infer_type`. If the input is not a local constant or
metavariable, `update_type` does nothing.
-/
meta def update_type : expr → tactic expr
| e@(expr.local_const ppname uname binfo _) :=
expr.local_const ppname uname binfo <$> infer_type e
| e@(expr.mvar ppname uname _) :=
expr.mvar ppname uname <$> infer_type e
| e := pure e
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Runs a tactic for a result, reverting the state after completion or error. -/
meta def retrieve' {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
(λ msg pos s', result.exception msg pos s)
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).
Returns the number of local constants that have been reverted. -/
meta def revert_target_deps : tactic ℕ :=
do tgt ← target,
ctx ← local_context,
l ← ctx.mfilter (kdepends_on tgt),
n ← revert_lst l,
if l = [] then return n
else do m ← revert_target_deps, return (m + n)
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro n) <|> note n none e
/--
`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name
provided by the binder to name the new local constant.
Unlike `intron`, it does not rename introduced constants if the names shadow existing constants.
-/
meta def intron_no_renames : ℕ → tactic unit
| 0 := pure ()
| (n+1) := do
expr.pi pp_n _ _ _ ← target,
intro pp_n,
intron_no_renames n
/-!
### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`
(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.
whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes
them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition
running up to the first match. -/
private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) :
list α → list α → list (list α)
| [] acc := [acc.reverse]
| (l :: ls) acc :=
if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l]
else partition_local_deps_aux ls (l :: acc)
/-- `partition_local_deps vs`, with `vs` a list of local constants,
reorders `vs` in the order they appear in the local context together
with the variables that follow them. If local context is `[a,b,c,d,e,f]`,
and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.
The head of each list is one of the variables given as a parameter. -/
meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=
do ls ← local_context,
pure (partition_local_deps_aux vs ls []).tail.reverse
/-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ...
changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of
locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type
correctness. This tactic is called `clearbody` in Coq. -/
meta def clear_value (vs : list expr) : tactic unit := do
ls ← partition_local_deps vs,
ls.mmap' $ λ vs, do
{ revert_lst vs,
(expr.elet v t d b) ← target |
fail format!"Cannot clear the body of {vs.head}. It is not a local definition.",
let e := expr.pi v binder_info.default t b,
type_check e <|>
fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.",
g ← mk_meta_var e,
h ← note `h none g,
tactic.exact $ h d,
gs ← get_goals,
set_goals $ g :: gs },
ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name
/--
`context_has_local_def` is true iff there is at least one local definition in
the context.
-/
meta def context_has_local_def : tactic bool := do
ctx ← local_context,
ctx.many (succeeds ∘ local_def_value)
/--
`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the
context up to and including `h` is a local definition.
-/
meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do
ff ← succeeds (local_def_value h) | pure tt,
ctx ← local_context,
let ctx := ctx.take_while (≠ h),
ctx.many (succeeds ∘ local_def_value)
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
c ← match env.constructors_of struct_n with
| [c] := pure c
| [] :=
if env.is_inductive struct_n
then fail format!"{struct_n} does not have constructors"
else fail format!"{struct_n} is not an inductive type"
| _ := fail "too many constructors"
end,
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`.
`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
/--
Finds an instance of an implication `cond → tgt`.
Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention
`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,
since it has been "proven" by a metavariable.
-/
meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do
f ← mk_meta_var cond,
e ← assertv `c cond f, swap,
reset_instance_cache,
inst ← mk_instance tgt,
return (e, inst)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
`apply_list l`, for `l : list (tactic expr)`,
tries to apply the lemmas generated by the tactics in `l` on the first goal, and
fail if none succeeds.
-/
meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit
| [] := fail "no matching rule"
| (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t
/--
Constructs a list of `tactic expr` given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.
We need to return a list of `tactic expr`, rather than just `expr`, because these expressions
will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.
-/
meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr))
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n),
-- We reverse the list of lemmas marked with an attribute,
-- on the assumption that lemmas proved earlier are more often applicable
-- than lemmas proved later. This is a performance optimization.
build_list_expr_for_apply (m.reverse ++ t))
<|> return ((i_to_expr_for_apply h) :: tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit :=
do l ← lock_tactic_state $ build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt extends apply_cfg :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip)
(on_success : expr → tactic unit := (λ _, skip))
(on_failure : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>
(on_failure >> fail "apply_any tactic failed; no lemma could be applied")
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange