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