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 `resolve_imports.rs`.
8 use GenericParameters::*;
11 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
12 use crate::{Module, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult};
13 use crate::{ResolutionError, Resolver, Segment, UseError};
16 use rustc::{bug, lint, span_bug};
17 use rustc::hir::def::{self, PartialRes, DefKind, CtorKind, PerNS};
18 use rustc::hir::def::Namespace::{self, *};
19 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
20 use rustc::hir::TraitCandidate;
21 use rustc::util::nodemap::FxHashMap;
22 use smallvec::{smallvec, SmallVec};
23 use syntax::{unwrap_or, walk_list};
26 use syntax::symbol::{kw, sym};
27 use syntax::util::lev_distance::find_best_match_for_name;
28 use syntax::visit::{self, Visitor, FnKind};
31 use std::collections::BTreeSet;
32 use std::mem::replace;
36 type Res = def::Res<NodeId>;
38 /// Map from the name in a pattern to its binding mode.
39 type BindingMap = FxHashMap<Ident, BindingInfo>;
41 #[derive(Copy, Clone, Debug)]
44 binding_mode: BindingMode,
47 #[derive(Copy, Clone)]
48 enum GenericParameters<'a, 'b> {
50 HasGenericParams(// Type parameters.
53 // The kind of the rib used for type parameters.
57 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
66 fn descr(self) -> &'static str {
68 PatternSource::Match => "match binding",
69 PatternSource::Let => "let binding",
70 PatternSource::For => "for binding",
71 PatternSource::FnParam => "function parameter",
76 /// The rib kind restricts certain accesses,
77 /// e.g. to a `Res::Local` of an outer item.
78 #[derive(Copy, Clone, Debug)]
79 crate enum RibKind<'a> {
80 /// No restriction needs to be applied.
83 /// We passed through an impl or trait and are now in one of its
84 /// methods or associated types. Allow references to ty params that impl or trait
85 /// binds. Disallow any other upvars (including other ty params that are
89 /// We passed through a function definition. Disallow upvars.
90 /// Permit only those const parameters that are specified in the function's generics.
93 /// We passed through an item scope. Disallow upvars.
96 /// We're in a constant item. Can't refer to dynamic stuff.
99 /// We passed through a module.
100 ModuleRibKind(Module<'a>),
102 /// We passed through a `macro_rules!` statement
103 MacroDefinition(DefId),
105 /// All bindings in this rib are type parameters that can't be used
106 /// from the default of a type parameter because they're not declared
107 /// before said type parameter. Also see the `visit_generics` override.
108 ForwardTyParamBanRibKind,
110 /// We forbid the use of type parameters as the types of const parameters.
111 TyParamAsConstParamTy,
115 // Whether this rib kind contains generic parameters, as opposed to local
117 crate fn contains_params(&self) -> bool {
121 | ConstantItemRibKind
123 | MacroDefinition(_) => false,
126 | ForwardTyParamBanRibKind
127 | TyParamAsConstParamTy => true,
132 /// A single local scope.
134 /// A rib represents a scope names can live in. Note that these appear in many places, not just
135 /// around braces. At any place where the list of accessible names (of the given namespace)
136 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
137 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
140 /// Different [rib kinds](enum.RibKind) are transparent for different names.
142 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
143 /// resolving, the name is looked up from inside out.
145 crate struct Rib<'a, R = Res> {
146 pub bindings: FxHashMap<Ident, R>,
147 pub kind: RibKind<'a>,
150 impl<'a, R> Rib<'a, R> {
151 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
153 bindings: Default::default(),
159 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
160 crate enum AliasPossibility {
165 #[derive(Copy, Clone, Debug)]
166 crate enum PathSource<'a> {
167 // Type paths `Path`.
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`.
175 // Paths in struct expressions and patterns `Path { .. }`.
177 // Paths in tuple struct patterns `Path(..)`.
179 // `m::A::B` in `<T as m::A>::B::C`.
180 TraitItem(Namespace),
183 impl<'a> PathSource<'a> {
184 fn namespace(self) -> Namespace {
186 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
187 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
188 PathSource::TraitItem(ns) => ns,
192 fn defer_to_typeck(self) -> bool {
194 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
195 PathSource::Struct | PathSource::TupleStruct => true,
196 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
200 fn descr_expected(self) -> &'static str {
202 PathSource::Type => "type",
203 PathSource::Trait(_) => "trait",
204 PathSource::Pat => "unit struct/variant or constant",
205 PathSource::Struct => "struct, variant or union type",
206 PathSource::TupleStruct => "tuple struct/variant",
207 PathSource::TraitItem(ns) => match ns {
208 TypeNS => "associated type",
209 ValueNS => "method or associated constant",
210 MacroNS => bug!("associated macro"),
212 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
213 // "function" here means "anything callable" rather than `DefKind::Fn`,
214 // this is not precise but usually more helpful than just "value".
215 Some(&ExprKind::Call(..)) => "function",
221 crate fn is_expected(self, res: Res) -> bool {
223 PathSource::Type => match res {
224 Res::Def(DefKind::Struct, _)
225 | Res::Def(DefKind::Union, _)
226 | Res::Def(DefKind::Enum, _)
227 | Res::Def(DefKind::Trait, _)
228 | Res::Def(DefKind::TraitAlias, _)
229 | Res::Def(DefKind::TyAlias, _)
230 | Res::Def(DefKind::AssocTy, _)
232 | Res::Def(DefKind::TyParam, _)
234 | Res::Def(DefKind::OpaqueTy, _)
235 | Res::Def(DefKind::ForeignTy, _) => true,
238 PathSource::Trait(AliasPossibility::No) => match res {
239 Res::Def(DefKind::Trait, _) => true,
242 PathSource::Trait(AliasPossibility::Maybe) => match res {
243 Res::Def(DefKind::Trait, _) => true,
244 Res::Def(DefKind::TraitAlias, _) => true,
247 PathSource::Expr(..) => match res {
248 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
249 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
250 | Res::Def(DefKind::Const, _)
251 | Res::Def(DefKind::Static, _)
253 | Res::Def(DefKind::Fn, _)
254 | Res::Def(DefKind::Method, _)
255 | Res::Def(DefKind::AssocConst, _)
257 | Res::Def(DefKind::ConstParam, _) => true,
260 PathSource::Pat => match res {
261 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
262 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
263 Res::SelfCtor(..) => true,
266 PathSource::TupleStruct => match res {
267 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
270 PathSource::Struct => match res {
271 Res::Def(DefKind::Struct, _)
272 | Res::Def(DefKind::Union, _)
273 | Res::Def(DefKind::Variant, _)
274 | Res::Def(DefKind::TyAlias, _)
275 | Res::Def(DefKind::AssocTy, _)
276 | Res::SelfTy(..) => true,
279 PathSource::TraitItem(ns) => match res {
280 Res::Def(DefKind::AssocConst, _)
281 | Res::Def(DefKind::Method, _) if ns == ValueNS => true,
282 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
288 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
289 __diagnostic_used!(E0404);
290 __diagnostic_used!(E0405);
291 __diagnostic_used!(E0412);
292 __diagnostic_used!(E0422);
293 __diagnostic_used!(E0423);
294 __diagnostic_used!(E0425);
295 __diagnostic_used!(E0531);
296 __diagnostic_used!(E0532);
297 __diagnostic_used!(E0573);
298 __diagnostic_used!(E0574);
299 __diagnostic_used!(E0575);
300 __diagnostic_used!(E0576);
301 match (self, has_unexpected_resolution) {
302 (PathSource::Trait(_), true) => "E0404",
303 (PathSource::Trait(_), false) => "E0405",
304 (PathSource::Type, true) => "E0573",
305 (PathSource::Type, false) => "E0412",
306 (PathSource::Struct, true) => "E0574",
307 (PathSource::Struct, false) => "E0422",
308 (PathSource::Expr(..), true) => "E0423",
309 (PathSource::Expr(..), false) => "E0425",
310 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
311 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
312 (PathSource::TraitItem(..), true) => "E0575",
313 (PathSource::TraitItem(..), false) => "E0576",
318 struct LateResolutionVisitor<'a, 'b> {
319 r: &'b mut Resolver<'a>,
321 /// The module that represents the current item scope.
322 parent_scope: ParentScope<'a>,
324 /// The current set of local scopes for types and values.
325 /// FIXME #4948: Reuse ribs to avoid allocation.
326 ribs: PerNS<Vec<Rib<'a>>>,
328 /// The current set of local scopes, for labels.
329 label_ribs: Vec<Rib<'a, NodeId>>,
331 /// The trait that the current context can refer to.
332 current_trait_ref: Option<(Module<'a>, TraitRef)>,
334 /// The current trait's associated types' ident, used for diagnostic suggestions.
335 current_trait_assoc_types: Vec<Ident>,
337 /// The current self type if inside an impl (used for better errors).
338 current_self_type: Option<Ty>,
340 /// The current self item if inside an ADT (used for better errors).
341 current_self_item: Option<NodeId>,
343 /// A list of labels as of yet unused. Labels will be removed from this map when
344 /// they are used (in a `break` or `continue` statement)
345 unused_labels: FxHashMap<NodeId, Span>,
347 /// Only used for better errors on `fn(): fn()`.
348 current_type_ascription: Vec<Span>,
351 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
352 impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
353 fn visit_item(&mut self, item: &'tcx Item) {
354 self.resolve_item(item);
356 fn visit_arm(&mut self, arm: &'tcx Arm) {
357 self.resolve_arm(arm);
359 fn visit_block(&mut self, block: &'tcx Block) {
360 self.resolve_block(block);
362 fn visit_anon_const(&mut self, constant: &'tcx AnonConst) {
363 debug!("visit_anon_const {:?}", constant);
364 self.with_constant_rib(|this| {
365 visit::walk_anon_const(this, constant);
368 fn visit_expr(&mut self, expr: &'tcx Expr) {
369 self.resolve_expr(expr, None);
371 fn visit_local(&mut self, local: &'tcx Local) {
372 self.resolve_local(local);
374 fn visit_ty(&mut self, ty: &'tcx Ty) {
376 TyKind::Path(ref qself, ref path) => {
377 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
379 TyKind::ImplicitSelf => {
380 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
381 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
382 .map_or(Res::Err, |d| d.res());
383 self.r.record_partial_res(ty.id, PartialRes::new(res));
387 visit::walk_ty(self, ty);
389 fn visit_poly_trait_ref(&mut self,
390 tref: &'tcx PolyTraitRef,
391 m: &'tcx TraitBoundModifier) {
392 self.smart_resolve_path(tref.trait_ref.ref_id, None,
393 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
394 visit::walk_poly_trait_ref(self, tref, m);
396 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
397 let generic_params = match foreign_item.node {
398 ForeignItemKind::Fn(_, ref generics) => {
399 HasGenericParams(generics, ItemRibKind)
401 ForeignItemKind::Static(..) => NoGenericParams,
402 ForeignItemKind::Ty => NoGenericParams,
403 ForeignItemKind::Macro(..) => NoGenericParams,
405 self.with_generic_param_rib(generic_params, |this| {
406 visit::walk_foreign_item(this, foreign_item);
409 fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, declaration: &'tcx FnDecl, _: Span, _: NodeId) {
410 debug!("(resolving function) entering function");
411 let rib_kind = match fn_kind {
412 FnKind::ItemFn(..) => FnItemRibKind,
413 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
416 // Create a value rib for the function.
417 self.with_rib(ValueNS, rib_kind, |this| {
418 // Create a label rib for the function.
419 this.with_label_rib(rib_kind, |this| {
420 // Add each argument to the rib.
421 this.resolve_params(&declaration.inputs);
423 visit::walk_fn_ret_ty(this, &declaration.output);
425 // Resolve the function body, potentially inside the body of an async closure
427 FnKind::ItemFn(.., body) |
428 FnKind::Method(.., body) => this.visit_block(body),
429 FnKind::Closure(body) => this.visit_expr(body),
432 debug!("(resolving function) leaving function");
437 fn visit_generics(&mut self, generics: &'tcx Generics) {
438 // For type parameter defaults, we have to ban access
439 // to following type parameters, as the InternalSubsts can only
440 // provide previous type parameters as they're built. We
441 // put all the parameters on the ban list and then remove
442 // them one by one as they are processed and become available.
443 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
444 let mut found_default = false;
445 default_ban_rib.bindings.extend(generics.params.iter()
446 .filter_map(|param| match param.kind {
447 GenericParamKind::Const { .. } |
448 GenericParamKind::Lifetime { .. } => None,
449 GenericParamKind::Type { ref default, .. } => {
450 found_default |= default.is_some();
452 Some((Ident::with_dummy_span(param.ident.name), Res::Err))
459 // We also ban access to type parameters for use as the types of const parameters.
460 let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
461 const_ty_param_ban_rib.bindings.extend(generics.params.iter()
463 if let GenericParamKind::Type { .. } = param.kind {
469 .map(|param| (Ident::with_dummy_span(param.ident.name), Res::Err)));
471 for param in &generics.params {
473 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
474 GenericParamKind::Type { ref default, .. } => {
475 for bound in ¶m.bounds {
476 self.visit_param_bound(bound);
479 if let Some(ref ty) = default {
480 self.ribs[TypeNS].push(default_ban_rib);
482 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
485 // Allow all following defaults to refer to this type parameter.
486 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
488 GenericParamKind::Const { ref ty } => {
489 self.ribs[TypeNS].push(const_ty_param_ban_rib);
491 for bound in ¶m.bounds {
492 self.visit_param_bound(bound);
497 const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
501 for p in &generics.where_clause.predicates {
502 self.visit_where_predicate(p);
507 impl<'a, 'b> LateResolutionVisitor<'a, '_> {
508 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
509 // During late resolution we only track the module component of the parent scope,
510 // although it may be useful to track other components as well for diagnostics.
511 let graph_root = resolver.graph_root;
512 let parent_scope = ParentScope::module(graph_root);
513 let start_rib_kind = ModuleRibKind(graph_root);
514 LateResolutionVisitor {
518 value_ns: vec![Rib::new(start_rib_kind)],
519 type_ns: vec![Rib::new(start_rib_kind)],
520 macro_ns: vec![Rib::new(start_rib_kind)],
522 label_ribs: Vec::new(),
523 current_trait_ref: None,
524 current_trait_assoc_types: Vec::new(),
525 current_self_type: None,
526 current_self_item: None,
527 unused_labels: Default::default(),
528 current_type_ascription: Vec::new(),
532 fn resolve_ident_in_lexical_scope(&mut self,
535 record_used_id: Option<NodeId>,
537 -> Option<LexicalScopeBinding<'a>> {
538 self.r.resolve_ident_in_lexical_scope(
539 ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
546 opt_ns: Option<Namespace>, // `None` indicates a module path in import
549 crate_lint: CrateLint,
550 ) -> PathResult<'a> {
551 self.r.resolve_path_with_ribs(
552 path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, Some(&self.ribs)
558 // We maintain a list of value ribs and type ribs.
560 // Simultaneously, we keep track of the current position in the module
561 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
562 // the value or type namespaces, we first look through all the ribs and
563 // then query the module graph. When we resolve a name in the module
564 // namespace, we can skip all the ribs (since nested modules are not
565 // allowed within blocks in Rust) and jump straight to the current module
568 // Named implementations are handled separately. When we find a method
569 // call, we consult the module node to find all of the implementations in
570 // scope. This information is lazily cached in the module node. We then
571 // generate a fake "implementation scope" containing all the
572 // implementations thus found, for compatibility with old resolve pass.
574 /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
579 work: impl FnOnce(&mut Self) -> T,
581 self.ribs[ns].push(Rib::new(kind));
582 let ret = work(self);
587 fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
588 let id = self.r.definitions.local_def_id(id);
589 let module = self.r.module_map.get(&id).cloned(); // clones a reference
590 if let Some(module) = module {
591 // Move down in the graph.
592 let orig_module = replace(&mut self.parent_scope.module, module);
593 self.with_rib(ValueNS, ModuleRibKind(module), |this| {
594 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
596 this.parent_scope.module = orig_module;
605 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
606 /// is returned by the given predicate function
608 /// Stops after meeting a closure.
609 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
610 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
612 for rib in self.label_ribs.iter().rev() {
615 // If an invocation of this macro created `ident`, give up on `ident`
616 // and switch to `ident`'s source from the macro definition.
617 MacroDefinition(def) => {
618 if def == self.r.macro_def(ident.span.ctxt()) {
619 ident.span.remove_mark();
623 // Do not resolve labels across function boundary
627 let r = pred(rib, ident);
635 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
636 debug!("resolve_adt");
637 self.with_current_self_item(item, |this| {
638 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
639 let item_def_id = this.r.definitions.local_def_id(item.id);
640 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
641 visit::walk_item(this, item);
647 fn future_proof_import(&mut self, use_tree: &UseTree) {
648 let segments = &use_tree.prefix.segments;
649 if !segments.is_empty() {
650 let ident = segments[0].ident;
651 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
655 let nss = match use_tree.kind {
656 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
659 let report_error = |this: &Self, ns| {
660 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
661 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
665 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
666 Some(LexicalScopeBinding::Res(..)) => {
667 report_error(self, ns);
669 Some(LexicalScopeBinding::Item(binding)) => {
670 let orig_blacklisted_binding =
671 replace(&mut self.r.blacklisted_binding, Some(binding));
672 if let Some(LexicalScopeBinding::Res(..)) =
673 self.resolve_ident_in_lexical_scope(ident, ns, None,
674 use_tree.prefix.span) {
675 report_error(self, ns);
677 self.r.blacklisted_binding = orig_blacklisted_binding;
682 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
683 for (use_tree, _) in use_trees {
684 self.future_proof_import(use_tree);
689 fn resolve_item(&mut self, item: &Item) {
690 let name = item.ident.name;
691 debug!("(resolving item) resolving {} ({:?})", name, item.node);
694 ItemKind::TyAlias(_, ref generics) |
695 ItemKind::OpaqueTy(_, ref generics) |
696 ItemKind::Fn(_, _, ref generics, _) => {
697 self.with_generic_param_rib(
698 HasGenericParams(generics, ItemRibKind),
699 |this| visit::walk_item(this, item)
703 ItemKind::Enum(_, ref generics) |
704 ItemKind::Struct(_, ref generics) |
705 ItemKind::Union(_, ref generics) => {
706 self.resolve_adt(item, generics);
709 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
710 self.resolve_implementation(generics,
716 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
717 // Create a new rib for the trait-wide type parameters.
718 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
719 let local_def_id = this.r.definitions.local_def_id(item.id);
720 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
721 this.visit_generics(generics);
722 walk_list!(this, visit_param_bound, bounds);
724 for trait_item in trait_items {
725 this.with_trait_items(trait_items, |this| {
726 let generic_params = HasGenericParams(
727 &trait_item.generics,
730 this.with_generic_param_rib(generic_params, |this| {
731 match trait_item.node {
732 TraitItemKind::Const(ref ty, ref default) => {
735 // Only impose the restrictions of
736 // ConstRibKind for an actual constant
737 // expression in a provided default.
738 if let Some(ref expr) = *default{
739 this.with_constant_rib(|this| {
740 this.visit_expr(expr);
744 TraitItemKind::Method(_, _) => {
745 visit::walk_trait_item(this, trait_item)
747 TraitItemKind::Type(..) => {
748 visit::walk_trait_item(this, trait_item)
750 TraitItemKind::Macro(_) => {
751 panic!("unexpanded macro in resolve!")
761 ItemKind::TraitAlias(ref generics, ref bounds) => {
762 // Create a new rib for the trait-wide type parameters.
763 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
764 let local_def_id = this.r.definitions.local_def_id(item.id);
765 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
766 this.visit_generics(generics);
767 walk_list!(this, visit_param_bound, bounds);
772 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
773 self.with_scope(item.id, |this| {
774 visit::walk_item(this, item);
778 ItemKind::Static(ref ty, _, ref expr) |
779 ItemKind::Const(ref ty, ref expr) => {
780 debug!("resolve_item ItemKind::Const");
781 self.with_item_rib(|this| {
783 this.with_constant_rib(|this| {
784 this.visit_expr(expr);
789 ItemKind::Use(ref use_tree) => {
790 self.future_proof_import(use_tree);
793 ItemKind::ExternCrate(..) |
794 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
795 // do nothing, these are just around to be encoded
798 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
802 fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
803 where F: FnOnce(&mut Self)
805 debug!("with_generic_param_rib");
806 match generic_params {
807 HasGenericParams(generics, rib_kind) => {
808 let mut function_type_rib = Rib::new(rib_kind);
809 let mut function_value_rib = Rib::new(rib_kind);
810 let mut seen_bindings = FxHashMap::default();
811 // We also can't shadow bindings from the parent item
812 if let AssocItemRibKind = rib_kind {
813 let mut add_bindings_for_ns = |ns| {
814 let parent_rib = self.ribs[ns].iter()
815 .rfind(|rib| if let ItemRibKind = rib.kind { true } else { false })
816 .expect("associated item outside of an item");
817 seen_bindings.extend(
818 parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)),
821 add_bindings_for_ns(ValueNS);
822 add_bindings_for_ns(TypeNS);
824 for param in &generics.params {
826 GenericParamKind::Lifetime { .. } => {}
827 GenericParamKind::Type { .. } => {
828 let ident = param.ident.modern();
829 debug!("with_generic_param_rib: {}", param.id);
831 if seen_bindings.contains_key(&ident) {
832 let span = seen_bindings.get(&ident).unwrap();
833 let err = ResolutionError::NameAlreadyUsedInParameterList(
837 self.r.report_error(param.ident.span, err);
839 seen_bindings.entry(ident).or_insert(param.ident.span);
841 // Plain insert (no renaming).
844 self.r.definitions.local_def_id(param.id),
846 function_type_rib.bindings.insert(ident, res);
847 self.r.record_partial_res(param.id, PartialRes::new(res));
849 GenericParamKind::Const { .. } => {
850 let ident = param.ident.modern();
851 debug!("with_generic_param_rib: {}", param.id);
853 if seen_bindings.contains_key(&ident) {
854 let span = seen_bindings.get(&ident).unwrap();
855 let err = ResolutionError::NameAlreadyUsedInParameterList(
859 self.r.report_error(param.ident.span, err);
861 seen_bindings.entry(ident).or_insert(param.ident.span);
865 self.r.definitions.local_def_id(param.id),
867 function_value_rib.bindings.insert(ident, res);
868 self.r.record_partial_res(param.id, PartialRes::new(res));
872 self.ribs[ValueNS].push(function_value_rib);
873 self.ribs[TypeNS].push(function_type_rib);
883 if let HasGenericParams(..) = generic_params {
884 self.ribs[TypeNS].pop();
885 self.ribs[ValueNS].pop();
889 fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
890 self.label_ribs.push(Rib::new(kind));
892 self.label_ribs.pop();
895 fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
896 self.with_rib(ValueNS, ItemRibKind, |this| this.with_rib(TypeNS, ItemRibKind, f))
899 fn with_constant_rib(&mut self, f: impl FnOnce(&mut Self)) {
900 debug!("with_constant_rib");
901 self.with_rib(ValueNS, ConstantItemRibKind, |this| {
902 this.with_label_rib(ConstantItemRibKind, f);
906 fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
907 // Handle nested impls (inside fn bodies)
908 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
909 let result = f(self);
910 self.current_self_type = previous_value;
914 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
915 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
916 let result = f(self);
917 self.current_self_item = previous_value;
921 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
922 fn with_trait_items<T>(
924 trait_items: &Vec<TraitItem>,
925 f: impl FnOnce(&mut Self) -> T,
927 let trait_assoc_types = replace(
928 &mut self.current_trait_assoc_types,
929 trait_items.iter().filter_map(|item| match &item.node {
930 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
934 let result = f(self);
935 self.current_trait_assoc_types = trait_assoc_types;
939 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
940 fn with_optional_trait_ref<T>(
942 opt_trait_ref: Option<&TraitRef>,
943 f: impl FnOnce(&mut Self, Option<DefId>) -> T
945 let mut new_val = None;
946 let mut new_id = None;
947 if let Some(trait_ref) = opt_trait_ref {
948 let path: Vec<_> = Segment::from_path(&trait_ref.path);
949 let res = self.smart_resolve_path_fragment(
954 PathSource::Trait(AliasPossibility::No),
955 CrateLint::SimplePath(trait_ref.ref_id),
958 new_id = Some(res.def_id());
959 let span = trait_ref.path.span;
960 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
966 CrateLint::SimplePath(trait_ref.ref_id),
969 new_val = Some((module, trait_ref.clone()));
973 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
974 let result = f(self, new_id);
975 self.current_trait_ref = original_trait_ref;
979 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
980 let mut self_type_rib = Rib::new(NormalRibKind);
982 // Plain insert (no renaming, since types are not currently hygienic)
983 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
984 self.ribs[ns].push(self_type_rib);
989 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
990 self.with_self_rib_ns(TypeNS, self_res, f)
993 fn resolve_implementation(&mut self,
995 opt_trait_reference: &Option<TraitRef>,
998 impl_items: &[ImplItem]) {
999 debug!("resolve_implementation");
1000 // If applicable, create a rib for the type parameters.
1001 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
1002 // Dummy self type for better errors if `Self` is used in the trait path.
1003 this.with_self_rib(Res::SelfTy(None, None), |this| {
1004 // Resolve the trait reference, if necessary.
1005 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1006 let item_def_id = this.r.definitions.local_def_id(item_id);
1007 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1008 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1009 // Resolve type arguments in the trait path.
1010 visit::walk_trait_ref(this, trait_ref);
1012 // Resolve the self type.
1013 this.visit_ty(self_type);
1014 // Resolve the generic parameters.
1015 this.visit_generics(generics);
1016 // Resolve the items within the impl.
1017 this.with_current_self_type(self_type, |this| {
1018 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
1019 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
1020 for impl_item in impl_items {
1021 // We also need a new scope for the impl item type parameters.
1022 let generic_params = HasGenericParams(&impl_item.generics,
1024 this.with_generic_param_rib(generic_params, |this| {
1025 use crate::ResolutionError::*;
1026 match impl_item.node {
1027 ImplItemKind::Const(..) => {
1029 "resolve_implementation ImplItemKind::Const",
1031 // If this is a trait impl, ensure the const
1033 this.check_trait_item(
1037 |n, s| ConstNotMemberOfTrait(n, s),
1040 this.with_constant_rib(|this| {
1041 visit::walk_impl_item(this, impl_item)
1044 ImplItemKind::Method(..) => {
1045 // If this is a trait impl, ensure the method
1047 this.check_trait_item(impl_item.ident,
1050 |n, s| MethodNotMemberOfTrait(n, s));
1052 visit::walk_impl_item(this, impl_item);
1054 ImplItemKind::TyAlias(ref ty) => {
1055 // If this is a trait impl, ensure the type
1057 this.check_trait_item(impl_item.ident,
1060 |n, s| TypeNotMemberOfTrait(n, s));
1064 ImplItemKind::OpaqueTy(ref bounds) => {
1065 // If this is a trait impl, ensure the type
1067 this.check_trait_item(impl_item.ident,
1070 |n, s| TypeNotMemberOfTrait(n, s));
1072 for bound in bounds {
1073 this.visit_param_bound(bound);
1076 ImplItemKind::Macro(_) =>
1077 panic!("unexpanded macro in resolve!"),
1089 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1090 where F: FnOnce(Name, &str) -> ResolutionError<'_>
1092 // If there is a TraitRef in scope for an impl, then the method must be in the
1094 if let Some((module, _)) = self.current_trait_ref {
1095 if self.r.resolve_ident_in_module(
1096 ModuleOrUniformRoot::Module(module),
1103 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1104 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1109 fn resolve_params(&mut self, params: &[Arg]) {
1110 let mut bindings_list = FxHashMap::default();
1111 for param in params {
1112 self.resolve_pattern(¶m.pat, PatternSource::FnParam, &mut bindings_list);
1113 self.visit_ty(¶m.ty);
1114 debug!("(resolving function / closure) recorded parameter");
1118 fn resolve_local(&mut self, local: &Local) {
1119 // Resolve the type.
1120 walk_list!(self, visit_ty, &local.ty);
1122 // Resolve the initializer.
1123 walk_list!(self, visit_expr, &local.init);
1125 // Resolve the pattern.
1126 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
1129 // build a map from pattern identifiers to binding-info's.
1130 // this is done hygienically. This could arise for a macro
1131 // that expands into an or-pattern where one 'x' was from the
1132 // user and one 'x' came from the macro.
1133 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1134 let mut binding_map = FxHashMap::default();
1136 pat.walk(&mut |pat| {
1137 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1138 if sub_pat.is_some() || match self.r.partial_res_map.get(&pat.id)
1139 .map(|res| res.base_res()) {
1140 Some(Res::Local(..)) => true,
1143 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
1144 binding_map.insert(ident, binding_info);
1153 // Checks that all of the arms in an or-pattern have exactly the
1154 // same set of bindings, with the same binding modes for each.
1155 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
1156 let mut missing_vars = FxHashMap::default();
1157 let mut inconsistent_vars = FxHashMap::default();
1159 for pat_outer in pats.iter() {
1160 let map_outer = self.binding_mode_map(&pat_outer);
1162 for pat_inner in pats.iter().filter(|pat| pat.id != pat_outer.id) {
1163 let map_inner = self.binding_mode_map(&pat_inner);
1165 for (&key_inner, &binding_inner) in map_inner.iter() {
1166 match map_outer.get(&key_inner) {
1167 None => { // missing binding
1168 let binding_error = missing_vars
1169 .entry(key_inner.name)
1170 .or_insert(BindingError {
1171 name: key_inner.name,
1172 origin: BTreeSet::new(),
1173 target: BTreeSet::new(),
1175 key_inner.name.as_str().starts_with(char::is_uppercase)
1177 binding_error.origin.insert(binding_inner.span);
1178 binding_error.target.insert(pat_outer.span);
1180 Some(binding_outer) => { // check consistent binding
1181 if binding_outer.binding_mode != binding_inner.binding_mode {
1183 .entry(key_inner.name)
1184 .or_insert((binding_inner.span, binding_outer.span));
1192 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1193 missing_vars.sort();
1194 for (name, mut v) in missing_vars {
1195 if inconsistent_vars.contains_key(name) {
1196 v.could_be_path = false;
1198 self.r.report_error(
1199 *v.origin.iter().next().unwrap(),
1200 ResolutionError::VariableNotBoundInPattern(v));
1203 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1204 inconsistent_vars.sort();
1205 for (name, v) in inconsistent_vars {
1206 self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1210 fn resolve_arm(&mut self, arm: &Arm) {
1211 self.with_rib(ValueNS, NormalRibKind, |this| {
1212 this.resolve_pats(&arm.pats, PatternSource::Match);
1213 walk_list!(this, visit_expr, &arm.guard);
1214 this.visit_expr(&arm.body);
1218 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
1219 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
1220 let mut bindings_list = FxHashMap::default();
1222 self.resolve_pattern(pat, source, &mut bindings_list);
1224 // This has to happen *after* we determine which pat_idents are variants
1226 self.check_consistent_bindings(pats);
1230 fn resolve_block(&mut self, block: &Block) {
1231 debug!("(resolving block) entering block");
1232 // Move down in the graph, if there's an anonymous module rooted here.
1233 let orig_module = self.parent_scope.module;
1234 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1236 let mut num_macro_definition_ribs = 0;
1237 if let Some(anonymous_module) = anonymous_module {
1238 debug!("(resolving block) found anonymous module, moving down");
1239 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1240 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1241 self.parent_scope.module = anonymous_module;
1243 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1246 // Descend into the block.
1247 for stmt in &block.stmts {
1248 if let StmtKind::Item(ref item) = stmt.node {
1249 if let ItemKind::MacroDef(..) = item.node {
1250 num_macro_definition_ribs += 1;
1251 let res = self.r.definitions.local_def_id(item.id);
1252 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1253 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1257 self.visit_stmt(stmt);
1261 self.parent_scope.module = orig_module;
1262 for _ in 0 .. num_macro_definition_ribs {
1263 self.ribs[ValueNS].pop();
1264 self.label_ribs.pop();
1266 self.ribs[ValueNS].pop();
1267 if anonymous_module.is_some() {
1268 self.ribs[TypeNS].pop();
1270 debug!("(resolving block) leaving block");
1273 fn fresh_binding(&mut self,
1276 outer_pat_id: NodeId,
1277 pat_src: PatternSource,
1278 bindings: &mut FxHashMap<Ident, NodeId>)
1280 // Add the binding to the local ribs, if it
1281 // doesn't already exist in the bindings map. (We
1282 // must not add it if it's in the bindings map
1283 // because that breaks the assumptions later
1284 // passes make about or-patterns.)
1285 let ident = ident.modern_and_legacy();
1286 let mut res = Res::Local(pat_id);
1287 match bindings.get(&ident).cloned() {
1288 Some(id) if id == outer_pat_id => {
1289 // `Variant(a, a)`, error
1290 self.r.report_error(
1292 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
1296 Some(..) if pat_src == PatternSource::FnParam => {
1297 // `fn f(a: u8, a: u8)`, error
1298 self.r.report_error(
1300 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
1304 Some(..) if pat_src == PatternSource::Match ||
1305 pat_src == PatternSource::Let => {
1306 // `Variant1(a) | Variant2(a)`, ok
1307 // Reuse definition from the first `a`.
1308 res = self.innermost_rib_bindings(ValueNS)[&ident];
1311 span_bug!(ident.span, "two bindings with the same name from \
1312 unexpected pattern source {:?}", pat_src);
1315 // A completely fresh binding, add to the lists if it's valid.
1316 if ident.name != kw::Invalid {
1317 bindings.insert(ident, outer_pat_id);
1318 self.innermost_rib_bindings(ValueNS).insert(ident, res);
1326 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxHashMap<Ident, Res> {
1327 &mut self.ribs[ns].last_mut().unwrap().bindings
1330 fn resolve_pattern(&mut self,
1332 pat_src: PatternSource,
1333 // Maps idents to the node ID for the
1334 // outermost pattern that binds them.
1335 bindings: &mut FxHashMap<Ident, NodeId>) {
1336 // Visit all direct subpatterns of this pattern.
1337 let outer_pat_id = pat.id;
1338 pat.walk(&mut |pat| {
1339 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1341 PatKind::Ident(bmode, ident, ref opt_pat) => {
1342 // First try to resolve the identifier as some existing
1343 // entity, then fall back to a fresh binding.
1344 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
1346 .and_then(LexicalScopeBinding::item);
1347 let res = binding.map(NameBinding::res).and_then(|res| {
1348 let is_syntactic_ambiguity = opt_pat.is_none() &&
1349 bmode == BindingMode::ByValue(Mutability::Immutable);
1351 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1352 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1353 // Disambiguate in favor of a unit struct/variant
1354 // or constant pattern.
1355 self.r.record_use(ident, ValueNS, binding.unwrap(), false);
1358 Res::Def(DefKind::Ctor(..), _)
1359 | Res::Def(DefKind::Const, _)
1360 | Res::Def(DefKind::Static, _) => {
1361 // This is unambiguously a fresh binding, either syntactically
1362 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1363 // to something unusable as a pattern (e.g., constructor function),
1364 // but we still conservatively report an error, see
1365 // issues/33118#issuecomment-233962221 for one reason why.
1366 self.r.report_error(
1368 ResolutionError::BindingShadowsSomethingUnacceptable(
1369 pat_src.descr(), ident.name, binding.unwrap())
1373 Res::Def(DefKind::Fn, _) | Res::Err => {
1374 // These entities are explicitly allowed
1375 // to be shadowed by fresh bindings.
1379 span_bug!(ident.span, "unexpected resolution for an \
1380 identifier in pattern: {:?}", res);
1383 }).unwrap_or_else(|| {
1384 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1387 self.r.record_partial_res(pat.id, PartialRes::new(res));
1390 PatKind::TupleStruct(ref path, ..) => {
1391 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1394 PatKind::Path(ref qself, ref path) => {
1395 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1398 PatKind::Struct(ref path, ..) => {
1399 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1407 visit::walk_pat(self, pat);
1410 // High-level and context dependent path resolution routine.
1411 // Resolves the path and records the resolution into definition map.
1412 // If resolution fails tries several techniques to find likely
1413 // resolution candidates, suggest imports or other help, and report
1414 // errors in user friendly way.
1415 fn smart_resolve_path(&mut self,
1417 qself: Option<&QSelf>,
1419 source: PathSource<'_>) {
1420 self.smart_resolve_path_fragment(
1423 &Segment::from_path(path),
1426 CrateLint::SimplePath(id),
1430 fn smart_resolve_path_fragment(&mut self,
1432 qself: Option<&QSelf>,
1435 source: PathSource<'_>,
1436 crate_lint: CrateLint)
1438 let ns = source.namespace();
1439 let is_expected = &|res| source.is_expected(res);
1441 let report_errors = |this: &mut Self, res: Option<Res>| {
1442 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1443 let def_id = this.parent_scope.module.normal_ancestor_id;
1444 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1445 let better = res.is_some();
1446 this.r.use_injections.push(UseError { err, candidates, node_id, better });
1447 PartialRes::new(Res::Err)
1450 let partial_res = match self.resolve_qpath_anywhere(
1456 source.defer_to_typeck(),
1459 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1460 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1463 // Add a temporary hack to smooth the transition to new struct ctor
1464 // visibility rules. See #38932 for more details.
1466 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1467 if let Some((ctor_res, ctor_vis))
1468 = self.r.struct_constructors.get(&def_id).cloned() {
1469 if is_expected(ctor_res) &&
1470 self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1471 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1472 self.r.session.buffer_lint(lint, id, span,
1473 "private struct constructors are not usable through \
1474 re-exports in outer modules",
1476 res = Some(PartialRes::new(ctor_res));
1481 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1484 Some(partial_res) if source.defer_to_typeck() => {
1485 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1486 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1487 // it needs to be added to the trait map.
1489 let item_name = path.last().unwrap().ident;
1490 let traits = self.get_traits_containing_item(item_name, ns);
1491 self.r.trait_map.insert(id, traits);
1494 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1495 std_path.extend(path);
1496 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1497 let cl = CrateLint::No;
1499 if let PathResult::Module(_) | PathResult::NonModule(_) =
1500 self.resolve_path(&std_path, ns, false, span, cl) {
1501 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1502 let item_span = path.iter().last().map(|segment| segment.ident.span)
1504 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1505 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1506 hm.insert(item_span, span);
1507 // In some places (E0223) we only have access to the full path
1508 hm.insert(span, span);
1513 _ => report_errors(self, None)
1516 if let PathSource::TraitItem(..) = source {} else {
1517 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1518 self.r.record_partial_res(id, partial_res);
1523 fn self_type_is_available(&mut self, span: Span) -> bool {
1524 let binding = self.resolve_ident_in_lexical_scope(
1525 Ident::with_dummy_span(kw::SelfUpper),
1530 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1533 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1534 let ident = Ident::new(kw::SelfLower, self_span);
1535 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1536 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1539 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1540 fn resolve_qpath_anywhere(
1543 qself: Option<&QSelf>,
1545 primary_ns: Namespace,
1547 defer_to_typeck: bool,
1548 crate_lint: CrateLint,
1549 ) -> Option<PartialRes> {
1550 let mut fin_res = None;
1551 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1552 if i == 0 || ns != primary_ns {
1553 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1554 // If defer_to_typeck, then resolution > no resolution,
1555 // otherwise full resolution > partial resolution > no resolution.
1556 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1558 return Some(partial_res),
1559 partial_res => if fin_res.is_none() { fin_res = partial_res },
1565 assert!(primary_ns != MacroNS);
1566 if qself.is_none() {
1567 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1568 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1569 if let Ok((_, res)) = self.r.resolve_macro_path(
1570 &path, None, &self.parent_scope, false, false
1572 return Some(PartialRes::new(res));
1579 /// Handles paths that may refer to associated items.
1583 qself: Option<&QSelf>,
1587 crate_lint: CrateLint,
1588 ) -> Option<PartialRes> {
1590 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1598 if let Some(qself) = qself {
1599 if qself.position == 0 {
1600 // This is a case like `<T>::B`, where there is no
1601 // trait to resolve. In that case, we leave the `B`
1602 // segment to be resolved by type-check.
1603 return Some(PartialRes::with_unresolved_segments(
1604 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1608 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1610 // Currently, `path` names the full item (`A::B::C`, in
1611 // our example). so we extract the prefix of that that is
1612 // the trait (the slice upto and including
1613 // `qself.position`). And then we recursively resolve that,
1614 // but with `qself` set to `None`.
1616 // However, setting `qself` to none (but not changing the
1617 // span) loses the information about where this path
1618 // *actually* appears, so for the purposes of the crate
1619 // lint we pass along information that this is the trait
1620 // name from a fully qualified path, and this also
1621 // contains the full span (the `CrateLint::QPathTrait`).
1622 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1623 let partial_res = self.smart_resolve_path_fragment(
1626 &path[..=qself.position],
1628 PathSource::TraitItem(ns),
1629 CrateLint::QPathTrait {
1631 qpath_span: qself.path_span,
1635 // The remaining segments (the `C` in our example) will
1636 // have to be resolved by type-check, since that requires doing
1637 // trait resolution.
1638 return Some(PartialRes::with_unresolved_segments(
1639 partial_res.base_res(),
1640 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1644 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1645 PathResult::NonModule(path_res) => path_res,
1646 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1647 PartialRes::new(module.res().unwrap())
1649 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1650 // don't report an error right away, but try to fallback to a primitive type.
1651 // So, we are still able to successfully resolve something like
1653 // use std::u8; // bring module u8 in scope
1654 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1655 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1656 // // not to non-existent std::u8::max_value
1659 // Such behavior is required for backward compatibility.
1660 // The same fallback is used when `a` resolves to nothing.
1661 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1662 PathResult::Failed { .. }
1663 if (ns == TypeNS || path.len() > 1) &&
1664 self.r.primitive_type_table.primitive_types
1665 .contains_key(&path[0].ident.name) => {
1666 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1667 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1669 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1670 PartialRes::new(module.res().unwrap()),
1671 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1672 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1673 PartialRes::new(Res::Err)
1675 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1676 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1679 if path.len() > 1 && result.base_res() != Res::Err &&
1680 path[0].ident.name != kw::PathRoot &&
1681 path[0].ident.name != kw::DollarCrate {
1682 let unqualified_result = {
1683 match self.resolve_path(
1684 &[*path.last().unwrap()],
1690 PathResult::NonModule(path_res) => path_res.base_res(),
1691 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1692 module.res().unwrap(),
1693 _ => return Some(result),
1696 if result.base_res() == unqualified_result {
1697 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1698 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1705 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
1706 if let Some(label) = label {
1707 self.unused_labels.insert(id, label.ident.span);
1708 self.with_label_rib(NormalRibKind, |this| {
1709 let ident = label.ident.modern_and_legacy();
1710 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1718 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1719 self.with_resolved_label(label, id, |this| this.visit_block(block));
1722 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1723 // First, record candidate traits for this expression if it could
1724 // result in the invocation of a method call.
1726 self.record_candidate_traits_for_expr_if_necessary(expr);
1728 // Next, resolve the node.
1730 ExprKind::Path(ref qself, ref path) => {
1731 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1732 visit::walk_expr(self, expr);
1735 ExprKind::Struct(ref path, ..) => {
1736 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1737 visit::walk_expr(self, expr);
1740 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1741 let node_id = self.search_label(label.ident, |rib, ident| {
1742 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1746 // Search again for close matches...
1747 // Picks the first label that is "close enough", which is not necessarily
1748 // the closest match
1749 let close_match = self.search_label(label.ident, |rib, ident| {
1750 let names = rib.bindings.iter().filter_map(|(id, _)| {
1751 if id.span.ctxt() == label.ident.span.ctxt() {
1757 find_best_match_for_name(names, &*ident.as_str(), None)
1759 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1760 self.r.report_error(
1762 ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1766 // Since this res is a label, it is never read.
1767 self.r.label_res_map.insert(expr.id, node_id);
1768 self.unused_labels.remove(&node_id);
1772 // visit `break` argument if any
1773 visit::walk_expr(self, expr);
1776 ExprKind::Let(ref pats, ref scrutinee) => {
1777 self.visit_expr(scrutinee);
1778 self.resolve_pats(pats, PatternSource::Let);
1781 ExprKind::If(ref cond, ref then, ref opt_else) => {
1782 self.with_rib(ValueNS, NormalRibKind, |this| {
1783 this.visit_expr(cond);
1784 this.visit_block(then);
1786 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1789 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1791 ExprKind::While(ref cond, ref block, label) => {
1792 self.with_resolved_label(label, expr.id, |this| {
1793 this.with_rib(ValueNS, NormalRibKind, |this| {
1794 this.visit_expr(cond);
1795 this.visit_block(block);
1800 ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
1801 self.visit_expr(iter_expr);
1802 self.with_rib(ValueNS, NormalRibKind, |this| {
1803 this.resolve_pattern(pat, PatternSource::For, &mut FxHashMap::default());
1804 this.resolve_labeled_block(label, expr.id, block);
1808 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1810 // Equivalent to `visit::walk_expr` + passing some context to children.
1811 ExprKind::Field(ref subexpression, _) => {
1812 self.resolve_expr(subexpression, Some(expr));
1814 ExprKind::MethodCall(ref segment, ref arguments) => {
1815 let mut arguments = arguments.iter();
1816 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1817 for argument in arguments {
1818 self.resolve_expr(argument, None);
1820 self.visit_path_segment(expr.span, segment);
1823 ExprKind::Call(ref callee, ref arguments) => {
1824 self.resolve_expr(callee, Some(expr));
1825 for argument in arguments {
1826 self.resolve_expr(argument, None);
1829 ExprKind::Type(ref type_expr, _) => {
1830 self.current_type_ascription.push(type_expr.span);
1831 visit::walk_expr(self, expr);
1832 self.current_type_ascription.pop();
1834 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1835 // resolve the arguments within the proper scopes so that usages of them inside the
1836 // closure are detected as upvars rather than normal closure arg usages.
1837 ExprKind::Closure(_, IsAsync::Async { .. }, _, ref fn_decl, ref body, _span) => {
1838 self.with_rib(ValueNS, NormalRibKind, |this| {
1839 // Resolve arguments:
1840 this.resolve_params(&fn_decl.inputs);
1841 // No need to resolve return type --
1842 // the outer closure return type is `FunctionRetTy::Default`.
1844 // Now resolve the inner closure
1846 // No need to resolve arguments: the inner closure has none.
1847 // Resolve the return type:
1848 visit::walk_fn_ret_ty(this, &fn_decl.output);
1850 this.visit_expr(body);
1855 visit::walk_expr(self, expr);
1860 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1862 ExprKind::Field(_, ident) => {
1863 // FIXME(#6890): Even though you can't treat a method like a
1864 // field, we need to add any trait methods we find that match
1865 // the field name so that we can do some nice error reporting
1866 // later on in typeck.
1867 let traits = self.get_traits_containing_item(ident, ValueNS);
1868 self.r.trait_map.insert(expr.id, traits);
1870 ExprKind::MethodCall(ref segment, ..) => {
1871 debug!("(recording candidate traits for expr) recording traits for {}",
1873 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1874 self.r.trait_map.insert(expr.id, traits);
1882 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1883 -> Vec<TraitCandidate> {
1884 debug!("(getting traits containing item) looking for '{}'", ident.name);
1886 let mut found_traits = Vec::new();
1887 // Look for the current trait.
1888 if let Some((module, _)) = self.current_trait_ref {
1889 if self.r.resolve_ident_in_module(
1890 ModuleOrUniformRoot::Module(module),
1897 let def_id = module.def_id().unwrap();
1898 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1902 ident.span = ident.span.modern();
1903 let mut search_module = self.parent_scope.module;
1905 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1906 search_module = unwrap_or!(
1907 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1911 if let Some(prelude) = self.r.prelude {
1912 if !search_module.no_implicit_prelude {
1913 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1920 fn get_traits_in_module_containing_item(&mut self,
1924 found_traits: &mut Vec<TraitCandidate>) {
1925 assert!(ns == TypeNS || ns == ValueNS);
1926 let mut traits = module.traits.borrow_mut();
1927 if traits.is_none() {
1928 let mut collected_traits = Vec::new();
1929 module.for_each_child(self.r, |_, name, ns, binding| {
1930 if ns != TypeNS { return }
1931 match binding.res() {
1932 Res::Def(DefKind::Trait, _) |
1933 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1937 *traits = Some(collected_traits.into_boxed_slice());
1940 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1941 // Traits have pseudo-modules that can be used to search for the given ident.
1942 if let Some(module) = binding.module() {
1943 let mut ident = ident;
1944 if ident.span.glob_adjust(
1950 if self.r.resolve_ident_in_module_unadjusted(
1951 ModuleOrUniformRoot::Module(module),
1958 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1959 let trait_def_id = module.def_id().unwrap();
1960 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1962 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1963 // For now, just treat all trait aliases as possible candidates, since we don't
1964 // know if the ident is somewhere in the transitive bounds.
1965 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1966 let trait_def_id = binding.res().def_id();
1967 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1969 bug!("candidate is not trait or trait alias?")
1974 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
1975 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
1976 let mut import_ids = smallvec![];
1977 while let NameBindingKind::Import { directive, binding, .. } = kind {
1978 self.r.maybe_unused_trait_imports.insert(directive.id);
1979 self.r.add_to_glob_map(&directive, trait_name);
1980 import_ids.push(directive.id);
1981 kind = &binding.kind;
1987 impl<'a> Resolver<'a> {
1988 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
1989 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
1990 visit::walk_crate(&mut late_resolution_visitor, krate);
1991 for (id, span) in late_resolution_visitor.unused_labels.iter() {
1992 self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");