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