-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
late.rs
2229 lines (2038 loc) · 91.5 KB
/
late.rs
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
//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
//! It runs when the crate is fully expanded and its module structure is fully built.
//! So it just walks through the crate and resolves all the expressions, types, etc.
//!
//! If you wonder why there's no `early.rs`, that's because it's split into three files -
//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
use RibKind::*;
use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
use crate::{Module, ModuleOrUniformRoot, NameBindingKind, ParentScope, PathResult};
use crate::{ResolutionError, Resolver, Segment, UseError};
use rustc_ast::ast::*;
use rustc_ast::ptr::P;
use rustc_ast::util::lev_distance::find_best_match_for_name;
use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
use rustc_ast::{unwrap_or, walk_list};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::DiagnosticId;
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
use rustc_hir::TraitCandidate;
use rustc_middle::{bug, span_bug};
use rustc_session::lint;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::Span;
use smallvec::{smallvec, SmallVec};
use log::debug;
use std::collections::BTreeSet;
use std::mem::replace;
mod diagnostics;
crate mod lifetimes;
type Res = def::Res<NodeId>;
type IdentMap<T> = FxHashMap<Ident, T>;
/// Map from the name in a pattern to its binding mode.
type BindingMap = IdentMap<BindingInfo>;
#[derive(Copy, Clone, Debug)]
struct BindingInfo {
span: Span,
binding_mode: BindingMode,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum PatternSource {
Match,
Let,
For,
FnParam,
}
impl PatternSource {
fn descr(self) -> &'static str {
match self {
PatternSource::Match => "match binding",
PatternSource::Let => "let binding",
PatternSource::For => "for binding",
PatternSource::FnParam => "function parameter",
}
}
}
/// Denotes whether the context for the set of already bound bindings is a `Product`
/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
/// See those functions for more information.
#[derive(PartialEq)]
enum PatBoundCtx {
/// A product pattern context, e.g., `Variant(a, b)`.
Product,
/// An or-pattern context, e.g., `p_0 | ... | p_n`.
Or,
}
/// Does this the item (from the item rib scope) allow generic parameters?
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
crate enum HasGenericParams {
Yes,
No,
}
/// The rib kind restricts certain accesses,
/// e.g. to a `Res::Local` of an outer item.
#[derive(Copy, Clone, Debug)]
crate enum RibKind<'a> {
/// No restriction needs to be applied.
NormalRibKind,
/// We passed through an impl or trait and are now in one of its
/// methods or associated types. Allow references to ty params that impl or trait
/// binds. Disallow any other upvars (including other ty params that are
/// upvars).
AssocItemRibKind,
/// We passed through a function definition. Disallow upvars.
/// Permit only those const parameters that are specified in the function's generics.
FnItemRibKind,
/// We passed through an item scope. Disallow upvars.
ItemRibKind(HasGenericParams),
/// We're in a constant item. Can't refer to dynamic stuff.
ConstantItemRibKind,
/// We passed through a module.
ModuleRibKind(Module<'a>),
/// We passed through a `macro_rules!` statement
MacroDefinition(DefId),
/// All bindings in this rib are type parameters that can't be used
/// from the default of a type parameter because they're not declared
/// before said type parameter. Also see the `visit_generics` override.
ForwardTyParamBanRibKind,
}
impl RibKind<'_> {
// Whether this rib kind contains generic parameters, as opposed to local
// variables.
crate fn contains_params(&self) -> bool {
match self {
NormalRibKind | FnItemRibKind | ConstantItemRibKind | ModuleRibKind(_)
| MacroDefinition(_) => false,
AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
}
}
}
/// A single local scope.
///
/// A rib represents a scope names can live in. Note that these appear in many places, not just
/// around braces. At any place where the list of accessible names (of the given namespace)
/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
/// etc.
///
/// Different [rib kinds](enum.RibKind) are transparent for different names.
///
/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
/// resolving, the name is looked up from inside out.
#[derive(Debug)]
crate struct Rib<'a, R = Res> {
pub bindings: IdentMap<R>,
pub kind: RibKind<'a>,
}
impl<'a, R> Rib<'a, R> {
fn new(kind: RibKind<'a>) -> Rib<'a, R> {
Rib { bindings: Default::default(), kind }
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
crate enum AliasPossibility {
No,
Maybe,
}
#[derive(Copy, Clone, Debug)]
crate enum PathSource<'a> {
// Type paths `Path`.
Type,
// Trait paths in bounds or impls.
Trait(AliasPossibility),
// Expression paths `path`, with optional parent context.
Expr(Option<&'a Expr>),
// Paths in path patterns `Path`.
Pat,
// Paths in struct expressions and patterns `Path { .. }`.
Struct,
// Paths in tuple struct patterns `Path(..)`.
TupleStruct,
// `m::A::B` in `<T as m::A>::B::C`.
TraitItem(Namespace),
}
impl<'a> PathSource<'a> {
fn namespace(self) -> Namespace {
match self {
PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
PathSource::TraitItem(ns) => ns,
}
}
fn defer_to_typeck(self) -> bool {
match self {
PathSource::Type
| PathSource::Expr(..)
| PathSource::Pat
| PathSource::Struct
| PathSource::TupleStruct => true,
PathSource::Trait(_) | PathSource::TraitItem(..) => false,
}
}
fn descr_expected(self) -> &'static str {
match &self {
PathSource::Type => "type",
PathSource::Trait(_) => "trait",
PathSource::Pat => "unit struct, unit variant or constant",
PathSource::Struct => "struct, variant or union type",
PathSource::TupleStruct => "tuple struct or tuple variant",
PathSource::TraitItem(ns) => match ns {
TypeNS => "associated type",
ValueNS => "method or associated constant",
MacroNS => bug!("associated macro"),
},
PathSource::Expr(parent) => match &parent.as_ref().map(|p| &p.kind) {
// "function" here means "anything callable" rather than `DefKind::Fn`,
// this is not precise but usually more helpful than just "value".
Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
ExprKind::Path(_, path) => {
let mut msg = "function";
if let Some(segment) = path.segments.iter().last() {
if let Some(c) = segment.ident.to_string().chars().next() {
if c.is_uppercase() {
msg = "function, tuple struct or tuple variant";
}
}
}
msg
}
_ => "function",
},
_ => "value",
},
}
}
crate fn is_expected(self, res: Res) -> bool {
match self {
PathSource::Type => match res {
Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Enum
| DefKind::Trait
| DefKind::TraitAlias
| DefKind::TyAlias
| DefKind::AssocTy
| DefKind::TyParam
| DefKind::OpaqueTy
| DefKind::ForeignTy,
_,
)
| Res::PrimTy(..)
| Res::SelfTy(..) => true,
_ => false,
},
PathSource::Trait(AliasPossibility::No) => match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
},
PathSource::Trait(AliasPossibility::Maybe) => match res {
Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
_ => false,
},
PathSource::Expr(..) => match res {
Res::Def(
DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
| DefKind::Const
| DefKind::Static
| DefKind::Fn
| DefKind::AssocFn
| DefKind::AssocConst
| DefKind::ConstParam,
_,
)
| Res::Local(..)
| Res::SelfCtor(..) => true,
_ => false,
},
PathSource::Pat => match res {
Res::Def(
DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
_,
)
| Res::SelfCtor(..) => true,
_ => false,
},
PathSource::TupleStruct => match res {
Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
_ => false,
},
PathSource::Struct => match res {
Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Variant
| DefKind::TyAlias
| DefKind::AssocTy,
_,
)
| Res::SelfTy(..) => true,
_ => false,
},
PathSource::TraitItem(ns) => match res {
Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
_ => false,
},
}
}
fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
use rustc_errors::error_code;
match (self, has_unexpected_resolution) {
(PathSource::Trait(_), true) => error_code!(E0404),
(PathSource::Trait(_), false) => error_code!(E0405),
(PathSource::Type, true) => error_code!(E0573),
(PathSource::Type, false) => error_code!(E0412),
(PathSource::Struct, true) => error_code!(E0574),
(PathSource::Struct, false) => error_code!(E0422),
(PathSource::Expr(..), true) => error_code!(E0423),
(PathSource::Expr(..), false) => error_code!(E0425),
(PathSource::Pat | PathSource::TupleStruct, true) => error_code!(E0532),
(PathSource::Pat | PathSource::TupleStruct, false) => error_code!(E0531),
(PathSource::TraitItem(..), true) => error_code!(E0575),
(PathSource::TraitItem(..), false) => error_code!(E0576),
}
}
}
#[derive(Default)]
struct DiagnosticMetadata<'ast> {
/// The current trait's associated types' ident, used for diagnostic suggestions.
current_trait_assoc_types: Vec<Ident>,
/// The current self type if inside an impl (used for better errors).
current_self_type: Option<Ty>,
/// The current self item if inside an ADT (used for better errors).
current_self_item: Option<NodeId>,
/// The current trait (used to suggest).
current_item: Option<&'ast Item>,
/// When processing generics and encountering a type not found, suggest introducing a type
/// param.
currently_processing_generics: bool,
/// The current enclosing function (used for better errors).
current_function: Option<(FnKind<'ast>, Span)>,
/// A list of labels as of yet unused. Labels will be removed from this map when
/// they are used (in a `break` or `continue` statement)
unused_labels: FxHashMap<NodeId, Span>,
/// Only used for better errors on `fn(): fn()`.
current_type_ascription: Vec<Span>,
/// Only used for better errors on `let <pat>: <expr, not type>;`.
current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
}
struct LateResolutionVisitor<'a, 'b, 'ast> {
r: &'b mut Resolver<'a>,
/// The module that represents the current item scope.
parent_scope: ParentScope<'a>,
/// The current set of local scopes for types and values.
/// FIXME #4948: Reuse ribs to avoid allocation.
ribs: PerNS<Vec<Rib<'a>>>,
/// The current set of local scopes, for labels.
label_ribs: Vec<Rib<'a, NodeId>>,
/// The trait that the current context can refer to.
current_trait_ref: Option<(Module<'a>, TraitRef)>,
/// Fields used to add information to diagnostic errors.
diagnostic_metadata: DiagnosticMetadata<'ast>,
}
/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
impl<'a, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
fn visit_item(&mut self, item: &'ast Item) {
let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
self.resolve_item(item);
self.diagnostic_metadata.current_item = prev;
}
fn visit_arm(&mut self, arm: &'ast Arm) {
self.resolve_arm(arm);
}
fn visit_block(&mut self, block: &'ast Block) {
self.resolve_block(block);
}
fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
debug!("visit_anon_const {:?}", constant);
self.with_constant_rib(|this| {
visit::walk_anon_const(this, constant);
});
}
fn visit_expr(&mut self, expr: &'ast Expr) {
self.resolve_expr(expr, None);
}
fn visit_local(&mut self, local: &'ast Local) {
let local_spans = match local.pat.kind {
// We check for this to avoid tuple struct fields.
PatKind::Wild => None,
_ => Some((
local.pat.span,
local.ty.as_ref().map(|ty| ty.span),
local.init.as_ref().map(|init| init.span),
)),
};
let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
self.resolve_local(local);
self.diagnostic_metadata.current_let_binding = original;
}
fn visit_ty(&mut self, ty: &'ast Ty) {
match ty.kind {
TyKind::Path(ref qself, ref path) => {
self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
}
TyKind::ImplicitSelf => {
let self_ty = Ident::with_dummy_span(kw::SelfUpper);
let res = self
.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
.map_or(Res::Err, |d| d.res());
self.r.record_partial_res(ty.id, PartialRes::new(res));
}
_ => (),
}
visit::walk_ty(self, ty);
}
fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
self.smart_resolve_path(
tref.trait_ref.ref_id,
None,
&tref.trait_ref.path,
PathSource::Trait(AliasPossibility::Maybe),
);
visit::walk_poly_trait_ref(self, tref, m);
}
fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
match foreign_item.kind {
ForeignItemKind::Fn(_, _, ref generics, _)
| ForeignItemKind::TyAlias(_, ref generics, ..) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
visit::walk_foreign_item(this, foreign_item);
});
}
ForeignItemKind::Static(..) => {
self.with_item_rib(HasGenericParams::No, |this| {
visit::walk_foreign_item(this, foreign_item);
});
}
ForeignItemKind::MacCall(..) => {
visit::walk_foreign_item(self, foreign_item);
}
}
}
fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
let rib_kind = match fn_kind {
// Bail if there's no body.
FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp),
FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind,
FnKind::Fn(FnCtxt::Assoc(_), ..) | FnKind::Closure(..) => NormalRibKind,
};
let previous_value =
replace(&mut self.diagnostic_metadata.current_function, Some((fn_kind, sp)));
debug!("(resolving function) entering function");
let declaration = fn_kind.decl();
// Create a value rib for the function.
self.with_rib(ValueNS, rib_kind, |this| {
// Create a label rib for the function.
this.with_label_rib(rib_kind, |this| {
// Add each argument to the rib.
this.resolve_params(&declaration.inputs);
visit::walk_fn_ret_ty(this, &declaration.output);
// Resolve the function body, potentially inside the body of an async closure
match fn_kind {
FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
FnKind::Closure(_, body) => this.visit_expr(body),
};
debug!("(resolving function) leaving function");
})
});
self.diagnostic_metadata.current_function = previous_value;
}
fn visit_generics(&mut self, generics: &'ast Generics) {
// For type parameter defaults, we have to ban access
// to following type parameters, as the InternalSubsts can only
// provide previous type parameters as they're built. We
// put all the parameters on the ban list and then remove
// them one by one as they are processed and become available.
let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
let mut found_default = false;
default_ban_rib.bindings.extend(generics.params.iter().filter_map(
|param| match param.kind {
GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
GenericParamKind::Type { ref default, .. } => {
found_default |= default.is_some();
found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
}
},
));
// rust-lang/rust#61631: The type `Self` is essentially
// another type parameter. For ADTs, we consider it
// well-defined only after all of the ADT type parameters have
// been provided. Therefore, we do not allow use of `Self`
// anywhere in ADT type parameter defaults.
//
// (We however cannot ban `Self` for defaults on *all* generic
// lists; e.g. trait generics can usefully refer to `Self`,
// such as in the case of `trait Add<Rhs = Self>`.)
if self.diagnostic_metadata.current_self_item.is_some() {
// (`Some` if + only if we are in ADT's generics.)
default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
}
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
GenericParamKind::Type { ref default, .. } => {
for bound in ¶m.bounds {
self.visit_param_bound(bound);
}
if let Some(ref ty) = default {
self.ribs[TypeNS].push(default_ban_rib);
self.visit_ty(ty);
default_ban_rib = self.ribs[TypeNS].pop().unwrap();
}
// Allow all following defaults to refer to this type parameter.
default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
}
GenericParamKind::Const { ref ty } => {
for bound in ¶m.bounds {
self.visit_param_bound(bound);
}
self.visit_ty(ty);
}
}
}
for p in &generics.where_clause.predicates {
self.visit_where_predicate(p);
}
}
fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
debug!("visit_generic_arg({:?})", arg);
let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
match arg {
GenericArg::Type(ref ty) => {
// We parse const arguments as path types as we cannot distinguish them during
// parsing. We try to resolve that ambiguity by attempting resolution the type
// namespace first, and if that fails we try again in the value namespace. If
// resolution in the value namespace succeeds, we have an generic const argument on
// our hands.
if let TyKind::Path(ref qself, ref path) = ty.kind {
// We cannot disambiguate multi-segment paths right now as that requires type
// checking.
if path.segments.len() == 1 && path.segments[0].args.is_none() {
let mut check_ns = |ns| {
self.resolve_ident_in_lexical_scope(
path.segments[0].ident,
ns,
None,
path.span,
)
.is_some()
};
if !check_ns(TypeNS) && check_ns(ValueNS) {
// This must be equivalent to `visit_anon_const`, but we cannot call it
// directly due to visitor lifetimes so we have to copy-paste some code.
self.with_constant_rib(|this| {
this.smart_resolve_path(
ty.id,
qself.as_ref(),
path,
PathSource::Expr(None),
);
if let Some(ref qself) = *qself {
this.visit_ty(&qself.ty);
}
this.visit_path(path, ty.id);
});
self.diagnostic_metadata.currently_processing_generics = prev;
return;
}
}
}
self.visit_ty(ty);
}
GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
GenericArg::Const(ct) => self.visit_anon_const(ct),
}
self.diagnostic_metadata.currently_processing_generics = prev;
}
}
impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
// During late resolution we only track the module component of the parent scope,
// although it may be useful to track other components as well for diagnostics.
let graph_root = resolver.graph_root;
let parent_scope = ParentScope::module(graph_root);
let start_rib_kind = ModuleRibKind(graph_root);
LateResolutionVisitor {
r: resolver,
parent_scope,
ribs: PerNS {
value_ns: vec![Rib::new(start_rib_kind)],
type_ns: vec![Rib::new(start_rib_kind)],
macro_ns: vec![Rib::new(start_rib_kind)],
},
label_ribs: Vec::new(),
current_trait_ref: None,
diagnostic_metadata: DiagnosticMetadata::default(),
}
}
fn resolve_ident_in_lexical_scope(
&mut self,
ident: Ident,
ns: Namespace,
record_used_id: Option<NodeId>,
path_span: Span,
) -> Option<LexicalScopeBinding<'a>> {
self.r.resolve_ident_in_lexical_scope(
ident,
ns,
&self.parent_scope,
record_used_id,
path_span,
&self.ribs[ns],
)
}
fn resolve_path(
&mut self,
path: &[Segment],
opt_ns: Option<Namespace>, // `None` indicates a module path in import
record_used: bool,
path_span: Span,
crate_lint: CrateLint,
) -> PathResult<'a> {
self.r.resolve_path_with_ribs(
path,
opt_ns,
&self.parent_scope,
record_used,
path_span,
crate_lint,
Some(&self.ribs),
)
}
// AST resolution
//
// We maintain a list of value ribs and type ribs.
//
// Simultaneously, we keep track of the current position in the module
// graph in the `parent_scope.module` pointer. When we go to resolve a name in
// the value or type namespaces, we first look through all the ribs and
// then query the module graph. When we resolve a name in the module
// namespace, we can skip all the ribs (since nested modules are not
// allowed within blocks in Rust) and jump straight to the current module
// graph node.
//
// Named implementations are handled separately. When we find a method
// call, we consult the module node to find all of the implementations in
// scope. This information is lazily cached in the module node. We then
// generate a fake "implementation scope" containing all the
// implementations thus found, for compatibility with old resolve pass.
/// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
fn with_rib<T>(
&mut self,
ns: Namespace,
kind: RibKind<'a>,
work: impl FnOnce(&mut Self) -> T,
) -> T {
self.ribs[ns].push(Rib::new(kind));
let ret = work(self);
self.ribs[ns].pop();
ret
}
fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
let id = self.r.definitions.local_def_id(id);
let module = self.r.module_map.get(&id).cloned(); // clones a reference
if let Some(module) = module {
// Move down in the graph.
let orig_module = replace(&mut self.parent_scope.module, module);
self.with_rib(ValueNS, ModuleRibKind(module), |this| {
this.with_rib(TypeNS, ModuleRibKind(module), |this| {
let ret = f(this);
this.parent_scope.module = orig_module;
ret
})
})
} else {
f(self)
}
}
/// Searches the current set of local scopes for labels. Returns the first non-`None` label that
/// is returned by the given predicate function
///
/// Stops after meeting a closure.
fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
where
P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>,
{
for rib in self.label_ribs.iter().rev() {
match rib.kind {
NormalRibKind => {}
// If an invocation of this macro created `ident`, give up on `ident`
// and switch to `ident`'s source from the macro definition.
MacroDefinition(def) => {
if def == self.r.macro_def(ident.span.ctxt()) {
ident.span.remove_mark();
}
}
_ => {
// Do not resolve labels across function boundary
return None;
}
}
let r = pred(rib, ident);
if r.is_some() {
return r;
}
}
None
}
fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
debug!("resolve_adt");
self.with_current_self_item(item, |this| {
this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
let item_def_id = this.r.definitions.local_def_id(item.id).to_def_id();
this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
visit::walk_item(this, item);
});
});
});
}
fn future_proof_import(&mut self, use_tree: &UseTree) {
let segments = &use_tree.prefix.segments;
if !segments.is_empty() {
let ident = segments[0].ident;
if ident.is_path_segment_keyword() || ident.span.rust_2015() {
return;
}
let nss = match use_tree.kind {
UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
_ => &[TypeNS],
};
let report_error = |this: &Self, ns| {
let what = if ns == TypeNS { "type parameters" } else { "local variables" };
this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
};
for &ns in nss {
match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
Some(LexicalScopeBinding::Res(..)) => {
report_error(self, ns);
}
Some(LexicalScopeBinding::Item(binding)) => {
let orig_blacklisted_binding =
replace(&mut self.r.blacklisted_binding, Some(binding));
if let Some(LexicalScopeBinding::Res(..)) = self
.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
{
report_error(self, ns);
}
self.r.blacklisted_binding = orig_blacklisted_binding;
}
None => {}
}
}
} else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
for (use_tree, _) in use_trees {
self.future_proof_import(use_tree);
}
}
}
fn resolve_item(&mut self, item: &'ast Item) {
let name = item.ident.name;
debug!("(resolving item) resolving {} ({:?})", name, item.kind);
match item.kind {
ItemKind::TyAlias(_, ref generics, _, _) | ItemKind::Fn(_, _, ref generics, _) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
visit::walk_item(this, item)
});
}
ItemKind::Enum(_, ref generics)
| ItemKind::Struct(_, ref generics)
| ItemKind::Union(_, ref generics) => {
self.resolve_adt(item, generics);
}
ItemKind::Impl {
ref generics,
ref of_trait,
ref self_ty,
items: ref impl_items,
..
} => {
self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
}
ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
// Create a new rib for the trait-wide type parameters.
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
let local_def_id = this.r.definitions.local_def_id(item.id).to_def_id();
this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
let walk_assoc_item = |this: &mut Self, generics, item| {
this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
visit::walk_assoc_item(this, item, AssocCtxt::Trait)
});
};
for item in trait_items {
this.with_trait_items(trait_items, |this| {
match &item.kind {
AssocItemKind::Const(_, ty, default) => {
this.visit_ty(ty);
// Only impose the restrictions of `ConstRibKind` for an
// actual constant expression in a provided default.
if let Some(expr) = default {
this.with_constant_rib(|this| this.visit_expr(expr));
}
}
AssocItemKind::Fn(_, _, generics, _) => {
walk_assoc_item(this, generics, item);
}
AssocItemKind::TyAlias(_, generics, _, _) => {
walk_assoc_item(this, generics, item);
}
AssocItemKind::MacCall(_) => {
panic!("unexpanded macro in resolve!")
}
};
});
}
});
});
}
ItemKind::TraitAlias(ref generics, ref bounds) => {
// Create a new rib for the trait-wide type parameters.
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
let local_def_id = this.r.definitions.local_def_id(item.id).to_def_id();
this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
});
});
}
ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
self.with_scope(item.id, |this| {
visit::walk_item(this, item);
});
}
ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
debug!("resolve_item ItemKind::Const");
self.with_item_rib(HasGenericParams::No, |this| {
this.visit_ty(ty);
if let Some(expr) = expr {
this.with_constant_rib(|this| this.visit_expr(expr));
}
});
}
ItemKind::Use(ref use_tree) => {
self.future_proof_import(use_tree);
}
ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
// do nothing, these are just around to be encoded
}
ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
}
}
fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
where
F: FnOnce(&mut Self),
{
debug!("with_generic_param_rib");
let mut function_type_rib = Rib::new(kind);
let mut function_value_rib = Rib::new(kind);
let mut seen_bindings = FxHashMap::default();
// We also can't shadow bindings from the parent item
if let AssocItemRibKind = kind {
let mut add_bindings_for_ns = |ns| {
let parent_rib = self.ribs[ns]
.iter()
.rfind(|r| if let ItemRibKind(_) = r.kind { true } else { false })
.expect("associated item outside of an item");
seen_bindings
.extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
};
add_bindings_for_ns(ValueNS);
add_bindings_for_ns(TypeNS);
}
for param in &generics.params {
if let GenericParamKind::Lifetime { .. } = param.kind {
continue;
}
let def_kind = match param.kind {
GenericParamKind::Type { .. } => DefKind::TyParam,
GenericParamKind::Const { .. } => DefKind::ConstParam,
_ => unreachable!(),
};
let ident = param.ident.normalize_to_macros_2_0();
debug!("with_generic_param_rib: {}", param.id);
if seen_bindings.contains_key(&ident) {
let span = seen_bindings.get(&ident).unwrap();
let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, *span);
self.r.report_error(param.ident.span, err);
}
seen_bindings.entry(ident).or_insert(param.ident.span);
// Plain insert (no renaming).
let res = Res::Def(def_kind, self.r.definitions.local_def_id(param.id).to_def_id());
match param.kind {
GenericParamKind::Type { .. } => {
function_type_rib.bindings.insert(ident, res);
self.r.record_partial_res(param.id, PartialRes::new(res));
}
GenericParamKind::Const { .. } => {
function_value_rib.bindings.insert(ident, res);
self.r.record_partial_res(param.id, PartialRes::new(res));
}
_ => unreachable!(),
}
}
self.ribs[ValueNS].push(function_value_rib);
self.ribs[TypeNS].push(function_type_rib);
f(self);
self.ribs[TypeNS].pop();
self.ribs[ValueNS].pop();
}
fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
self.label_ribs.push(Rib::new(kind));
f(self);
self.label_ribs.pop();
}
fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
let kind = ItemRibKind(has_generic_params);
self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
}
fn with_constant_rib(&mut self, f: impl FnOnce(&mut Self)) {
debug!("with_constant_rib");
self.with_rib(ValueNS, ConstantItemRibKind, |this| {
this.with_label_rib(ConstantItemRibKind, f);
});
}
fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
// Handle nested impls (inside fn bodies)
let previous_value =
replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));