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