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,
114 /// A single local scope.
116 /// A rib represents a scope names can live in. Note that these appear in many places, not just
117 /// around braces. At any place where the list of accessible names (of the given namespace)
118 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
119 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
122 /// Different [rib kinds](enum.RibKind) are transparent for different names.
124 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
125 /// resolving, the name is looked up from inside out.
127 crate struct Rib<'a, R = Res> {
128 pub bindings: FxHashMap<Ident, R>,
129 pub kind: RibKind<'a>,
132 impl<'a, R> Rib<'a, R> {
133 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
135 bindings: Default::default(),
141 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
142 crate enum AliasPossibility {
147 #[derive(Copy, Clone, Debug)]
148 crate enum PathSource<'a> {
149 // Type paths `Path`.
151 // Trait paths in bounds or impls.
152 Trait(AliasPossibility),
153 // Expression paths `path`, with optional parent context.
154 Expr(Option<&'a Expr>),
155 // Paths in path patterns `Path`.
157 // Paths in struct expressions and patterns `Path { .. }`.
159 // Paths in tuple struct patterns `Path(..)`.
161 // `m::A::B` in `<T as m::A>::B::C`.
162 TraitItem(Namespace),
165 impl<'a> PathSource<'a> {
166 fn namespace(self) -> Namespace {
168 PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
169 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
170 PathSource::TraitItem(ns) => ns,
174 fn defer_to_typeck(self) -> bool {
176 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
177 PathSource::Struct | PathSource::TupleStruct => true,
178 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
182 fn descr_expected(self) -> &'static str {
184 PathSource::Type => "type",
185 PathSource::Trait(_) => "trait",
186 PathSource::Pat => "unit struct/variant or constant",
187 PathSource::Struct => "struct, variant or union type",
188 PathSource::TupleStruct => "tuple struct/variant",
189 PathSource::TraitItem(ns) => match ns {
190 TypeNS => "associated type",
191 ValueNS => "method or associated constant",
192 MacroNS => bug!("associated macro"),
194 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
195 // "function" here means "anything callable" rather than `DefKind::Fn`,
196 // this is not precise but usually more helpful than just "value".
197 Some(&ExprKind::Call(..)) => "function",
203 crate fn is_expected(self, res: Res) -> bool {
205 PathSource::Type => match res {
206 Res::Def(DefKind::Struct, _)
207 | Res::Def(DefKind::Union, _)
208 | Res::Def(DefKind::Enum, _)
209 | Res::Def(DefKind::Trait, _)
210 | Res::Def(DefKind::TraitAlias, _)
211 | Res::Def(DefKind::TyAlias, _)
212 | Res::Def(DefKind::AssocTy, _)
214 | Res::Def(DefKind::TyParam, _)
216 | Res::Def(DefKind::OpaqueTy, _)
217 | Res::Def(DefKind::ForeignTy, _) => true,
220 PathSource::Trait(AliasPossibility::No) => match res {
221 Res::Def(DefKind::Trait, _) => true,
224 PathSource::Trait(AliasPossibility::Maybe) => match res {
225 Res::Def(DefKind::Trait, _) => true,
226 Res::Def(DefKind::TraitAlias, _) => true,
229 PathSource::Expr(..) => match res {
230 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
231 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
232 | Res::Def(DefKind::Const, _)
233 | Res::Def(DefKind::Static, _)
235 | Res::Def(DefKind::Fn, _)
236 | Res::Def(DefKind::Method, _)
237 | Res::Def(DefKind::AssocConst, _)
239 | Res::Def(DefKind::ConstParam, _) => true,
242 PathSource::Pat => match res {
243 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
244 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
245 Res::SelfCtor(..) => true,
248 PathSource::TupleStruct => match res {
249 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
252 PathSource::Struct => match res {
253 Res::Def(DefKind::Struct, _)
254 | Res::Def(DefKind::Union, _)
255 | Res::Def(DefKind::Variant, _)
256 | Res::Def(DefKind::TyAlias, _)
257 | Res::Def(DefKind::AssocTy, _)
258 | Res::SelfTy(..) => true,
261 PathSource::TraitItem(ns) => match res {
262 Res::Def(DefKind::AssocConst, _)
263 | Res::Def(DefKind::Method, _) if ns == ValueNS => true,
264 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
270 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
271 __diagnostic_used!(E0404);
272 __diagnostic_used!(E0405);
273 __diagnostic_used!(E0412);
274 __diagnostic_used!(E0422);
275 __diagnostic_used!(E0423);
276 __diagnostic_used!(E0425);
277 __diagnostic_used!(E0531);
278 __diagnostic_used!(E0532);
279 __diagnostic_used!(E0573);
280 __diagnostic_used!(E0574);
281 __diagnostic_used!(E0575);
282 __diagnostic_used!(E0576);
283 match (self, has_unexpected_resolution) {
284 (PathSource::Trait(_), true) => "E0404",
285 (PathSource::Trait(_), false) => "E0405",
286 (PathSource::Type, true) => "E0573",
287 (PathSource::Type, false) => "E0412",
288 (PathSource::Struct, true) => "E0574",
289 (PathSource::Struct, false) => "E0422",
290 (PathSource::Expr(..), true) => "E0423",
291 (PathSource::Expr(..), false) => "E0425",
292 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
293 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
294 (PathSource::TraitItem(..), true) => "E0575",
295 (PathSource::TraitItem(..), false) => "E0576",
300 struct LateResolutionVisitor<'a, 'b> {
301 r: &'b mut Resolver<'a>,
303 /// The module that represents the current item scope.
304 parent_scope: ParentScope<'a>,
306 /// The current set of local scopes for types and values.
307 /// FIXME #4948: Reuse ribs to avoid allocation.
308 ribs: PerNS<Vec<Rib<'a>>>,
310 /// The current set of local scopes, for labels.
311 label_ribs: Vec<Rib<'a, NodeId>>,
313 /// The trait that the current context can refer to.
314 current_trait_ref: Option<(Module<'a>, TraitRef)>,
316 /// The current trait's associated types' ident, used for diagnostic suggestions.
317 current_trait_assoc_types: Vec<Ident>,
319 /// The current self type if inside an impl (used for better errors).
320 current_self_type: Option<Ty>,
322 /// The current self item if inside an ADT (used for better errors).
323 current_self_item: Option<NodeId>,
325 /// A list of labels as of yet unused. Labels will be removed from this map when
326 /// they are used (in a `break` or `continue` statement)
327 unused_labels: FxHashMap<NodeId, Span>,
329 /// Only used for better errors on `fn(): fn()`.
330 current_type_ascription: Vec<Span>,
333 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
334 impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
335 fn visit_item(&mut self, item: &'tcx Item) {
336 self.resolve_item(item);
338 fn visit_arm(&mut self, arm: &'tcx Arm) {
339 self.resolve_arm(arm);
341 fn visit_block(&mut self, block: &'tcx Block) {
342 self.resolve_block(block);
344 fn visit_anon_const(&mut self, constant: &'tcx AnonConst) {
345 debug!("visit_anon_const {:?}", constant);
346 self.with_constant_rib(|this| {
347 visit::walk_anon_const(this, constant);
350 fn visit_expr(&mut self, expr: &'tcx Expr) {
351 self.resolve_expr(expr, None);
353 fn visit_local(&mut self, local: &'tcx Local) {
354 self.resolve_local(local);
356 fn visit_ty(&mut self, ty: &'tcx Ty) {
358 TyKind::Path(ref qself, ref path) => {
359 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
361 TyKind::ImplicitSelf => {
362 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
363 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
364 .map_or(Res::Err, |d| d.res());
365 self.r.record_partial_res(ty.id, PartialRes::new(res));
369 visit::walk_ty(self, ty);
371 fn visit_poly_trait_ref(&mut self,
372 tref: &'tcx PolyTraitRef,
373 m: &'tcx TraitBoundModifier) {
374 self.smart_resolve_path(tref.trait_ref.ref_id, None,
375 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
376 visit::walk_poly_trait_ref(self, tref, m);
378 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
379 let generic_params = match foreign_item.node {
380 ForeignItemKind::Fn(_, ref generics) => {
381 HasGenericParams(generics, ItemRibKind)
383 ForeignItemKind::Static(..) => NoGenericParams,
384 ForeignItemKind::Ty => NoGenericParams,
385 ForeignItemKind::Macro(..) => NoGenericParams,
387 self.with_generic_param_rib(generic_params, |this| {
388 visit::walk_foreign_item(this, foreign_item);
391 fn visit_fn(&mut self,
392 function_kind: FnKind<'tcx>,
393 declaration: &'tcx FnDecl,
397 debug!("(resolving function) entering function");
398 let rib_kind = match function_kind {
399 FnKind::ItemFn(..) => FnItemRibKind,
400 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
403 // Create a value rib for the function.
404 self.ribs[ValueNS].push(Rib::new(rib_kind));
406 // Create a label rib for the function.
407 self.label_ribs.push(Rib::new(rib_kind));
409 // Add each argument to the rib.
410 let mut bindings_list = FxHashMap::default();
411 for argument in &declaration.inputs {
412 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
414 self.visit_ty(&argument.ty);
416 debug!("(resolving function) recorded argument");
418 visit::walk_fn_ret_ty(self, &declaration.output);
420 // Resolve the function body, potentially inside the body of an async closure
421 match function_kind {
422 FnKind::ItemFn(.., body) |
423 FnKind::Method(.., body) => {
424 self.visit_block(body);
426 FnKind::Closure(body) => {
427 self.visit_expr(body);
431 debug!("(resolving function) leaving function");
433 self.label_ribs.pop();
434 self.ribs[ValueNS].pop();
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 LateResolutionVisitor {
517 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
518 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
519 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
521 label_ribs: Vec::new(),
522 current_trait_ref: None,
523 current_trait_assoc_types: Vec::new(),
524 current_self_type: None,
525 current_self_item: None,
526 unused_labels: Default::default(),
527 current_type_ascription: Vec::new(),
531 fn resolve_ident_in_lexical_scope(&mut self,
534 record_used_id: Option<NodeId>,
536 -> Option<LexicalScopeBinding<'a>> {
537 self.r.resolve_ident_in_lexical_scope(
538 ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
545 opt_ns: Option<Namespace>, // `None` indicates a module path in import
548 crate_lint: CrateLint,
549 ) -> PathResult<'a> {
550 self.r.resolve_path_with_ribs(
551 path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, Some(&self.ribs)
557 // We maintain a list of value ribs and type ribs.
559 // Simultaneously, we keep track of the current position in the module
560 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
561 // the value or type namespaces, we first look through all the ribs and
562 // then query the module graph. When we resolve a name in the module
563 // namespace, we can skip all the ribs (since nested modules are not
564 // allowed within blocks in Rust) and jump straight to the current module
567 // Named implementations are handled separately. When we find a method
568 // call, we consult the module node to find all of the implementations in
569 // scope. This information is lazily cached in the module node. We then
570 // generate a fake "implementation scope" containing all the
571 // implementations thus found, for compatibility with old resolve pass.
573 fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
574 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
576 let id = self.r.definitions.local_def_id(id);
577 let module = self.r.module_map.get(&id).cloned(); // clones a reference
578 if let Some(module) = module {
579 // Move down in the graph.
580 let orig_module = replace(&mut self.parent_scope.module, module);
581 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
582 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
586 self.parent_scope.module = orig_module;
587 self.ribs[ValueNS].pop();
588 self.ribs[TypeNS].pop();
595 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
596 /// is returned by the given predicate function
598 /// Stops after meeting a closure.
599 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
600 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
602 for rib in self.label_ribs.iter().rev() {
605 // If an invocation of this macro created `ident`, give up on `ident`
606 // and switch to `ident`'s source from the macro definition.
607 MacroDefinition(def) => {
608 if def == self.r.macro_def(ident.span.ctxt()) {
609 ident.span.remove_mark();
613 // Do not resolve labels across function boundary
617 let r = pred(rib, ident);
625 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
626 debug!("resolve_adt");
627 self.with_current_self_item(item, |this| {
628 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
629 let item_def_id = this.r.definitions.local_def_id(item.id);
630 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
631 visit::walk_item(this, item);
637 fn future_proof_import(&mut self, use_tree: &UseTree) {
638 let segments = &use_tree.prefix.segments;
639 if !segments.is_empty() {
640 let ident = segments[0].ident;
641 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
645 let nss = match use_tree.kind {
646 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
649 let report_error = |this: &Self, ns| {
650 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
651 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
655 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
656 Some(LexicalScopeBinding::Res(..)) => {
657 report_error(self, ns);
659 Some(LexicalScopeBinding::Item(binding)) => {
660 let orig_blacklisted_binding =
661 replace(&mut self.r.blacklisted_binding, Some(binding));
662 if let Some(LexicalScopeBinding::Res(..)) =
663 self.resolve_ident_in_lexical_scope(ident, ns, None,
664 use_tree.prefix.span) {
665 report_error(self, ns);
667 self.r.blacklisted_binding = orig_blacklisted_binding;
672 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
673 for (use_tree, _) in use_trees {
674 self.future_proof_import(use_tree);
679 fn resolve_item(&mut self, item: &Item) {
680 let name = item.ident.name;
681 debug!("(resolving item) resolving {} ({:?})", name, item.node);
684 ItemKind::TyAlias(_, ref generics) |
685 ItemKind::OpaqueTy(_, ref generics) |
686 ItemKind::Fn(_, _, ref generics, _) => {
687 self.with_generic_param_rib(
688 HasGenericParams(generics, ItemRibKind),
689 |this| visit::walk_item(this, item)
693 ItemKind::Enum(_, ref generics) |
694 ItemKind::Struct(_, ref generics) |
695 ItemKind::Union(_, ref generics) => {
696 self.resolve_adt(item, generics);
699 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
700 self.resolve_implementation(generics,
706 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
707 // Create a new rib for the trait-wide type parameters.
708 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
709 let local_def_id = this.r.definitions.local_def_id(item.id);
710 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
711 this.visit_generics(generics);
712 walk_list!(this, visit_param_bound, bounds);
714 for trait_item in trait_items {
715 this.with_trait_items(trait_items, |this| {
716 let generic_params = HasGenericParams(
717 &trait_item.generics,
720 this.with_generic_param_rib(generic_params, |this| {
721 match trait_item.node {
722 TraitItemKind::Const(ref ty, ref default) => {
725 // Only impose the restrictions of
726 // ConstRibKind for an actual constant
727 // expression in a provided default.
728 if let Some(ref expr) = *default{
729 this.with_constant_rib(|this| {
730 this.visit_expr(expr);
734 TraitItemKind::Method(_, _) => {
735 visit::walk_trait_item(this, trait_item)
737 TraitItemKind::Type(..) => {
738 visit::walk_trait_item(this, trait_item)
740 TraitItemKind::Macro(_) => {
741 panic!("unexpanded macro in resolve!")
751 ItemKind::TraitAlias(ref generics, ref bounds) => {
752 // Create a new rib for the trait-wide type parameters.
753 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
754 let local_def_id = this.r.definitions.local_def_id(item.id);
755 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
756 this.visit_generics(generics);
757 walk_list!(this, visit_param_bound, bounds);
762 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
763 self.with_scope(item.id, |this| {
764 visit::walk_item(this, item);
768 ItemKind::Static(ref ty, _, ref expr) |
769 ItemKind::Const(ref ty, ref expr) => {
770 debug!("resolve_item ItemKind::Const");
771 self.with_item_rib(|this| {
773 this.with_constant_rib(|this| {
774 this.visit_expr(expr);
779 ItemKind::Use(ref use_tree) => {
780 self.future_proof_import(use_tree);
783 ItemKind::ExternCrate(..) |
784 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
785 // do nothing, these are just around to be encoded
788 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
792 fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
793 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
795 debug!("with_generic_param_rib");
796 match generic_params {
797 HasGenericParams(generics, rib_kind) => {
798 let mut function_type_rib = Rib::new(rib_kind);
799 let mut function_value_rib = Rib::new(rib_kind);
800 let mut seen_bindings = FxHashMap::default();
801 for param in &generics.params {
803 GenericParamKind::Lifetime { .. } => {}
804 GenericParamKind::Type { .. } => {
805 let ident = param.ident.modern();
806 debug!("with_generic_param_rib: {}", param.id);
808 if seen_bindings.contains_key(&ident) {
809 let span = seen_bindings.get(&ident).unwrap();
810 let err = ResolutionError::NameAlreadyUsedInParameterList(
814 self.r.report_error(param.ident.span, err);
816 seen_bindings.entry(ident).or_insert(param.ident.span);
818 // Plain insert (no renaming).
821 self.r.definitions.local_def_id(param.id),
823 function_type_rib.bindings.insert(ident, res);
824 self.r.record_partial_res(param.id, PartialRes::new(res));
826 GenericParamKind::Const { .. } => {
827 let ident = param.ident.modern();
828 debug!("with_generic_param_rib: {}", param.id);
830 if seen_bindings.contains_key(&ident) {
831 let span = seen_bindings.get(&ident).unwrap();
832 let err = ResolutionError::NameAlreadyUsedInParameterList(
836 self.r.report_error(param.ident.span, err);
838 seen_bindings.entry(ident).or_insert(param.ident.span);
842 self.r.definitions.local_def_id(param.id),
844 function_value_rib.bindings.insert(ident, res);
845 self.r.record_partial_res(param.id, PartialRes::new(res));
849 self.ribs[ValueNS].push(function_value_rib);
850 self.ribs[TypeNS].push(function_type_rib);
860 if let HasGenericParams(..) = generic_params {
861 self.ribs[TypeNS].pop();
862 self.ribs[ValueNS].pop();
866 fn with_label_rib<F>(&mut self, f: F)
867 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
869 self.label_ribs.push(Rib::new(NormalRibKind));
871 self.label_ribs.pop();
874 fn with_item_rib<F>(&mut self, f: F)
875 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
877 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
878 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
880 self.ribs[TypeNS].pop();
881 self.ribs[ValueNS].pop();
884 fn with_constant_rib<F>(&mut self, f: F)
885 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
887 debug!("with_constant_rib");
888 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
889 self.label_ribs.push(Rib::new(ConstantItemRibKind));
891 self.label_ribs.pop();
892 self.ribs[ValueNS].pop();
895 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
896 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
898 // Handle nested impls (inside fn bodies)
899 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
900 let result = f(self);
901 self.current_self_type = previous_value;
905 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
906 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
908 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
909 let result = f(self);
910 self.current_self_item = previous_value;
914 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
915 fn with_trait_items<T, F>(&mut self, trait_items: &Vec<TraitItem>, f: F) -> T
916 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
918 let trait_assoc_types = replace(
919 &mut self.current_trait_assoc_types,
920 trait_items.iter().filter_map(|item| match &item.node {
921 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
925 let result = f(self);
926 self.current_trait_assoc_types = trait_assoc_types;
930 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
931 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
932 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>, Option<DefId>) -> T
934 let mut new_val = None;
935 let mut new_id = None;
936 if let Some(trait_ref) = opt_trait_ref {
937 let path: Vec<_> = Segment::from_path(&trait_ref.path);
938 let res = self.smart_resolve_path_fragment(
943 PathSource::Trait(AliasPossibility::No),
944 CrateLint::SimplePath(trait_ref.ref_id),
947 new_id = Some(res.def_id());
948 let span = trait_ref.path.span;
949 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
955 CrateLint::SimplePath(trait_ref.ref_id),
958 new_val = Some((module, trait_ref.clone()));
962 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
963 let result = f(self, new_id);
964 self.current_trait_ref = original_trait_ref;
968 fn with_self_rib<F>(&mut self, self_res: Res, f: F)
969 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
971 let mut self_type_rib = Rib::new(NormalRibKind);
973 // Plain insert (no renaming, since types are not currently hygienic)
974 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
975 self.ribs[TypeNS].push(self_type_rib);
977 self.ribs[TypeNS].pop();
980 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
981 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
983 let self_res = Res::SelfCtor(impl_id);
984 let mut self_type_rib = Rib::new(NormalRibKind);
985 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
986 self.ribs[ValueNS].push(self_type_rib);
988 self.ribs[ValueNS].pop();
991 fn resolve_implementation(&mut self,
993 opt_trait_reference: &Option<TraitRef>,
996 impl_items: &[ImplItem]) {
997 debug!("resolve_implementation");
998 // If applicable, create a rib for the type parameters.
999 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
1000 // Dummy self type for better errors if `Self` is used in the trait path.
1001 this.with_self_rib(Res::SelfTy(None, None), |this| {
1002 // Resolve the trait reference, if necessary.
1003 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1004 let item_def_id = this.r.definitions.local_def_id(item_id);
1005 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1006 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1007 // Resolve type arguments in the trait path.
1008 visit::walk_trait_ref(this, trait_ref);
1010 // Resolve the self type.
1011 this.visit_ty(self_type);
1012 // Resolve the generic parameters.
1013 this.visit_generics(generics);
1014 // Resolve the items within the impl.
1015 this.with_current_self_type(self_type, |this| {
1016 this.with_self_struct_ctor_rib(item_def_id, |this| {
1017 debug!("resolve_implementation with_self_struct_ctor_rib");
1018 for impl_item in impl_items {
1019 // We also need a new scope for the impl item type parameters.
1020 let generic_params = HasGenericParams(&impl_item.generics,
1022 this.with_generic_param_rib(generic_params, |this| {
1023 use crate::ResolutionError::*;
1024 match impl_item.node {
1025 ImplItemKind::Const(..) => {
1027 "resolve_implementation ImplItemKind::Const",
1029 // If this is a trait impl, ensure the const
1031 this.check_trait_item(
1035 |n, s| ConstNotMemberOfTrait(n, s),
1038 this.with_constant_rib(|this| {
1039 visit::walk_impl_item(this, impl_item)
1042 ImplItemKind::Method(..) => {
1043 // If this is a trait impl, ensure the method
1045 this.check_trait_item(impl_item.ident,
1048 |n, s| MethodNotMemberOfTrait(n, s));
1050 visit::walk_impl_item(this, impl_item);
1052 ImplItemKind::TyAlias(ref ty) => {
1053 // If this is a trait impl, ensure the type
1055 this.check_trait_item(impl_item.ident,
1058 |n, s| TypeNotMemberOfTrait(n, s));
1062 ImplItemKind::OpaqueTy(ref bounds) => {
1063 // If this is a trait impl, ensure the type
1065 this.check_trait_item(impl_item.ident,
1068 |n, s| TypeNotMemberOfTrait(n, s));
1070 for bound in bounds {
1071 this.visit_param_bound(bound);
1074 ImplItemKind::Macro(_) =>
1075 panic!("unexpanded macro in resolve!"),
1087 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1088 where F: FnOnce(Name, &str) -> ResolutionError<'_>
1090 // If there is a TraitRef in scope for an impl, then the method must be in the
1092 if let Some((module, _)) = self.current_trait_ref {
1093 if self.r.resolve_ident_in_module(
1094 ModuleOrUniformRoot::Module(module),
1101 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1102 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1107 fn resolve_local(&mut self, local: &Local) {
1108 // Resolve the type.
1109 walk_list!(self, visit_ty, &local.ty);
1111 // Resolve the initializer.
1112 walk_list!(self, visit_expr, &local.init);
1114 // Resolve the pattern.
1115 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
1118 // build a map from pattern identifiers to binding-info's.
1119 // this is done hygienically. This could arise for a macro
1120 // that expands into an or-pattern where one 'x' was from the
1121 // user and one 'x' came from the macro.
1122 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1123 let mut binding_map = FxHashMap::default();
1125 pat.walk(&mut |pat| {
1126 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1127 if sub_pat.is_some() || match self.r.partial_res_map.get(&pat.id)
1128 .map(|res| res.base_res()) {
1129 Some(Res::Local(..)) => true,
1132 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
1133 binding_map.insert(ident, binding_info);
1142 // Checks that all of the arms in an or-pattern have exactly the
1143 // same set of bindings, with the same binding modes for each.
1144 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
1145 let mut missing_vars = FxHashMap::default();
1146 let mut inconsistent_vars = FxHashMap::default();
1148 for pat_outer in pats.iter() {
1149 let map_outer = self.binding_mode_map(&pat_outer);
1151 for pat_inner in pats.iter().filter(|pat| pat.id != pat_outer.id) {
1152 let map_inner = self.binding_mode_map(&pat_inner);
1154 for (&key_inner, &binding_inner) in map_inner.iter() {
1155 match map_outer.get(&key_inner) {
1156 None => { // missing binding
1157 let binding_error = missing_vars
1158 .entry(key_inner.name)
1159 .or_insert(BindingError {
1160 name: key_inner.name,
1161 origin: BTreeSet::new(),
1162 target: BTreeSet::new(),
1164 key_inner.name.as_str().starts_with(char::is_uppercase)
1166 binding_error.origin.insert(binding_inner.span);
1167 binding_error.target.insert(pat_outer.span);
1169 Some(binding_outer) => { // check consistent binding
1170 if binding_outer.binding_mode != binding_inner.binding_mode {
1172 .entry(key_inner.name)
1173 .or_insert((binding_inner.span, binding_outer.span));
1181 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1182 missing_vars.sort();
1183 for (name, mut v) in missing_vars {
1184 if inconsistent_vars.contains_key(name) {
1185 v.could_be_path = false;
1187 self.r.report_error(
1188 *v.origin.iter().next().unwrap(),
1189 ResolutionError::VariableNotBoundInPattern(v));
1192 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1193 inconsistent_vars.sort();
1194 for (name, v) in inconsistent_vars {
1195 self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1199 fn resolve_arm(&mut self, arm: &Arm) {
1200 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1202 self.resolve_pats(&arm.pats, PatternSource::Match);
1204 if let Some(ref expr) = arm.guard {
1205 self.visit_expr(expr)
1207 self.visit_expr(&arm.body);
1209 self.ribs[ValueNS].pop();
1212 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
1213 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
1214 let mut bindings_list = FxHashMap::default();
1216 self.resolve_pattern(pat, source, &mut bindings_list);
1218 // This has to happen *after* we determine which pat_idents are variants
1220 self.check_consistent_bindings(pats);
1224 fn resolve_block(&mut self, block: &Block) {
1225 debug!("(resolving block) entering block");
1226 // Move down in the graph, if there's an anonymous module rooted here.
1227 let orig_module = self.parent_scope.module;
1228 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1230 let mut num_macro_definition_ribs = 0;
1231 if let Some(anonymous_module) = anonymous_module {
1232 debug!("(resolving block) found anonymous module, moving down");
1233 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1234 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1235 self.parent_scope.module = anonymous_module;
1237 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1240 // Descend into the block.
1241 for stmt in &block.stmts {
1242 if let StmtKind::Item(ref item) = stmt.node {
1243 if let ItemKind::MacroDef(..) = item.node {
1244 num_macro_definition_ribs += 1;
1245 let res = self.r.definitions.local_def_id(item.id);
1246 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1247 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1251 self.visit_stmt(stmt);
1255 self.parent_scope.module = orig_module;
1256 for _ in 0 .. num_macro_definition_ribs {
1257 self.ribs[ValueNS].pop();
1258 self.label_ribs.pop();
1260 self.ribs[ValueNS].pop();
1261 if anonymous_module.is_some() {
1262 self.ribs[TypeNS].pop();
1264 debug!("(resolving block) leaving block");
1267 fn fresh_binding(&mut self,
1270 outer_pat_id: NodeId,
1271 pat_src: PatternSource,
1272 bindings: &mut FxHashMap<Ident, NodeId>)
1274 // Add the binding to the local ribs, if it
1275 // doesn't already exist in the bindings map. (We
1276 // must not add it if it's in the bindings map
1277 // because that breaks the assumptions later
1278 // passes make about or-patterns.)
1279 let ident = ident.modern_and_legacy();
1280 let mut res = Res::Local(pat_id);
1281 match bindings.get(&ident).cloned() {
1282 Some(id) if id == outer_pat_id => {
1283 // `Variant(a, a)`, error
1284 self.r.report_error(
1286 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
1290 Some(..) if pat_src == PatternSource::FnParam => {
1291 // `fn f(a: u8, a: u8)`, error
1292 self.r.report_error(
1294 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
1298 Some(..) if pat_src == PatternSource::Match ||
1299 pat_src == PatternSource::Let => {
1300 // `Variant1(a) | Variant2(a)`, ok
1301 // Reuse definition from the first `a`.
1302 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
1305 span_bug!(ident.span, "two bindings with the same name from \
1306 unexpected pattern source {:?}", pat_src);
1309 // A completely fresh binding, add to the lists if it's valid.
1310 if ident.name != kw::Invalid {
1311 bindings.insert(ident, outer_pat_id);
1312 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
1320 fn resolve_pattern(&mut self,
1322 pat_src: PatternSource,
1323 // Maps idents to the node ID for the
1324 // outermost pattern that binds them.
1325 bindings: &mut FxHashMap<Ident, NodeId>) {
1326 // Visit all direct subpatterns of this pattern.
1327 let outer_pat_id = pat.id;
1328 pat.walk(&mut |pat| {
1329 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1331 PatKind::Ident(bmode, ident, ref opt_pat) => {
1332 // First try to resolve the identifier as some existing
1333 // entity, then fall back to a fresh binding.
1334 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
1336 .and_then(LexicalScopeBinding::item);
1337 let res = binding.map(NameBinding::res).and_then(|res| {
1338 let is_syntactic_ambiguity = opt_pat.is_none() &&
1339 bmode == BindingMode::ByValue(Mutability::Immutable);
1341 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1342 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1343 // Disambiguate in favor of a unit struct/variant
1344 // or constant pattern.
1345 self.r.record_use(ident, ValueNS, binding.unwrap(), false);
1348 Res::Def(DefKind::Ctor(..), _)
1349 | Res::Def(DefKind::Const, _)
1350 | Res::Def(DefKind::Static, _) => {
1351 // This is unambiguously a fresh binding, either syntactically
1352 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1353 // to something unusable as a pattern (e.g., constructor function),
1354 // but we still conservatively report an error, see
1355 // issues/33118#issuecomment-233962221 for one reason why.
1356 self.r.report_error(
1358 ResolutionError::BindingShadowsSomethingUnacceptable(
1359 pat_src.descr(), ident.name, binding.unwrap())
1363 Res::Def(DefKind::Fn, _) | Res::Err => {
1364 // These entities are explicitly allowed
1365 // to be shadowed by fresh bindings.
1369 span_bug!(ident.span, "unexpected resolution for an \
1370 identifier in pattern: {:?}", res);
1373 }).unwrap_or_else(|| {
1374 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1377 self.r.record_partial_res(pat.id, PartialRes::new(res));
1380 PatKind::TupleStruct(ref path, ..) => {
1381 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1384 PatKind::Path(ref qself, ref path) => {
1385 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1388 PatKind::Struct(ref path, ..) => {
1389 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1397 visit::walk_pat(self, pat);
1400 // High-level and context dependent path resolution routine.
1401 // Resolves the path and records the resolution into definition map.
1402 // If resolution fails tries several techniques to find likely
1403 // resolution candidates, suggest imports or other help, and report
1404 // errors in user friendly way.
1405 fn smart_resolve_path(&mut self,
1407 qself: Option<&QSelf>,
1409 source: PathSource<'_>) {
1410 self.smart_resolve_path_fragment(
1413 &Segment::from_path(path),
1416 CrateLint::SimplePath(id),
1420 fn smart_resolve_path_fragment(&mut self,
1422 qself: Option<&QSelf>,
1425 source: PathSource<'_>,
1426 crate_lint: CrateLint)
1428 let ns = source.namespace();
1429 let is_expected = &|res| source.is_expected(res);
1431 let report_errors = |this: &mut Self, res: Option<Res>| {
1432 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1433 let def_id = this.parent_scope.module.normal_ancestor_id;
1434 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1435 let better = res.is_some();
1436 this.r.use_injections.push(UseError { err, candidates, node_id, better });
1437 PartialRes::new(Res::Err)
1440 let partial_res = match self.resolve_qpath_anywhere(
1446 source.defer_to_typeck(),
1449 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1450 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1453 // Add a temporary hack to smooth the transition to new struct ctor
1454 // visibility rules. See #38932 for more details.
1456 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1457 if let Some((ctor_res, ctor_vis))
1458 = self.r.struct_constructors.get(&def_id).cloned() {
1459 if is_expected(ctor_res) &&
1460 self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1461 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1462 self.r.session.buffer_lint(lint, id, span,
1463 "private struct constructors are not usable through \
1464 re-exports in outer modules",
1466 res = Some(PartialRes::new(ctor_res));
1471 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1474 Some(partial_res) if source.defer_to_typeck() => {
1475 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1476 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1477 // it needs to be added to the trait map.
1479 let item_name = path.last().unwrap().ident;
1480 let traits = self.get_traits_containing_item(item_name, ns);
1481 self.r.trait_map.insert(id, traits);
1484 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1485 std_path.extend(path);
1486 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1487 let cl = CrateLint::No;
1489 if let PathResult::Module(_) | PathResult::NonModule(_) =
1490 self.resolve_path(&std_path, ns, false, span, cl) {
1491 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1492 let item_span = path.iter().last().map(|segment| segment.ident.span)
1494 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1495 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1496 hm.insert(item_span, span);
1497 // In some places (E0223) we only have access to the full path
1498 hm.insert(span, span);
1503 _ => report_errors(self, None)
1506 if let PathSource::TraitItem(..) = source {} else {
1507 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1508 self.r.record_partial_res(id, partial_res);
1513 fn self_type_is_available(&mut self, span: Span) -> bool {
1514 let binding = self.resolve_ident_in_lexical_scope(
1515 Ident::with_dummy_span(kw::SelfUpper),
1520 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1523 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1524 let ident = Ident::new(kw::SelfLower, self_span);
1525 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1526 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1529 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1530 fn resolve_qpath_anywhere(
1533 qself: Option<&QSelf>,
1535 primary_ns: Namespace,
1537 defer_to_typeck: bool,
1538 crate_lint: CrateLint,
1539 ) -> Option<PartialRes> {
1540 let mut fin_res = None;
1541 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1542 if i == 0 || ns != primary_ns {
1543 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1544 // If defer_to_typeck, then resolution > no resolution,
1545 // otherwise full resolution > partial resolution > no resolution.
1546 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1548 return Some(partial_res),
1549 partial_res => if fin_res.is_none() { fin_res = partial_res },
1555 assert!(primary_ns != MacroNS);
1556 if qself.is_none() {
1557 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1558 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1559 if let Ok((_, res)) = self.r.resolve_macro_path(
1560 &path, None, &self.parent_scope, false, false
1562 return Some(PartialRes::new(res));
1569 /// Handles paths that may refer to associated items.
1573 qself: Option<&QSelf>,
1577 crate_lint: CrateLint,
1578 ) -> Option<PartialRes> {
1580 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1588 if let Some(qself) = qself {
1589 if qself.position == 0 {
1590 // This is a case like `<T>::B`, where there is no
1591 // trait to resolve. In that case, we leave the `B`
1592 // segment to be resolved by type-check.
1593 return Some(PartialRes::with_unresolved_segments(
1594 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1598 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1600 // Currently, `path` names the full item (`A::B::C`, in
1601 // our example). so we extract the prefix of that that is
1602 // the trait (the slice upto and including
1603 // `qself.position`). And then we recursively resolve that,
1604 // but with `qself` set to `None`.
1606 // However, setting `qself` to none (but not changing the
1607 // span) loses the information about where this path
1608 // *actually* appears, so for the purposes of the crate
1609 // lint we pass along information that this is the trait
1610 // name from a fully qualified path, and this also
1611 // contains the full span (the `CrateLint::QPathTrait`).
1612 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1613 let partial_res = self.smart_resolve_path_fragment(
1616 &path[..=qself.position],
1618 PathSource::TraitItem(ns),
1619 CrateLint::QPathTrait {
1621 qpath_span: qself.path_span,
1625 // The remaining segments (the `C` in our example) will
1626 // have to be resolved by type-check, since that requires doing
1627 // trait resolution.
1628 return Some(PartialRes::with_unresolved_segments(
1629 partial_res.base_res(),
1630 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1634 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1635 PathResult::NonModule(path_res) => path_res,
1636 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1637 PartialRes::new(module.res().unwrap())
1639 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1640 // don't report an error right away, but try to fallback to a primitive type.
1641 // So, we are still able to successfully resolve something like
1643 // use std::u8; // bring module u8 in scope
1644 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1645 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1646 // // not to non-existent std::u8::max_value
1649 // Such behavior is required for backward compatibility.
1650 // The same fallback is used when `a` resolves to nothing.
1651 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1652 PathResult::Failed { .. }
1653 if (ns == TypeNS || path.len() > 1) &&
1654 self.r.primitive_type_table.primitive_types
1655 .contains_key(&path[0].ident.name) => {
1656 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1657 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1659 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1660 PartialRes::new(module.res().unwrap()),
1661 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1662 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1663 PartialRes::new(Res::Err)
1665 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1666 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1669 if path.len() > 1 && result.base_res() != Res::Err &&
1670 path[0].ident.name != kw::PathRoot &&
1671 path[0].ident.name != kw::DollarCrate {
1672 let unqualified_result = {
1673 match self.resolve_path(
1674 &[*path.last().unwrap()],
1680 PathResult::NonModule(path_res) => path_res.base_res(),
1681 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1682 module.res().unwrap(),
1683 _ => return Some(result),
1686 if result.base_res() == unqualified_result {
1687 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1688 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1695 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
1696 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1698 if let Some(label) = label {
1699 self.unused_labels.insert(id, label.ident.span);
1700 self.with_label_rib(|this| {
1701 let ident = label.ident.modern_and_legacy();
1702 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1710 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1711 self.with_resolved_label(label, id, |this| this.visit_block(block));
1714 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1715 // First, record candidate traits for this expression if it could
1716 // result in the invocation of a method call.
1718 self.record_candidate_traits_for_expr_if_necessary(expr);
1720 // Next, resolve the node.
1722 ExprKind::Path(ref qself, ref path) => {
1723 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1724 visit::walk_expr(self, expr);
1727 ExprKind::Struct(ref path, ..) => {
1728 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1729 visit::walk_expr(self, expr);
1732 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1733 let node_id = self.search_label(label.ident, |rib, ident| {
1734 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1738 // Search again for close matches...
1739 // Picks the first label that is "close enough", which is not necessarily
1740 // the closest match
1741 let close_match = self.search_label(label.ident, |rib, ident| {
1742 let names = rib.bindings.iter().filter_map(|(id, _)| {
1743 if id.span.ctxt() == label.ident.span.ctxt() {
1749 find_best_match_for_name(names, &*ident.as_str(), None)
1751 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1752 self.r.report_error(
1754 ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1758 // Since this res is a label, it is never read.
1759 self.r.label_res_map.insert(expr.id, node_id);
1760 self.unused_labels.remove(&node_id);
1764 // visit `break` argument if any
1765 visit::walk_expr(self, expr);
1768 ExprKind::Let(ref pats, ref scrutinee) => {
1769 self.visit_expr(scrutinee);
1770 self.resolve_pats(pats, PatternSource::Let);
1773 ExprKind::If(ref cond, ref then, ref opt_else) => {
1774 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1775 self.visit_expr(cond);
1776 self.visit_block(then);
1777 self.ribs[ValueNS].pop();
1779 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1782 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1784 ExprKind::While(ref subexpression, ref block, label) => {
1785 self.with_resolved_label(label, expr.id, |this| {
1786 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
1787 this.visit_expr(subexpression);
1788 this.visit_block(block);
1789 this.ribs[ValueNS].pop();
1793 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
1794 self.visit_expr(subexpression);
1795 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1796 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
1798 self.resolve_labeled_block(label, expr.id, block);
1800 self.ribs[ValueNS].pop();
1803 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1805 // Equivalent to `visit::walk_expr` + passing some context to children.
1806 ExprKind::Field(ref subexpression, _) => {
1807 self.resolve_expr(subexpression, Some(expr));
1809 ExprKind::MethodCall(ref segment, ref arguments) => {
1810 let mut arguments = arguments.iter();
1811 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1812 for argument in arguments {
1813 self.resolve_expr(argument, None);
1815 self.visit_path_segment(expr.span, segment);
1818 ExprKind::Call(ref callee, ref arguments) => {
1819 self.resolve_expr(callee, Some(expr));
1820 for argument in arguments {
1821 self.resolve_expr(argument, None);
1824 ExprKind::Type(ref type_expr, _) => {
1825 self.current_type_ascription.push(type_expr.span);
1826 visit::walk_expr(self, expr);
1827 self.current_type_ascription.pop();
1829 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1830 // resolve the arguments within the proper scopes so that usages of them inside the
1831 // closure are detected as upvars rather than normal closure arg usages.
1833 _, IsAsync::Async { .. }, _,
1834 ref fn_decl, ref body, _span,
1836 let rib_kind = NormalRibKind;
1837 self.ribs[ValueNS].push(Rib::new(rib_kind));
1838 // Resolve arguments:
1839 let mut bindings_list = FxHashMap::default();
1840 for argument in &fn_decl.inputs {
1841 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1842 self.visit_ty(&argument.ty);
1844 // No need to resolve return type-- the outer closure return type is
1845 // FunctionRetTy::Default
1847 // Now resolve the inner closure
1849 // No need to resolve arguments: the inner closure has none.
1850 // Resolve the return type:
1851 visit::walk_fn_ret_ty(self, &fn_decl.output);
1853 self.visit_expr(body);
1855 self.ribs[ValueNS].pop();
1858 visit::walk_expr(self, expr);
1863 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1865 ExprKind::Field(_, ident) => {
1866 // FIXME(#6890): Even though you can't treat a method like a
1867 // field, we need to add any trait methods we find that match
1868 // the field name so that we can do some nice error reporting
1869 // later on in typeck.
1870 let traits = self.get_traits_containing_item(ident, ValueNS);
1871 self.r.trait_map.insert(expr.id, traits);
1873 ExprKind::MethodCall(ref segment, ..) => {
1874 debug!("(recording candidate traits for expr) recording traits for {}",
1876 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1877 self.r.trait_map.insert(expr.id, traits);
1885 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1886 -> Vec<TraitCandidate> {
1887 debug!("(getting traits containing item) looking for '{}'", ident.name);
1889 let mut found_traits = Vec::new();
1890 // Look for the current trait.
1891 if let Some((module, _)) = self.current_trait_ref {
1892 if self.r.resolve_ident_in_module(
1893 ModuleOrUniformRoot::Module(module),
1900 let def_id = module.def_id().unwrap();
1901 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1905 ident.span = ident.span.modern();
1906 let mut search_module = self.parent_scope.module;
1908 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1909 search_module = unwrap_or!(
1910 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1914 if let Some(prelude) = self.r.prelude {
1915 if !search_module.no_implicit_prelude {
1916 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1923 fn get_traits_in_module_containing_item(&mut self,
1927 found_traits: &mut Vec<TraitCandidate>) {
1928 assert!(ns == TypeNS || ns == ValueNS);
1929 let mut traits = module.traits.borrow_mut();
1930 if traits.is_none() {
1931 let mut collected_traits = Vec::new();
1932 module.for_each_child(self.r, |_, name, ns, binding| {
1933 if ns != TypeNS { return }
1934 match binding.res() {
1935 Res::Def(DefKind::Trait, _) |
1936 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1940 *traits = Some(collected_traits.into_boxed_slice());
1943 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1944 // Traits have pseudo-modules that can be used to search for the given ident.
1945 if let Some(module) = binding.module() {
1946 let mut ident = ident;
1947 if ident.span.glob_adjust(
1953 if self.r.resolve_ident_in_module_unadjusted(
1954 ModuleOrUniformRoot::Module(module),
1961 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1962 let trait_def_id = module.def_id().unwrap();
1963 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1965 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1966 // For now, just treat all trait aliases as possible candidates, since we don't
1967 // know if the ident is somewhere in the transitive bounds.
1968 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1969 let trait_def_id = binding.res().def_id();
1970 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1972 bug!("candidate is not trait or trait alias?")
1977 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
1978 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
1979 let mut import_ids = smallvec![];
1980 while let NameBindingKind::Import { directive, binding, .. } = kind {
1981 self.r.maybe_unused_trait_imports.insert(directive.id);
1982 self.r.add_to_glob_map(&directive, trait_name);
1983 import_ids.push(directive.id);
1984 kind = &binding.kind;
1990 impl<'a> Resolver<'a> {
1991 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
1992 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
1993 visit::walk_crate(&mut late_resolution_visitor, krate);
1994 for (id, span) in late_resolution_visitor.unused_labels.iter() {
1995 self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");