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