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