-
Notifications
You must be signed in to change notification settings - Fork 81
/
elaborator.cpp
4367 lines (3990 loc) · 181 KB
/
elaborator.cpp
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) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include <utility>
#include "util/flet.h"
#include "util/thread.h"
#include "util/sexpr/option_declarations.h"
#include "kernel/find_fn.h"
#include "kernel/error_msgs.h"
#include "kernel/for_each_fn.h"
#include "kernel/abstract.h"
#include "kernel/replace_fn.h"
#include "kernel/instantiate.h"
#include "kernel/scope_pos_info_provider.h"
#include "kernel/inductive/inductive.h"
#include "library/trace.h"
#include "library/user_recursors.h"
#include "library/aux_recursors.h"
#include "library/app_builder.h"
#include "library/constants.h"
#include "library/placeholder.h"
#include "library/explicit.h"
#include "library/choice.h"
#include "library/string.h"
#include "library/class.h"
#include "library/sorry.h"
#include "library/quote.h"
#include "library/util.h"
#include "library/typed_expr.h"
#include "library/annotation.h"
#include "library/pp_options.h"
#include "library/replace_visitor.h"
#include "library/locals.h"
#include "library/private.h"
#include "library/attribute_manager.h"
#include "library/scoped_ext.h"
#include "library/protected.h"
#include "library/message_builder.h"
#include "library/aliases.h"
#include "library/inverse.h"
#include "library/aux_definition.h"
#include "library/check.h"
#include "library/delayed_abstraction.h"
#include "library/vm/vm_name.h"
#include "library/vm/vm_expr.h"
#include "library/vm/vm_environment.h"
#include "library/vm/vm_exceptional.h"
#include "library/vm/vm_options.h"
#include "library/vm/vm_option.h"
#include "library/vm/vm_list.h"
#include "library/compiler/vm_compiler.h"
#include "library/tactic/kabstract.h"
#include "library/tactic/unfold_tactic.h"
#include "library/tactic/tactic_state.h"
#include "library/tactic/elaborate.h"
#include "library/tactic/tactic_evaluator.h"
#include "library/equations_compiler/compiler.h"
#include "library/equations_compiler/util.h"
#include "library/inductive_compiler/ginductive.h"
#include "frontends/lean/builtin_exprs.h"
#include "frontends/lean/brackets.h"
#include "frontends/lean/definition_cmds.h"
#include "frontends/lean/util.h"
#include "frontends/lean/parser.h"
#include "frontends/lean/prenum.h"
#include "frontends/lean/structure_cmd.h"
#include "frontends/lean/structure_instance.h"
#include "frontends/lean/elaborator.h"
#ifndef LEAN_DEFAULT_ELABORATOR_COERCIONS
#define LEAN_DEFAULT_ELABORATOR_COERCIONS true
#endif
namespace lean {
static name * g_elab_strategy = nullptr;
static name * g_elaborator_coercions = nullptr;
bool get_elaborator_coercions(options const & opts) {
return opts.get_bool(*g_elaborator_coercions, LEAN_DEFAULT_ELABORATOR_COERCIONS);
}
struct elaborator_strategy_attribute_data : public attr_data {
elaborator_strategy m_status;
elaborator_strategy_attribute_data() {}
elaborator_strategy_attribute_data(elaborator_strategy status) : m_status(status) {}
virtual unsigned hash() const override { return static_cast<unsigned>(m_status); }
void write(serializer & s) const { s << static_cast<char>(m_status); }
void read(deserializer & d) {
char c; d >> c;
m_status = static_cast<elaborator_strategy>(c);
}
};
bool operator==(elaborator_strategy_attribute_data const & d1, elaborator_strategy_attribute_data const & d2) {
return d1.m_status == d2.m_status;
}
template class typed_attribute<elaborator_strategy_attribute_data>;
typedef typed_attribute<elaborator_strategy_attribute_data> elaborator_strategy_attribute;
static elaborator_strategy_attribute const & get_elaborator_strategy_attribute() {
return static_cast<elaborator_strategy_attribute const &>(get_system_attribute(*g_elab_strategy));
}
class elaborator_strategy_proxy_attribute : public proxy_attribute<elaborator_strategy_attribute_data> {
typedef proxy_attribute<elaborator_strategy_attribute_data> parent;
public:
elaborator_strategy_proxy_attribute(char const * id, char const * descr, elaborator_strategy status):
parent(id, descr, status) {}
virtual typed_attribute<elaborator_strategy_attribute_data> const & get_attribute() const {
return get_elaborator_strategy_attribute();
}
};
elaborator_strategy get_elaborator_strategy(environment const & env, name const & n) {
if (auto data = get_elaborator_strategy_attribute().get(env, n))
return data->m_status;
if (inductive::is_elim_rule(env, n) ||
is_aux_recursor(env, n) ||
is_user_defined_recursor(env, n)) {
return elaborator_strategy::AsEliminator;
}
return elaborator_strategy::WithExpectedType;
}
#define trace_elab(CODE) lean_trace("elaborator", scope_trace_env _scope(m_env, m_ctx); CODE)
#define trace_elab_detail(CODE) lean_trace("elaborator_detail", scope_trace_env _scope(m_env, m_ctx); CODE)
#define trace_elab_debug(CODE) lean_trace("elaborator_debug", scope_trace_env _scope(m_env, m_ctx); CODE)
elaborator::elaborator(environment const & env, options const & opts, name const & decl_name,
metavar_context const & mctx, local_context const & lctx, bool recover_from_errors,
bool in_pattern, bool in_quote):
m_env(env), m_opts(opts), m_cache(opts), m_decl_name(decl_name),
m_ctx(env, mctx, lctx, m_cache, transparency_mode::Semireducible),
m_recover_from_errors(recover_from_errors),
m_uses_infom(get_global_info_manager() != nullptr), m_in_pattern(in_pattern), m_in_quote(in_quote) {
m_coercions = get_elaborator_coercions(opts);
}
elaborator::elaborator(type_context_old && ctx, options const & opts, name const & decl_name, bool recover_from_errors,
bool in_pattern, bool in_quote):
m_env(ctx.env()), m_opts(opts), m_cache(), m_decl_name(decl_name),
m_ctx(std::move(ctx)),
m_recover_from_errors(recover_from_errors),
m_uses_infom(get_global_info_manager() != nullptr), m_in_pattern(in_pattern), m_in_quote(in_quote) {
m_coercions = get_elaborator_coercions(opts);
}
elaborator::~elaborator() {
try {
if (m_uses_infom && get_global_info_manager() && !in_thread_finalization()) {
m_info.instantiate_mvars(m_ctx.mctx());
get_global_info_manager()->merge(m_info);
}
} catch (...) {}
}
auto elaborator::mk_pp_ctx() -> pp_fn {
return ::lean::mk_pp_ctx(m_ctx.env(), m_opts, m_ctx.mctx(), m_ctx.lctx());
}
formatter elaborator::mk_fmt_ctx() {
return formatter(m_opts, [=](expr const & e, options const & o) {
return ::lean::mk_pp_ctx(m_ctx.env(), o, m_ctx.mctx(), m_ctx.lctx())(e);
});
}
format elaborator::pp_indent(pp_fn const & pp_fn, expr const & e) {
unsigned i = get_pp_indent(m_opts);
return nest(i, line() + pp_fn(e));
}
format elaborator::pp_indent(expr const & e) {
return pp_indent(mk_pp_ctx(), e);
}
format elaborator::pp(expr const & e) {
auto fn = mk_pp_ctx();
return fn(e);
}
format elaborator::pp_overload(pp_fn const & pp_fn, expr const & fn) {
return is_constant(fn) ? format(const_name(fn)) : pp_fn(fn);
}
format elaborator::pp_overloads(pp_fn const & pp_fn, buffer<expr> const & fns) {
format r("overloads:");
r += space();
bool first = true;
for (expr const & fn : fns) {
if (first) first = false; else r += format(", ");
r += pp_overload(pp_fn, fn);
}
return paren(r);
}
format elaborator::pp_type_mismatch(expr const & e, expr const & e_type, expr const & expected_type) {
try {
expr e_type_type = instantiate_mvars(whnf(infer_type(e_type)));
expr expected_type_type = instantiate_mvars(whnf(infer_type(expected_type)));
return ::lean::pp_type_mismatch(mk_fmt_ctx(), e, e_type, expected_type, some_expr(e_type_type), some_expr(expected_type_type));
} catch (exception &) {
return ::lean::pp_type_mismatch(mk_fmt_ctx(), e, e_type, expected_type);
}
}
format elaborator::pp_type_mismatch(expr const & e_type, expr const & expected_type) {
try {
expr e_type_type = instantiate_mvars(whnf(infer_type(e_type)));
expr expected_type_type = instantiate_mvars(whnf(infer_type(expected_type)));
return ::lean::pp_type_mismatch(mk_fmt_ctx(), e_type, expected_type, some_expr(e_type_type), some_expr(expected_type_type));
} catch (exception &) {
return ::lean::pp_type_mismatch(mk_fmt_ctx(), e_type, expected_type);
}
}
bool elaborator::try_report(std::exception const & ex) {
return try_report(ex, none_expr());
}
bool elaborator::try_report(std::exception const & ex, optional<expr> const & ref) {
if (auto elab_ex = dynamic_cast<elaborator_exception const *>(&ex)) {
if (elab_ex->is_ignored()) return true;
}
if (!m_recover_from_errors) return false;
auto pip = get_pos_info_provider();
if (!pip) return false;
auto tc = std::make_shared<type_context_old>(m_env, m_opts, m_ctx.mctx(), m_ctx.lctx());
message_builder out(tc, m_env, get_global_ios(), pip->get_file_name(),
ref ? pip->get_pos_info_or_some(*ref) : pip->get_some_pos(), ERROR);
out.set_exception(ex);
out.report();
m_has_errors = true;
return true;
}
void elaborator::report_or_throw(elaborator_exception const & ex) {
if (!try_report(ex))
throw elaborator_exception(ex);
}
bool elaborator::has_synth_sorry(std::initializer_list<expr> && es) {
for (auto & e : es) {
if (has_synthetic_sorry(instantiate_mvars(e))) {
return true;
}
}
return false;
}
expr elaborator::mk_sorry(optional<expr> const & expected_type, expr const & ref, bool synthetic) {
auto sorry_type = expected_type ? *expected_type : mk_type_metavar(ref);
return copy_tag(ref, mk_sorry(sorry_type, synthetic));
}
expr elaborator::recoverable_error(optional<expr> const & expected_type, expr const & ref, elaborator_exception const & ex) {
report_or_throw(ex);
return mk_sorry(expected_type, ref);
}
level elaborator::mk_univ_metavar() {
return m_ctx.mk_univ_metavar_decl();
}
expr elaborator::mk_metavar(expr const & A, expr const & ref) {
return copy_tag(ref, m_ctx.mk_metavar_decl(m_ctx.lctx(), A));
}
expr elaborator::mk_metavar(name const & pp_n, expr const & A, expr const & ref) {
return copy_tag(ref, m_ctx.mk_metavar_decl(pp_n, m_ctx.lctx(), A));
}
expr elaborator::mk_metavar(optional<expr> const & A, expr const & ref) {
if (A)
return mk_metavar(*A, ref);
else
return mk_metavar(mk_type_metavar(ref), ref);
}
expr elaborator::mk_type_metavar(expr const & ref) {
level l = mk_univ_metavar();
return mk_metavar(mk_sort(l), ref);
}
expr elaborator::mk_instance_core(local_context const & lctx, expr const & C, expr const & ref) {
scope_traces_as_messages traces_as_messages(get_pos_info_provider(), ref);
// TODO(gabriel): cache failures so that we do not report errors twice
optional<expr> inst = m_ctx.mk_class_instance_at(lctx, C);
if (!inst) {
metavar_context mctx = m_ctx.mctx();
local_context new_lctx = lctx.instantiate_mvars(mctx);
new_lctx = erase_inaccessible_annotations(new_lctx);
tactic_state s = ::lean::mk_tactic_state_for(m_env, m_opts, m_decl_name, mctx, new_lctx, C);
return recoverable_error(some_expr(C), ref, elaborator_exception(
ref, format("failed to synthesize type class instance for") + line() + s.pp())
.ignore_if(has_synth_sorry({C})));
}
return *inst;
}
expr elaborator::mk_instance_core(expr const & C, expr const & ref) {
return mk_instance_core(m_ctx.lctx(), C, ref);
}
/* We say a type class (Pi X, (C a_1 ... a_n)), where X may be empty, is
ready to synthesize if it does not contain metavariables,
or if the a_i's that contain metavariables are marked as output params. */
bool elaborator::ready_to_synthesize(expr inst_type) {
if (!has_expr_metavar(inst_type))
return true;
while (is_pi(inst_type))
inst_type = binding_body(inst_type);
buffer<expr> C_args;
expr const & C = get_app_args(inst_type, C_args);
if (!is_constant(C))
return false;
expr it = m_ctx.infer(C);
for (expr const & C_arg : C_args) {
if (!is_pi(it))
return false; /* failed */
expr const & d = binding_domain(it);
if (has_expr_metavar(C_arg) && !is_class_out_param(d))
return false;
it = binding_body(it);
}
return true;
}
expr elaborator::mk_instance(expr const & C, expr const & ref) {
if (!ready_to_synthesize(C)) {
expr inst = mk_metavar(C, ref);
m_instances = cons(inst, m_instances);
return inst;
} else {
return mk_instance_core(C, ref);
}
}
expr elaborator::instantiate_mvars(expr const & e) {
expr r = m_ctx.instantiate_mvars(e);
if (r.get_tag() == nulltag)
r.set_tag(e.get_tag());
return r;
}
level elaborator::get_level(expr const & A, expr const & ref) {
expr A_type = whnf(infer_type(A));
if (is_sort(A_type)) {
return sort_level(A_type);
}
if (is_meta(A_type)) {
level l = mk_univ_metavar();
if (try_is_def_eq(A_type, mk_sort(l))) {
return l;
}
}
auto pp_fn = mk_pp_ctx();
throw elaborator_exception(ref, pp_type_expected(mk_fmt_ctx(), A, &A_type));
}
level elaborator::replace_univ_placeholder(level const & l) {
auto fn = [&](level const & l) {
if (is_one_placeholder(l))
return some_level(mk_level_one());
else if (is_placeholder(l))
return some_level(mk_univ_metavar());
else
return none_level();
};
return replace(l, fn);
}
static bool contains_placeholder(level const & l) {
bool contains = false;
auto fn = [&](level const & l) {
if (contains) return false;
if (is_placeholder(l) || is_one_placeholder(l))
contains = true;
return true;
};
for_each(l, fn);
return contains;
}
/* Here, we say a term is first-order IF all applications are of the form (f ...) where f is a constant. */
static bool is_first_order(expr const & e) {
return !find(e, [&](expr const & e, unsigned) {
return is_app(e) && !is_constant(get_app_fn(e));
});
}
bool elaborator::is_elim_elab_candidate(name const & fn) {
return get_elaborator_strategy(m_env, fn) == elaborator_strategy::AsEliminator;
}
/* Temporary hack for get_elim_info_for_builtin.
It doesn't work for drec recursors for inductive predicates.
TODO(Leo): fix it. */
static bool is_basic_aux_recursor(environment const & env, name const & n) {
if (!is_aux_recursor(env, n))
return false;
return strcmp(n.get_string(), "drec") != 0;
}
/** See comment at elim_info */
auto elaborator::get_elim_info_for_builtin(name const & fn) -> elim_info {
lean_assert(is_basic_aux_recursor(m_env, fn) || inductive::is_elim_rule(m_env, fn));
/* Remark: this is not just an optimization. The code at use_elim_elab_core
only works for dependent elimination. */
lean_assert(!fn.is_atomic());
name const & I_name = fn.get_prefix();
optional<inductive::inductive_decl> decl = inductive::is_inductive_decl(m_env, I_name);
lean_assert(decl);
unsigned nparams = decl->m_num_params;
unsigned nindices = *inductive::get_num_indices(m_env, I_name);
unsigned nminors = length(decl->m_intro_rules);
elim_info r;
if (strcmp(fn.get_string(), "brec_on") == 0 || strcmp(fn.get_string(), "binduction_on") == 0) {
r.m_arity = nparams + 1 /* motive */ + nindices + 1 /* major */ + 1;
} else {
r.m_arity = nparams + 1 /* motive */ + nindices + 1 /* major */ + nminors;
}
r.m_nexplicit = 1 /* major premise */ + nminors;
if (nminors == 0) {
/* The motive is marked as explicit in builtin recursors that do not have
minor premises */
r.m_nexplicit++;
}
r.m_motive_idx = nparams;
unsigned major_idx;
if (inductive::is_elim_rule(m_env, fn)) {
major_idx = nparams + 1 + nindices + nminors;
} else {
major_idx = nparams + 1 + nindices;
}
r.m_idxs = to_list(major_idx);
return r;
}
/** See comment at elim_info */
auto elaborator::use_elim_elab_core(name const & fn) -> optional<elim_info> {
if (!is_elim_elab_candidate(fn))
return optional<elim_info>();
if (is_basic_aux_recursor(m_env, fn) || inductive::is_elim_rule(m_env, fn)) {
return optional<elim_info>(get_elim_info_for_builtin(fn));
}
type_context_old::tmp_locals locals(m_ctx);
declaration d = m_env.get(fn);
expr type = d.get_type();
while (is_pi(type)) {
type = instantiate(binding_body(type), locals.push_local_from_binding(type));
}
buffer<expr> C_args;
expr const & C = get_app_args(type, C_args);
if (!is_local(C) || C_args.empty() || !std::all_of(C_args.begin(), C_args.end(), is_local)) {
format msg = format("'eliminator' elaboration is not used for '") + format(fn) +
format("' because resulting type is not of the expected form\n");
m_elim_failure_info.insert(fn, msg);
return optional<elim_info>();
}
buffer<expr> const & params = locals.as_buffer();
optional<unsigned> _midx = params.index_of(C);
if (!_midx)
return optional<elim_info>();
unsigned midx = *_midx;
buffer<unsigned> idxs;
buffer<bool> found;
found.resize(C_args.size(), false);
unsigned i = params.size();
unsigned nexplicit = 0;
while (i > 0) {
--i;
expr const & param = params[i];
if (!is_explicit(local_info(param))) {
continue;
}
nexplicit++;
if (optional<unsigned> pos = C_args.index_of(param)) {
// Parameter is an argument of the resulting type (C ...)
if (!found[*pos]) {
// We store it if we could not infer it using the type of other arguments.
found[*pos] = true;
idxs.push_back(i);
}
}
expr param_type = m_ctx.infer(param);
if (!is_first_order(param_type))
continue;
bool collected = false;
for_each(param_type, [&](expr const & e, unsigned) {
if (is_local(e)) {
if (optional<unsigned> pos = C_args.index_of(e)) {
if (!found[*pos]) {
collected = true;
found[*pos] = true;
}
}
}
return true;
});
if (collected)
idxs.push_back(i);
}
for (unsigned i = 0; i < found.size(); i++) {
if (!found[i]) {
format msg = format("'eliminator' elaboration is not used for '") + format(fn) +
format("' because a (reliable) way to synthesize '") + pp(C_args[i]) +
format("', which occurs in the resulting type, was not found\n");
m_elim_failure_info.insert(fn, msg);
return optional<elim_info>();
}
}
std::reverse(idxs.begin(), idxs.end());
trace_elab_detail(tout() << "'eliminator' elaboration is going to be used for '" << fn << "' applications, "
<< "the motive is computed using the argument(s):";
for (unsigned idx : idxs) tout() << " #" << (idx+1);
tout() << "\n";);
return optional<elim_info>(params.size(), nexplicit, midx, to_list(idxs));
}
/** See comment at elim_info */
auto elaborator::use_elim_elab(name const & fn) -> optional<elim_info> {
if (auto it = m_elim_cache.find(fn))
return *it;
optional<elim_info> r = use_elim_elab_core(fn);
m_elim_cache.insert(fn, r);
return r;
}
void elaborator::trace_coercion_failure(expr const & e_type, expr const & type, expr const & ref, char const * error_msg) {
trace_elab({
auto pp_fn = mk_pp_ctx();
format msg("coercion at ");
msg += format(pos_string_for(ref));
msg += space() + format("from");
msg += pp_indent(pp_fn, e_type);
msg += line() + format("to");
msg += pp_indent(pp_fn, type);
msg += line() + format(error_msg);
tout() << msg << "\n";
});
}
optional<expr> elaborator::mk_Prop_to_bool_coercion(expr const & e, expr const & ref) {
expr dec = mk_app(mk_constant(get_decidable_name()), e);
expr inst = mk_instance(dec, ref);
expr r = mk_app(mk_constant(get_decidable_to_bool_name()), e, inst);
return some_expr(r);
}
optional<expr> elaborator::mk_coercion_core(expr const & e, expr const & e_type, expr const & type, expr const & ref) {
if (e_type == mk_Prop() && m_ctx.is_def_eq(type, mk_bool())) {
return mk_Prop_to_bool_coercion(e, ref);
} else {
expr has_coe_t;
try {
has_coe_t = mk_app(m_ctx, get_has_coe_t_name(), e_type, type);
} catch (app_builder_exception & ex) {
trace_coercion_failure(e_type, type, ref,
"failed create type class expression 'has_coe_t' "
"('set_option trace.app_builder true' for more information)");
return none_expr();
}
optional<expr> inst;
try {
inst = m_ctx.mk_class_instance_at(m_ctx.lctx(), has_coe_t);
} catch (class_exception &) {
trace_coercion_failure(e_type, type, ref,
"failed to synthesize class instance for 'has_coe_t' "
"('set_option trace.class_instances true' for more information)");
return none_expr();
}
if (!inst) {
trace_coercion_failure(e_type, type, ref,
"failed to synthesize 'has_coe_t' type class instance "
"('set_option trace.class_instances true' for more information)");
return none_expr();
}
level u_1 = get_level(e_type, ref);
level u_2 = get_level(type, ref);
expr coe_to_lift = mk_app(mk_constant(get_coe_to_lift_name(), {u_1, u_2}), e_type, type, *inst);
expr coe = mk_app(mk_constant(get_coe_name(), {u_1, u_2}), e_type, type, coe_to_lift, e);
return some_expr(coe);
}
}
bool elaborator::is_monad(expr const & e) {
try {
expr m = mk_app(m_ctx, get_monad_name(), e);
return static_cast<bool>(m_ctx.mk_class_instance(m));
} catch (app_builder_exception &) {
return false;
} catch (class_exception &) {
return false;
}
}
bool elaborator::is_monad_fail(expr const & e) {
try {
expr m = mk_app(m_ctx, get_monad_fail_name(), e);
return static_cast<bool>(m_ctx.mk_class_instance(m));
} catch (app_builder_exception &) {
return false;
} catch (class_exception &) {
return false;
}
}
/*
When lifting monads in do-notation and/or bind, it is very common to have coercion problems such as
tactic name ===> solver ?a
Coercion resolution cannot be used because (solver ?a) contains meta-variables. Recall that
coercion resolution is based on type class resolution, and we can only synthesize type class instances
if the type does not contain meta-variables.
The coercion problem above is generated in scenarios such as
do v ← t1,
...
which is notation for
@bind ?m ?inst ?a ?b t1 (fun v : ?a, ...)
Now, assume (t1 : tactic name) and the expected type is (solver unit).
Then, the following meta-variables can be resolved.
?m := solver
?b := unit
?inst := solver.monad
and we get
@bind solver solver.monad ?a unit t1 (fun v : ?a, ...)
At this point, we get a type mismatch at t1 because th expected type is (solver ?a) and the given type
is (tactic name).
In this method, we consider the following compromise: we assign ?a := name, and then, try to perform
coercion resolution again.
Remark: this method also handle the case where the metavariable is at e_type. Example:
tactic ?a ===> smt_tactic unit
TODO(leo): can/should we generalize this approach? */
optional<expr> elaborator::try_monad_coercion(expr const & e, expr const & e_type, expr type, expr const & ref) {
if ((has_expr_metavar(e_type) && has_expr_metavar(type))
|| (!has_expr_metavar(e_type) && !has_expr_metavar(type))
|| !is_app(e_type)
|| !is_app(type)
|| has_expr_metavar(app_fn(type))
|| has_expr_metavar(app_fn(e_type))
|| (!is_metavar(app_arg(e_type)) && !is_metavar(app_arg(type)))
|| !is_monad(app_fn(e_type))
|| !is_monad(app_fn(type))) {
/* Not applicable */
return none_expr();
}
if (!m_ctx.is_def_eq(app_arg(e_type), app_arg(type)))
return none_expr();
type = instantiate_mvars(type);
return mk_coercion_core(e, e_type, type, ref);
}
optional<expr> elaborator::mk_coercion(expr const & e, expr e_type, expr type, expr const & ref) {
if (!m_coercions) return none_expr();
synthesize_type_class_instances();
e_type = instantiate_mvars(e_type);
type = instantiate_mvars(type);
if (auto r = try_monad_coercion(e, e_type, type, ref)) {
return r;
}
auto whnf_type = whnf(type);
if (is_pi(whnf_type)) {
if (auto r = mk_coercion_to_fn(e, e_type, ref)) {
return r;
}
}
if (is_sort(whnf_type)) {
if (auto r = mk_coercion_to_sort(e, e_type, ref)) {
return r;
}
}
return mk_coercion_core(e, e_type, type, ref);
}
bool elaborator::is_def_eq(expr const & e1, expr const & e2) {
type_context_old::approximate_scope scope(m_ctx);
try {
return m_ctx.is_def_eq(e1, e2);
} catch (exception &) {
return false;
}
}
bool elaborator::try_is_def_eq(expr const & e1, expr const & e2) {
snapshot S(*this);
flet<bool> dont_recover(m_recover_from_errors, false);
try {
return is_def_eq(e1, e2);
} catch (exception &) {
S.restore(*this);
throw;
}
S.restore(*this);
return false;
}
optional<expr> elaborator::ensure_has_type(expr const & e, expr const & e_type, expr const & type, expr const & ref) {
if (is_def_eq(e_type, type))
return some_expr(e);
return mk_coercion(e, e_type, type, ref);
}
expr elaborator::enforce_type(expr const & e, expr const & expected_type, char const * header, expr const & ref) {
expr e_type = infer_type(e);
if (auto r = ensure_has_type(e, e_type, expected_type, ref)) {
return *r;
} else {
auto exc = elaborator_exception(ref, format(header) + format(", term") +
pp_type_mismatch(e, e_type, expected_type))
.ignore_if(has_synth_sorry({e, e_type, expected_type}));
return recoverable_error(some(expected_type), ref, exc);
}
}
void elaborator::trace_coercion_fn_sort_failure(bool is_fn, expr const & e_type, expr const & ref, char const * error_msg) {
trace_elab({
format msg("coercion at ");
auto pp_fn = mk_pp_ctx();
msg += format(pos_string_for(ref));
msg += space() + format("from");
msg += pp_indent(pp_fn, e_type);
if (is_fn)
msg += line() + format("to function space");
else
msg += line() + format("to sort");
msg += line() + format(error_msg);
tout() << msg << "\n";
});
}
optional<expr> elaborator::mk_coercion_to_fn_sort(bool is_fn, expr const & e, expr const & _e_type, expr const & ref) {
if (!m_coercions) return none_expr();
expr e_type = instantiate_mvars(_e_type);
try {
bool mask[4] = { true, false, false, true };
expr args[2] = { e_type, e };
expr new_e = mk_app(m_ctx, is_fn ? get_coe_fn_name() : get_coe_sort_name(), 4, mask, args);
expr new_e_type = whnf(infer_type(new_e));
if ((is_fn && is_pi(new_e_type)) || (!is_fn && is_sort(new_e_type))) {
return some_expr(new_e);
}
trace_coercion_fn_sort_failure(is_fn, e_type, ref,
"coercion was successfully generated, but resulting type is not the expected one");
return none_expr();
} catch (app_builder_exception & ex) {
trace_coercion_fn_sort_failure(is_fn, e_type, ref,
"failed create coercion application using type class resolution "
"('set_option trace.app_builder true' and 'set_option trace.class_instances true' for more information)");
return none_expr();
}
}
expr elaborator::ensure_function(expr const & e, expr const & ref) {
expr e_type = whnf(infer_type(e));
if (is_pi(e_type)) {
return e;
}
if (auto r = mk_coercion_to_fn(e, e_type, ref)) {
return *r;
}
throw elaborator_exception(ref, pp_function_expected(mk_fmt_ctx(), e, e_type))
.ignore_if(has_synth_sorry({e, e_type}));
}
expr elaborator::ensure_type(expr const & e, expr const & ref) {
expr e_type = whnf(infer_type(e));
if (is_sort(e_type)) {
return e;
}
if (is_meta(e_type) && is_def_eq(e_type, mk_sort(mk_univ_metavar()))) {
return e;
}
if (auto r = mk_coercion_to_sort(e, e_type, ref)) {
return *r;
}
report_or_throw(elaborator_exception(ref, pp_type_expected(mk_fmt_ctx(), e, &e_type)));
// only create the metavar if can actually recover from the error
return mk_sorry(some_expr(mk_sort(mk_univ_metavar())), ref);
}
static expr get_ref_for_child(expr const & arg, expr const & ref) {
if (get_pos_info_provider() && get_pos_info_provider()->get_pos_info(arg)) {
return arg;
} else {
/* using ref because position info for argument is not available */
return ref;
}
}
expr elaborator::visit_typed_expr(expr const & e) {
expr val = get_typed_expr_expr(e);
expr ref = val;
expr type = get_typed_expr_type(e);
expr new_type;
expr ref_type = get_ref_for_child(type, e);
new_type = ensure_type(visit(type, none_expr()), ref_type);
synthesize_type_class_instances();
expr new_val = visit(val, some_expr(new_type));
expr new_val_type = infer_type(new_val);
if (auto r = ensure_has_type(new_val, new_val_type, new_type, ref))
return *r;
return recoverable_error(some_expr(new_type), ref, elaborator_exception(ref, format("invalid type ascription, term ") +
pp_type_mismatch(new_val_type, new_type)));
}
level elaborator::dec_level(level const & l, expr const & ref) {
if (auto d = ::lean::dec_level(l))
return *d;
level r = m_ctx.mk_univ_metavar_decl();
if (!m_ctx.is_def_eq(mk_succ(r), l))
throw elaborator_exception(ref, "invalid pre-numeral, universe level must be > 0");
return r;
}
expr elaborator::visit_prenum(expr const & e, optional<expr> const & expected_type) {
lean_assert(is_prenum(e));
expr ref = e;
mpz const & v = prenum_value(e);
tag e_tag = e.get_tag();
expr A;
if (expected_type) {
A = *expected_type;
if (is_metavar(*expected_type))
m_numeral_types = cons(A, m_numeral_types);
} else {
A = mk_type_metavar(ref);
m_numeral_types = cons(A, m_numeral_types);
}
level A_lvl = get_level(A, ref);
levels ls(dec_level(A_lvl, ref));
if (v.is_neg())
return recoverable_error(some_expr(A), ref, elaborator_exception(ref, "invalid pre-numeral, it must be a non-negative value"));
if (v.is_zero()) {
expr has_zero_A = mk_app(mk_constant(get_has_zero_name(), ls), A, e_tag);
expr S = mk_instance(has_zero_A, ref);
return mk_app(mk_app(mk_constant(get_has_zero_zero_name(), ls), A, e_tag), S, e_tag);
} else {
expr has_one_A = mk_app(mk_constant(get_has_one_name(), ls), A, e_tag);
expr S_one = mk_instance(has_one_A, ref);
expr one = mk_app(mk_app(mk_constant(get_has_one_one_name(), ls), A, e_tag), S_one, e_tag);
if (v == 1) {
return one;
} else {
expr has_add_A = mk_app(mk_constant(get_has_add_name(), ls), A, e_tag);
expr S_add = mk_instance(has_add_A, ref);
std::function<expr(mpz const & v)> convert = [&](mpz const & v) {
lean_assert(v > 0);
if (v == 1)
return one;
else if (v % mpz(2) == 0) {
expr r = convert(v / 2);
return mk_app(mk_app(mk_app(mk_constant(get_bit0_name(), ls), A, e_tag), S_add, e_tag), r, e_tag);
} else {
expr r = convert(v / 2);
return mk_app(mk_app(mk_app(mk_app(mk_constant(get_bit1_name(), ls), A, e_tag), S_one, e_tag),
S_add, e_tag), r, e_tag);
}
};
return convert(v);
}
}
}
expr elaborator::visit_sort(expr const & e) {
level new_l = replace_univ_placeholder(sort_level(e));
expr r = update_sort(e, new_l);
if (contains_placeholder(sort_level(e)))
m_to_check_sorts.emplace_back(e, r);
return r;
}
expr elaborator::visit_const_core(expr const & e) {
declaration d = m_env.get(const_name(e));
buffer<level> ls;
for (level const & l : const_levels(e)) {
level new_l = replace_univ_placeholder(l);
ls.push_back(new_l);
}
unsigned num_univ_params = d.get_num_univ_params();
if (num_univ_params < ls.size()) {
format msg("incorrect number of universe levels parameters for '");
msg += format(const_name(e)) + format("', #") + format(num_univ_params);
msg += format(" expected, #") + format(ls.size()) + format("provided");
return recoverable_error({}, e, elaborator_exception(e, msg));
}
// "fill" with meta universe parameters
for (unsigned i = ls.size(); i < num_univ_params; i++)
ls.push_back(mk_univ_metavar());
lean_assert(num_univ_params == ls.size());
return update_constant(e, to_list(ls.begin(), ls.end()));
}
/** \brief Auxiliary function for saving information about which overloaded identifier was used by the elaborator. */
void elaborator::save_identifier_info(expr const & f) {
if (!m_no_info && m_uses_infom && get_pos_info_provider() && (is_constant(f) || is_local(f))) {
if (auto p = get_pos_info_provider()->get_pos_info(f)) {
m_info.add_identifier_info(*p, is_constant(f) ? const_name(f) : mlocal_pp_name(f));
m_info.add_type_info(*p, infer_type(f));
}
}
}
expr elaborator::visit_function(expr const & fn, bool has_args, optional<expr> const & expected_type, expr const & ref) {
if (is_placeholder(fn)) {
throw elaborator_exception(ref, "placeholders '_' cannot be used where a function is expected");
}
if (is_field_notation(fn))
throw elaborator_exception(ref, "invalid occurrence of field notation");
expr r;
switch (fn.kind()) {
case expr_kind::Var:
case expr_kind::Pi:
case expr_kind::Meta:
case expr_kind::Sort:
throw elaborator_exception(ref, "invalid application, function expected");
// The expr_kind::App case can only happen when nary notation is used
case expr_kind::App: r = visit(fn, expected_type); break;
case expr_kind::Local: r = fn; break;
case expr_kind::Constant: r = visit_const_core(fn); break;
case expr_kind::Macro: r = visit_macro(fn, expected_type, true); break;
case expr_kind::Lambda: r = visit_lambda(fn, expected_type); break;
case expr_kind::Let: r = visit_let(fn, expected_type); break;
}
save_identifier_info(r);
if (has_args)
r = ensure_function(r, ref);
return r;
}
void elaborator::validate_overloads(buffer<expr> const & fns, expr const & ref) {
for (expr const & fn_i : fns) {
if (is_constant(fn_i) && use_elim_elab(const_name(fn_i))) {
auto pp_fn = mk_pp_ctx();
format msg("invalid overloaded application, "
"elaborator has special support for '");
msg += pp_fn(fn_i);
msg += format("' (it is handled as an \"eliminator\"), "
"but this kind of constant cannot be overloaded "
"(solution: use fully qualified names) ");
msg += pp_overloads(pp_fn, fns);
throw elaborator_exception(ref, msg);
}
}
}
void elaborator::throw_app_type_mismatch_error(expr const & t, expr const & arg, expr const & arg_type,
expr const & expected_type, expr const & ref) {
format msg = format("type mismatch at application");
msg += pp_indent(mk_pp_ctx(), t);
msg += line() + format("term") + pp_type_mismatch(arg, arg_type, expected_type);
throw elaborator_exception(ref, msg).
ignore_if(has_synth_sorry({arg, arg_type, expected_type}));
}
format elaborator::mk_app_arg_mismatch_error(expr const & t, expr const & arg, expr const & expected_arg) {
auto pp_data = pp_until_different(mk_fmt_ctx(), arg, expected_arg);
auto fmt = std::get<0>(pp_data);
format msg = format("unexpected argument at application");
msg += pp_indent_expr(fmt, t);