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.
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`.
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};
14 use rustc::{bug, lint, span_bug};
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_errors::DiagnosticId;
17 use rustc_hir::def::Namespace::{self, *};
18 use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS};
19 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
20 use rustc_hir::TraitCandidate;
21 use rustc_span::symbol::{kw, sym};
23 use smallvec::{smallvec, SmallVec};
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use syntax::visit::{self, FnKind, Visitor};
28 use syntax::{unwrap_or, walk_list};
31 use std::collections::BTreeSet;
32 use std::mem::replace;
36 type Res = def::Res<NodeId>;
38 type IdentMap<T> = FxHashMap<Ident, T>;
40 /// Map from the name in a pattern to its binding mode.
41 type BindingMap = IdentMap<BindingInfo>;
43 #[derive(Copy, Clone, Debug)]
46 binding_mode: BindingMode,
49 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
58 fn descr(self) -> &'static str {
60 PatternSource::Match => "match binding",
61 PatternSource::Let => "let binding",
62 PatternSource::For => "for binding",
63 PatternSource::FnParam => "function parameter",
68 /// Denotes whether the context for the set of already bound bindings is a `Product`
69 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
70 /// See those functions for more information.
73 /// A product pattern context, e.g., `Variant(a, b)`.
75 /// An or-pattern context, e.g., `p_0 | ... | p_n`.
79 /// Does this the item (from the item rib scope) allow generic parameters?
80 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
81 crate enum HasGenericParams {
86 /// The rib kind restricts certain accesses,
87 /// e.g. to a `Res::Local` of an outer item.
88 #[derive(Copy, Clone, Debug)]
89 crate enum RibKind<'a> {
90 /// No restriction needs to be applied.
93 /// We passed through an impl or trait and are now in one of its
94 /// methods or associated types. Allow references to ty params that impl or trait
95 /// binds. Disallow any other upvars (including other ty params that are
99 /// We passed through a function definition. Disallow upvars.
100 /// Permit only those const parameters that are specified in the function's generics.
103 /// We passed through an item scope. Disallow upvars.
104 ItemRibKind(HasGenericParams),
106 /// We're in a constant item. Can't refer to dynamic stuff.
109 /// We passed through a module.
110 ModuleRibKind(Module<'a>),
112 /// We passed through a `macro_rules!` statement
113 MacroDefinition(DefId),
115 /// All bindings in this rib are type parameters that can't be used
116 /// from the default of a type parameter because they're not declared
117 /// before said type parameter. Also see the `visit_generics` override.
118 ForwardTyParamBanRibKind,
122 // Whether this rib kind contains generic parameters, as opposed to local
124 crate fn contains_params(&self) -> bool {
126 NormalRibKind | FnItemRibKind | ConstantItemRibKind | ModuleRibKind(_)
127 | MacroDefinition(_) => false,
128 AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true,
133 /// A single local scope.
135 /// A rib represents a scope names can live in. Note that these appear in many places, not just
136 /// around braces. At any place where the list of accessible names (of the given namespace)
137 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
138 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
141 /// Different [rib kinds](enum.RibKind) are transparent for different names.
143 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
144 /// resolving, the name is looked up from inside out.
146 crate struct Rib<'a, R = Res> {
147 pub bindings: IdentMap<R>,
148 pub kind: RibKind<'a>,
151 impl<'a, R> Rib<'a, R> {
152 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
153 Rib { bindings: Default::default(), kind }
157 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
158 crate enum AliasPossibility {
163 #[derive(Copy, Clone, Debug)]
164 crate enum PathSource<'a> {
165 // Type paths `Path`.
167 // Trait paths in bounds or impls.
168 Trait(AliasPossibility),
169 // Expression paths `path`, with optional parent context.
170 Expr(Option<&'a Expr>),
171 // Paths in path patterns `Path`.
173 // Paths in struct expressions and patterns `Path { .. }`.
175 // Paths in tuple struct patterns `Path(..)`.
177 // `m::A::B` in `<T as m::A>::B::C`.
178 TraitItem(Namespace),
181 impl<'a> PathSource<'a> {
182 fn namespace(self) -> Namespace {
184 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
185 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
186 PathSource::TraitItem(ns) => ns,
190 fn defer_to_typeck(self) -> bool {
193 | PathSource::Expr(..)
196 | PathSource::TupleStruct => true,
197 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
201 fn descr_expected(self) -> &'static str {
203 PathSource::Type => "type",
204 PathSource::Trait(_) => "trait",
205 PathSource::Pat => "unit struct, unit variant or constant",
206 PathSource::Struct => "struct, variant or union type",
207 PathSource::TupleStruct => "tuple struct or tuple variant",
208 PathSource::TraitItem(ns) => match ns {
209 TypeNS => "associated type",
210 ValueNS => "method or associated constant",
211 MacroNS => bug!("associated macro"),
213 PathSource::Expr(parent) => match &parent.as_ref().map(|p| &p.kind) {
214 // "function" here means "anything callable" rather than `DefKind::Fn`,
215 // this is not precise but usually more helpful than just "value".
216 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
217 ExprKind::Path(_, path) => {
218 let mut msg = "function";
219 if let Some(segment) = path.segments.iter().last() {
220 if let Some(c) = segment.ident.to_string().chars().next() {
221 if c.is_uppercase() {
222 msg = "function, tuple struct or tuple variant";
235 crate fn is_expected(self, res: Res) -> bool {
237 PathSource::Type => match res {
238 Res::Def(DefKind::Struct, _)
239 | Res::Def(DefKind::Union, _)
240 | Res::Def(DefKind::Enum, _)
241 | Res::Def(DefKind::Trait, _)
242 | Res::Def(DefKind::TraitAlias, _)
243 | Res::Def(DefKind::TyAlias, _)
244 | Res::Def(DefKind::AssocTy, _)
246 | Res::Def(DefKind::TyParam, _)
248 | Res::Def(DefKind::OpaqueTy, _)
249 | Res::Def(DefKind::ForeignTy, _) => true,
252 PathSource::Trait(AliasPossibility::No) => match res {
253 Res::Def(DefKind::Trait, _) => true,
256 PathSource::Trait(AliasPossibility::Maybe) => match res {
257 Res::Def(DefKind::Trait, _) => true,
258 Res::Def(DefKind::TraitAlias, _) => true,
261 PathSource::Expr(..) => match res {
262 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
263 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
264 | Res::Def(DefKind::Const, _)
265 | Res::Def(DefKind::Static, _)
267 | Res::Def(DefKind::Fn, _)
268 | Res::Def(DefKind::Method, _)
269 | Res::Def(DefKind::AssocConst, _)
271 | Res::Def(DefKind::ConstParam, _) => true,
274 PathSource::Pat => match res {
275 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
276 | Res::Def(DefKind::Const, _)
277 | Res::Def(DefKind::AssocConst, _)
278 | Res::SelfCtor(..) => true,
281 PathSource::TupleStruct => match res {
282 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
285 PathSource::Struct => match res {
286 Res::Def(DefKind::Struct, _)
287 | Res::Def(DefKind::Union, _)
288 | Res::Def(DefKind::Variant, _)
289 | Res::Def(DefKind::TyAlias, _)
290 | Res::Def(DefKind::AssocTy, _)
291 | Res::SelfTy(..) => true,
294 PathSource::TraitItem(ns) => match res {
295 Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::Method, _)
300 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
306 fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
307 use rustc_errors::error_code;
308 match (self, has_unexpected_resolution) {
309 (PathSource::Trait(_), true) => error_code!(E0404),
310 (PathSource::Trait(_), false) => error_code!(E0405),
311 (PathSource::Type, true) => error_code!(E0573),
312 (PathSource::Type, false) => error_code!(E0412),
313 (PathSource::Struct, true) => error_code!(E0574),
314 (PathSource::Struct, false) => error_code!(E0422),
315 (PathSource::Expr(..), true) => error_code!(E0423),
316 (PathSource::Expr(..), false) => error_code!(E0425),
317 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => error_code!(E0532),
318 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => error_code!(E0531),
319 (PathSource::TraitItem(..), true) => error_code!(E0575),
320 (PathSource::TraitItem(..), false) => error_code!(E0576),
326 struct DiagnosticMetadata<'ast> {
327 /// The current trait's associated types' ident, used for diagnostic suggestions.
328 current_trait_assoc_types: Vec<Ident>,
330 /// The current self type if inside an impl (used for better errors).
331 current_self_type: Option<Ty>,
333 /// The current self item if inside an ADT (used for better errors).
334 current_self_item: Option<NodeId>,
336 /// The current trait (used to suggest).
337 current_item: Option<&'ast Item>,
339 /// When processing generics and encountering a type not found, suggest introducing a type
341 currently_processing_generics: bool,
343 /// The current enclosing function (used for better errors).
344 current_function: Option<Span>,
346 /// A list of labels as of yet unused. Labels will be removed from this map when
347 /// they are used (in a `break` or `continue` statement)
348 unused_labels: FxHashMap<NodeId, Span>,
350 /// Only used for better errors on `fn(): fn()`.
351 current_type_ascription: Vec<Span>,
353 /// Only used for better errors on `let <pat>: <expr, not type>;`.
354 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
357 struct LateResolutionVisitor<'a, 'b, 'ast> {
358 r: &'b mut Resolver<'a>,
360 /// The module that represents the current item scope.
361 parent_scope: ParentScope<'a>,
363 /// The current set of local scopes for types and values.
364 /// FIXME #4948: Reuse ribs to avoid allocation.
365 ribs: PerNS<Vec<Rib<'a>>>,
367 /// The current set of local scopes, for labels.
368 label_ribs: Vec<Rib<'a, NodeId>>,
370 /// The trait that the current context can refer to.
371 current_trait_ref: Option<(Module<'a>, TraitRef)>,
373 /// Fields used to add information to diagnostic errors.
374 diagnostic_metadata: DiagnosticMetadata<'ast>,
377 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
378 impl<'a, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
379 fn visit_item(&mut self, item: &'ast Item) {
380 let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
381 self.resolve_item(item);
382 self.diagnostic_metadata.current_item = prev;
384 fn visit_arm(&mut self, arm: &'ast Arm) {
385 self.resolve_arm(arm);
387 fn visit_block(&mut self, block: &'ast Block) {
388 self.resolve_block(block);
390 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
391 debug!("visit_anon_const {:?}", constant);
392 self.with_constant_rib(|this| {
393 visit::walk_anon_const(this, constant);
396 fn visit_expr(&mut self, expr: &'ast Expr) {
397 self.resolve_expr(expr, None);
399 fn visit_local(&mut self, local: &'ast Local) {
400 let local_spans = match local.pat.kind {
401 // We check for this to avoid tuple struct fields.
402 PatKind::Wild => None,
405 local.ty.as_ref().map(|ty| ty.span),
406 local.init.as_ref().map(|init| init.span),
409 let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
410 self.resolve_local(local);
411 self.diagnostic_metadata.current_let_binding = original;
413 fn visit_ty(&mut self, ty: &'ast Ty) {
415 TyKind::Path(ref qself, ref path) => {
416 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
418 TyKind::ImplicitSelf => {
419 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
421 .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
422 .map_or(Res::Err, |d| d.res());
423 self.r.record_partial_res(ty.id, PartialRes::new(res));
427 visit::walk_ty(self, ty);
429 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
430 self.smart_resolve_path(
431 tref.trait_ref.ref_id,
433 &tref.trait_ref.path,
434 PathSource::Trait(AliasPossibility::Maybe),
436 visit::walk_poly_trait_ref(self, tref, m);
438 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
439 match foreign_item.kind {
440 ForeignItemKind::Fn(_, ref generics) => {
441 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
442 visit::walk_foreign_item(this, foreign_item);
445 ForeignItemKind::Static(..) => {
446 self.with_item_rib(HasGenericParams::No, |this| {
447 visit::walk_foreign_item(this, foreign_item);
450 ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {
451 visit::walk_foreign_item(self, foreign_item);
455 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, declaration: &'ast FnDecl, sp: Span, _: NodeId) {
456 let previous_value = replace(&mut self.diagnostic_metadata.current_function, Some(sp));
457 debug!("(resolving function) entering function");
458 let rib_kind = match fn_kind {
459 FnKind::ItemFn(..) => FnItemRibKind,
460 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
463 // Create a value rib for the function.
464 self.with_rib(ValueNS, rib_kind, |this| {
465 // Create a label rib for the function.
466 this.with_label_rib(rib_kind, |this| {
467 // Add each argument to the rib.
468 this.resolve_params(&declaration.inputs);
470 visit::walk_fn_ret_ty(this, &declaration.output);
472 // Resolve the function body, potentially inside the body of an async closure
474 FnKind::ItemFn(.., body) | FnKind::Method(.., body) => this.visit_block(body),
475 FnKind::Closure(body) => this.visit_expr(body),
478 debug!("(resolving function) leaving function");
481 self.diagnostic_metadata.current_function = previous_value;
484 fn visit_generics(&mut self, generics: &'ast Generics) {
485 // For type parameter defaults, we have to ban access
486 // to following type parameters, as the InternalSubsts can only
487 // provide previous type parameters as they're built. We
488 // put all the parameters on the ban list and then remove
489 // them one by one as they are processed and become available.
490 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
491 let mut found_default = false;
492 default_ban_rib.bindings.extend(generics.params.iter().filter_map(
493 |param| match param.kind {
494 GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None,
495 GenericParamKind::Type { ref default, .. } => {
496 found_default |= default.is_some();
497 found_default.then_some((Ident::with_dummy_span(param.ident.name), Res::Err))
502 // rust-lang/rust#61631: The type `Self` is essentially
503 // another type parameter. For ADTs, we consider it
504 // well-defined only after all of the ADT type parameters have
505 // been provided. Therefore, we do not allow use of `Self`
506 // anywhere in ADT type parameter defaults.
508 // (We however cannot ban `Self` for defaults on *all* generic
509 // lists; e.g. trait generics can usefully refer to `Self`,
510 // such as in the case of `trait Add<Rhs = Self>`.)
511 if self.diagnostic_metadata.current_self_item.is_some() {
512 // (`Some` if + only if we are in ADT's generics.)
513 default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
516 for param in &generics.params {
518 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
519 GenericParamKind::Type { ref default, .. } => {
520 for bound in ¶m.bounds {
521 self.visit_param_bound(bound);
524 if let Some(ref ty) = default {
525 self.ribs[TypeNS].push(default_ban_rib);
527 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
530 // Allow all following defaults to refer to this type parameter.
531 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
533 GenericParamKind::Const { ref ty } => {
534 for bound in ¶m.bounds {
535 self.visit_param_bound(bound);
541 for p in &generics.where_clause.predicates {
542 self.visit_where_predicate(p);
546 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
547 debug!("visit_generic_arg({:?})", arg);
548 let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
550 GenericArg::Type(ref ty) => {
551 // We parse const arguments as path types as we cannot distiguish them during
552 // parsing. We try to resolve that ambiguity by attempting resolution the type
553 // namespace first, and if that fails we try again in the value namespace. If
554 // resolution in the value namespace succeeds, we have an generic const argument on
556 if let TyKind::Path(ref qself, ref path) = ty.kind {
557 // We cannot disambiguate multi-segment paths right now as that requires type
559 if path.segments.len() == 1 && path.segments[0].args.is_none() {
560 let mut check_ns = |ns| {
561 self.resolve_ident_in_lexical_scope(
562 path.segments[0].ident,
569 if !check_ns(TypeNS) && check_ns(ValueNS) {
570 // This must be equivalent to `visit_anon_const`, but we cannot call it
571 // directly due to visitor lifetimes so we have to copy-paste some code.
572 self.with_constant_rib(|this| {
573 this.smart_resolve_path(
577 PathSource::Expr(None),
580 if let Some(ref qself) = *qself {
581 this.visit_ty(&qself.ty);
583 this.visit_path(path, ty.id);
586 self.diagnostic_metadata.currently_processing_generics = prev;
594 GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
595 GenericArg::Const(ct) => self.visit_anon_const(ct),
597 self.diagnostic_metadata.currently_processing_generics = prev;
601 impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
602 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
603 // During late resolution we only track the module component of the parent scope,
604 // although it may be useful to track other components as well for diagnostics.
605 let graph_root = resolver.graph_root;
606 let parent_scope = ParentScope::module(graph_root);
607 let start_rib_kind = ModuleRibKind(graph_root);
608 LateResolutionVisitor {
612 value_ns: vec![Rib::new(start_rib_kind)],
613 type_ns: vec![Rib::new(start_rib_kind)],
614 macro_ns: vec![Rib::new(start_rib_kind)],
616 label_ribs: Vec::new(),
617 current_trait_ref: None,
618 diagnostic_metadata: DiagnosticMetadata::default(),
622 fn resolve_ident_in_lexical_scope(
626 record_used_id: Option<NodeId>,
628 ) -> Option<LexicalScopeBinding<'a>> {
629 self.r.resolve_ident_in_lexical_scope(
642 opt_ns: Option<Namespace>, // `None` indicates a module path in import
645 crate_lint: CrateLint,
646 ) -> PathResult<'a> {
647 self.r.resolve_path_with_ribs(
660 // We maintain a list of value ribs and type ribs.
662 // Simultaneously, we keep track of the current position in the module
663 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
664 // the value or type namespaces, we first look through all the ribs and
665 // then query the module graph. When we resolve a name in the module
666 // namespace, we can skip all the ribs (since nested modules are not
667 // allowed within blocks in Rust) and jump straight to the current module
670 // Named implementations are handled separately. When we find a method
671 // call, we consult the module node to find all of the implementations in
672 // scope. This information is lazily cached in the module node. We then
673 // generate a fake "implementation scope" containing all the
674 // implementations thus found, for compatibility with old resolve pass.
676 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
681 work: impl FnOnce(&mut Self) -> T,
683 self.ribs[ns].push(Rib::new(kind));
684 let ret = work(self);
689 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
690 let id = self.r.definitions.local_def_id(id);
691 let module = self.r.module_map.get(&id).cloned(); // clones a reference
692 if let Some(module) = module {
693 // Move down in the graph.
694 let orig_module = replace(&mut self.parent_scope.module, module);
695 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
696 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
698 this.parent_scope.module = orig_module;
707 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
708 /// is returned by the given predicate function
710 /// Stops after meeting a closure.
711 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
713 P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>,
715 for rib in self.label_ribs.iter().rev() {
718 // If an invocation of this macro created `ident`, give up on `ident`
719 // and switch to `ident`'s source from the macro definition.
720 MacroDefinition(def) => {
721 if def == self.r.macro_def(ident.span.ctxt()) {
722 ident.span.remove_mark();
726 // Do not resolve labels across function boundary
730 let r = pred(rib, ident);
738 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
739 debug!("resolve_adt");
740 self.with_current_self_item(item, |this| {
741 this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
742 let item_def_id = this.r.definitions.local_def_id(item.id);
743 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
744 visit::walk_item(this, item);
750 fn future_proof_import(&mut self, use_tree: &UseTree) {
751 let segments = &use_tree.prefix.segments;
752 if !segments.is_empty() {
753 let ident = segments[0].ident;
754 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
758 let nss = match use_tree.kind {
759 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
762 let report_error = |this: &Self, ns| {
763 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
764 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
768 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
769 Some(LexicalScopeBinding::Res(..)) => {
770 report_error(self, ns);
772 Some(LexicalScopeBinding::Item(binding)) => {
773 let orig_blacklisted_binding =
774 replace(&mut self.r.blacklisted_binding, Some(binding));
775 if let Some(LexicalScopeBinding::Res(..)) = self
776 .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span)
778 report_error(self, ns);
780 self.r.blacklisted_binding = orig_blacklisted_binding;
785 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
786 for (use_tree, _) in use_trees {
787 self.future_proof_import(use_tree);
792 fn resolve_item(&mut self, item: &'ast Item) {
793 let name = item.ident.name;
794 debug!("(resolving item) resolving {} ({:?})", name, item.kind);
797 ItemKind::TyAlias(_, ref generics) | ItemKind::Fn(_, ref generics, _) => {
798 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
799 visit::walk_item(this, item)
803 ItemKind::Enum(_, ref generics)
804 | ItemKind::Struct(_, ref generics)
805 | ItemKind::Union(_, ref generics) => {
806 self.resolve_adt(item, generics);
813 items: ref impl_items,
816 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
819 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
820 // Create a new rib for the trait-wide type parameters.
821 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
822 let local_def_id = this.r.definitions.local_def_id(item.id);
823 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
824 this.visit_generics(generics);
825 walk_list!(this, visit_param_bound, bounds);
827 for trait_item in trait_items {
828 this.with_trait_items(trait_items, |this| {
829 this.with_generic_param_rib(
830 &trait_item.generics,
833 match trait_item.kind {
834 AssocItemKind::Const(ref ty, ref default) => {
837 // Only impose the restrictions of
838 // ConstRibKind for an actual constant
839 // expression in a provided default.
840 if let Some(ref expr) = *default {
841 this.with_constant_rib(|this| {
842 this.visit_expr(expr);
846 AssocItemKind::Fn(_, _) => {
847 visit::walk_trait_item(this, trait_item)
849 AssocItemKind::TyAlias(..) => {
850 visit::walk_trait_item(this, trait_item)
852 AssocItemKind::Macro(_) => {
853 panic!("unexpanded macro in resolve!")
864 ItemKind::TraitAlias(ref generics, ref bounds) => {
865 // Create a new rib for the trait-wide type parameters.
866 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
867 let local_def_id = this.r.definitions.local_def_id(item.id);
868 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
869 this.visit_generics(generics);
870 walk_list!(this, visit_param_bound, bounds);
875 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
876 self.with_scope(item.id, |this| {
877 visit::walk_item(this, item);
881 ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(ref ty, ref expr) => {
882 debug!("resolve_item ItemKind::Const");
883 self.with_item_rib(HasGenericParams::No, |this| {
885 this.with_constant_rib(|this| {
886 this.visit_expr(expr);
891 ItemKind::Use(ref use_tree) => {
892 self.future_proof_import(use_tree);
895 ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
896 // do nothing, these are just around to be encoded
899 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
903 fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F)
905 F: FnOnce(&mut Self),
907 debug!("with_generic_param_rib");
908 let mut function_type_rib = Rib::new(kind);
909 let mut function_value_rib = Rib::new(kind);
910 let mut seen_bindings = FxHashMap::default();
912 // We also can't shadow bindings from the parent item
913 if let AssocItemRibKind = kind {
914 let mut add_bindings_for_ns = |ns| {
915 let parent_rib = self.ribs[ns]
917 .rfind(|r| if let ItemRibKind(_) = r.kind { true } else { false })
918 .expect("associated item outside of an item");
920 .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
922 add_bindings_for_ns(ValueNS);
923 add_bindings_for_ns(TypeNS);
926 for param in &generics.params {
927 if let GenericParamKind::Lifetime { .. } = param.kind {
931 let def_kind = match param.kind {
932 GenericParamKind::Type { .. } => DefKind::TyParam,
933 GenericParamKind::Const { .. } => DefKind::ConstParam,
937 let ident = param.ident.modern();
938 debug!("with_generic_param_rib: {}", param.id);
940 if seen_bindings.contains_key(&ident) {
941 let span = seen_bindings.get(&ident).unwrap();
942 let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, *span);
943 self.r.report_error(param.ident.span, err);
945 seen_bindings.entry(ident).or_insert(param.ident.span);
947 // Plain insert (no renaming).
948 let res = Res::Def(def_kind, self.r.definitions.local_def_id(param.id));
951 GenericParamKind::Type { .. } => {
952 function_type_rib.bindings.insert(ident, res);
953 self.r.record_partial_res(param.id, PartialRes::new(res));
955 GenericParamKind::Const { .. } => {
956 function_value_rib.bindings.insert(ident, res);
957 self.r.record_partial_res(param.id, PartialRes::new(res));
963 self.ribs[ValueNS].push(function_value_rib);
964 self.ribs[TypeNS].push(function_type_rib);
968 self.ribs[TypeNS].pop();
969 self.ribs[ValueNS].pop();
972 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
973 self.label_ribs.push(Rib::new(kind));
975 self.label_ribs.pop();
978 fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) {
979 let kind = ItemRibKind(has_generic_params);
980 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
983 fn with_constant_rib(&mut self, f: impl FnOnce(&mut Self)) {
984 debug!("with_constant_rib");
985 self.with_rib(ValueNS, ConstantItemRibKind, |this| {
986 this.with_label_rib(ConstantItemRibKind, f);
990 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
991 // Handle nested impls (inside fn bodies)
993 replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
994 let result = f(self);
995 self.diagnostic_metadata.current_self_type = previous_value;
999 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
1000 let previous_value =
1001 replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
1002 let result = f(self);
1003 self.diagnostic_metadata.current_self_item = previous_value;
1007 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
1008 fn with_trait_items<T>(
1010 trait_items: &Vec<P<AssocItem>>,
1011 f: impl FnOnce(&mut Self) -> T,
1013 let trait_assoc_types = replace(
1014 &mut self.diagnostic_metadata.current_trait_assoc_types,
1017 .filter_map(|item| match &item.kind {
1018 AssocItemKind::TyAlias(bounds, _) if bounds.len() == 0 => Some(item.ident),
1023 let result = f(self);
1024 self.diagnostic_metadata.current_trait_assoc_types = trait_assoc_types;
1028 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
1029 fn with_optional_trait_ref<T>(
1031 opt_trait_ref: Option<&TraitRef>,
1032 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
1034 let mut new_val = None;
1035 let mut new_id = None;
1036 if let Some(trait_ref) = opt_trait_ref {
1037 let path: Vec<_> = Segment::from_path(&trait_ref.path);
1038 let res = self.smart_resolve_path_fragment(
1042 trait_ref.path.span,
1043 PathSource::Trait(AliasPossibility::No),
1044 CrateLint::SimplePath(trait_ref.ref_id),
1046 let res = res.base_res();
1047 if res != Res::Err {
1048 new_id = Some(res.def_id());
1049 let span = trait_ref.path.span;
1050 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
1055 CrateLint::SimplePath(trait_ref.ref_id),
1057 new_val = Some((module, trait_ref.clone()));
1061 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
1062 let result = f(self, new_id);
1063 self.current_trait_ref = original_trait_ref;
1067 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
1068 let mut self_type_rib = Rib::new(NormalRibKind);
1070 // Plain insert (no renaming, since types are not currently hygienic)
1071 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1072 self.ribs[ns].push(self_type_rib);
1074 self.ribs[ns].pop();
1077 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
1078 self.with_self_rib_ns(TypeNS, self_res, f)
1081 fn resolve_implementation(
1083 generics: &'ast Generics,
1084 opt_trait_reference: &'ast Option<TraitRef>,
1085 self_type: &'ast Ty,
1087 impl_items: &'ast [P<AssocItem>],
1089 debug!("resolve_implementation");
1090 // If applicable, create a rib for the type parameters.
1091 self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
1092 // Dummy self type for better errors if `Self` is used in the trait path.
1093 this.with_self_rib(Res::SelfTy(None, None), |this| {
1094 // Resolve the trait reference, if necessary.
1095 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1096 let item_def_id = this.r.definitions.local_def_id(item_id);
1097 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1098 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1099 // Resolve type arguments in the trait path.
1100 visit::walk_trait_ref(this, trait_ref);
1102 // Resolve the self type.
1103 this.visit_ty(self_type);
1104 // Resolve the generic parameters.
1105 this.visit_generics(generics);
1106 // Resolve the items within the impl.
1107 this.with_current_self_type(self_type, |this| {
1108 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1109 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1110 for impl_item in impl_items {
1111 // We also need a new scope for the impl item type parameters.
1112 this.with_generic_param_rib(&impl_item.generics,
1115 use crate::ResolutionError::*;
1116 match impl_item.kind {
1117 AssocItemKind::Const(..) => {
1119 "resolve_implementation AssocItemKind::Const",
1121 // If this is a trait impl, ensure the const
1123 this.check_trait_item(
1127 |n, s| ConstNotMemberOfTrait(n, s),
1130 this.with_constant_rib(|this| {
1131 visit::walk_impl_item(this, impl_item)
1134 AssocItemKind::Fn(..) => {
1135 // If this is a trait impl, ensure the method
1137 this.check_trait_item(impl_item.ident,
1140 |n, s| MethodNotMemberOfTrait(n, s));
1142 visit::walk_impl_item(this, impl_item);
1144 AssocItemKind::TyAlias(_, _) => {
1145 // If this is a trait impl, ensure the type
1147 this.check_trait_item(impl_item.ident,
1150 |n, s| TypeNotMemberOfTrait(n, s));
1152 visit::walk_impl_item(this, impl_item);
1154 AssocItemKind::Macro(_) =>
1155 panic!("unexpanded macro in resolve!"),
1167 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1169 F: FnOnce(Name, &str) -> ResolutionError<'_>,
1171 // If there is a TraitRef in scope for an impl, then the method must be in the
1173 if let Some((module, _)) = self.current_trait_ref {
1176 .resolve_ident_in_module(
1177 ModuleOrUniformRoot::Module(module),
1186 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1187 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1192 fn resolve_params(&mut self, params: &'ast [Param]) {
1193 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1194 for Param { pat, ty, .. } in params {
1195 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1197 debug!("(resolving function / closure) recorded parameter");
1201 fn resolve_local(&mut self, local: &'ast Local) {
1202 // Resolve the type.
1203 walk_list!(self, visit_ty, &local.ty);
1205 // Resolve the initializer.
1206 walk_list!(self, visit_expr, &local.init);
1208 // Resolve the pattern.
1209 self.resolve_pattern_top(&local.pat, PatternSource::Let);
1212 /// build a map from pattern identifiers to binding-info's.
1213 /// this is done hygienically. This could arise for a macro
1214 /// that expands into an or-pattern where one 'x' was from the
1215 /// user and one 'x' came from the macro.
1216 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1217 let mut binding_map = FxHashMap::default();
1219 pat.walk(&mut |pat| {
1221 PatKind::Ident(binding_mode, ident, ref sub_pat)
1222 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
1224 binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode });
1226 PatKind::Or(ref ps) => {
1227 // Check the consistency of this or-pattern and
1228 // then add all bindings to the larger map.
1229 for bm in self.check_consistent_bindings(ps) {
1230 binding_map.extend(bm);
1243 fn is_base_res_local(&self, nid: NodeId) -> bool {
1244 match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) {
1245 Some(Res::Local(..)) => true,
1250 /// Checks that all of the arms in an or-pattern have exactly the
1251 /// same set of bindings, with the same binding modes for each.
1252 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
1253 let mut missing_vars = FxHashMap::default();
1254 let mut inconsistent_vars = FxHashMap::default();
1256 // 1) Compute the binding maps of all arms.
1257 let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
1259 // 2) Record any missing bindings or binding mode inconsistencies.
1260 for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
1261 // Check against all arms except for the same pattern which is always self-consistent.
1265 .filter(|(_, pat)| pat.id != pat_outer.id)
1266 .flat_map(|(idx, _)| maps[idx].iter())
1267 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
1269 for (name, info, &binding_inner) in inners {
1272 // The inner binding is missing in the outer.
1274 missing_vars.entry(name).or_insert_with(|| BindingError {
1276 origin: BTreeSet::new(),
1277 target: BTreeSet::new(),
1278 could_be_path: name.as_str().starts_with(char::is_uppercase),
1280 binding_error.origin.insert(binding_inner.span);
1281 binding_error.target.insert(pat_outer.span);
1283 Some(binding_outer) => {
1284 if binding_outer.binding_mode != binding_inner.binding_mode {
1285 // The binding modes in the outer and inner bindings differ.
1288 .or_insert((binding_inner.span, binding_outer.span));
1295 // 3) Report all missing variables we found.
1296 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1297 missing_vars.sort();
1298 for (name, mut v) in missing_vars {
1299 if inconsistent_vars.contains_key(name) {
1300 v.could_be_path = false;
1302 self.r.report_error(
1303 *v.origin.iter().next().unwrap(),
1304 ResolutionError::VariableNotBoundInPattern(v),
1308 // 4) Report all inconsistencies in binding modes we found.
1309 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1310 inconsistent_vars.sort();
1311 for (name, v) in inconsistent_vars {
1312 self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1315 // 5) Finally bubble up all the binding maps.
1319 /// Check the consistency of the outermost or-patterns.
1320 fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
1321 pat.walk(&mut |pat| match pat.kind {
1322 PatKind::Or(ref ps) => {
1323 self.check_consistent_bindings(ps);
1330 fn resolve_arm(&mut self, arm: &'ast Arm) {
1331 self.with_rib(ValueNS, NormalRibKind, |this| {
1332 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
1333 walk_list!(this, visit_expr, &arm.guard);
1334 this.visit_expr(&arm.body);
1338 /// Arising from `source`, resolve a top level pattern.
1339 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
1340 let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1341 self.resolve_pattern(pat, pat_src, &mut bindings);
1347 pat_src: PatternSource,
1348 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1350 self.resolve_pattern_inner(pat, pat_src, bindings);
1351 // This has to happen *after* we determine which pat_idents are variants:
1352 self.check_consistent_bindings_top(pat);
1353 visit::walk_pat(self, pat);
1356 /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
1360 /// A stack of sets of bindings accumulated.
1362 /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
1363 /// be interpreted as re-binding an already bound binding. This results in an error.
1364 /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
1365 /// in reusing this binding rather than creating a fresh one.
1367 /// When called at the top level, the stack must have a single element
1368 /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
1369 /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
1370 /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
1371 /// When each `p_i` has been dealt with, the top set is merged with its parent.
1372 /// When a whole or-pattern has been dealt with, the thing happens.
1374 /// See the implementation and `fresh_binding` for more details.
1375 fn resolve_pattern_inner(
1378 pat_src: PatternSource,
1379 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1381 // Visit all direct subpatterns of this pattern.
1382 pat.walk(&mut |pat| {
1383 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
1385 PatKind::Ident(bmode, ident, ref sub) => {
1386 // First try to resolve the identifier as some existing entity,
1387 // then fall back to a fresh binding.
1388 let has_sub = sub.is_some();
1390 .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1391 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
1392 self.r.record_partial_res(pat.id, PartialRes::new(res));
1394 PatKind::TupleStruct(ref path, ..) => {
1395 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1397 PatKind::Path(ref qself, ref path) => {
1398 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1400 PatKind::Struct(ref path, ..) => {
1401 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1403 PatKind::Or(ref ps) => {
1404 // Add a new set of bindings to the stack. `Or` here records that when a
1405 // binding already exists in this set, it should not result in an error because
1406 // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
1407 bindings.push((PatBoundCtx::Or, Default::default()));
1409 // Now we need to switch back to a product context so that each
1410 // part of the or-pattern internally rejects already bound names.
1411 // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
1412 bindings.push((PatBoundCtx::Product, Default::default()));
1413 self.resolve_pattern_inner(p, pat_src, bindings);
1414 // Move up the non-overlapping bindings to the or-pattern.
1415 // Existing bindings just get "merged".
1416 let collected = bindings.pop().unwrap().1;
1417 bindings.last_mut().unwrap().1.extend(collected);
1419 // This or-pattern itself can itself be part of a product,
1420 // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
1421 // Both cases bind `a` again in a product pattern and must be rejected.
1422 let collected = bindings.pop().unwrap().1;
1423 bindings.last_mut().unwrap().1.extend(collected);
1425 // Prevent visiting `ps` as we've already done so above.
1438 pat_src: PatternSource,
1439 bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
1441 // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
1442 // (We must not add it if it's in the bindings map because that breaks the assumptions
1443 // later passes make about or-patterns.)
1444 let ident = ident.modern_and_legacy();
1446 let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
1447 // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
1448 let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
1449 // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
1450 // This is *required* for consistency which is checked later.
1451 let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
1453 if already_bound_and {
1454 // Overlap in a product pattern somewhere; report an error.
1455 use ResolutionError::*;
1456 let error = match pat_src {
1457 // `fn f(a: u8, a: u8)`:
1458 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
1460 _ => IdentifierBoundMoreThanOnceInSamePattern,
1462 self.r.report_error(ident.span, error(&ident.as_str()));
1465 // Record as bound if it's valid:
1466 let ident_valid = ident.name != kw::Invalid;
1468 bindings.last_mut().unwrap().1.insert(ident);
1471 if already_bound_or {
1472 // `Variant1(a) | Variant2(a)`, ok
1473 // Reuse definition from the first `a`.
1474 self.innermost_rib_bindings(ValueNS)[&ident]
1476 let res = Res::Local(pat_id);
1478 // A completely fresh binding add to the set if it's valid.
1479 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1485 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
1486 &mut self.ribs[ns].last_mut().unwrap().bindings
1489 fn try_resolve_as_non_binding(
1491 pat_src: PatternSource,
1498 self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?.item()?;
1499 let res = binding.res();
1501 // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1502 // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1503 // also be interpreted as a path to e.g. a constant, variant, etc.
1504 let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not);
1507 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::Def(DefKind::Const, _)
1508 if is_syntactic_ambiguity =>
1510 // Disambiguate in favor of a unit struct/variant or constant pattern.
1511 self.r.record_use(ident, ValueNS, binding, false);
1514 Res::Def(DefKind::Ctor(..), _)
1515 | Res::Def(DefKind::Const, _)
1516 | Res::Def(DefKind::Static, _) => {
1517 // This is unambiguously a fresh binding, either syntactically
1518 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1519 // to something unusable as a pattern (e.g., constructor function),
1520 // but we still conservatively report an error, see
1521 // issues/33118#issuecomment-233962221 for one reason why.
1522 self.r.report_error(
1524 ResolutionError::BindingShadowsSomethingUnacceptable(
1532 Res::Def(DefKind::Fn, _) | Res::Err => {
1533 // These entities are explicitly allowed to be shadowed by fresh bindings.
1539 "unexpected resolution for an \
1540 identifier in pattern: {:?}",
1547 // High-level and context dependent path resolution routine.
1548 // Resolves the path and records the resolution into definition map.
1549 // If resolution fails tries several techniques to find likely
1550 // resolution candidates, suggest imports or other help, and report
1551 // errors in user friendly way.
1552 fn smart_resolve_path(
1555 qself: Option<&QSelf>,
1557 source: PathSource<'ast>,
1559 self.smart_resolve_path_fragment(
1562 &Segment::from_path(path),
1565 CrateLint::SimplePath(id),
1569 fn smart_resolve_path_fragment(
1572 qself: Option<&QSelf>,
1575 source: PathSource<'ast>,
1576 crate_lint: CrateLint,
1578 let ns = source.namespace();
1579 let is_expected = &|res| source.is_expected(res);
1581 let report_errors = |this: &mut Self, res: Option<Res>| {
1582 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1583 let def_id = this.parent_scope.module.normal_ancestor_id;
1584 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1585 let better = res.is_some();
1587 if res.is_none() { this.report_missing_type_error(path) } else { None };
1588 this.r.use_injections.push(UseError { err, candidates, node_id, better, suggestion });
1589 PartialRes::new(Res::Err)
1592 let partial_res = match self.resolve_qpath_anywhere(
1598 source.defer_to_typeck(),
1601 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1602 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1605 report_errors(self, Some(partial_res.base_res()))
1608 Some(partial_res) if source.defer_to_typeck() => {
1609 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1610 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1611 // it needs to be added to the trait map.
1613 let item_name = path.last().unwrap().ident;
1614 let traits = self.get_traits_containing_item(item_name, ns);
1615 self.r.trait_map.insert(id, traits);
1618 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1619 std_path.extend(path);
1620 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1621 let cl = CrateLint::No;
1623 if let PathResult::Module(_) | PathResult::NonModule(_) =
1624 self.resolve_path(&std_path, ns, false, span, cl)
1626 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1628 path.iter().last().map(|segment| segment.ident.span).unwrap_or(span);
1629 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1630 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1631 hm.insert(item_span, span);
1632 // In some places (E0223) we only have access to the full path
1633 hm.insert(span, span);
1638 _ => report_errors(self, None),
1641 if let PathSource::TraitItem(..) = source {
1643 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1644 self.r.record_partial_res(id, partial_res);
1649 fn self_type_is_available(&mut self, span: Span) -> bool {
1650 let binding = self.resolve_ident_in_lexical_scope(
1651 Ident::with_dummy_span(kw::SelfUpper),
1656 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1659 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1660 let ident = Ident::new(kw::SelfLower, self_span);
1661 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1662 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1665 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1666 fn resolve_qpath_anywhere(
1669 qself: Option<&QSelf>,
1671 primary_ns: Namespace,
1673 defer_to_typeck: bool,
1674 crate_lint: CrateLint,
1675 ) -> Option<PartialRes> {
1676 let mut fin_res = None;
1677 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1678 if i == 0 || ns != primary_ns {
1679 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1680 // If defer_to_typeck, then resolution > no resolution,
1681 // otherwise full resolution > partial resolution > no resolution.
1683 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
1685 return Some(partial_res);
1688 if fin_res.is_none() {
1689 fin_res = partial_res
1697 assert!(primary_ns != MacroNS);
1698 if qself.is_none() {
1699 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1700 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1701 if let Ok((_, res)) =
1702 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
1704 return Some(PartialRes::new(res));
1711 /// Handles paths that may refer to associated items.
1715 qself: Option<&QSelf>,
1719 crate_lint: CrateLint,
1720 ) -> Option<PartialRes> {
1722 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1723 id, qself, path, ns, span,
1726 if let Some(qself) = qself {
1727 if qself.position == 0 {
1728 // This is a case like `<T>::B`, where there is no
1729 // trait to resolve. In that case, we leave the `B`
1730 // segment to be resolved by type-check.
1731 return Some(PartialRes::with_unresolved_segments(
1732 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)),
1737 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1739 // Currently, `path` names the full item (`A::B::C`, in
1740 // our example). so we extract the prefix of that that is
1741 // the trait (the slice upto and including
1742 // `qself.position`). And then we recursively resolve that,
1743 // but with `qself` set to `None`.
1745 // However, setting `qself` to none (but not changing the
1746 // span) loses the information about where this path
1747 // *actually* appears, so for the purposes of the crate
1748 // lint we pass along information that this is the trait
1749 // name from a fully qualified path, and this also
1750 // contains the full span (the `CrateLint::QPathTrait`).
1751 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1752 let partial_res = self.smart_resolve_path_fragment(
1755 &path[..=qself.position],
1757 PathSource::TraitItem(ns),
1758 CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span },
1761 // The remaining segments (the `C` in our example) will
1762 // have to be resolved by type-check, since that requires doing
1763 // trait resolution.
1764 return Some(PartialRes::with_unresolved_segments(
1765 partial_res.base_res(),
1766 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1770 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1771 PathResult::NonModule(path_res) => path_res,
1772 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1773 PartialRes::new(module.res().unwrap())
1775 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1776 // don't report an error right away, but try to fallback to a primitive type.
1777 // So, we are still able to successfully resolve something like
1779 // use std::u8; // bring module u8 in scope
1780 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1781 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1782 // // not to non-existent std::u8::max_value
1785 // Such behavior is required for backward compatibility.
1786 // The same fallback is used when `a` resolves to nothing.
1787 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
1788 if (ns == TypeNS || path.len() > 1)
1791 .primitive_type_table
1793 .contains_key(&path[0].ident.name) =>
1795 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1796 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1798 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
1799 PartialRes::new(module.res().unwrap())
1801 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1802 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1803 PartialRes::new(Res::Err)
1805 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1806 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1810 && result.base_res() != Res::Err
1811 && path[0].ident.name != kw::PathRoot
1812 && path[0].ident.name != kw::DollarCrate
1814 let unqualified_result = {
1815 match self.resolve_path(
1816 &[*path.last().unwrap()],
1822 PathResult::NonModule(path_res) => path_res.base_res(),
1823 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
1824 module.res().unwrap()
1826 _ => return Some(result),
1829 if result.base_res() == unqualified_result {
1830 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1831 self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification")
1838 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
1839 if let Some(label) = label {
1840 if label.ident.as_str().as_bytes()[1] != b'_' {
1841 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
1843 self.with_label_rib(NormalRibKind, |this| {
1844 let ident = label.ident.modern_and_legacy();
1845 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1853 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
1854 self.with_resolved_label(label, id, |this| this.visit_block(block));
1857 fn resolve_block(&mut self, block: &'ast Block) {
1858 debug!("(resolving block) entering block");
1859 // Move down in the graph, if there's an anonymous module rooted here.
1860 let orig_module = self.parent_scope.module;
1861 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1863 let mut num_macro_definition_ribs = 0;
1864 if let Some(anonymous_module) = anonymous_module {
1865 debug!("(resolving block) found anonymous module, moving down");
1866 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1867 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1868 self.parent_scope.module = anonymous_module;
1870 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1873 // Descend into the block.
1874 for stmt in &block.stmts {
1875 if let StmtKind::Item(ref item) = stmt.kind {
1876 if let ItemKind::MacroDef(..) = item.kind {
1877 num_macro_definition_ribs += 1;
1878 let res = self.r.definitions.local_def_id(item.id);
1879 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1880 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1884 self.visit_stmt(stmt);
1888 self.parent_scope.module = orig_module;
1889 for _ in 0..num_macro_definition_ribs {
1890 self.ribs[ValueNS].pop();
1891 self.label_ribs.pop();
1893 self.ribs[ValueNS].pop();
1894 if anonymous_module.is_some() {
1895 self.ribs[TypeNS].pop();
1897 debug!("(resolving block) leaving block");
1900 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
1901 // First, record candidate traits for this expression if it could
1902 // result in the invocation of a method call.
1904 self.record_candidate_traits_for_expr_if_necessary(expr);
1906 // Next, resolve the node.
1908 ExprKind::Path(ref qself, ref path) => {
1909 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1910 visit::walk_expr(self, expr);
1913 ExprKind::Struct(ref path, ..) => {
1914 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1915 visit::walk_expr(self, expr);
1918 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1919 let node_id = self.search_label(label.ident, |rib, ident| {
1920 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1924 // Search again for close matches...
1925 // Picks the first label that is "close enough", which is not necessarily
1926 // the closest match
1927 let close_match = self.search_label(label.ident, |rib, ident| {
1928 let names = rib.bindings.iter().filter_map(|(id, _)| {
1929 if id.span.ctxt() == label.ident.span.ctxt() {
1935 find_best_match_for_name(names, &ident.as_str(), None)
1937 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1938 self.r.report_error(
1940 ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1944 // Since this res is a label, it is never read.
1945 self.r.label_res_map.insert(expr.id, node_id);
1946 self.diagnostic_metadata.unused_labels.remove(&node_id);
1950 // visit `break` argument if any
1951 visit::walk_expr(self, expr);
1954 ExprKind::Let(ref pat, ref scrutinee) => {
1955 self.visit_expr(scrutinee);
1956 self.resolve_pattern_top(pat, PatternSource::Let);
1959 ExprKind::If(ref cond, ref then, ref opt_else) => {
1960 self.with_rib(ValueNS, NormalRibKind, |this| {
1961 this.visit_expr(cond);
1962 this.visit_block(then);
1964 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1967 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1969 ExprKind::While(ref cond, ref block, label) => {
1970 self.with_resolved_label(label, expr.id, |this| {
1971 this.with_rib(ValueNS, NormalRibKind, |this| {
1972 this.visit_expr(cond);
1973 this.visit_block(block);
1978 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
1979 self.visit_expr(iter_expr);
1980 self.with_rib(ValueNS, NormalRibKind, |this| {
1981 this.resolve_pattern_top(pat, PatternSource::For);
1982 this.resolve_labeled_block(label, expr.id, block);
1986 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1988 // Equivalent to `visit::walk_expr` + passing some context to children.
1989 ExprKind::Field(ref subexpression, _) => {
1990 self.resolve_expr(subexpression, Some(expr));
1992 ExprKind::MethodCall(ref segment, ref arguments) => {
1993 let mut arguments = arguments.iter();
1994 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1995 for argument in arguments {
1996 self.resolve_expr(argument, None);
1998 self.visit_path_segment(expr.span, segment);
2001 ExprKind::Call(ref callee, ref arguments) => {
2002 self.resolve_expr(callee, Some(expr));
2003 for argument in arguments {
2004 self.resolve_expr(argument, None);
2007 ExprKind::Type(ref type_expr, _) => {
2008 self.diagnostic_metadata.current_type_ascription.push(type_expr.span);
2009 visit::walk_expr(self, expr);
2010 self.diagnostic_metadata.current_type_ascription.pop();
2012 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
2013 // resolve the arguments within the proper scopes so that usages of them inside the
2014 // closure are detected as upvars rather than normal closure arg usages.
2015 ExprKind::Closure(_, IsAsync::Async { .. }, _, ref fn_decl, ref body, _span) => {
2016 self.with_rib(ValueNS, NormalRibKind, |this| {
2017 // Resolve arguments:
2018 this.resolve_params(&fn_decl.inputs);
2019 // No need to resolve return type --
2020 // the outer closure return type is `FunctionRetTy::Default`.
2022 // Now resolve the inner closure
2024 // No need to resolve arguments: the inner closure has none.
2025 // Resolve the return type:
2026 visit::walk_fn_ret_ty(this, &fn_decl.output);
2028 this.visit_expr(body);
2033 visit::walk_expr(self, expr);
2038 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
2040 ExprKind::Field(_, ident) => {
2041 // FIXME(#6890): Even though you can't treat a method like a
2042 // field, we need to add any trait methods we find that match
2043 // the field name so that we can do some nice error reporting
2044 // later on in typeck.
2045 let traits = self.get_traits_containing_item(ident, ValueNS);
2046 self.r.trait_map.insert(expr.id, traits);
2048 ExprKind::MethodCall(ref segment, ..) => {
2049 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
2050 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
2051 self.r.trait_map.insert(expr.id, traits);
2059 fn get_traits_containing_item(
2063 ) -> Vec<TraitCandidate> {
2064 debug!("(getting traits containing item) looking for '{}'", ident.name);
2066 let mut found_traits = Vec::new();
2067 // Look for the current trait.
2068 if let Some((module, _)) = self.current_trait_ref {
2071 .resolve_ident_in_module(
2072 ModuleOrUniformRoot::Module(module),
2081 let def_id = module.def_id().unwrap();
2082 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
2086 ident.span = ident.span.modern();
2087 let mut search_module = self.parent_scope.module;
2089 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
2091 unwrap_or!(self.r.hygienic_lexical_parent(search_module, &mut ident.span), break);
2094 if let Some(prelude) = self.r.prelude {
2095 if !search_module.no_implicit_prelude {
2096 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
2103 fn get_traits_in_module_containing_item(
2108 found_traits: &mut Vec<TraitCandidate>,
2110 assert!(ns == TypeNS || ns == ValueNS);
2111 let mut traits = module.traits.borrow_mut();
2112 if traits.is_none() {
2113 let mut collected_traits = Vec::new();
2114 module.for_each_child(self.r, |_, name, ns, binding| {
2118 match binding.res() {
2119 Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => {
2120 collected_traits.push((name, binding))
2125 *traits = Some(collected_traits.into_boxed_slice());
2128 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
2129 // Traits have pseudo-modules that can be used to search for the given ident.
2130 if let Some(module) = binding.module() {
2131 let mut ident = ident;
2132 if ident.span.glob_adjust(module.expansion, binding.span).is_none() {
2137 .resolve_ident_in_module_unadjusted(
2138 ModuleOrUniformRoot::Module(module),
2147 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2148 let trait_def_id = module.def_id().unwrap();
2149 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2151 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
2152 // For now, just treat all trait aliases as possible candidates, since we don't
2153 // know if the ident is somewhere in the transitive bounds.
2154 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2155 let trait_def_id = binding.res().def_id();
2156 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2158 bug!("candidate is not trait or trait alias?")
2163 fn find_transitive_imports(
2165 mut kind: &NameBindingKind<'_>,
2167 ) -> SmallVec<[NodeId; 1]> {
2168 let mut import_ids = smallvec![];
2169 while let NameBindingKind::Import { directive, binding, .. } = kind {
2170 self.r.maybe_unused_trait_imports.insert(directive.id);
2171 self.r.add_to_glob_map(&directive, trait_name);
2172 import_ids.push(directive.id);
2173 kind = &binding.kind;
2179 impl<'a> Resolver<'a> {
2180 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2181 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2182 visit::walk_crate(&mut late_resolution_visitor, krate);
2183 for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
2184 self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");