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