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