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