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