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