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