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