]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late.rs
Rollup merge of #73418 - doctorn:variants-intrinsic, r=kennytm
[rust.git] / src / librustc_resolve / late.rs
1 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
2 //! It runs when the crate is fully expanded and its module structure is fully built.
3 //! So it just walks through the crate and resolves all the expressions, types, etc.
4 //!
5 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
6 //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
7
8 use RibKind::*;
9
10 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
11 use crate::{Module, ModuleOrUniformRoot, NameBindingKind, ParentScope, PathResult};
12 use crate::{ResolutionError, Resolver, Segment, UseError};
13
14 use rustc_ast::ast::*;
15 use rustc_ast::ptr::P;
16 use rustc_ast::util::lev_distance::find_best_match_for_name;
17 use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
18 use rustc_ast::{unwrap_or, walk_list};
19 use rustc_ast_lowering::Resolver as ResolverAstLowering;
20 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use rustc_errors::DiagnosticId;
22 use rustc_hir::def::Namespace::{self, *};
23 use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
24 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
25 use rustc_hir::TraitCandidate;
26 use rustc_middle::{bug, span_bug};
27 use rustc_session::lint;
28 use rustc_span::def_id::LocalDefId;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::Span;
31 use smallvec::{smallvec, SmallVec};
32
33 use log::debug;
34 use rustc_span::source_map::{respan, Spanned};
35 use std::collections::BTreeSet;
36 use std::mem::{replace, take};
37
38 mod diagnostics;
39 crate mod lifetimes;
40
41 type Res = def::Res<NodeId>;
42
43 type IdentMap<T> = FxHashMap<Ident, T>;
44
45 /// Map from the name in a pattern to its binding mode.
46 type BindingMap = IdentMap<BindingInfo>;
47
48 #[derive(Copy, Clone, Debug)]
49 struct BindingInfo {
50     span: Span,
51     binding_mode: BindingMode,
52 }
53
54 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
55 enum PatternSource {
56     Match,
57     Let,
58     For,
59     FnParam,
60 }
61
62 impl PatternSource {
63     fn descr(self) -> &'static str {
64         match self {
65             PatternSource::Match => "match binding",
66             PatternSource::Let => "let binding",
67             PatternSource::For => "for binding",
68             PatternSource::FnParam => "function parameter",
69         }
70     }
71 }
72
73 /// Denotes whether the context for the set of already bound bindings is a `Product`
74 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
75 /// See those functions for more information.
76 #[derive(PartialEq)]
77 enum PatBoundCtx {
78     /// A product pattern context, e.g., `Variant(a, b)`.
79     Product,
80     /// An or-pattern context, e.g., `p_0 | ... | p_n`.
81     Or,
82 }
83
84 /// Does this the item (from the item rib scope) allow generic parameters?
85 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
86 crate enum HasGenericParams {
87     Yes,
88     No,
89 }
90
91 /// The rib kind restricts certain accesses,
92 /// e.g. to a `Res::Local` of an outer item.
93 #[derive(Copy, Clone, Debug)]
94 crate enum RibKind<'a> {
95     /// No restriction needs to be applied.
96     NormalRibKind,
97
98     /// We passed through an impl or trait and are now in one of its
99     /// methods or associated types. Allow references to ty params that impl or trait
100     /// binds. Disallow any other upvars (including other ty params that are
101     /// upvars).
102     AssocItemRibKind,
103
104     /// We passed through a function definition. Disallow upvars.
105     /// Permit only those const parameters that are specified in the function's generics.
106     FnItemRibKind,
107
108     /// We passed through an item scope. Disallow upvars.
109     ItemRibKind(HasGenericParams),
110
111     /// We're in a constant item. Can't refer to dynamic stuff.
112     ConstantItemRibKind,
113
114     /// We passed through a module.
115     ModuleRibKind(Module<'a>),
116
117     /// We passed through a `macro_rules!` statement
118     MacroDefinition(DefId),
119
120     /// All bindings in this rib are type parameters that can't be used
121     /// from the default of a type parameter because they're not declared
122     /// before said type parameter. Also see the `visit_generics` override.
123     ForwardTyParamBanRibKind,
124 }
125
126 impl RibKind<'_> {
127     // Whether this rib kind contains generic parameters, as opposed to local
128     // variables.
129     crate fn contains_params(&self) -> bool {
130         match self {
131             NormalRibKind | FnItemRibKind | ConstantItemRibKind | ModuleRibKind(_)
132             | MacroDefinition(_) => false,
133             AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
134         }
135     }
136 }
137
138 /// A single local scope.
139 ///
140 /// A rib represents a scope names can live in. Note that these appear in many places, not just
141 /// around braces. At any place where the list of accessible names (of the given namespace)
142 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
143 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
144 /// etc.
145 ///
146 /// Different [rib kinds](enum.RibKind) are transparent for different names.
147 ///
148 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
149 /// resolving, the name is looked up from inside out.
150 #[derive(Debug)]
151 crate struct Rib<'a, R = Res> {
152     pub bindings: IdentMap<R>,
153     pub kind: RibKind<'a>,
154 }
155
156 impl<'a, R> Rib<'a, R> {
157     fn new(kind: RibKind<'a>) -> Rib<'a, R> {
158         Rib { bindings: Default::default(), kind }
159     }
160 }
161
162 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
163 crate enum AliasPossibility {
164     No,
165     Maybe,
166 }
167
168 #[derive(Copy, Clone, Debug)]
169 crate enum PathSource<'a> {
170     // Type paths `Path`.
171     Type,
172     // Trait paths in bounds or impls.
173     Trait(AliasPossibility),
174     // Expression paths `path`, with optional parent context.
175     Expr(Option<&'a Expr>),
176     // Paths in path patterns `Path`.
177     Pat,
178     // Paths in struct expressions and patterns `Path { .. }`.
179     Struct,
180     // Paths in tuple struct patterns `Path(..)`.
181     TupleStruct,
182     // `m::A::B` in `<T as m::A>::B::C`.
183     TraitItem(Namespace),
184 }
185
186 impl<'a> PathSource<'a> {
187     fn namespace(self) -> Namespace {
188         match self {
189             PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
190             PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
191             PathSource::TraitItem(ns) => ns,
192         }
193     }
194
195     fn defer_to_typeck(self) -> bool {
196         match self {
197             PathSource::Type
198             | PathSource::Expr(..)
199             | PathSource::Pat
200             | PathSource::Struct
201             | PathSource::TupleStruct => true,
202             PathSource::Trait(_) | PathSource::TraitItem(..) => false,
203         }
204     }
205
206     fn descr_expected(self) -> &'static str {
207         match &self {
208             PathSource::Type => "type",
209             PathSource::Trait(_) => "trait",
210             PathSource::Pat => "unit struct, unit variant or constant",
211             PathSource::Struct => "struct, variant or union type",
212             PathSource::TupleStruct => "tuple struct or tuple variant",
213             PathSource::TraitItem(ns) => match ns {
214                 TypeNS => "associated type",
215                 ValueNS => "method or associated constant",
216                 MacroNS => bug!("associated macro"),
217             },
218             PathSource::Expr(parent) => match &parent.as_ref().map(|p| &p.kind) {
219                 // "function" here means "anything callable" rather than `DefKind::Fn`,
220                 // this is not precise but usually more helpful than just "value".
221                 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
222                     ExprKind::Path(_, path) => {
223                         let mut msg = "function";
224                         if let Some(segment) = path.segments.iter().last() {
225                             if let Some(c) = segment.ident.to_string().chars().next() {
226                                 if c.is_uppercase() {
227                                     msg = "function, tuple struct or tuple variant";
228                                 }
229                             }
230                         }
231                         msg
232                     }
233                     _ => "function",
234                 },
235                 _ => "value",
236             },
237         }
238     }
239
240     fn is_call(self) -> bool {
241         match self {
242             PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
243             _ => false,
244         }
245     }
246
247     crate fn is_expected(self, res: Res) -> bool {
248         match self {
249             PathSource::Type => match res {
250                 Res::Def(
251                     DefKind::Struct
252                     | DefKind::Union
253                     | DefKind::Enum
254                     | DefKind::Trait
255                     | DefKind::TraitAlias
256                     | DefKind::TyAlias
257                     | DefKind::AssocTy
258                     | DefKind::TyParam
259                     | DefKind::OpaqueTy
260                     | DefKind::ForeignTy,
261                     _,
262                 )
263                 | Res::PrimTy(..)
264                 | Res::SelfTy(..) => true,
265                 _ => false,
266             },
267             PathSource::Trait(AliasPossibility::No) => match res {
268                 Res::Def(DefKind::Trait, _) => true,
269                 _ => false,
270             },
271             PathSource::Trait(AliasPossibility::Maybe) => match res {
272                 Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
273                 _ => false,
274             },
275             PathSource::Expr(..) => match res {
276                 Res::Def(
277                     DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
278                     | DefKind::Const
279                     | DefKind::Static
280                     | DefKind::Fn
281                     | DefKind::AssocFn
282                     | DefKind::AssocConst
283                     | DefKind::ConstParam,
284                     _,
285                 )
286                 | Res::Local(..)
287                 | Res::SelfCtor(..) => true,
288                 _ => false,
289             },
290             PathSource::Pat => match res {
291                 Res::Def(
292                     DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
293                     _,
294                 )
295                 | Res::SelfCtor(..) => true,
296                 _ => false,
297             },
298             PathSource::TupleStruct => match res {
299                 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
300                 _ => false,
301             },
302             PathSource::Struct => match res {
303                 Res::Def(
304                     DefKind::Struct
305                     | DefKind::Union
306                     | DefKind::Variant
307                     | DefKind::TyAlias
308                     | DefKind::AssocTy,
309                     _,
310                 )
311                 | Res::SelfTy(..) => true,
312                 _ => false,
313             },
314             PathSource::TraitItem(ns) => match res {
315                 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
316                 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
317                 _ => false,
318             },
319         }
320     }
321
322     fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
323         use rustc_errors::error_code;
324         match (self, has_unexpected_resolution) {
325             (PathSource::Trait(_), true) => error_code!(E0404),
326             (PathSource::Trait(_), false) => error_code!(E0405),
327             (PathSource::Type, true) => error_code!(E0573),
328             (PathSource::Type, false) => error_code!(E0412),
329             (PathSource::Struct, true) => error_code!(E0574),
330             (PathSource::Struct, false) => error_code!(E0422),
331             (PathSource::Expr(..), true) => error_code!(E0423),
332             (PathSource::Expr(..), false) => error_code!(E0425),
333             (PathSource::Pat | PathSource::TupleStruct, true) => error_code!(E0532),
334             (PathSource::Pat | PathSource::TupleStruct, false) => error_code!(E0531),
335             (PathSource::TraitItem(..), true) => error_code!(E0575),
336             (PathSource::TraitItem(..), false) => error_code!(E0576),
337         }
338     }
339 }
340
341 #[derive(Default)]
342 struct DiagnosticMetadata<'ast> {
343     /// The current trait's associated types' ident, used for diagnostic suggestions.
344     current_trait_assoc_types: Vec<Ident>,
345
346     /// The current self type if inside an impl (used for better errors).
347     current_self_type: Option<Ty>,
348
349     /// The current self item if inside an ADT (used for better errors).
350     current_self_item: Option<NodeId>,
351
352     /// The current trait (used to suggest).
353     current_item: Option<&'ast Item>,
354
355     /// When processing generics and encountering a type not found, suggest introducing a type
356     /// param.
357     currently_processing_generics: bool,
358
359     /// The current enclosing function (used for better errors).
360     current_function: Option<(FnKind<'ast>, Span)>,
361
362     /// A list of labels as of yet unused. Labels will be removed from this map when
363     /// they are used (in a `break` or `continue` statement)
364     unused_labels: FxHashMap<NodeId, Span>,
365
366     /// Only used for better errors on `fn(): fn()`.
367     current_type_ascription: Vec<Span>,
368
369     /// Only used for better errors on `let <pat>: <expr, not type>;`.
370     current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
371 }
372
373 struct LateResolutionVisitor<'a, 'b, 'ast> {
374     r: &'b mut Resolver<'a>,
375
376     /// The module that represents the current item scope.
377     parent_scope: ParentScope<'a>,
378
379     /// The current set of local scopes for types and values.
380     /// FIXME #4948: Reuse ribs to avoid allocation.
381     ribs: PerNS<Vec<Rib<'a>>>,
382
383     /// The current set of local scopes, for labels.
384     label_ribs: Vec<Rib<'a, NodeId>>,
385
386     /// The trait that the current context can refer to.
387     current_trait_ref: Option<(Module<'a>, TraitRef)>,
388
389     /// Fields used to add information to diagnostic errors.
390     diagnostic_metadata: DiagnosticMetadata<'ast>,
391 }
392
393 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
394 impl<'a, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
395     fn visit_item(&mut self, item: &'ast Item) {
396         let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
397         self.resolve_item(item);
398         self.diagnostic_metadata.current_item = prev;
399     }
400     fn visit_arm(&mut self, arm: &'ast Arm) {
401         self.resolve_arm(arm);
402     }
403     fn visit_block(&mut self, block: &'ast Block) {
404         self.resolve_block(block);
405     }
406     fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
407         debug!("visit_anon_const {:?}", constant);
408         self.with_constant_rib(|this| {
409             visit::walk_anon_const(this, constant);
410         });
411     }
412     fn visit_expr(&mut self, expr: &'ast Expr) {
413         self.resolve_expr(expr, None);
414     }
415     fn visit_local(&mut self, local: &'ast Local) {
416         let local_spans = match local.pat.kind {
417             // We check for this to avoid tuple struct fields.
418             PatKind::Wild => None,
419             _ => Some((
420                 local.pat.span,
421                 local.ty.as_ref().map(|ty| ty.span),
422                 local.init.as_ref().map(|init| init.span),
423             )),
424         };
425         let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
426         self.resolve_local(local);
427         self.diagnostic_metadata.current_let_binding = original;
428     }
429     fn visit_ty(&mut self, ty: &'ast Ty) {
430         match ty.kind {
431             TyKind::Path(ref qself, ref path) => {
432                 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
433             }
434             TyKind::ImplicitSelf => {
435                 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
436                 let res = self
437                     .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
438                     .map_or(Res::Err, |d| d.res());
439                 self.r.record_partial_res(ty.id, PartialRes::new(res));
440             }
441             _ => (),
442         }
443         visit::walk_ty(self, ty);
444     }
445     fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
446         self.smart_resolve_path(
447             tref.trait_ref.ref_id,
448             None,
449             &tref.trait_ref.path,
450             PathSource::Trait(AliasPossibility::Maybe),
451         );
452         visit::walk_poly_trait_ref(self, tref, m);
453     }
454     fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
455         match foreign_item.kind {
456             ForeignItemKind::Fn(_, _, ref generics, _)
457             | ForeignItemKind::TyAlias(_, ref generics, ..) => {
458                 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
459                     visit::walk_foreign_item(this, foreign_item);
460                 });
461             }
462             ForeignItemKind::Static(..) => {
463                 self.with_item_rib(HasGenericParams::No, |this| {
464                     visit::walk_foreign_item(this, foreign_item);
465                 });
466             }
467             ForeignItemKind::MacCall(..) => {
468                 visit::walk_foreign_item(self, foreign_item);
469             }
470         }
471     }
472     fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) {
473         let rib_kind = match fn_kind {
474             // Bail if there's no body.
475             FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp),
476             FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind,
477             FnKind::Fn(FnCtxt::Assoc(_), ..) | FnKind::Closure(..) => NormalRibKind,
478         };
479         let previous_value =
480             replace(&mut self.diagnostic_metadata.current_function, Some((fn_kind, sp)));
481         debug!("(resolving function) entering function");
482         let declaration = fn_kind.decl();
483
484         // Create a value rib for the function.
485         self.with_rib(ValueNS, rib_kind, |this| {
486             // Create a label rib for the function.
487             this.with_label_rib(rib_kind, |this| {
488                 // Add each argument to the rib.
489                 this.resolve_params(&declaration.inputs);
490
491                 visit::walk_fn_ret_ty(this, &declaration.output);
492
493                 // Resolve the function body, potentially inside the body of an async closure
494                 match fn_kind {
495                     FnKind::Fn(.., body) => walk_list!(this, visit_block, body),
496                     FnKind::Closure(_, body) => this.visit_expr(body),
497                 };
498
499                 debug!("(resolving function) leaving function");
500             })
501         });
502         self.diagnostic_metadata.current_function = previous_value;
503     }
504
505     fn visit_generics(&mut self, generics: &'ast Generics) {
506         // For type parameter defaults, we have to ban access
507         // to following type parameters, as the InternalSubsts can only
508         // provide previous type parameters as they're built. We
509         // put all the parameters on the ban list and then remove
510         // them one by one as they are processed and become available.
511         let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
512         let mut found_default = false;
513         default_ban_rib.bindings.extend(generics.params.iter().filter_map(
514             |param| match param.kind {
515                 GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
516                 GenericParamKind::Type { ref default, .. } => {
517                     found_default |= default.is_some();
518                     found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
519                 }
520             },
521         ));
522
523         // rust-lang/rust#61631: The type `Self` is essentially
524         // another type parameter. For ADTs, we consider it
525         // well-defined only after all of the ADT type parameters have
526         // been provided. Therefore, we do not allow use of `Self`
527         // anywhere in ADT type parameter defaults.
528         //
529         // (We however cannot ban `Self` for defaults on *all* generic
530         // lists; e.g. trait generics can usefully refer to `Self`,
531         // such as in the case of `trait Add<Rhs = Self>`.)
532         if self.diagnostic_metadata.current_self_item.is_some() {
533             // (`Some` if + only if we are in ADT's generics.)
534             default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
535         }
536
537         for param in &generics.params {
538             match param.kind {
539                 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
540                 GenericParamKind::Type { ref default, .. } => {
541                     for bound in &param.bounds {
542                         self.visit_param_bound(bound);
543                     }
544
545                     if let Some(ref ty) = default {
546                         self.ribs[TypeNS].push(default_ban_rib);
547                         self.visit_ty(ty);
548                         default_ban_rib = self.ribs[TypeNS].pop().unwrap();
549                     }
550
551                     // Allow all following defaults to refer to this type parameter.
552                     default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
553                 }
554                 GenericParamKind::Const { ref ty } => {
555                     for bound in &param.bounds {
556                         self.visit_param_bound(bound);
557                     }
558                     self.visit_ty(ty);
559                 }
560             }
561         }
562         for p in &generics.where_clause.predicates {
563             self.visit_where_predicate(p);
564         }
565     }
566
567     fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
568         debug!("visit_generic_arg({:?})", arg);
569         let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
570         match arg {
571             GenericArg::Type(ref ty) => {
572                 // We parse const arguments as path types as we cannot distinguish them during
573                 // parsing. We try to resolve that ambiguity by attempting resolution the type
574                 // namespace first, and if that fails we try again in the value namespace. If
575                 // resolution in the value namespace succeeds, we have an generic const argument on
576                 // our hands.
577                 if let TyKind::Path(ref qself, ref path) = ty.kind {
578                     // We cannot disambiguate multi-segment paths right now as that requires type
579                     // checking.
580                     if path.segments.len() == 1 && path.segments[0].args.is_none() {
581                         let mut check_ns = |ns| {
582                             self.resolve_ident_in_lexical_scope(
583                                 path.segments[0].ident,
584                                 ns,
585                                 None,
586                                 path.span,
587                             )
588                             .is_some()
589                         };
590                         if !check_ns(TypeNS) && check_ns(ValueNS) {
591                             // This must be equivalent to `visit_anon_const`, but we cannot call it
592                             // directly due to visitor lifetimes so we have to copy-paste some code.
593                             self.with_constant_rib(|this| {
594                                 this.smart_resolve_path(
595                                     ty.id,
596                                     qself.as_ref(),
597                                     path,
598                                     PathSource::Expr(None),
599                                 );
600
601                                 if let Some(ref qself) = *qself {
602                                     this.visit_ty(&qself.ty);
603                                 }
604                                 this.visit_path(path, ty.id);
605                             });
606
607                             self.diagnostic_metadata.currently_processing_generics = prev;
608                             return;
609                         }
610                     }
611                 }
612
613                 self.visit_ty(ty);
614             }
615             GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
616             GenericArg::Const(ct) => self.visit_anon_const(ct),
617         }
618         self.diagnostic_metadata.currently_processing_generics = prev;
619     }
620 }
621
622 impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
623     fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
624         // During late resolution we only track the module component of the parent scope,
625         // although it may be useful to track other components as well for diagnostics.
626         let graph_root = resolver.graph_root;
627         let parent_scope = ParentScope::module(graph_root);
628         let start_rib_kind = ModuleRibKind(graph_root);
629         LateResolutionVisitor {
630             r: resolver,
631             parent_scope,
632             ribs: PerNS {
633                 value_ns: vec![Rib::new(start_rib_kind)],
634                 type_ns: vec![Rib::new(start_rib_kind)],
635                 macro_ns: vec![Rib::new(start_rib_kind)],
636             },
637             label_ribs: Vec::new(),
638             current_trait_ref: None,
639             diagnostic_metadata: DiagnosticMetadata::default(),
640         }
641     }
642
643     fn resolve_ident_in_lexical_scope(
644         &mut self,
645         ident: Ident,
646         ns: Namespace,
647         record_used_id: Option<NodeId>,
648         path_span: Span,
649     ) -> Option<LexicalScopeBinding<'a>> {
650         self.r.resolve_ident_in_lexical_scope(
651             ident,
652             ns,
653             &self.parent_scope,
654             record_used_id,
655             path_span,
656             &self.ribs[ns],
657         )
658     }
659
660     fn resolve_path(
661         &mut self,
662         path: &[Segment],
663         opt_ns: Option<Namespace>, // `None` indicates a module path in import
664         record_used: bool,
665         path_span: Span,
666         crate_lint: CrateLint,
667     ) -> PathResult<'a> {
668         self.r.resolve_path_with_ribs(
669             path,
670             opt_ns,
671             &self.parent_scope,
672             record_used,
673             path_span,
674             crate_lint,
675             Some(&self.ribs),
676         )
677     }
678
679     // AST resolution
680     //
681     // We maintain a list of value ribs and type ribs.
682     //
683     // Simultaneously, we keep track of the current position in the module
684     // graph in the `parent_scope.module` pointer. When we go to resolve a name in
685     // the value or type namespaces, we first look through all the ribs and
686     // then query the module graph. When we resolve a name in the module
687     // namespace, we can skip all the ribs (since nested modules are not
688     // allowed within blocks in Rust) and jump straight to the current module
689     // graph node.
690     //
691     // Named implementations are handled separately. When we find a method
692     // call, we consult the module node to find all of the implementations in
693     // scope. This information is lazily cached in the module node. We then
694     // generate a fake "implementation scope" containing all the
695     // implementations thus found, for compatibility with old resolve pass.
696
697     /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
698     fn with_rib<T>(
699         &mut self,
700         ns: Namespace,
701         kind: RibKind<'a>,
702         work: impl FnOnce(&mut Self) -> T,
703     ) -> T {
704         self.ribs[ns].push(Rib::new(kind));
705         let ret = work(self);
706         self.ribs[ns].pop();
707         ret
708     }
709
710     fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
711         let id = self.r.local_def_id(id);
712         let module = self.r.module_map.get(&id).cloned(); // clones a reference
713         if let Some(module) = module {
714             // Move down in the graph.
715             let orig_module = replace(&mut self.parent_scope.module, module);
716             self.with_rib(ValueNS, ModuleRibKind(module), |this| {
717                 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
718                     let ret = f(this);
719                     this.parent_scope.module = orig_module;
720                     ret
721                 })
722             })
723         } else {
724             f(self)
725         }
726     }
727
728     /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
729     /// is returned by the given predicate function
730     ///
731     /// Stops after meeting a closure.
732     fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
733     where
734         P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>,
735     {
736         for rib in self.label_ribs.iter().rev() {
737             match rib.kind {
738                 NormalRibKind => {}
739                 // If an invocation of this macro created `ident`, give up on `ident`
740                 // and switch to `ident`'s source from the macro definition.
741                 MacroDefinition(def) => {
742                     if def == self.r.macro_def(ident.span.ctxt()) {
743                         ident.span.remove_mark();
744                     }
745                 }
746                 _ => {
747                     // Do not resolve labels across function boundary
748                     return None;
749                 }
750             }
751             let r = pred(rib, ident);
752             if r.is_some() {
753                 return r;
754             }
755         }
756         None
757     }
758
759     fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
760         debug!("resolve_adt");
761         self.with_current_self_item(item, |this| {
762             this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
763                 let item_def_id = this.r.local_def_id(item.id).to_def_id();
764                 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
765                     visit::walk_item(this, item);
766                 });
767             });
768         });
769     }
770
771     fn future_proof_import(&mut self, use_tree: &UseTree) {
772         let segments = &use_tree.prefix.segments;
773         if !segments.is_empty() {
774             let ident = segments[0].ident;
775             if ident.is_path_segment_keyword() || ident.span.rust_2015() {
776                 return;
777             }
778
779             let nss = match use_tree.kind {
780                 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
781                 _ => &[TypeNS],
782             };
783             let report_error = |this: &Self, ns| {
784                 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
785                 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
786             };
787
788             for &ns in nss {
789                 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
790                     Some(LexicalScopeBinding::Res(..)) => {
791                         report_error(self, ns);
792                     }
793                     Some(LexicalScopeBinding::Item(binding)) => {
794                         let orig_blacklisted_binding =
795                             replace(&mut self.r.blacklisted_binding, Some(binding));
796                         if let Some(LexicalScopeBinding::Res(..)) = self
797                             .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
798                         {
799                             report_error(self, ns);
800                         }
801                         self.r.blacklisted_binding = orig_blacklisted_binding;
802                     }
803                     None => {}
804                 }
805             }
806         } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
807             for (use_tree, _) in use_trees {
808                 self.future_proof_import(use_tree);
809             }
810         }
811     }
812
813     fn resolve_item(&mut self, item: &'ast Item) {
814         let name = item.ident.name;
815         debug!("(resolving item) resolving {} ({:?})", name, item.kind);
816
817         match item.kind {
818             ItemKind::TyAlias(_, ref generics, _, _) | ItemKind::Fn(_, _, ref generics, _) => {
819                 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
820                     visit::walk_item(this, item)
821                 });
822             }
823
824             ItemKind::Enum(_, ref generics)
825             | ItemKind::Struct(_, ref generics)
826             | ItemKind::Union(_, ref generics) => {
827                 self.resolve_adt(item, generics);
828             }
829
830             ItemKind::Impl {
831                 ref generics,
832                 ref of_trait,
833                 ref self_ty,
834                 items: ref impl_items,
835                 ..
836             } => {
837                 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
838             }
839
840             ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
841                 // Create a new rib for the trait-wide type parameters.
842                 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
843                     let local_def_id = this.r.local_def_id(item.id).to_def_id();
844                     this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
845                         this.visit_generics(generics);
846                         walk_list!(this, visit_param_bound, bounds);
847
848                         let walk_assoc_item = |this: &mut Self, generics, item| {
849                             this.with_generic_param_rib(generics, AssocItemRibKind, |this| {
850                                 visit::walk_assoc_item(this, item, AssocCtxt::Trait)
851                             });
852                         };
853
854                         for item in trait_items {
855                             this.with_trait_items(trait_items, |this| {
856                                 match &item.kind {
857                                     AssocItemKind::Const(_, ty, default) => {
858                                         this.visit_ty(ty);
859                                         // Only impose the restrictions of `ConstRibKind` for an
860                                         // actual constant expression in a provided default.
861                                         if let Some(expr) = default {
862                                             this.with_constant_rib(|this| this.visit_expr(expr));
863                                         }
864                                     }
865                                     AssocItemKind::Fn(_, _, generics, _) => {
866                                         walk_assoc_item(this, generics, item);
867                                     }
868                                     AssocItemKind::TyAlias(_, generics, _, _) => {
869                                         walk_assoc_item(this, generics, item);
870                                     }
871                                     AssocItemKind::MacCall(_) => {
872                                         panic!("unexpanded macro in resolve!")
873                                     }
874                                 };
875                             });
876                         }
877                     });
878                 });
879             }
880
881             ItemKind::TraitAlias(ref generics, ref bounds) => {
882                 // Create a new rib for the trait-wide type parameters.
883                 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
884                     let local_def_id = this.r.local_def_id(item.id).to_def_id();
885                     this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
886                         this.visit_generics(generics);
887                         walk_list!(this, visit_param_bound, bounds);
888                     });
889                 });
890             }
891
892             ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
893                 self.with_scope(item.id, |this| {
894                     visit::walk_item(this, item);
895                 });
896             }
897
898             ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
899                 debug!("resolve_item ItemKind::Const");
900                 self.with_item_rib(HasGenericParams::No, |this| {
901                     this.visit_ty(ty);
902                     if let Some(expr) = expr {
903                         this.with_constant_rib(|this| this.visit_expr(expr));
904                     }
905                 });
906             }
907
908             ItemKind::Use(ref use_tree) => {
909                 self.future_proof_import(use_tree);
910             }
911
912             ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
913                 // do nothing, these are just around to be encoded
914             }
915
916             ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
917         }
918     }
919
920     fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
921     where
922         F: FnOnce(&mut Self),
923     {
924         debug!("with_generic_param_rib");
925         let mut function_type_rib = Rib::new(kind);
926         let mut function_value_rib = Rib::new(kind);
927         let mut seen_bindings = FxHashMap::default();
928
929         // We also can't shadow bindings from the parent item
930         if let AssocItemRibKind = kind {
931             let mut add_bindings_for_ns = |ns| {
932                 let parent_rib = self.ribs[ns]
933                     .iter()
934                     .rfind(|r| if let ItemRibKind(_) = r.kind { true } else { false })
935                     .expect("associated item outside of an item");
936                 seen_bindings
937                     .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
938             };
939             add_bindings_for_ns(ValueNS);
940             add_bindings_for_ns(TypeNS);
941         }
942
943         for param in &generics.params {
944             if let GenericParamKind::Lifetime { .. } = param.kind {
945                 continue;
946             }
947
948             let def_kind = match param.kind {
949                 GenericParamKind::Type { .. } => DefKind::TyParam,
950                 GenericParamKind::Const { .. } => DefKind::ConstParam,
951                 _ => unreachable!(),
952             };
953
954             let ident = param.ident.normalize_to_macros_2_0();
955             debug!("with_generic_param_rib: {}", param.id);
956
957             if seen_bindings.contains_key(&ident) {
958                 let span = seen_bindings.get(&ident).unwrap();
959                 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, *span);
960                 self.r.report_error(param.ident.span, err);
961             }
962             seen_bindings.entry(ident).or_insert(param.ident.span);
963
964             // Plain insert (no renaming).
965             let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id());
966
967             match param.kind {
968                 GenericParamKind::Type { .. } => {
969                     function_type_rib.bindings.insert(ident, res);
970                     self.r.record_partial_res(param.id, PartialRes::new(res));
971                 }
972                 GenericParamKind::Const { .. } => {
973                     function_value_rib.bindings.insert(ident, res);
974                     self.r.record_partial_res(param.id, PartialRes::new(res));
975                 }
976                 _ => unreachable!(),
977             }
978         }
979
980         self.ribs[ValueNS].push(function_value_rib);
981         self.ribs[TypeNS].push(function_type_rib);
982
983         f(self);
984
985         self.ribs[TypeNS].pop();
986         self.ribs[ValueNS].pop();
987     }
988
989     fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
990         self.label_ribs.push(Rib::new(kind));
991         f(self);
992         self.label_ribs.pop();
993     }
994
995     fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
996         let kind = ItemRibKind(has_generic_params);
997         self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
998     }
999
1000     fn with_constant_rib(&mut self, f: impl FnOnce(&mut Self)) {
1001         debug!("with_constant_rib");
1002         self.with_rib(ValueNS, ConstantItemRibKind, |this| {
1003             this.with_label_rib(ConstantItemRibKind, f);
1004         });
1005     }
1006
1007     fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
1008         // Handle nested impls (inside fn bodies)
1009         let previous_value =
1010             replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
1011         let result = f(self);
1012         self.diagnostic_metadata.current_self_type = previous_value;
1013         result
1014     }
1015
1016     fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
1017         let previous_value =
1018             replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
1019         let result = f(self);
1020         self.diagnostic_metadata.current_self_item = previous_value;
1021         result
1022     }
1023
1024     /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
1025     fn with_trait_items<T>(
1026         &mut self,
1027         trait_items: &Vec<P<AssocItem>>,
1028         f: impl FnOnce(&mut Self) -> T,
1029     ) -> T {
1030         let trait_assoc_types = replace(
1031             &mut self.diagnostic_metadata.current_trait_assoc_types,
1032             trait_items
1033                 .iter()
1034                 .filter_map(|item| match &item.kind {
1035                     AssocItemKind::TyAlias(_, _, bounds, _) if bounds.is_empty() => {
1036                         Some(item.ident)
1037                     }
1038                     _ => None,
1039                 })
1040                 .collect(),
1041         );
1042         let result = f(self);
1043         self.diagnostic_metadata.current_trait_assoc_types = trait_assoc_types;
1044         result
1045     }
1046
1047     /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
1048     fn with_optional_trait_ref<T>(
1049         &mut self,
1050         opt_trait_ref: Option<&TraitRef>,
1051         f: impl FnOnce(&mut Self, Option<DefId>) -> T,
1052     ) -> T {
1053         let mut new_val = None;
1054         let mut new_id = None;
1055         if let Some(trait_ref) = opt_trait_ref {
1056             let path: Vec<_> = Segment::from_path(&trait_ref.path);
1057             let res = self.smart_resolve_path_fragment(
1058                 trait_ref.ref_id,
1059                 None,
1060                 &path,
1061                 trait_ref.path.span,
1062                 PathSource::Trait(AliasPossibility::No),
1063                 CrateLint::SimplePath(trait_ref.ref_id),
1064             );
1065             let res = res.base_res();
1066             if res != Res::Err {
1067                 new_id = Some(res.def_id());
1068                 let span = trait_ref.path.span;
1069                 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
1070                     &path,
1071                     Some(TypeNS),
1072                     false,
1073                     span,
1074                     CrateLint::SimplePath(trait_ref.ref_id),
1075                 ) {
1076                     new_val = Some((module, trait_ref.clone()));
1077                 }
1078             }
1079         }
1080         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1081         let result = f(self, new_id);
1082         self.current_trait_ref = original_trait_ref;
1083         result
1084     }
1085
1086     fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
1087         let mut self_type_rib = Rib::new(NormalRibKind);
1088
1089         // Plain insert (no renaming, since types are not currently hygienic)
1090         self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1091         self.ribs[ns].push(self_type_rib);
1092         f(self);
1093         self.ribs[ns].pop();
1094     }
1095
1096     fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
1097         self.with_self_rib_ns(TypeNS, self_res, f)
1098     }
1099
1100     fn resolve_implementation(
1101         &mut self,
1102         generics: &'ast Generics,
1103         opt_trait_reference: &'ast Option<TraitRef>,
1104         self_type: &'ast Ty,
1105         item_id: NodeId,
1106         impl_items: &'ast [P<AssocItem>],
1107     ) {
1108         debug!("resolve_implementation");
1109         // If applicable, create a rib for the type parameters.
1110         self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1111             // Dummy self type for better errors if `Self` is used in the trait path.
1112             this.with_self_rib(Res::SelfTy(None, None), |this| {
1113                 // Resolve the trait reference, if necessary.
1114                 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1115                     let item_def_id = this.r.local_def_id(item_id).to_def_id();
1116                     this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1117                         if let Some(trait_ref) = opt_trait_reference.as_ref() {
1118                             // Resolve type arguments in the trait path.
1119                             visit::walk_trait_ref(this, trait_ref);
1120                         }
1121                         // Resolve the self type.
1122                         this.visit_ty(self_type);
1123                         // Resolve the generic parameters.
1124                         this.visit_generics(generics);
1125                         // Resolve the items within the impl.
1126                         this.with_current_self_type(self_type, |this| {
1127                             this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1128                                 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1129                                 for item in impl_items {
1130                                     use crate::ResolutionError::*;
1131                                     match &item.kind {
1132                                         AssocItemKind::Const(..) => {
1133                                             debug!("resolve_implementation AssocItemKind::Const",);
1134                                             // If this is a trait impl, ensure the const
1135                                             // exists in trait
1136                                             this.check_trait_item(
1137                                                 item.ident,
1138                                                 ValueNS,
1139                                                 item.span,
1140                                                 |n, s| ConstNotMemberOfTrait(n, s),
1141                                             );
1142
1143                                             this.with_constant_rib(|this| {
1144                                                 visit::walk_assoc_item(this, item, AssocCtxt::Impl)
1145                                             });
1146                                         }
1147                                         AssocItemKind::Fn(_, _, generics, _) => {
1148                                             // We also need a new scope for the impl item type parameters.
1149                                             this.with_generic_param_rib(
1150                                                 generics,
1151                                                 AssocItemRibKind,
1152                                                 |this| {
1153                                                     // If this is a trait impl, ensure the method
1154                                                     // exists in trait
1155                                                     this.check_trait_item(
1156                                                         item.ident,
1157                                                         ValueNS,
1158                                                         item.span,
1159                                                         |n, s| MethodNotMemberOfTrait(n, s),
1160                                                     );
1161
1162                                                     visit::walk_assoc_item(
1163                                                         this,
1164                                                         item,
1165                                                         AssocCtxt::Impl,
1166                                                     )
1167                                                 },
1168                                             );
1169                                         }
1170                                         AssocItemKind::TyAlias(_, generics, _, _) => {
1171                                             // We also need a new scope for the impl item type parameters.
1172                                             this.with_generic_param_rib(
1173                                                 generics,
1174                                                 AssocItemRibKind,
1175                                                 |this| {
1176                                                     // If this is a trait impl, ensure the type
1177                                                     // exists in trait
1178                                                     this.check_trait_item(
1179                                                         item.ident,
1180                                                         TypeNS,
1181                                                         item.span,
1182                                                         |n, s| TypeNotMemberOfTrait(n, s),
1183                                                     );
1184
1185                                                     visit::walk_assoc_item(
1186                                                         this,
1187                                                         item,
1188                                                         AssocCtxt::Impl,
1189                                                     )
1190                                                 },
1191                                             );
1192                                         }
1193                                         AssocItemKind::MacCall(_) => {
1194                                             panic!("unexpanded macro in resolve!")
1195                                         }
1196                                     }
1197                                 }
1198                             });
1199                         });
1200                     });
1201                 });
1202             });
1203         });
1204     }
1205
1206     fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1207     where
1208         F: FnOnce(Symbol, &str) -> ResolutionError<'_>,
1209     {
1210         // If there is a TraitRef in scope for an impl, then the method must be in the
1211         // trait.
1212         if let Some((module, _)) = self.current_trait_ref {
1213             if self
1214                 .r
1215                 .resolve_ident_in_module(
1216                     ModuleOrUniformRoot::Module(module),
1217                     ident,
1218                     ns,
1219                     &self.parent_scope,
1220                     false,
1221                     span,
1222                 )
1223                 .is_err()
1224             {
1225                 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1226                 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1227             }
1228         }
1229     }
1230
1231     fn resolve_params(&mut self, params: &'ast [Param]) {
1232         let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1233         for Param { pat, ty, .. } in params {
1234             self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1235             self.visit_ty(ty);
1236             debug!("(resolving function / closure) recorded parameter");
1237         }
1238     }
1239
1240     fn resolve_local(&mut self, local: &'ast Local) {
1241         // Resolve the type.
1242         walk_list!(self, visit_ty, &local.ty);
1243
1244         // Resolve the initializer.
1245         walk_list!(self, visit_expr, &local.init);
1246
1247         // Resolve the pattern.
1248         self.resolve_pattern_top(&local.pat, PatternSource::Let);
1249     }
1250
1251     /// build a map from pattern identifiers to binding-info's.
1252     /// this is done hygienically. This could arise for a macro
1253     /// that expands into an or-pattern where one 'x' was from the
1254     /// user and one 'x' came from the macro.
1255     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1256         let mut binding_map = FxHashMap::default();
1257
1258         pat.walk(&mut |pat| {
1259             match pat.kind {
1260                 PatKind::Ident(binding_mode, ident, ref sub_pat)
1261                     if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
1262                 {
1263                     binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
1264                 }
1265                 PatKind::Or(ref ps) => {
1266                     // Check the consistency of this or-pattern and
1267                     // then add all bindings to the larger map.
1268                     for bm in self.check_consistent_bindings(ps) {
1269                         binding_map.extend(bm);
1270                     }
1271                     return false;
1272                 }
1273                 _ => {}
1274             }
1275
1276             true
1277         });
1278
1279         binding_map
1280     }
1281
1282     fn is_base_res_local(&self, nid: NodeId) -> bool {
1283         match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) {
1284             Some(Res::Local(..)) => true,
1285             _ => false,
1286         }
1287     }
1288
1289     /// Checks that all of the arms in an or-pattern have exactly the
1290     /// same set of bindings, with the same binding modes for each.
1291     fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
1292         let mut missing_vars = FxHashMap::default();
1293         let mut inconsistent_vars = FxHashMap::default();
1294
1295         // 1) Compute the binding maps of all arms.
1296         let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
1297
1298         // 2) Record any missing bindings or binding mode inconsistencies.
1299         for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
1300             // Check against all arms except for the same pattern which is always self-consistent.
1301             let inners = pats
1302                 .iter()
1303                 .enumerate()
1304                 .filter(|(_, pat)| pat.id != pat_outer.id)
1305                 .flat_map(|(idx, _)| maps[idx].iter())
1306                 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
1307
1308             for (name, info, &binding_inner) in inners {
1309                 match info {
1310                     None => {
1311                         // The inner binding is missing in the outer.
1312                         let binding_error =
1313                             missing_vars.entry(name).or_insert_with(|| BindingError {
1314                                 name,
1315                                 origin: BTreeSet::new(),
1316                                 target: BTreeSet::new(),
1317                                 could_be_path: name.as_str().starts_with(char::is_uppercase),
1318                             });
1319                         binding_error.origin.insert(binding_inner.span);
1320                         binding_error.target.insert(pat_outer.span);
1321                     }
1322                     Some(binding_outer) => {
1323                         if binding_outer.binding_mode != binding_inner.binding_mode {
1324                             // The binding modes in the outer and inner bindings differ.
1325                             inconsistent_vars
1326                                 .entry(name)
1327                                 .or_insert((binding_inner.span, binding_outer.span));
1328                         }
1329                     }
1330                 }
1331             }
1332         }
1333
1334         // 3) Report all missing variables we found.
1335         let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1336         missing_vars.sort_by_key(|(sym, _err)| sym.as_str());
1337
1338         for (name, mut v) in missing_vars {
1339             if inconsistent_vars.contains_key(name) {
1340                 v.could_be_path = false;
1341             }
1342             self.r.report_error(
1343                 *v.origin.iter().next().unwrap(),
1344                 ResolutionError::VariableNotBoundInPattern(v),
1345             );
1346         }
1347
1348         // 4) Report all inconsistencies in binding modes we found.
1349         let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1350         inconsistent_vars.sort();
1351         for (name, v) in inconsistent_vars {
1352             self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1353         }
1354
1355         // 5) Finally bubble up all the binding maps.
1356         maps
1357     }
1358
1359     /// Check the consistency of the outermost or-patterns.
1360     fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
1361         pat.walk(&mut |pat| match pat.kind {
1362             PatKind::Or(ref ps) => {
1363                 self.check_consistent_bindings(ps);
1364                 false
1365             }
1366             _ => true,
1367         })
1368     }
1369
1370     fn resolve_arm(&mut self, arm: &'ast Arm) {
1371         self.with_rib(ValueNS, NormalRibKind, |this| {
1372             this.resolve_pattern_top(&arm.pat, PatternSource::Match);
1373             walk_list!(this, visit_expr, &arm.guard);
1374             this.visit_expr(&arm.body);
1375         });
1376     }
1377
1378     /// Arising from `source`, resolve a top level pattern.
1379     fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
1380         let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1381         self.resolve_pattern(pat, pat_src, &mut bindings);
1382     }
1383
1384     fn resolve_pattern(
1385         &mut self,
1386         pat: &'ast Pat,
1387         pat_src: PatternSource,
1388         bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1389     ) {
1390         self.resolve_pattern_inner(pat, pat_src, bindings);
1391         // This has to happen *after* we determine which pat_idents are variants:
1392         self.check_consistent_bindings_top(pat);
1393         visit::walk_pat(self, pat);
1394     }
1395
1396     /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
1397     ///
1398     /// ### `bindings`
1399     ///
1400     /// A stack of sets of bindings accumulated.
1401     ///
1402     /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
1403     /// be interpreted as re-binding an already bound binding. This results in an error.
1404     /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
1405     /// in reusing this binding rather than creating a fresh one.
1406     ///
1407     /// When called at the top level, the stack must have a single element
1408     /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
1409     /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
1410     /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
1411     /// When each `p_i` has been dealt with, the top set is merged with its parent.
1412     /// When a whole or-pattern has been dealt with, the thing happens.
1413     ///
1414     /// See the implementation and `fresh_binding` for more details.
1415     fn resolve_pattern_inner(
1416         &mut self,
1417         pat: &Pat,
1418         pat_src: PatternSource,
1419         bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1420     ) {
1421         // Visit all direct subpatterns of this pattern.
1422         pat.walk(&mut |pat| {
1423             debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
1424             match pat.kind {
1425                 PatKind::Ident(bmode, ident, ref sub) => {
1426                     // First try to resolve the identifier as some existing entity,
1427                     // then fall back to a fresh binding.
1428                     let has_sub = sub.is_some();
1429                     let res = self
1430                         .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1431                         .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
1432                     self.r.record_partial_res(pat.id, PartialRes::new(res));
1433                 }
1434                 PatKind::TupleStruct(ref path, ..) => {
1435                     self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1436                 }
1437                 PatKind::Path(ref qself, ref path) => {
1438                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1439                 }
1440                 PatKind::Struct(ref path, ..) => {
1441                     self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1442                 }
1443                 PatKind::Or(ref ps) => {
1444                     // Add a new set of bindings to the stack. `Or` here records that when a
1445                     // binding already exists in this set, it should not result in an error because
1446                     // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
1447                     bindings.push((PatBoundCtx::Or, Default::default()));
1448                     for p in ps {
1449                         // Now we need to switch back to a product context so that each
1450                         // part of the or-pattern internally rejects already bound names.
1451                         // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
1452                         bindings.push((PatBoundCtx::Product, Default::default()));
1453                         self.resolve_pattern_inner(p, pat_src, bindings);
1454                         // Move up the non-overlapping bindings to the or-pattern.
1455                         // Existing bindings just get "merged".
1456                         let collected = bindings.pop().unwrap().1;
1457                         bindings.last_mut().unwrap().1.extend(collected);
1458                     }
1459                     // This or-pattern itself can itself be part of a product,
1460                     // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
1461                     // Both cases bind `a` again in a product pattern and must be rejected.
1462                     let collected = bindings.pop().unwrap().1;
1463                     bindings.last_mut().unwrap().1.extend(collected);
1464
1465                     // Prevent visiting `ps` as we've already done so above.
1466                     return false;
1467                 }
1468                 _ => {}
1469             }
1470             true
1471         });
1472     }
1473
1474     fn fresh_binding(
1475         &mut self,
1476         ident: Ident,
1477         pat_id: NodeId,
1478         pat_src: PatternSource,
1479         bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1480     ) -> Res {
1481         // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
1482         // (We must not add it if it's in the bindings map because that breaks the assumptions
1483         // later passes make about or-patterns.)
1484         let ident = ident.normalize_to_macro_rules();
1485
1486         let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
1487         // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
1488         let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
1489         // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
1490         // This is *required* for consistency which is checked later.
1491         let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
1492
1493         if already_bound_and {
1494             // Overlap in a product pattern somewhere; report an error.
1495             use ResolutionError::*;
1496             let error = match pat_src {
1497                 // `fn f(a: u8, a: u8)`:
1498                 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
1499                 // `Variant(a, a)`:
1500                 _ => IdentifierBoundMoreThanOnceInSamePattern,
1501             };
1502             self.r.report_error(ident.span, error(&ident.as_str()));
1503         }
1504
1505         // Record as bound if it's valid:
1506         let ident_valid = ident.name != kw::Invalid;
1507         if ident_valid {
1508             bindings.last_mut().unwrap().1.insert(ident);
1509         }
1510
1511         if already_bound_or {
1512             // `Variant1(a) | Variant2(a)`, ok
1513             // Reuse definition from the first `a`.
1514             self.innermost_rib_bindings(ValueNS)[&ident]
1515         } else {
1516             let res = Res::Local(pat_id);
1517             if ident_valid {
1518                 // A completely fresh binding add to the set if it's valid.
1519                 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1520             }
1521             res
1522         }
1523     }
1524
1525     fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
1526         &mut self.ribs[ns].last_mut().unwrap().bindings
1527     }
1528
1529     fn try_resolve_as_non_binding(
1530         &mut self,
1531         pat_src: PatternSource,
1532         pat: &Pat,
1533         bm: BindingMode,
1534         ident: Ident,
1535         has_sub: bool,
1536     ) -> Option<Res> {
1537         // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1538         // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1539         // also be interpreted as a path to e.g. a constant, variant, etc.
1540         let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
1541
1542         let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?;
1543         let (res, binding) = match ls_binding {
1544             LexicalScopeBinding::Item(binding)
1545                 if is_syntactic_ambiguity && binding.is_ambiguity() =>
1546             {
1547                 // For ambiguous bindings we don't know all their definitions and cannot check
1548                 // whether they can be shadowed by fresh bindings or not, so force an error.
1549                 // issues/33118#issuecomment-233962221 (see below) still applies here,
1550                 // but we have to ignore it for backward compatibility.
1551                 self.r.record_use(ident, ValueNS, binding, false);
1552                 return None;
1553             }
1554             LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
1555             LexicalScopeBinding::Res(res) => (res, None),
1556         };
1557
1558         match res {
1559             Res::SelfCtor(_) // See #70549.
1560             | Res::Def(
1561                 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
1562                 _,
1563             ) if is_syntactic_ambiguity => {
1564                 // Disambiguate in favor of a unit struct/variant or constant pattern.
1565                 if let Some(binding) = binding {
1566                     self.r.record_use(ident, ValueNS, binding, false);
1567                 }
1568                 Some(res)
1569             }
1570             Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => {
1571                 // This is unambiguously a fresh binding, either syntactically
1572                 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1573                 // to something unusable as a pattern (e.g., constructor function),
1574                 // but we still conservatively report an error, see
1575                 // issues/33118#issuecomment-233962221 for one reason why.
1576                 self.r.report_error(
1577                     ident.span,
1578                     ResolutionError::BindingShadowsSomethingUnacceptable(
1579                         pat_src.descr(),
1580                         ident.name,
1581                         binding.expect("no binding for a ctor or static"),
1582                     ),
1583                 );
1584                 None
1585             }
1586             Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
1587                 // These entities are explicitly allowed to be shadowed by fresh bindings.
1588                 None
1589             }
1590             _ => span_bug!(
1591                 ident.span,
1592                 "unexpected resolution for an identifier in pattern: {:?}",
1593                 res,
1594             ),
1595         }
1596     }
1597
1598     // High-level and context dependent path resolution routine.
1599     // Resolves the path and records the resolution into definition map.
1600     // If resolution fails tries several techniques to find likely
1601     // resolution candidates, suggest imports or other help, and report
1602     // errors in user friendly way.
1603     fn smart_resolve_path(
1604         &mut self,
1605         id: NodeId,
1606         qself: Option<&QSelf>,
1607         path: &Path,
1608         source: PathSource<'ast>,
1609     ) {
1610         self.smart_resolve_path_fragment(
1611             id,
1612             qself,
1613             &Segment::from_path(path),
1614             path.span,
1615             source,
1616             CrateLint::SimplePath(id),
1617         );
1618     }
1619
1620     fn smart_resolve_path_fragment(
1621         &mut self,
1622         id: NodeId,
1623         qself: Option<&QSelf>,
1624         path: &[Segment],
1625         span: Span,
1626         source: PathSource<'ast>,
1627         crate_lint: CrateLint,
1628     ) -> PartialRes {
1629         let ns = source.namespace();
1630         let is_expected = &|res| source.is_expected(res);
1631
1632         let report_errors = |this: &mut Self, res: Option<Res>| {
1633             let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1634
1635             let def_id = this.parent_scope.module.normal_ancestor_id;
1636             let instead = res.is_some();
1637             let suggestion =
1638                 if res.is_none() { this.report_missing_type_error(path) } else { None };
1639
1640             this.r.use_injections.push(UseError { err, candidates, def_id, instead, suggestion });
1641
1642             PartialRes::new(Res::Err)
1643         };
1644
1645         // For paths originating from calls (like in `HashMap::new()`), tries
1646         // to enrich the plain `failed to resolve: ...` message with hints
1647         // about possible missing imports.
1648         //
1649         // Similar thing, for types, happens in `report_errors` above.
1650         let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
1651             if !source.is_call() {
1652                 return Some(parent_err);
1653             }
1654
1655             // Before we start looking for candidates, we have to get our hands
1656             // on the type user is trying to perform invocation on; basically:
1657             // we're transforming `HashMap::new` into just `HashMap`
1658             let path = if let Some((_, path)) = path.split_last() {
1659                 path
1660             } else {
1661                 return Some(parent_err);
1662             };
1663
1664             let (mut err, candidates) =
1665                 this.smart_resolve_report_errors(path, span, PathSource::Type, None);
1666
1667             if candidates.is_empty() {
1668                 err.cancel();
1669                 return Some(parent_err);
1670             }
1671
1672             // There are two different error messages user might receive at
1673             // this point:
1674             // - E0412 cannot find type `{}` in this scope
1675             // - E0433 failed to resolve: use of undeclared type or module `{}`
1676             //
1677             // The first one is emitted for paths in type-position, and the
1678             // latter one - for paths in expression-position.
1679             //
1680             // Thus (since we're in expression-position at this point), not to
1681             // confuse the user, we want to keep the *message* from E0432 (so
1682             // `parent_err`), but we want *hints* from E0412 (so `err`).
1683             //
1684             // And that's what happens below - we're just mixing both messages
1685             // into a single one.
1686             let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
1687
1688             parent_err.cancel();
1689
1690             err.message = take(&mut parent_err.message);
1691             err.code = take(&mut parent_err.code);
1692             err.children = take(&mut parent_err.children);
1693
1694             drop(parent_err);
1695
1696             let def_id = this.parent_scope.module.normal_ancestor_id;
1697
1698             this.r.use_injections.push(UseError {
1699                 err,
1700                 candidates,
1701                 def_id,
1702                 instead: false,
1703                 suggestion: None,
1704             });
1705
1706             // We don't return `Some(parent_err)` here, because the error will
1707             // be already printed as part of the `use` injections
1708             None
1709         };
1710
1711         let partial_res = match self.resolve_qpath_anywhere(
1712             id,
1713             qself,
1714             path,
1715             ns,
1716             span,
1717             source.defer_to_typeck(),
1718             crate_lint,
1719         ) {
1720             Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => {
1721                 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1722                     partial_res
1723                 } else {
1724                     report_errors(self, Some(partial_res.base_res()))
1725                 }
1726             }
1727
1728             Ok(Some(partial_res)) if source.defer_to_typeck() => {
1729                 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1730                 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1731                 // it needs to be added to the trait map.
1732                 if ns == ValueNS {
1733                     let item_name = path.last().unwrap().ident;
1734                     let traits = self.get_traits_containing_item(item_name, ns);
1735                     self.r.trait_map.insert(id, traits);
1736                 }
1737
1738                 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1739
1740                 std_path.extend(path);
1741
1742                 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1743                     if let PathResult::Module(_) | PathResult::NonModule(_) =
1744                         self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No)
1745                     {
1746                         // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1747                         let item_span =
1748                             path.iter().last().map(|segment| segment.ident.span).unwrap_or(span);
1749
1750                         let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1751                         hm.insert(item_span, span);
1752                         hm.insert(span, span);
1753                     }
1754                 }
1755
1756                 partial_res
1757             }
1758
1759             Err(err) => {
1760                 if let Some(err) = report_errors_for_call(self, err) {
1761                     self.r.report_error(err.span, err.node);
1762                 }
1763
1764                 PartialRes::new(Res::Err)
1765             }
1766
1767             _ => report_errors(self, None),
1768         };
1769
1770         if let PathSource::TraitItem(..) = source {
1771         } else {
1772             // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1773             self.r.record_partial_res(id, partial_res);
1774         }
1775
1776         partial_res
1777     }
1778
1779     fn self_type_is_available(&mut self, span: Span) -> bool {
1780         let binding = self.resolve_ident_in_lexical_scope(
1781             Ident::with_dummy_span(kw::SelfUpper),
1782             TypeNS,
1783             None,
1784             span,
1785         );
1786         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1787     }
1788
1789     fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1790         let ident = Ident::new(kw::SelfLower, self_span);
1791         let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1792         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1793     }
1794
1795     // Resolve in alternative namespaces if resolution in the primary namespace fails.
1796     fn resolve_qpath_anywhere(
1797         &mut self,
1798         id: NodeId,
1799         qself: Option<&QSelf>,
1800         path: &[Segment],
1801         primary_ns: Namespace,
1802         span: Span,
1803         defer_to_typeck: bool,
1804         crate_lint: CrateLint,
1805     ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
1806         let mut fin_res = None;
1807
1808         for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1809             if i == 0 || ns != primary_ns {
1810                 match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? {
1811                     Some(partial_res)
1812                         if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
1813                     {
1814                         return Ok(Some(partial_res));
1815                     }
1816                     partial_res => {
1817                         if fin_res.is_none() {
1818                             fin_res = partial_res
1819                         }
1820                     }
1821                 }
1822             }
1823         }
1824
1825         assert!(primary_ns != MacroNS);
1826
1827         if qself.is_none() {
1828             let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1829             let path = Path { segments: path.iter().map(path_seg).collect(), span };
1830             if let Ok((_, res)) =
1831                 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
1832             {
1833                 return Ok(Some(PartialRes::new(res)));
1834             }
1835         }
1836
1837         Ok(fin_res)
1838     }
1839
1840     /// Handles paths that may refer to associated items.
1841     fn resolve_qpath(
1842         &mut self,
1843         id: NodeId,
1844         qself: Option<&QSelf>,
1845         path: &[Segment],
1846         ns: Namespace,
1847         span: Span,
1848         crate_lint: CrateLint,
1849     ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
1850         debug!(
1851             "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1852             id, qself, path, ns, span,
1853         );
1854
1855         if let Some(qself) = qself {
1856             if qself.position == 0 {
1857                 // This is a case like `<T>::B`, where there is no
1858                 // trait to resolve.  In that case, we leave the `B`
1859                 // segment to be resolved by type-check.
1860                 return Ok(Some(PartialRes::with_unresolved_segments(
1861                     Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
1862                     path.len(),
1863                 )));
1864             }
1865
1866             // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1867             //
1868             // Currently, `path` names the full item (`A::B::C`, in
1869             // our example).  so we extract the prefix of that that is
1870             // the trait (the slice upto and including
1871             // `qself.position`). And then we recursively resolve that,
1872             // but with `qself` set to `None`.
1873             //
1874             // However, setting `qself` to none (but not changing the
1875             // span) loses the information about where this path
1876             // *actually* appears, so for the purposes of the crate
1877             // lint we pass along information that this is the trait
1878             // name from a fully qualified path, and this also
1879             // contains the full span (the `CrateLint::QPathTrait`).
1880             let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1881             let partial_res = self.smart_resolve_path_fragment(
1882                 id,
1883                 None,
1884                 &path[..=qself.position],
1885                 span,
1886                 PathSource::TraitItem(ns),
1887                 CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
1888             );
1889
1890             // The remaining segments (the `C` in our example) will
1891             // have to be resolved by type-check, since that requires doing
1892             // trait resolution.
1893             return Ok(Some(PartialRes::with_unresolved_segments(
1894                 partial_res.base_res(),
1895                 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1896             )));
1897         }
1898
1899         let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1900             PathResult::NonModule(path_res) => path_res,
1901             PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1902                 PartialRes::new(module.res().unwrap())
1903             }
1904             // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1905             // don't report an error right away, but try to fallback to a primitive type.
1906             // So, we are still able to successfully resolve something like
1907             //
1908             // use std::u8; // bring module u8 in scope
1909             // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1910             //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
1911             //                     // not to non-existent std::u8::max_value
1912             // }
1913             //
1914             // Such behavior is required for backward compatibility.
1915             // The same fallback is used when `a` resolves to nothing.
1916             PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
1917                 if (ns == TypeNS || path.len() > 1)
1918                     && self
1919                         .r
1920                         .primitive_type_table
1921                         .primitive_types
1922                         .contains_key(&path[0].ident.name) =>
1923             {
1924                 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1925                 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1926             }
1927             PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
1928                 PartialRes::new(module.res().unwrap())
1929             }
1930             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1931                 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
1932             }
1933             PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
1934             PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
1935         };
1936
1937         if path.len() > 1
1938             && result.base_res() != Res::Err
1939             && path[0].ident.name != kw::PathRoot
1940             && path[0].ident.name != kw::DollarCrate
1941         {
1942             let unqualified_result = {
1943                 match self.resolve_path(
1944                     &[*path.last().unwrap()],
1945                     Some(ns),
1946                     false,
1947                     span,
1948                     CrateLint::No,
1949                 ) {
1950                     PathResult::NonModule(path_res) => path_res.base_res(),
1951                     PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
1952                         module.res().unwrap()
1953                     }
1954                     _ => return Ok(Some(result)),
1955                 }
1956             };
1957             if result.base_res() == unqualified_result {
1958                 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1959                 self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
1960             }
1961         }
1962
1963         Ok(Some(result))
1964     }
1965
1966     fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
1967         if let Some(label) = label {
1968             if label.ident.as_str().as_bytes()[1] != b'_' {
1969                 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
1970             }
1971             self.with_label_rib(NormalRibKind, |this| {
1972                 let ident = label.ident.normalize_to_macro_rules();
1973                 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1974                 f(this);
1975             });
1976         } else {
1977             f(self);
1978         }
1979     }
1980
1981     fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
1982         self.with_resolved_label(label, id, |this| this.visit_block(block));
1983     }
1984
1985     fn resolve_block(&mut self, block: &'ast Block) {
1986         debug!("(resolving block) entering block");
1987         // Move down in the graph, if there's an anonymous module rooted here.
1988         let orig_module = self.parent_scope.module;
1989         let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1990
1991         let mut num_macro_definition_ribs = 0;
1992         if let Some(anonymous_module) = anonymous_module {
1993             debug!("(resolving block) found anonymous module, moving down");
1994             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1995             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1996             self.parent_scope.module = anonymous_module;
1997         } else {
1998             self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1999         }
2000
2001         // Descend into the block.
2002         for stmt in &block.stmts {
2003             if let StmtKind::Item(ref item) = stmt.kind {
2004                 if let ItemKind::MacroDef(..) = item.kind {
2005                     num_macro_definition_ribs += 1;
2006                     let res = self.r.local_def_id(item.id).to_def_id();
2007                     self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
2008                     self.label_ribs.push(Rib::new(MacroDefinition(res)));
2009                 }
2010             }
2011
2012             self.visit_stmt(stmt);
2013         }
2014
2015         // Move back up.
2016         self.parent_scope.module = orig_module;
2017         for _ in 0..num_macro_definition_ribs {
2018             self.ribs[ValueNS].pop();
2019             self.label_ribs.pop();
2020         }
2021         self.ribs[ValueNS].pop();
2022         if anonymous_module.is_some() {
2023             self.ribs[TypeNS].pop();
2024         }
2025         debug!("(resolving block) leaving block");
2026     }
2027
2028     fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
2029         // First, record candidate traits for this expression if it could
2030         // result in the invocation of a method call.
2031
2032         self.record_candidate_traits_for_expr_if_necessary(expr);
2033
2034         // Next, resolve the node.
2035         match expr.kind {
2036             ExprKind::Path(ref qself, ref path) => {
2037                 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
2038                 visit::walk_expr(self, expr);
2039             }
2040
2041             ExprKind::Struct(ref path, ..) => {
2042                 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
2043                 visit::walk_expr(self, expr);
2044             }
2045
2046             ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
2047                 let node_id = self.search_label(label.ident, |rib, ident| {
2048                     rib.bindings.get(&ident.normalize_to_macro_rules()).cloned()
2049                 });
2050                 match node_id {
2051                     None => {
2052                         // Search again for close matches...
2053                         // Picks the first label that is "close enough", which is not necessarily
2054                         // the closest match
2055                         let close_match = self.search_label(label.ident, |rib, ident| {
2056                             let names = rib.bindings.iter().filter_map(|(id, _)| {
2057                                 if id.span.ctxt() == label.ident.span.ctxt() {
2058                                     Some(&id.name)
2059                                 } else {
2060                                     None
2061                                 }
2062                             });
2063                             find_best_match_for_name(names, &ident.as_str(), None)
2064                         });
2065                         self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
2066                         self.r.report_error(
2067                             label.ident.span,
2068                             ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
2069                         );
2070                     }
2071                     Some(node_id) => {
2072                         // Since this res is a label, it is never read.
2073                         self.r.label_res_map.insert(expr.id, node_id);
2074                         self.diagnostic_metadata.unused_labels.remove(&node_id);
2075                     }
2076                 }
2077
2078                 // visit `break` argument if any
2079                 visit::walk_expr(self, expr);
2080             }
2081
2082             ExprKind::Let(ref pat, ref scrutinee) => {
2083                 self.visit_expr(scrutinee);
2084                 self.resolve_pattern_top(pat, PatternSource::Let);
2085             }
2086
2087             ExprKind::If(ref cond, ref then, ref opt_else) => {
2088                 self.with_rib(ValueNS, NormalRibKind, |this| {
2089                     this.visit_expr(cond);
2090                     this.visit_block(then);
2091                 });
2092                 if let Some(expr) = opt_else {
2093                     self.visit_expr(expr);
2094                 }
2095             }
2096
2097             ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
2098
2099             ExprKind::While(ref cond, ref block, label) => {
2100                 self.with_resolved_label(label, expr.id, |this| {
2101                     this.with_rib(ValueNS, NormalRibKind, |this| {
2102                         this.visit_expr(cond);
2103                         this.visit_block(block);
2104                     })
2105                 });
2106             }
2107
2108             ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
2109                 self.visit_expr(iter_expr);
2110                 self.with_rib(ValueNS, NormalRibKind, |this| {
2111                     this.resolve_pattern_top(pat, PatternSource::For);
2112                     this.resolve_labeled_block(label, expr.id, block);
2113                 });
2114             }
2115
2116             ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
2117
2118             // Equivalent to `visit::walk_expr` + passing some context to children.
2119             ExprKind::Field(ref subexpression, _) => {
2120                 self.resolve_expr(subexpression, Some(expr));
2121             }
2122             ExprKind::MethodCall(ref segment, ref arguments, _) => {
2123                 let mut arguments = arguments.iter();
2124                 self.resolve_expr(arguments.next().unwrap(), Some(expr));
2125                 for argument in arguments {
2126                     self.resolve_expr(argument, None);
2127                 }
2128                 self.visit_path_segment(expr.span, segment);
2129             }
2130
2131             ExprKind::Call(ref callee, ref arguments) => {
2132                 self.resolve_expr(callee, Some(expr));
2133                 for argument in arguments {
2134                     self.resolve_expr(argument, None);
2135                 }
2136             }
2137             ExprKind::Type(ref type_expr, _) => {
2138                 self.diagnostic_metadata.current_type_ascription.push(type_expr.span);
2139                 visit::walk_expr(self, expr);
2140                 self.diagnostic_metadata.current_type_ascription.pop();
2141             }
2142             // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
2143             // resolve the arguments within the proper scopes so that usages of them inside the
2144             // closure are detected as upvars rather than normal closure arg usages.
2145             ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
2146                 self.with_rib(ValueNS, NormalRibKind, |this| {
2147                     // Resolve arguments:
2148                     this.resolve_params(&fn_decl.inputs);
2149                     // No need to resolve return type --
2150                     // the outer closure return type is `FnRetTy::Default`.
2151
2152                     // Now resolve the inner closure
2153                     {
2154                         // No need to resolve arguments: the inner closure has none.
2155                         // Resolve the return type:
2156                         visit::walk_fn_ret_ty(this, &fn_decl.output);
2157                         // Resolve the body
2158                         this.visit_expr(body);
2159                     }
2160                 });
2161             }
2162             _ => {
2163                 visit::walk_expr(self, expr);
2164             }
2165         }
2166     }
2167
2168     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
2169         match expr.kind {
2170             ExprKind::Field(_, ident) => {
2171                 // FIXME(#6890): Even though you can't treat a method like a
2172                 // field, we need to add any trait methods we find that match
2173                 // the field name so that we can do some nice error reporting
2174                 // later on in typeck.
2175                 let traits = self.get_traits_containing_item(ident, ValueNS);
2176                 self.r.trait_map.insert(expr.id, traits);
2177             }
2178             ExprKind::MethodCall(ref segment, ..) => {
2179                 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
2180                 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
2181                 self.r.trait_map.insert(expr.id, traits);
2182             }
2183             _ => {
2184                 // Nothing to do.
2185             }
2186         }
2187     }
2188
2189     fn get_traits_containing_item(
2190         &mut self,
2191         mut ident: Ident,
2192         ns: Namespace,
2193     ) -> Vec<TraitCandidate> {
2194         debug!("(getting traits containing item) looking for '{}'", ident.name);
2195
2196         let mut found_traits = Vec::new();
2197         // Look for the current trait.
2198         if let Some((module, _)) = self.current_trait_ref {
2199             if self
2200                 .r
2201                 .resolve_ident_in_module(
2202                     ModuleOrUniformRoot::Module(module),
2203                     ident,
2204                     ns,
2205                     &self.parent_scope,
2206                     false,
2207                     module.span,
2208                 )
2209                 .is_ok()
2210             {
2211                 let def_id = module.def_id().unwrap();
2212                 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
2213             }
2214         }
2215
2216         ident.span = ident.span.normalize_to_macros_2_0();
2217         let mut search_module = self.parent_scope.module;
2218         loop {
2219             self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
2220             search_module =
2221                 unwrap_or!(self.r.hygienic_lexical_parent(search_module, &mut ident.span), break);
2222         }
2223
2224         if let Some(prelude) = self.r.prelude {
2225             if !search_module.no_implicit_prelude {
2226                 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
2227             }
2228         }
2229
2230         found_traits
2231     }
2232
2233     fn get_traits_in_module_containing_item(
2234         &mut self,
2235         ident: Ident,
2236         ns: Namespace,
2237         module: Module<'a>,
2238         found_traits: &mut Vec<TraitCandidate>,
2239     ) {
2240         assert!(ns == TypeNS || ns == ValueNS);
2241         let mut traits = module.traits.borrow_mut();
2242         if traits.is_none() {
2243             let mut collected_traits = Vec::new();
2244             module.for_each_child(self.r, |_, name, ns, binding| {
2245                 if ns != TypeNS {
2246                     return;
2247                 }
2248                 match binding.res() {
2249                     Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2250                         collected_traits.push((name, binding))
2251                     }
2252                     _ => (),
2253                 }
2254             });
2255             *traits = Some(collected_traits.into_boxed_slice());
2256         }
2257
2258         for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
2259             // Traits have pseudo-modules that can be used to search for the given ident.
2260             if let Some(module) = binding.module() {
2261                 let mut ident = ident;
2262                 if ident.span.glob_adjust(module.expansion, binding.span).is_none() {
2263                     continue;
2264                 }
2265                 if self
2266                     .r
2267                     .resolve_ident_in_module_unadjusted(
2268                         ModuleOrUniformRoot::Module(module),
2269                         ident,
2270                         ns,
2271                         &self.parent_scope,
2272                         false,
2273                         module.span,
2274                     )
2275                     .is_ok()
2276                 {
2277                     let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2278                     let trait_def_id = module.def_id().unwrap();
2279                     found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2280                 }
2281             } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
2282                 // For now, just treat all trait aliases as possible candidates, since we don't
2283                 // know if the ident is somewhere in the transitive bounds.
2284                 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2285                 let trait_def_id = binding.res().def_id();
2286                 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2287             } else {
2288                 bug!("candidate is not trait or trait alias?")
2289             }
2290         }
2291     }
2292
2293     fn find_transitive_imports(
2294         &mut self,
2295         mut kind: &NameBindingKind<'_>,
2296         trait_name: Ident,
2297     ) -> SmallVec<[LocalDefId; 1]> {
2298         let mut import_ids = smallvec![];
2299         while let NameBindingKind::Import { import, binding, .. } = kind {
2300             let id = self.r.local_def_id(import.id);
2301             self.r.maybe_unused_trait_imports.insert(id);
2302             self.r.add_to_glob_map(&import, trait_name);
2303             import_ids.push(id);
2304             kind = &binding.kind;
2305         }
2306         import_ids
2307     }
2308 }
2309
2310 impl<'a> Resolver<'a> {
2311     pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2312         let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2313         visit::walk_crate(&mut late_resolution_visitor, krate);
2314         for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
2315             self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
2316         }
2317     }
2318 }