]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late.rs
Rollup merge of #63467 - terhechte:support-ios-catalyst-macabi-target-triple, r=estebank
[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_empty_ctxt(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_empty_ctxt(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_empty_ctxt(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_empty_ctxt(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             self.r.finalize_current_module_macro_resolutions(module);
578             let ret = f(self);
579
580             self.parent_scope.module = orig_module;
581             self.ribs[ValueNS].pop();
582             self.ribs[TypeNS].pop();
583             ret
584         } else {
585             f(self)
586         }
587     }
588
589     /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
590     /// is returned by the given predicate function
591     ///
592     /// Stops after meeting a closure.
593     fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
594         where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
595     {
596         for rib in self.label_ribs.iter().rev() {
597             match rib.kind {
598                 NormalRibKind => {}
599                 // If an invocation of this macro created `ident`, give up on `ident`
600                 // and switch to `ident`'s source from the macro definition.
601                 MacroDefinition(def) => {
602                     if def == self.r.macro_def(ident.span.ctxt()) {
603                         ident.span.remove_mark();
604                     }
605                 }
606                 _ => {
607                     // Do not resolve labels across function boundary
608                     return None;
609                 }
610             }
611             let r = pred(rib, ident);
612             if r.is_some() {
613                 return r;
614             }
615         }
616         None
617     }
618
619     fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
620         debug!("resolve_adt");
621         self.with_current_self_item(item, |this| {
622             this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
623                 let item_def_id = this.r.definitions.local_def_id(item.id);
624                 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
625                     visit::walk_item(this, item);
626                 });
627             });
628         });
629     }
630
631     fn future_proof_import(&mut self, use_tree: &UseTree) {
632         let segments = &use_tree.prefix.segments;
633         if !segments.is_empty() {
634             let ident = segments[0].ident;
635             if ident.is_path_segment_keyword() || ident.span.rust_2015() {
636                 return;
637             }
638
639             let nss = match use_tree.kind {
640                 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
641                 _ => &[TypeNS],
642             };
643             let report_error = |this: &Self, ns| {
644                 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
645                 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
646             };
647
648             for &ns in nss {
649                 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
650                     Some(LexicalScopeBinding::Res(..)) => {
651                         report_error(self, ns);
652                     }
653                     Some(LexicalScopeBinding::Item(binding)) => {
654                         let orig_blacklisted_binding =
655                             replace(&mut self.r.blacklisted_binding, Some(binding));
656                         if let Some(LexicalScopeBinding::Res(..)) =
657                                 self.resolve_ident_in_lexical_scope(ident, ns, None,
658                                                                     use_tree.prefix.span) {
659                             report_error(self, ns);
660                         }
661                         self.r.blacklisted_binding = orig_blacklisted_binding;
662                     }
663                     None => {}
664                 }
665             }
666         } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
667             for (use_tree, _) in use_trees {
668                 self.future_proof_import(use_tree);
669             }
670         }
671     }
672
673     fn resolve_item(&mut self, item: &Item) {
674         let name = item.ident.name;
675         debug!("(resolving item) resolving {} ({:?})", name, item.node);
676
677         match item.node {
678             ItemKind::TyAlias(_, ref generics) |
679             ItemKind::OpaqueTy(_, ref generics) |
680             ItemKind::Fn(_, _, ref generics, _) => {
681                 self.with_generic_param_rib(
682                     HasGenericParams(generics, ItemRibKind),
683                     |this| visit::walk_item(this, item)
684                 );
685             }
686
687             ItemKind::Enum(_, ref generics) |
688             ItemKind::Struct(_, ref generics) |
689             ItemKind::Union(_, ref generics) => {
690                 self.resolve_adt(item, generics);
691             }
692
693             ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
694                 self.resolve_implementation(generics,
695                                             opt_trait_ref,
696                                             &self_type,
697                                             item.id,
698                                             impl_items),
699
700             ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
701                 // Create a new rib for the trait-wide type parameters.
702                 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
703                     let local_def_id = this.r.definitions.local_def_id(item.id);
704                     this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
705                         this.visit_generics(generics);
706                         walk_list!(this, visit_param_bound, bounds);
707
708                         for trait_item in trait_items {
709                             this.with_trait_items(trait_items, |this| {
710                                 let generic_params = HasGenericParams(
711                                     &trait_item.generics,
712                                     AssocItemRibKind,
713                                 );
714                                 this.with_generic_param_rib(generic_params, |this| {
715                                     match trait_item.node {
716                                         TraitItemKind::Const(ref ty, ref default) => {
717                                             this.visit_ty(ty);
718
719                                             // Only impose the restrictions of
720                                             // ConstRibKind for an actual constant
721                                             // expression in a provided default.
722                                             if let Some(ref expr) = *default{
723                                                 this.with_constant_rib(|this| {
724                                                     this.visit_expr(expr);
725                                                 });
726                                             }
727                                         }
728                                         TraitItemKind::Method(_, _) => {
729                                             visit::walk_trait_item(this, trait_item)
730                                         }
731                                         TraitItemKind::Type(..) => {
732                                             visit::walk_trait_item(this, trait_item)
733                                         }
734                                         TraitItemKind::Macro(_) => {
735                                             panic!("unexpanded macro in resolve!")
736                                         }
737                                     };
738                                 });
739                             });
740                         }
741                     });
742                 });
743             }
744
745             ItemKind::TraitAlias(ref generics, ref bounds) => {
746                 // Create a new rib for the trait-wide type parameters.
747                 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
748                     let local_def_id = this.r.definitions.local_def_id(item.id);
749                     this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
750                         this.visit_generics(generics);
751                         walk_list!(this, visit_param_bound, bounds);
752                     });
753                 });
754             }
755
756             ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
757                 self.with_scope(item.id, |this| {
758                     visit::walk_item(this, item);
759                 });
760             }
761
762             ItemKind::Static(ref ty, _, ref expr) |
763             ItemKind::Const(ref ty, ref expr) => {
764                 debug!("resolve_item ItemKind::Const");
765                 self.with_item_rib(|this| {
766                     this.visit_ty(ty);
767                     this.with_constant_rib(|this| {
768                         this.visit_expr(expr);
769                     });
770                 });
771             }
772
773             ItemKind::Use(ref use_tree) => {
774                 self.future_proof_import(use_tree);
775             }
776
777             ItemKind::ExternCrate(..) |
778             ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
779                 // do nothing, these are just around to be encoded
780             }
781
782             ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
783         }
784     }
785
786     fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
787         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
788     {
789         debug!("with_generic_param_rib");
790         match generic_params {
791             HasGenericParams(generics, rib_kind) => {
792                 let mut function_type_rib = Rib::new(rib_kind);
793                 let mut function_value_rib = Rib::new(rib_kind);
794                 let mut seen_bindings = FxHashMap::default();
795                 for param in &generics.params {
796                     match param.kind {
797                         GenericParamKind::Lifetime { .. } => {}
798                         GenericParamKind::Type { .. } => {
799                             let ident = param.ident.modern();
800                             debug!("with_generic_param_rib: {}", param.id);
801
802                             if seen_bindings.contains_key(&ident) {
803                                 let span = seen_bindings.get(&ident).unwrap();
804                                 let err = ResolutionError::NameAlreadyUsedInParameterList(
805                                     ident.name,
806                                     *span,
807                                 );
808                                 self.r.report_error(param.ident.span, err);
809                             }
810                             seen_bindings.entry(ident).or_insert(param.ident.span);
811
812                             // Plain insert (no renaming).
813                             let res = Res::Def(
814                                 DefKind::TyParam,
815                                 self.r.definitions.local_def_id(param.id),
816                             );
817                             function_type_rib.bindings.insert(ident, res);
818                             self.r.record_partial_res(param.id, PartialRes::new(res));
819                         }
820                         GenericParamKind::Const { .. } => {
821                             let ident = param.ident.modern();
822                             debug!("with_generic_param_rib: {}", param.id);
823
824                             if seen_bindings.contains_key(&ident) {
825                                 let span = seen_bindings.get(&ident).unwrap();
826                                 let err = ResolutionError::NameAlreadyUsedInParameterList(
827                                     ident.name,
828                                     *span,
829                                 );
830                                 self.r.report_error(param.ident.span, err);
831                             }
832                             seen_bindings.entry(ident).or_insert(param.ident.span);
833
834                             let res = Res::Def(
835                                 DefKind::ConstParam,
836                                 self.r.definitions.local_def_id(param.id),
837                             );
838                             function_value_rib.bindings.insert(ident, res);
839                             self.r.record_partial_res(param.id, PartialRes::new(res));
840                         }
841                     }
842                 }
843                 self.ribs[ValueNS].push(function_value_rib);
844                 self.ribs[TypeNS].push(function_type_rib);
845             }
846
847             NoGenericParams => {
848                 // Nothing to do.
849             }
850         }
851
852         f(self);
853
854         if let HasGenericParams(..) = generic_params {
855             self.ribs[TypeNS].pop();
856             self.ribs[ValueNS].pop();
857         }
858     }
859
860     fn with_label_rib<F>(&mut self, f: F)
861         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
862     {
863         self.label_ribs.push(Rib::new(NormalRibKind));
864         f(self);
865         self.label_ribs.pop();
866     }
867
868     fn with_item_rib<F>(&mut self, f: F)
869         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
870     {
871         self.ribs[ValueNS].push(Rib::new(ItemRibKind));
872         self.ribs[TypeNS].push(Rib::new(ItemRibKind));
873         f(self);
874         self.ribs[TypeNS].pop();
875         self.ribs[ValueNS].pop();
876     }
877
878     fn with_constant_rib<F>(&mut self, f: F)
879         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
880     {
881         debug!("with_constant_rib");
882         self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
883         self.label_ribs.push(Rib::new(ConstantItemRibKind));
884         f(self);
885         self.label_ribs.pop();
886         self.ribs[ValueNS].pop();
887     }
888
889     fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
890         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
891     {
892         // Handle nested impls (inside fn bodies)
893         let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
894         let result = f(self);
895         self.current_self_type = previous_value;
896         result
897     }
898
899     fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
900         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
901     {
902         let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
903         let result = f(self);
904         self.current_self_item = previous_value;
905         result
906     }
907
908     /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
909     fn with_trait_items<T, F>(&mut self, trait_items: &Vec<TraitItem>, f: F) -> T
910         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
911     {
912         let trait_assoc_types = replace(
913             &mut self.current_trait_assoc_types,
914             trait_items.iter().filter_map(|item| match &item.node {
915                 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
916                 _ => None,
917             }).collect(),
918         );
919         let result = f(self);
920         self.current_trait_assoc_types = trait_assoc_types;
921         result
922     }
923
924     /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
925     fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
926         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>, Option<DefId>) -> T
927     {
928         let mut new_val = None;
929         let mut new_id = None;
930         if let Some(trait_ref) = opt_trait_ref {
931             let path: Vec<_> = Segment::from_path(&trait_ref.path);
932             let res = self.smart_resolve_path_fragment(
933                 trait_ref.ref_id,
934                 None,
935                 &path,
936                 trait_ref.path.span,
937                 PathSource::Trait(AliasPossibility::No),
938                 CrateLint::SimplePath(trait_ref.ref_id),
939             ).base_res();
940             if res != Res::Err {
941                 new_id = Some(res.def_id());
942                 let span = trait_ref.path.span;
943                 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
944                     self.resolve_path(
945                         &path,
946                         Some(TypeNS),
947                         false,
948                         span,
949                         CrateLint::SimplePath(trait_ref.ref_id),
950                     )
951                 {
952                     new_val = Some((module, trait_ref.clone()));
953                 }
954             }
955         }
956         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
957         let result = f(self, new_id);
958         self.current_trait_ref = original_trait_ref;
959         result
960     }
961
962     fn with_self_rib<F>(&mut self, self_res: Res, f: F)
963         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
964     {
965         let mut self_type_rib = Rib::new(NormalRibKind);
966
967         // Plain insert (no renaming, since types are not currently hygienic)
968         self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
969         self.ribs[TypeNS].push(self_type_rib);
970         f(self);
971         self.ribs[TypeNS].pop();
972     }
973
974     fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
975         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
976     {
977         let self_res = Res::SelfCtor(impl_id);
978         let mut self_type_rib = Rib::new(NormalRibKind);
979         self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
980         self.ribs[ValueNS].push(self_type_rib);
981         f(self);
982         self.ribs[ValueNS].pop();
983     }
984
985     fn resolve_implementation(&mut self,
986                               generics: &Generics,
987                               opt_trait_reference: &Option<TraitRef>,
988                               self_type: &Ty,
989                               item_id: NodeId,
990                               impl_items: &[ImplItem]) {
991         debug!("resolve_implementation");
992         // If applicable, create a rib for the type parameters.
993         self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
994             // Dummy self type for better errors if `Self` is used in the trait path.
995             this.with_self_rib(Res::SelfTy(None, None), |this| {
996                 // Resolve the trait reference, if necessary.
997                 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
998                     let item_def_id = this.r.definitions.local_def_id(item_id);
999                     this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1000                         if let Some(trait_ref) = opt_trait_reference.as_ref() {
1001                             // Resolve type arguments in the trait path.
1002                             visit::walk_trait_ref(this, trait_ref);
1003                         }
1004                         // Resolve the self type.
1005                         this.visit_ty(self_type);
1006                         // Resolve the generic parameters.
1007                         this.visit_generics(generics);
1008                         // Resolve the items within the impl.
1009                         this.with_current_self_type(self_type, |this| {
1010                             this.with_self_struct_ctor_rib(item_def_id, |this| {
1011                                 debug!("resolve_implementation with_self_struct_ctor_rib");
1012                                 for impl_item in impl_items {
1013                                     // We also need a new scope for the impl item type parameters.
1014                                     let generic_params = HasGenericParams(&impl_item.generics,
1015                                                                           AssocItemRibKind);
1016                                     this.with_generic_param_rib(generic_params, |this| {
1017                                         use crate::ResolutionError::*;
1018                                         match impl_item.node {
1019                                             ImplItemKind::Const(..) => {
1020                                                 debug!(
1021                                                     "resolve_implementation ImplItemKind::Const",
1022                                                 );
1023                                                 // If this is a trait impl, ensure the const
1024                                                 // exists in trait
1025                                                 this.check_trait_item(
1026                                                     impl_item.ident,
1027                                                     ValueNS,
1028                                                     impl_item.span,
1029                                                     |n, s| ConstNotMemberOfTrait(n, s),
1030                                                 );
1031
1032                                                 this.with_constant_rib(|this| {
1033                                                     visit::walk_impl_item(this, impl_item)
1034                                                 });
1035                                             }
1036                                             ImplItemKind::Method(..) => {
1037                                                 // If this is a trait impl, ensure the method
1038                                                 // exists in trait
1039                                                 this.check_trait_item(impl_item.ident,
1040                                                                       ValueNS,
1041                                                                       impl_item.span,
1042                                                     |n, s| MethodNotMemberOfTrait(n, s));
1043
1044                                                 visit::walk_impl_item(this, impl_item);
1045                                             }
1046                                             ImplItemKind::TyAlias(ref ty) => {
1047                                                 // If this is a trait impl, ensure the type
1048                                                 // exists in trait
1049                                                 this.check_trait_item(impl_item.ident,
1050                                                                       TypeNS,
1051                                                                       impl_item.span,
1052                                                     |n, s| TypeNotMemberOfTrait(n, s));
1053
1054                                                 this.visit_ty(ty);
1055                                             }
1056                                             ImplItemKind::OpaqueTy(ref bounds) => {
1057                                                 // If this is a trait impl, ensure the type
1058                                                 // exists in trait
1059                                                 this.check_trait_item(impl_item.ident,
1060                                                                       TypeNS,
1061                                                                       impl_item.span,
1062                                                     |n, s| TypeNotMemberOfTrait(n, s));
1063
1064                                                 for bound in bounds {
1065                                                     this.visit_param_bound(bound);
1066                                                 }
1067                                             }
1068                                             ImplItemKind::Macro(_) =>
1069                                                 panic!("unexpanded macro in resolve!"),
1070                                         }
1071                                     });
1072                                 }
1073                             });
1074                         });
1075                     });
1076                 });
1077             });
1078         });
1079     }
1080
1081     fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1082         where F: FnOnce(Name, &str) -> ResolutionError<'_>
1083     {
1084         // If there is a TraitRef in scope for an impl, then the method must be in the
1085         // trait.
1086         if let Some((module, _)) = self.current_trait_ref {
1087             if self.r.resolve_ident_in_module(
1088                 ModuleOrUniformRoot::Module(module),
1089                 ident,
1090                 ns,
1091                 &self.parent_scope,
1092                 false,
1093                 span,
1094             ).is_err() {
1095                 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1096                 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1097             }
1098         }
1099     }
1100
1101     fn resolve_local(&mut self, local: &Local) {
1102         // Resolve the type.
1103         walk_list!(self, visit_ty, &local.ty);
1104
1105         // Resolve the initializer.
1106         walk_list!(self, visit_expr, &local.init);
1107
1108         // Resolve the pattern.
1109         self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
1110     }
1111
1112     // build a map from pattern identifiers to binding-info's.
1113     // this is done hygienically. This could arise for a macro
1114     // that expands into an or-pattern where one 'x' was from the
1115     // user and one 'x' came from the macro.
1116     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1117         let mut binding_map = FxHashMap::default();
1118
1119         pat.walk(&mut |pat| {
1120             if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1121                 if sub_pat.is_some() || match self.r.partial_res_map.get(&pat.id)
1122                                                                   .map(|res| res.base_res()) {
1123                     Some(Res::Local(..)) => true,
1124                     _ => false,
1125                 } {
1126                     let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
1127                     binding_map.insert(ident, binding_info);
1128                 }
1129             }
1130             true
1131         });
1132
1133         binding_map
1134     }
1135
1136     // Checks that all of the arms in an or-pattern have exactly the
1137     // same set of bindings, with the same binding modes for each.
1138     fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
1139         let mut missing_vars = FxHashMap::default();
1140         let mut inconsistent_vars = FxHashMap::default();
1141
1142         for pat_outer in pats.iter() {
1143             let map_outer = self.binding_mode_map(&pat_outer);
1144
1145             for pat_inner in pats.iter().filter(|pat| pat.id != pat_outer.id) {
1146                 let map_inner = self.binding_mode_map(&pat_inner);
1147
1148                 for (&key_inner, &binding_inner) in map_inner.iter() {
1149                     match map_outer.get(&key_inner) {
1150                         None => {  // missing binding
1151                             let binding_error = missing_vars
1152                                 .entry(key_inner.name)
1153                                 .or_insert(BindingError {
1154                                     name: key_inner.name,
1155                                     origin: BTreeSet::new(),
1156                                     target: BTreeSet::new(),
1157                                     could_be_path:
1158                                         key_inner.name.as_str().starts_with(char::is_uppercase)
1159                                 });
1160                             binding_error.origin.insert(binding_inner.span);
1161                             binding_error.target.insert(pat_outer.span);
1162                         }
1163                         Some(binding_outer) => {  // check consistent binding
1164                             if binding_outer.binding_mode != binding_inner.binding_mode {
1165                                 inconsistent_vars
1166                                     .entry(key_inner.name)
1167                                     .or_insert((binding_inner.span, binding_outer.span));
1168                             }
1169                         }
1170                     }
1171                 }
1172             }
1173         }
1174
1175         let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1176         missing_vars.sort();
1177         for (name, mut v) in missing_vars {
1178             if inconsistent_vars.contains_key(name) {
1179                 v.could_be_path = false;
1180             }
1181             self.r.report_error(
1182                 *v.origin.iter().next().unwrap(),
1183                 ResolutionError::VariableNotBoundInPattern(v));
1184         }
1185
1186         let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1187         inconsistent_vars.sort();
1188         for (name, v) in inconsistent_vars {
1189             self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1190         }
1191     }
1192
1193     fn resolve_arm(&mut self, arm: &Arm) {
1194         self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1195
1196         self.resolve_pats(&arm.pats, PatternSource::Match);
1197
1198         if let Some(ref expr) = arm.guard {
1199             self.visit_expr(expr)
1200         }
1201         self.visit_expr(&arm.body);
1202
1203         self.ribs[ValueNS].pop();
1204     }
1205
1206     /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
1207     fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
1208         let mut bindings_list = FxHashMap::default();
1209         for pat in pats {
1210             self.resolve_pattern(pat, source, &mut bindings_list);
1211         }
1212         // This has to happen *after* we determine which pat_idents are variants
1213         if pats.len() > 1 {
1214             self.check_consistent_bindings(pats);
1215         }
1216     }
1217
1218     fn resolve_block(&mut self, block: &Block) {
1219         debug!("(resolving block) entering block");
1220         // Move down in the graph, if there's an anonymous module rooted here.
1221         let orig_module = self.parent_scope.module;
1222         let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1223
1224         let mut num_macro_definition_ribs = 0;
1225         if let Some(anonymous_module) = anonymous_module {
1226             debug!("(resolving block) found anonymous module, moving down");
1227             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1228             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1229             self.parent_scope.module = anonymous_module;
1230             self.r.finalize_current_module_macro_resolutions(anonymous_module);
1231         } else {
1232             self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1233         }
1234
1235         // Descend into the block.
1236         for stmt in &block.stmts {
1237             if let StmtKind::Item(ref item) = stmt.node {
1238                 if let ItemKind::MacroDef(..) = item.node {
1239                     num_macro_definition_ribs += 1;
1240                     let res = self.r.definitions.local_def_id(item.id);
1241                     self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1242                     self.label_ribs.push(Rib::new(MacroDefinition(res)));
1243                 }
1244             }
1245
1246             self.visit_stmt(stmt);
1247         }
1248
1249         // Move back up.
1250         self.parent_scope.module = orig_module;
1251         for _ in 0 .. num_macro_definition_ribs {
1252             self.ribs[ValueNS].pop();
1253             self.label_ribs.pop();
1254         }
1255         self.ribs[ValueNS].pop();
1256         if anonymous_module.is_some() {
1257             self.ribs[TypeNS].pop();
1258         }
1259         debug!("(resolving block) leaving block");
1260     }
1261
1262     fn fresh_binding(&mut self,
1263                      ident: Ident,
1264                      pat_id: NodeId,
1265                      outer_pat_id: NodeId,
1266                      pat_src: PatternSource,
1267                      bindings: &mut FxHashMap<Ident, NodeId>)
1268                      -> Res {
1269         // Add the binding to the local ribs, if it
1270         // doesn't already exist in the bindings map. (We
1271         // must not add it if it's in the bindings map
1272         // because that breaks the assumptions later
1273         // passes make about or-patterns.)
1274         let ident = ident.modern_and_legacy();
1275         let mut res = Res::Local(pat_id);
1276         match bindings.get(&ident).cloned() {
1277             Some(id) if id == outer_pat_id => {
1278                 // `Variant(a, a)`, error
1279                 self.r.report_error(
1280                     ident.span,
1281                     ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
1282                         &ident.as_str())
1283                 );
1284             }
1285             Some(..) if pat_src == PatternSource::FnParam => {
1286                 // `fn f(a: u8, a: u8)`, error
1287                 self.r.report_error(
1288                     ident.span,
1289                     ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
1290                         &ident.as_str())
1291                 );
1292             }
1293             Some(..) if pat_src == PatternSource::Match ||
1294                         pat_src == PatternSource::Let => {
1295                 // `Variant1(a) | Variant2(a)`, ok
1296                 // Reuse definition from the first `a`.
1297                 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
1298             }
1299             Some(..) => {
1300                 span_bug!(ident.span, "two bindings with the same name from \
1301                                        unexpected pattern source {:?}", pat_src);
1302             }
1303             None => {
1304                 // A completely fresh binding, add to the lists if it's valid.
1305                 if ident.name != kw::Invalid {
1306                     bindings.insert(ident, outer_pat_id);
1307                     self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
1308                 }
1309             }
1310         }
1311
1312         res
1313     }
1314
1315     fn resolve_pattern(&mut self,
1316                        pat: &Pat,
1317                        pat_src: PatternSource,
1318                        // Maps idents to the node ID for the
1319                        // outermost pattern that binds them.
1320                        bindings: &mut FxHashMap<Ident, NodeId>) {
1321         // Visit all direct subpatterns of this pattern.
1322         let outer_pat_id = pat.id;
1323         pat.walk(&mut |pat| {
1324             debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1325             match pat.node {
1326                 PatKind::Ident(bmode, ident, ref opt_pat) => {
1327                     // First try to resolve the identifier as some existing
1328                     // entity, then fall back to a fresh binding.
1329                     let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
1330                                                                       None, pat.span)
1331                                       .and_then(LexicalScopeBinding::item);
1332                     let res = binding.map(NameBinding::res).and_then(|res| {
1333                         let is_syntactic_ambiguity = opt_pat.is_none() &&
1334                             bmode == BindingMode::ByValue(Mutability::Immutable);
1335                         match res {
1336                             Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1337                             Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1338                                 // Disambiguate in favor of a unit struct/variant
1339                                 // or constant pattern.
1340                                 self.r.record_use(ident, ValueNS, binding.unwrap(), false);
1341                                 Some(res)
1342                             }
1343                             Res::Def(DefKind::Ctor(..), _)
1344                             | Res::Def(DefKind::Const, _)
1345                             | Res::Def(DefKind::Static, _) => {
1346                                 // This is unambiguously a fresh binding, either syntactically
1347                                 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1348                                 // to something unusable as a pattern (e.g., constructor function),
1349                                 // but we still conservatively report an error, see
1350                                 // issues/33118#issuecomment-233962221 for one reason why.
1351                                 self.r.report_error(
1352                                     ident.span,
1353                                     ResolutionError::BindingShadowsSomethingUnacceptable(
1354                                         pat_src.descr(), ident.name, binding.unwrap())
1355                                 );
1356                                 None
1357                             }
1358                             Res::Def(DefKind::Fn, _) | Res::Err => {
1359                                 // These entities are explicitly allowed
1360                                 // to be shadowed by fresh bindings.
1361                                 None
1362                             }
1363                             res => {
1364                                 span_bug!(ident.span, "unexpected resolution for an \
1365                                                        identifier in pattern: {:?}", res);
1366                             }
1367                         }
1368                     }).unwrap_or_else(|| {
1369                         self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1370                     });
1371
1372                     self.r.record_partial_res(pat.id, PartialRes::new(res));
1373                 }
1374
1375                 PatKind::TupleStruct(ref path, ..) => {
1376                     self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1377                 }
1378
1379                 PatKind::Path(ref qself, ref path) => {
1380                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1381                 }
1382
1383                 PatKind::Struct(ref path, ..) => {
1384                     self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1385                 }
1386
1387                 _ => {}
1388             }
1389             true
1390         });
1391
1392         visit::walk_pat(self, pat);
1393     }
1394
1395     // High-level and context dependent path resolution routine.
1396     // Resolves the path and records the resolution into definition map.
1397     // If resolution fails tries several techniques to find likely
1398     // resolution candidates, suggest imports or other help, and report
1399     // errors in user friendly way.
1400     fn smart_resolve_path(&mut self,
1401                           id: NodeId,
1402                           qself: Option<&QSelf>,
1403                           path: &Path,
1404                           source: PathSource<'_>) {
1405         self.smart_resolve_path_fragment(
1406             id,
1407             qself,
1408             &Segment::from_path(path),
1409             path.span,
1410             source,
1411             CrateLint::SimplePath(id),
1412         );
1413     }
1414
1415     fn smart_resolve_path_fragment(&mut self,
1416                                    id: NodeId,
1417                                    qself: Option<&QSelf>,
1418                                    path: &[Segment],
1419                                    span: Span,
1420                                    source: PathSource<'_>,
1421                                    crate_lint: CrateLint)
1422                                    -> PartialRes {
1423         let ns = source.namespace();
1424         let is_expected = &|res| source.is_expected(res);
1425
1426         let report_errors = |this: &mut Self, res: Option<Res>| {
1427             let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1428             let def_id = this.parent_scope.module.normal_ancestor_id;
1429             let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1430             let better = res.is_some();
1431             this.r.use_injections.push(UseError { err, candidates, node_id, better });
1432             PartialRes::new(Res::Err)
1433         };
1434
1435         let partial_res = match self.resolve_qpath_anywhere(
1436             id,
1437             qself,
1438             path,
1439             ns,
1440             span,
1441             source.defer_to_typeck(),
1442             crate_lint,
1443         ) {
1444             Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1445                 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1446                     partial_res
1447                 } else {
1448                     // Add a temporary hack to smooth the transition to new struct ctor
1449                     // visibility rules. See #38932 for more details.
1450                     let mut res = None;
1451                     if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1452                         if let Some((ctor_res, ctor_vis))
1453                                 = self.r.struct_constructors.get(&def_id).cloned() {
1454                             if is_expected(ctor_res) &&
1455                                self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1456                                 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1457                                 self.r.session.buffer_lint(lint, id, span,
1458                                     "private struct constructors are not usable through \
1459                                      re-exports in outer modules",
1460                                 );
1461                                 res = Some(PartialRes::new(ctor_res));
1462                             }
1463                         }
1464                     }
1465
1466                     res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1467                 }
1468             }
1469             Some(partial_res) if source.defer_to_typeck() => {
1470                 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1471                 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1472                 // it needs to be added to the trait map.
1473                 if ns == ValueNS {
1474                     let item_name = path.last().unwrap().ident;
1475                     let traits = self.get_traits_containing_item(item_name, ns);
1476                     self.r.trait_map.insert(id, traits);
1477                 }
1478
1479                 let mut std_path = vec![Segment::from_ident(Ident::with_empty_ctxt(sym::std))];
1480                 std_path.extend(path);
1481                 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1482                     let cl = CrateLint::No;
1483                     let ns = Some(ns);
1484                     if let PathResult::Module(_) | PathResult::NonModule(_) =
1485                             self.resolve_path(&std_path, ns, false, span, cl) {
1486                         // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1487                         let item_span = path.iter().last().map(|segment| segment.ident.span)
1488                             .unwrap_or(span);
1489                         debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1490                         let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1491                         hm.insert(item_span, span);
1492                         // In some places (E0223) we only have access to the full path
1493                         hm.insert(span, span);
1494                     }
1495                 }
1496                 partial_res
1497             }
1498             _ => report_errors(self, None)
1499         };
1500
1501         if let PathSource::TraitItem(..) = source {} else {
1502             // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1503             self.r.record_partial_res(id, partial_res);
1504         }
1505         partial_res
1506     }
1507
1508     fn self_type_is_available(&mut self, span: Span) -> bool {
1509         let binding = self.resolve_ident_in_lexical_scope(
1510             Ident::with_empty_ctxt(kw::SelfUpper),
1511             TypeNS,
1512             None,
1513             span,
1514         );
1515         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1516     }
1517
1518     fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1519         let ident = Ident::new(kw::SelfLower, self_span);
1520         let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1521         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1522     }
1523
1524     // Resolve in alternative namespaces if resolution in the primary namespace fails.
1525     fn resolve_qpath_anywhere(
1526         &mut self,
1527         id: NodeId,
1528         qself: Option<&QSelf>,
1529         path: &[Segment],
1530         primary_ns: Namespace,
1531         span: Span,
1532         defer_to_typeck: bool,
1533         crate_lint: CrateLint,
1534     ) -> Option<PartialRes> {
1535         let mut fin_res = None;
1536         for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1537             if i == 0 || ns != primary_ns {
1538                 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1539                     // If defer_to_typeck, then resolution > no resolution,
1540                     // otherwise full resolution > partial resolution > no resolution.
1541                     Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1542                                          defer_to_typeck =>
1543                         return Some(partial_res),
1544                     partial_res => if fin_res.is_none() { fin_res = partial_res },
1545                 }
1546             }
1547         }
1548
1549         // `MacroNS`
1550         assert!(primary_ns != MacroNS);
1551         if qself.is_none() {
1552             let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1553             let path = Path { segments: path.iter().map(path_seg).collect(), span };
1554             if let Ok((_, res)) = self.r.resolve_macro_path(
1555                 &path, None, &self.parent_scope, false, false
1556             ) {
1557                 return Some(PartialRes::new(res));
1558             }
1559         }
1560
1561         fin_res
1562     }
1563
1564     /// Handles paths that may refer to associated items.
1565     fn resolve_qpath(
1566         &mut self,
1567         id: NodeId,
1568         qself: Option<&QSelf>,
1569         path: &[Segment],
1570         ns: Namespace,
1571         span: Span,
1572         crate_lint: CrateLint,
1573     ) -> Option<PartialRes> {
1574         debug!(
1575             "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1576             id,
1577             qself,
1578             path,
1579             ns,
1580             span,
1581         );
1582
1583         if let Some(qself) = qself {
1584             if qself.position == 0 {
1585                 // This is a case like `<T>::B`, where there is no
1586                 // trait to resolve.  In that case, we leave the `B`
1587                 // segment to be resolved by type-check.
1588                 return Some(PartialRes::with_unresolved_segments(
1589                     Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1590                 ));
1591             }
1592
1593             // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1594             //
1595             // Currently, `path` names the full item (`A::B::C`, in
1596             // our example).  so we extract the prefix of that that is
1597             // the trait (the slice upto and including
1598             // `qself.position`). And then we recursively resolve that,
1599             // but with `qself` set to `None`.
1600             //
1601             // However, setting `qself` to none (but not changing the
1602             // span) loses the information about where this path
1603             // *actually* appears, so for the purposes of the crate
1604             // lint we pass along information that this is the trait
1605             // name from a fully qualified path, and this also
1606             // contains the full span (the `CrateLint::QPathTrait`).
1607             let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1608             let partial_res = self.smart_resolve_path_fragment(
1609                 id,
1610                 None,
1611                 &path[..=qself.position],
1612                 span,
1613                 PathSource::TraitItem(ns),
1614                 CrateLint::QPathTrait {
1615                     qpath_id: id,
1616                     qpath_span: qself.path_span,
1617                 },
1618             );
1619
1620             // The remaining segments (the `C` in our example) will
1621             // have to be resolved by type-check, since that requires doing
1622             // trait resolution.
1623             return Some(PartialRes::with_unresolved_segments(
1624                 partial_res.base_res(),
1625                 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1626             ));
1627         }
1628
1629         let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1630             PathResult::NonModule(path_res) => path_res,
1631             PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1632                 PartialRes::new(module.res().unwrap())
1633             }
1634             // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1635             // don't report an error right away, but try to fallback to a primitive type.
1636             // So, we are still able to successfully resolve something like
1637             //
1638             // use std::u8; // bring module u8 in scope
1639             // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1640             //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
1641             //                     // not to non-existent std::u8::max_value
1642             // }
1643             //
1644             // Such behavior is required for backward compatibility.
1645             // The same fallback is used when `a` resolves to nothing.
1646             PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1647             PathResult::Failed { .. }
1648                     if (ns == TypeNS || path.len() > 1) &&
1649                        self.r.primitive_type_table.primitive_types
1650                            .contains_key(&path[0].ident.name) => {
1651                 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1652                 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1653             }
1654             PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1655                 PartialRes::new(module.res().unwrap()),
1656             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1657                 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1658                 PartialRes::new(Res::Err)
1659             }
1660             PathResult::Module(..) | PathResult::Failed { .. } => return None,
1661             PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1662         };
1663
1664         if path.len() > 1 && result.base_res() != Res::Err &&
1665            path[0].ident.name != kw::PathRoot &&
1666            path[0].ident.name != kw::DollarCrate {
1667             let unqualified_result = {
1668                 match self.resolve_path(
1669                     &[*path.last().unwrap()],
1670                     Some(ns),
1671                     false,
1672                     span,
1673                     CrateLint::No,
1674                 ) {
1675                     PathResult::NonModule(path_res) => path_res.base_res(),
1676                     PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1677                         module.res().unwrap(),
1678                     _ => return Some(result),
1679                 }
1680             };
1681             if result.base_res() == unqualified_result {
1682                 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1683                 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1684             }
1685         }
1686
1687         Some(result)
1688     }
1689
1690     fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
1691         where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1692     {
1693         if let Some(label) = label {
1694             self.unused_labels.insert(id, label.ident.span);
1695             self.with_label_rib(|this| {
1696                 let ident = label.ident.modern_and_legacy();
1697                 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1698                 f(this);
1699             });
1700         } else {
1701             f(self);
1702         }
1703     }
1704
1705     fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1706         self.with_resolved_label(label, id, |this| this.visit_block(block));
1707     }
1708
1709     fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1710         // First, record candidate traits for this expression if it could
1711         // result in the invocation of a method call.
1712
1713         self.record_candidate_traits_for_expr_if_necessary(expr);
1714
1715         // Next, resolve the node.
1716         match expr.node {
1717             ExprKind::Path(ref qself, ref path) => {
1718                 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1719                 visit::walk_expr(self, expr);
1720             }
1721
1722             ExprKind::Struct(ref path, ..) => {
1723                 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1724                 visit::walk_expr(self, expr);
1725             }
1726
1727             ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1728                 let node_id = self.search_label(label.ident, |rib, ident| {
1729                     rib.bindings.get(&ident.modern_and_legacy()).cloned()
1730                 });
1731                 match node_id {
1732                     None => {
1733                         // Search again for close matches...
1734                         // Picks the first label that is "close enough", which is not necessarily
1735                         // the closest match
1736                         let close_match = self.search_label(label.ident, |rib, ident| {
1737                             let names = rib.bindings.iter().filter_map(|(id, _)| {
1738                                 if id.span.ctxt() == label.ident.span.ctxt() {
1739                                     Some(&id.name)
1740                                 } else {
1741                                     None
1742                                 }
1743                             });
1744                             find_best_match_for_name(names, &*ident.as_str(), None)
1745                         });
1746                         self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1747                         self.r.report_error(
1748                             label.ident.span,
1749                             ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1750                         );
1751                     }
1752                     Some(node_id) => {
1753                         // Since this res is a label, it is never read.
1754                         self.r.label_res_map.insert(expr.id, node_id);
1755                         self.unused_labels.remove(&node_id);
1756                     }
1757                 }
1758
1759                 // visit `break` argument if any
1760                 visit::walk_expr(self, expr);
1761             }
1762
1763             ExprKind::Let(ref pats, ref scrutinee) => {
1764                 self.visit_expr(scrutinee);
1765                 self.resolve_pats(pats, PatternSource::Let);
1766             }
1767
1768             ExprKind::If(ref cond, ref then, ref opt_else) => {
1769                 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1770                 self.visit_expr(cond);
1771                 self.visit_block(then);
1772                 self.ribs[ValueNS].pop();
1773
1774                 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1775             }
1776
1777             ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1778
1779             ExprKind::While(ref subexpression, ref block, label) => {
1780                 self.with_resolved_label(label, expr.id, |this| {
1781                     this.ribs[ValueNS].push(Rib::new(NormalRibKind));
1782                     this.visit_expr(subexpression);
1783                     this.visit_block(block);
1784                     this.ribs[ValueNS].pop();
1785                 });
1786             }
1787
1788             ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
1789                 self.visit_expr(subexpression);
1790                 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1791                 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
1792
1793                 self.resolve_labeled_block(label, expr.id, block);
1794
1795                 self.ribs[ValueNS].pop();
1796             }
1797
1798             ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1799
1800             // Equivalent to `visit::walk_expr` + passing some context to children.
1801             ExprKind::Field(ref subexpression, _) => {
1802                 self.resolve_expr(subexpression, Some(expr));
1803             }
1804             ExprKind::MethodCall(ref segment, ref arguments) => {
1805                 let mut arguments = arguments.iter();
1806                 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1807                 for argument in arguments {
1808                     self.resolve_expr(argument, None);
1809                 }
1810                 self.visit_path_segment(expr.span, segment);
1811             }
1812
1813             ExprKind::Call(ref callee, ref arguments) => {
1814                 self.resolve_expr(callee, Some(expr));
1815                 for argument in arguments {
1816                     self.resolve_expr(argument, None);
1817                 }
1818             }
1819             ExprKind::Type(ref type_expr, _) => {
1820                 self.current_type_ascription.push(type_expr.span);
1821                 visit::walk_expr(self, expr);
1822                 self.current_type_ascription.pop();
1823             }
1824             // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1825             // resolve the arguments within the proper scopes so that usages of them inside the
1826             // closure are detected as upvars rather than normal closure arg usages.
1827             ExprKind::Closure(
1828                 _, IsAsync::Async { .. }, _,
1829                 ref fn_decl, ref body, _span,
1830             ) => {
1831                 let rib_kind = NormalRibKind;
1832                 self.ribs[ValueNS].push(Rib::new(rib_kind));
1833                 // Resolve arguments:
1834                 let mut bindings_list = FxHashMap::default();
1835                 for argument in &fn_decl.inputs {
1836                     self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1837                     self.visit_ty(&argument.ty);
1838                 }
1839                 // No need to resolve return type-- the outer closure return type is
1840                 // FunctionRetTy::Default
1841
1842                 // Now resolve the inner closure
1843                 {
1844                     // No need to resolve arguments: the inner closure has none.
1845                     // Resolve the return type:
1846                     visit::walk_fn_ret_ty(self, &fn_decl.output);
1847                     // Resolve the body
1848                     self.visit_expr(body);
1849                 }
1850                 self.ribs[ValueNS].pop();
1851             }
1852             _ => {
1853                 visit::walk_expr(self, expr);
1854             }
1855         }
1856     }
1857
1858     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1859         match expr.node {
1860             ExprKind::Field(_, ident) => {
1861                 // FIXME(#6890): Even though you can't treat a method like a
1862                 // field, we need to add any trait methods we find that match
1863                 // the field name so that we can do some nice error reporting
1864                 // later on in typeck.
1865                 let traits = self.get_traits_containing_item(ident, ValueNS);
1866                 self.r.trait_map.insert(expr.id, traits);
1867             }
1868             ExprKind::MethodCall(ref segment, ..) => {
1869                 debug!("(recording candidate traits for expr) recording traits for {}",
1870                        expr.id);
1871                 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1872                 self.r.trait_map.insert(expr.id, traits);
1873             }
1874             _ => {
1875                 // Nothing to do.
1876             }
1877         }
1878     }
1879
1880     fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1881                                   -> Vec<TraitCandidate> {
1882         debug!("(getting traits containing item) looking for '{}'", ident.name);
1883
1884         let mut found_traits = Vec::new();
1885         // Look for the current trait.
1886         if let Some((module, _)) = self.current_trait_ref {
1887             if self.r.resolve_ident_in_module(
1888                 ModuleOrUniformRoot::Module(module),
1889                 ident,
1890                 ns,
1891                 &self.parent_scope,
1892                 false,
1893                 module.span,
1894             ).is_ok() {
1895                 let def_id = module.def_id().unwrap();
1896                 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1897             }
1898         }
1899
1900         ident.span = ident.span.modern();
1901         let mut search_module = self.parent_scope.module;
1902         loop {
1903             self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1904             search_module = unwrap_or!(
1905                 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1906             );
1907         }
1908
1909         if let Some(prelude) = self.r.prelude {
1910             if !search_module.no_implicit_prelude {
1911                 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1912             }
1913         }
1914
1915         found_traits
1916     }
1917
1918     fn get_traits_in_module_containing_item(&mut self,
1919                                             ident: Ident,
1920                                             ns: Namespace,
1921                                             module: Module<'a>,
1922                                             found_traits: &mut Vec<TraitCandidate>) {
1923         assert!(ns == TypeNS || ns == ValueNS);
1924         let mut traits = module.traits.borrow_mut();
1925         if traits.is_none() {
1926             let mut collected_traits = Vec::new();
1927             module.for_each_child(|name, ns, binding| {
1928                 if ns != TypeNS { return }
1929                 match binding.res() {
1930                     Res::Def(DefKind::Trait, _) |
1931                     Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1932                     _ => (),
1933                 }
1934             });
1935             *traits = Some(collected_traits.into_boxed_slice());
1936         }
1937
1938         for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1939             // Traits have pseudo-modules that can be used to search for the given ident.
1940             if let Some(module) = binding.module() {
1941                 let mut ident = ident;
1942                 if ident.span.glob_adjust(
1943                     module.expansion,
1944                     binding.span,
1945                 ).is_none() {
1946                     continue
1947                 }
1948                 if self.r.resolve_ident_in_module_unadjusted(
1949                     ModuleOrUniformRoot::Module(module),
1950                     ident,
1951                     ns,
1952                     &self.parent_scope,
1953                     false,
1954                     module.span,
1955                 ).is_ok() {
1956                     let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1957                     let trait_def_id = module.def_id().unwrap();
1958                     found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1959                 }
1960             } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1961                 // For now, just treat all trait aliases as possible candidates, since we don't
1962                 // know if the ident is somewhere in the transitive bounds.
1963                 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1964                 let trait_def_id = binding.res().def_id();
1965                 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1966             } else {
1967                 bug!("candidate is not trait or trait alias?")
1968             }
1969         }
1970     }
1971
1972     fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
1973                                trait_name: Ident) -> SmallVec<[NodeId; 1]> {
1974         let mut import_ids = smallvec![];
1975         while let NameBindingKind::Import { directive, binding, .. } = kind {
1976             self.r.maybe_unused_trait_imports.insert(directive.id);
1977             self.r.add_to_glob_map(&directive, trait_name);
1978             import_ids.push(directive.id);
1979             kind = &binding.kind;
1980         };
1981         import_ids
1982     }
1983 }
1984
1985 impl<'a> Resolver<'a> {
1986     pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
1987         self.finalize_current_module_macro_resolutions(self.graph_root);
1988         let mut late_resolution_visitor = LateResolutionVisitor::new(self);
1989         visit::walk_crate(&mut late_resolution_visitor, krate);
1990         for (id, span) in late_resolution_visitor.unused_labels.iter() {
1991             self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
1992         }
1993     }
1994 }