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