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