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,
410 function_kind: FnKind<'tcx>,
411 declaration: &'tcx FnDecl,
415 debug!("(resolving function) entering function");
416 let rib_kind = match function_kind {
417 FnKind::ItemFn(..) => FnItemRibKind,
418 FnKind::Method(..) | FnKind::Closure(_) => NormalRibKind,
421 // Create a value rib for the function.
422 self.ribs[ValueNS].push(Rib::new(rib_kind));
424 // Create a label rib for the function.
425 self.label_ribs.push(Rib::new(rib_kind));
427 // Add each argument to the rib.
428 let mut bindings_list = FxHashMap::default();
429 for argument in &declaration.inputs {
430 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
432 self.visit_ty(&argument.ty);
434 debug!("(resolving function) recorded argument");
436 visit::walk_fn_ret_ty(self, &declaration.output);
438 // Resolve the function body, potentially inside the body of an async closure
439 match function_kind {
440 FnKind::ItemFn(.., body) |
441 FnKind::Method(.., body) => {
442 self.visit_block(body);
444 FnKind::Closure(body) => {
445 self.visit_expr(body);
449 debug!("(resolving function) leaving function");
451 self.label_ribs.pop();
452 self.ribs[ValueNS].pop();
455 fn visit_generics(&mut self, generics: &'tcx Generics) {
456 // For type parameter defaults, we have to ban access
457 // to following type parameters, as the InternalSubsts can only
458 // provide previous type parameters as they're built. We
459 // put all the parameters on the ban list and then remove
460 // them one by one as they are processed and become available.
461 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
462 let mut found_default = false;
463 default_ban_rib.bindings.extend(generics.params.iter()
464 .filter_map(|param| match param.kind {
465 GenericParamKind::Const { .. } |
466 GenericParamKind::Lifetime { .. } => None,
467 GenericParamKind::Type { ref default, .. } => {
468 found_default |= default.is_some();
470 Some((Ident::with_dummy_span(param.ident.name), Res::Err))
477 // We also ban access to type parameters for use as the types of const parameters.
478 let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
479 const_ty_param_ban_rib.bindings.extend(generics.params.iter()
481 if let GenericParamKind::Type { .. } = param.kind {
487 .map(|param| (Ident::with_dummy_span(param.ident.name), Res::Err)));
489 for param in &generics.params {
491 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
492 GenericParamKind::Type { ref default, .. } => {
493 for bound in ¶m.bounds {
494 self.visit_param_bound(bound);
497 if let Some(ref ty) = default {
498 self.ribs[TypeNS].push(default_ban_rib);
500 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
503 // Allow all following defaults to refer to this type parameter.
504 default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
506 GenericParamKind::Const { ref ty } => {
507 self.ribs[TypeNS].push(const_ty_param_ban_rib);
509 for bound in ¶m.bounds {
510 self.visit_param_bound(bound);
515 const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
519 for p in &generics.where_clause.predicates {
520 self.visit_where_predicate(p);
525 impl<'a, 'b> LateResolutionVisitor<'a, '_> {
526 fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
527 // During late resolution we only track the module component of the parent scope,
528 // although it may be useful to track other components as well for diagnostics.
529 let graph_root = resolver.graph_root;
530 let parent_scope = ParentScope::module(graph_root);
531 LateResolutionVisitor {
535 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
536 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
537 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
539 label_ribs: Vec::new(),
540 current_trait_ref: None,
541 current_trait_assoc_types: Vec::new(),
542 current_self_type: None,
543 current_self_item: None,
544 unused_labels: Default::default(),
545 current_type_ascription: Vec::new(),
549 fn resolve_ident_in_lexical_scope(&mut self,
552 record_used_id: Option<NodeId>,
554 -> Option<LexicalScopeBinding<'a>> {
555 self.r.resolve_ident_in_lexical_scope(
556 ident, ns, &self.parent_scope, record_used_id, path_span, &self.ribs[ns]
563 opt_ns: Option<Namespace>, // `None` indicates a module path in import
566 crate_lint: CrateLint,
567 ) -> PathResult<'a> {
568 self.r.resolve_path_with_ribs(
569 path, opt_ns, &self.parent_scope, record_used, path_span, crate_lint, Some(&self.ribs)
575 // We maintain a list of value ribs and type ribs.
577 // Simultaneously, we keep track of the current position in the module
578 // graph in the `parent_scope.module` pointer. When we go to resolve a name in
579 // the value or type namespaces, we first look through all the ribs and
580 // then query the module graph. When we resolve a name in the module
581 // namespace, we can skip all the ribs (since nested modules are not
582 // allowed within blocks in Rust) and jump straight to the current module
585 // Named implementations are handled separately. When we find a method
586 // call, we consult the module node to find all of the implementations in
587 // scope. This information is lazily cached in the module node. We then
588 // generate a fake "implementation scope" containing all the
589 // implementations thus found, for compatibility with old resolve pass.
591 fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
592 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
594 let id = self.r.definitions.local_def_id(id);
595 let module = self.r.module_map.get(&id).cloned(); // clones a reference
596 if let Some(module) = module {
597 // Move down in the graph.
598 let orig_module = replace(&mut self.parent_scope.module, module);
599 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
600 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
604 self.parent_scope.module = orig_module;
605 self.ribs[ValueNS].pop();
606 self.ribs[TypeNS].pop();
613 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
614 /// is returned by the given predicate function
616 /// Stops after meeting a closure.
617 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
618 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
620 for rib in self.label_ribs.iter().rev() {
623 // If an invocation of this macro created `ident`, give up on `ident`
624 // and switch to `ident`'s source from the macro definition.
625 MacroDefinition(def) => {
626 if def == self.r.macro_def(ident.span.ctxt()) {
627 ident.span.remove_mark();
631 // Do not resolve labels across function boundary
635 let r = pred(rib, ident);
643 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
644 debug!("resolve_adt");
645 self.with_current_self_item(item, |this| {
646 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
647 let item_def_id = this.r.definitions.local_def_id(item.id);
648 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
649 visit::walk_item(this, item);
655 fn future_proof_import(&mut self, use_tree: &UseTree) {
656 let segments = &use_tree.prefix.segments;
657 if !segments.is_empty() {
658 let ident = segments[0].ident;
659 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
663 let nss = match use_tree.kind {
664 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
667 let report_error = |this: &Self, ns| {
668 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
669 this.r.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
673 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
674 Some(LexicalScopeBinding::Res(..)) => {
675 report_error(self, ns);
677 Some(LexicalScopeBinding::Item(binding)) => {
678 let orig_blacklisted_binding =
679 replace(&mut self.r.blacklisted_binding, Some(binding));
680 if let Some(LexicalScopeBinding::Res(..)) =
681 self.resolve_ident_in_lexical_scope(ident, ns, None,
682 use_tree.prefix.span) {
683 report_error(self, ns);
685 self.r.blacklisted_binding = orig_blacklisted_binding;
690 } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
691 for (use_tree, _) in use_trees {
692 self.future_proof_import(use_tree);
697 fn resolve_item(&mut self, item: &Item) {
698 let name = item.ident.name;
699 debug!("(resolving item) resolving {} ({:?})", name, item.node);
702 ItemKind::TyAlias(_, ref generics) |
703 ItemKind::OpaqueTy(_, ref generics) |
704 ItemKind::Fn(_, _, ref generics, _) => {
705 self.with_generic_param_rib(
706 HasGenericParams(generics, ItemRibKind),
707 |this| visit::walk_item(this, item)
711 ItemKind::Enum(_, ref generics) |
712 ItemKind::Struct(_, ref generics) |
713 ItemKind::Union(_, ref generics) => {
714 self.resolve_adt(item, generics);
717 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
718 self.resolve_implementation(generics,
724 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
725 // Create a new rib for the trait-wide type parameters.
726 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
727 let local_def_id = this.r.definitions.local_def_id(item.id);
728 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
729 this.visit_generics(generics);
730 walk_list!(this, visit_param_bound, bounds);
732 for trait_item in trait_items {
733 this.with_trait_items(trait_items, |this| {
734 let generic_params = HasGenericParams(
735 &trait_item.generics,
738 this.with_generic_param_rib(generic_params, |this| {
739 match trait_item.node {
740 TraitItemKind::Const(ref ty, ref default) => {
743 // Only impose the restrictions of
744 // ConstRibKind for an actual constant
745 // expression in a provided default.
746 if let Some(ref expr) = *default{
747 this.with_constant_rib(|this| {
748 this.visit_expr(expr);
752 TraitItemKind::Method(_, _) => {
753 visit::walk_trait_item(this, trait_item)
755 TraitItemKind::Type(..) => {
756 visit::walk_trait_item(this, trait_item)
758 TraitItemKind::Macro(_) => {
759 panic!("unexpanded macro in resolve!")
769 ItemKind::TraitAlias(ref generics, ref bounds) => {
770 // Create a new rib for the trait-wide type parameters.
771 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
772 let local_def_id = this.r.definitions.local_def_id(item.id);
773 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
774 this.visit_generics(generics);
775 walk_list!(this, visit_param_bound, bounds);
780 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
781 self.with_scope(item.id, |this| {
782 visit::walk_item(this, item);
786 ItemKind::Static(ref ty, _, ref expr) |
787 ItemKind::Const(ref ty, ref expr) => {
788 debug!("resolve_item ItemKind::Const");
789 self.with_item_rib(|this| {
791 this.with_constant_rib(|this| {
792 this.visit_expr(expr);
797 ItemKind::Use(ref use_tree) => {
798 self.future_proof_import(use_tree);
801 ItemKind::ExternCrate(..) |
802 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
803 // do nothing, these are just around to be encoded
806 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
810 fn with_generic_param_rib<'c, F>(&'c mut self, generic_params: GenericParameters<'a, 'c>, f: F)
811 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
813 debug!("with_generic_param_rib");
814 match generic_params {
815 HasGenericParams(generics, rib_kind) => {
816 let mut function_type_rib = Rib::new(rib_kind);
817 let mut function_value_rib = Rib::new(rib_kind);
818 let mut seen_bindings = FxHashMap::default();
819 // We also can't shadow bindings from the parent item
820 if let AssocItemRibKind = rib_kind {
821 let mut add_bindings_for_ns = |ns| {
822 let parent_rib = self.ribs[ns].iter()
823 .rfind(|rib| if let ItemRibKind = rib.kind { true } else { false })
824 .expect("associated item outside of an item");
825 seen_bindings.extend(
826 parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)),
829 add_bindings_for_ns(ValueNS);
830 add_bindings_for_ns(TypeNS);
832 for param in &generics.params {
834 GenericParamKind::Lifetime { .. } => {}
835 GenericParamKind::Type { .. } => {
836 let ident = param.ident.modern();
837 debug!("with_generic_param_rib: {}", param.id);
839 if seen_bindings.contains_key(&ident) {
840 let span = seen_bindings.get(&ident).unwrap();
841 let err = ResolutionError::NameAlreadyUsedInParameterList(
845 self.r.report_error(param.ident.span, err);
847 seen_bindings.entry(ident).or_insert(param.ident.span);
849 // Plain insert (no renaming).
852 self.r.definitions.local_def_id(param.id),
854 function_type_rib.bindings.insert(ident, res);
855 self.r.record_partial_res(param.id, PartialRes::new(res));
857 GenericParamKind::Const { .. } => {
858 let ident = param.ident.modern();
859 debug!("with_generic_param_rib: {}", param.id);
861 if seen_bindings.contains_key(&ident) {
862 let span = seen_bindings.get(&ident).unwrap();
863 let err = ResolutionError::NameAlreadyUsedInParameterList(
867 self.r.report_error(param.ident.span, err);
869 seen_bindings.entry(ident).or_insert(param.ident.span);
873 self.r.definitions.local_def_id(param.id),
875 function_value_rib.bindings.insert(ident, res);
876 self.r.record_partial_res(param.id, PartialRes::new(res));
880 self.ribs[ValueNS].push(function_value_rib);
881 self.ribs[TypeNS].push(function_type_rib);
891 if let HasGenericParams(..) = generic_params {
892 self.ribs[TypeNS].pop();
893 self.ribs[ValueNS].pop();
897 fn with_label_rib<F>(&mut self, f: F)
898 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
900 self.label_ribs.push(Rib::new(NormalRibKind));
902 self.label_ribs.pop();
905 fn with_item_rib<F>(&mut self, f: F)
906 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
908 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
909 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
911 self.ribs[TypeNS].pop();
912 self.ribs[ValueNS].pop();
915 fn with_constant_rib<F>(&mut self, f: F)
916 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
918 debug!("with_constant_rib");
919 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
920 self.label_ribs.push(Rib::new(ConstantItemRibKind));
922 self.label_ribs.pop();
923 self.ribs[ValueNS].pop();
926 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
927 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
929 // Handle nested impls (inside fn bodies)
930 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
931 let result = f(self);
932 self.current_self_type = previous_value;
936 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
937 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
939 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
940 let result = f(self);
941 self.current_self_item = previous_value;
945 /// When evaluating a `trait` use its associated types' idents for suggestionsa in E0412.
946 fn with_trait_items<T, F>(&mut self, trait_items: &Vec<TraitItem>, f: F) -> T
947 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>) -> T
949 let trait_assoc_types = replace(
950 &mut self.current_trait_assoc_types,
951 trait_items.iter().filter_map(|item| match &item.node {
952 TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
956 let result = f(self);
957 self.current_trait_assoc_types = trait_assoc_types;
961 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
962 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
963 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>, Option<DefId>) -> T
965 let mut new_val = None;
966 let mut new_id = None;
967 if let Some(trait_ref) = opt_trait_ref {
968 let path: Vec<_> = Segment::from_path(&trait_ref.path);
969 let res = self.smart_resolve_path_fragment(
974 PathSource::Trait(AliasPossibility::No),
975 CrateLint::SimplePath(trait_ref.ref_id),
978 new_id = Some(res.def_id());
979 let span = trait_ref.path.span;
980 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
986 CrateLint::SimplePath(trait_ref.ref_id),
989 new_val = Some((module, trait_ref.clone()));
993 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
994 let result = f(self, new_id);
995 self.current_trait_ref = original_trait_ref;
999 fn with_self_rib<F>(&mut self, self_res: Res, f: F)
1000 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1002 let mut self_type_rib = Rib::new(NormalRibKind);
1004 // Plain insert (no renaming, since types are not currently hygienic)
1005 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1006 self.ribs[TypeNS].push(self_type_rib);
1008 self.ribs[TypeNS].pop();
1011 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
1012 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1014 let self_res = Res::SelfCtor(impl_id);
1015 let mut self_type_rib = Rib::new(NormalRibKind);
1016 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
1017 self.ribs[ValueNS].push(self_type_rib);
1019 self.ribs[ValueNS].pop();
1022 fn resolve_implementation(&mut self,
1023 generics: &Generics,
1024 opt_trait_reference: &Option<TraitRef>,
1027 impl_items: &[ImplItem]) {
1028 debug!("resolve_implementation");
1029 // If applicable, create a rib for the type parameters.
1030 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
1031 // Dummy self type for better errors if `Self` is used in the trait path.
1032 this.with_self_rib(Res::SelfTy(None, None), |this| {
1033 // Resolve the trait reference, if necessary.
1034 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
1035 let item_def_id = this.r.definitions.local_def_id(item_id);
1036 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
1037 if let Some(trait_ref) = opt_trait_reference.as_ref() {
1038 // Resolve type arguments in the trait path.
1039 visit::walk_trait_ref(this, trait_ref);
1041 // Resolve the self type.
1042 this.visit_ty(self_type);
1043 // Resolve the generic parameters.
1044 this.visit_generics(generics);
1045 // Resolve the items within the impl.
1046 this.with_current_self_type(self_type, |this| {
1047 this.with_self_struct_ctor_rib(item_def_id, |this| {
1048 debug!("resolve_implementation with_self_struct_ctor_rib");
1049 for impl_item in impl_items {
1050 // We also need a new scope for the impl item type parameters.
1051 let generic_params = HasGenericParams(&impl_item.generics,
1053 this.with_generic_param_rib(generic_params, |this| {
1054 use crate::ResolutionError::*;
1055 match impl_item.node {
1056 ImplItemKind::Const(..) => {
1058 "resolve_implementation ImplItemKind::Const",
1060 // If this is a trait impl, ensure the const
1062 this.check_trait_item(
1066 |n, s| ConstNotMemberOfTrait(n, s),
1069 this.with_constant_rib(|this| {
1070 visit::walk_impl_item(this, impl_item)
1073 ImplItemKind::Method(..) => {
1074 // If this is a trait impl, ensure the method
1076 this.check_trait_item(impl_item.ident,
1079 |n, s| MethodNotMemberOfTrait(n, s));
1081 visit::walk_impl_item(this, impl_item);
1083 ImplItemKind::TyAlias(ref ty) => {
1084 // If this is a trait impl, ensure the type
1086 this.check_trait_item(impl_item.ident,
1089 |n, s| TypeNotMemberOfTrait(n, s));
1093 ImplItemKind::OpaqueTy(ref bounds) => {
1094 // If this is a trait impl, ensure the type
1096 this.check_trait_item(impl_item.ident,
1099 |n, s| TypeNotMemberOfTrait(n, s));
1101 for bound in bounds {
1102 this.visit_param_bound(bound);
1105 ImplItemKind::Macro(_) =>
1106 panic!("unexpanded macro in resolve!"),
1118 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
1119 where F: FnOnce(Name, &str) -> ResolutionError<'_>
1121 // If there is a TraitRef in scope for an impl, then the method must be in the
1123 if let Some((module, _)) = self.current_trait_ref {
1124 if self.r.resolve_ident_in_module(
1125 ModuleOrUniformRoot::Module(module),
1132 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
1133 self.r.report_error(span, err(ident.name, &path_names_to_string(path)));
1138 fn resolve_local(&mut self, local: &Local) {
1139 // Resolve the type.
1140 walk_list!(self, visit_ty, &local.ty);
1142 // Resolve the initializer.
1143 walk_list!(self, visit_expr, &local.init);
1145 // Resolve the pattern.
1146 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
1149 // build a map from pattern identifiers to binding-info's.
1150 // this is done hygienically. This could arise for a macro
1151 // that expands into an or-pattern where one 'x' was from the
1152 // user and one 'x' came from the macro.
1153 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
1154 let mut binding_map = FxHashMap::default();
1156 pat.walk(&mut |pat| {
1157 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
1158 if sub_pat.is_some() || match self.r.partial_res_map.get(&pat.id)
1159 .map(|res| res.base_res()) {
1160 Some(Res::Local(..)) => true,
1163 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
1164 binding_map.insert(ident, binding_info);
1173 // Checks that all of the arms in an or-pattern have exactly the
1174 // same set of bindings, with the same binding modes for each.
1175 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
1176 let mut missing_vars = FxHashMap::default();
1177 let mut inconsistent_vars = FxHashMap::default();
1179 for pat_outer in pats.iter() {
1180 let map_outer = self.binding_mode_map(&pat_outer);
1182 for pat_inner in pats.iter().filter(|pat| pat.id != pat_outer.id) {
1183 let map_inner = self.binding_mode_map(&pat_inner);
1185 for (&key_inner, &binding_inner) in map_inner.iter() {
1186 match map_outer.get(&key_inner) {
1187 None => { // missing binding
1188 let binding_error = missing_vars
1189 .entry(key_inner.name)
1190 .or_insert(BindingError {
1191 name: key_inner.name,
1192 origin: BTreeSet::new(),
1193 target: BTreeSet::new(),
1195 key_inner.name.as_str().starts_with(char::is_uppercase)
1197 binding_error.origin.insert(binding_inner.span);
1198 binding_error.target.insert(pat_outer.span);
1200 Some(binding_outer) => { // check consistent binding
1201 if binding_outer.binding_mode != binding_inner.binding_mode {
1203 .entry(key_inner.name)
1204 .or_insert((binding_inner.span, binding_outer.span));
1212 let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>();
1213 missing_vars.sort();
1214 for (name, mut v) in missing_vars {
1215 if inconsistent_vars.contains_key(name) {
1216 v.could_be_path = false;
1218 self.r.report_error(
1219 *v.origin.iter().next().unwrap(),
1220 ResolutionError::VariableNotBoundInPattern(v));
1223 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
1224 inconsistent_vars.sort();
1225 for (name, v) in inconsistent_vars {
1226 self.r.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
1230 fn resolve_arm(&mut self, arm: &Arm) {
1231 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1233 self.resolve_pats(&arm.pats, PatternSource::Match);
1235 if let Some(ref expr) = arm.guard {
1236 self.visit_expr(expr)
1238 self.visit_expr(&arm.body);
1240 self.ribs[ValueNS].pop();
1243 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
1244 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
1245 let mut bindings_list = FxHashMap::default();
1247 self.resolve_pattern(pat, source, &mut bindings_list);
1249 // This has to happen *after* we determine which pat_idents are variants
1251 self.check_consistent_bindings(pats);
1255 fn resolve_block(&mut self, block: &Block) {
1256 debug!("(resolving block) entering block");
1257 // Move down in the graph, if there's an anonymous module rooted here.
1258 let orig_module = self.parent_scope.module;
1259 let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
1261 let mut num_macro_definition_ribs = 0;
1262 if let Some(anonymous_module) = anonymous_module {
1263 debug!("(resolving block) found anonymous module, moving down");
1264 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1265 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
1266 self.parent_scope.module = anonymous_module;
1268 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1271 // Descend into the block.
1272 for stmt in &block.stmts {
1273 if let StmtKind::Item(ref item) = stmt.node {
1274 if let ItemKind::MacroDef(..) = item.node {
1275 num_macro_definition_ribs += 1;
1276 let res = self.r.definitions.local_def_id(item.id);
1277 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
1278 self.label_ribs.push(Rib::new(MacroDefinition(res)));
1282 self.visit_stmt(stmt);
1286 self.parent_scope.module = orig_module;
1287 for _ in 0 .. num_macro_definition_ribs {
1288 self.ribs[ValueNS].pop();
1289 self.label_ribs.pop();
1291 self.ribs[ValueNS].pop();
1292 if anonymous_module.is_some() {
1293 self.ribs[TypeNS].pop();
1295 debug!("(resolving block) leaving block");
1298 fn fresh_binding(&mut self,
1301 outer_pat_id: NodeId,
1302 pat_src: PatternSource,
1303 bindings: &mut FxHashMap<Ident, NodeId>)
1305 // Add the binding to the local ribs, if it
1306 // doesn't already exist in the bindings map. (We
1307 // must not add it if it's in the bindings map
1308 // because that breaks the assumptions later
1309 // passes make about or-patterns.)
1310 let ident = ident.modern_and_legacy();
1311 let mut res = Res::Local(pat_id);
1312 match bindings.get(&ident).cloned() {
1313 Some(id) if id == outer_pat_id => {
1314 // `Variant(a, a)`, error
1315 self.r.report_error(
1317 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
1321 Some(..) if pat_src == PatternSource::FnParam => {
1322 // `fn f(a: u8, a: u8)`, error
1323 self.r.report_error(
1325 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
1329 Some(..) if pat_src == PatternSource::Match ||
1330 pat_src == PatternSource::Let => {
1331 // `Variant1(a) | Variant2(a)`, ok
1332 // Reuse definition from the first `a`.
1333 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
1336 span_bug!(ident.span, "two bindings with the same name from \
1337 unexpected pattern source {:?}", pat_src);
1340 // A completely fresh binding, add to the lists if it's valid.
1341 if ident.name != kw::Invalid {
1342 bindings.insert(ident, outer_pat_id);
1343 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
1351 fn resolve_pattern(&mut self,
1353 pat_src: PatternSource,
1354 // Maps idents to the node ID for the
1355 // outermost pattern that binds them.
1356 bindings: &mut FxHashMap<Ident, NodeId>) {
1357 // Visit all direct subpatterns of this pattern.
1358 let outer_pat_id = pat.id;
1359 pat.walk(&mut |pat| {
1360 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1362 PatKind::Ident(bmode, ident, ref opt_pat) => {
1363 // First try to resolve the identifier as some existing
1364 // entity, then fall back to a fresh binding.
1365 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
1367 .and_then(LexicalScopeBinding::item);
1368 let res = binding.map(NameBinding::res).and_then(|res| {
1369 let is_syntactic_ambiguity = opt_pat.is_none() &&
1370 bmode == BindingMode::ByValue(Mutability::Immutable);
1372 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1373 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1374 // Disambiguate in favor of a unit struct/variant
1375 // or constant pattern.
1376 self.r.record_use(ident, ValueNS, binding.unwrap(), false);
1379 Res::Def(DefKind::Ctor(..), _)
1380 | Res::Def(DefKind::Const, _)
1381 | Res::Def(DefKind::Static, _) => {
1382 // This is unambiguously a fresh binding, either syntactically
1383 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1384 // to something unusable as a pattern (e.g., constructor function),
1385 // but we still conservatively report an error, see
1386 // issues/33118#issuecomment-233962221 for one reason why.
1387 self.r.report_error(
1389 ResolutionError::BindingShadowsSomethingUnacceptable(
1390 pat_src.descr(), ident.name, binding.unwrap())
1394 Res::Def(DefKind::Fn, _) | Res::Err => {
1395 // These entities are explicitly allowed
1396 // to be shadowed by fresh bindings.
1400 span_bug!(ident.span, "unexpected resolution for an \
1401 identifier in pattern: {:?}", res);
1404 }).unwrap_or_else(|| {
1405 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1408 self.r.record_partial_res(pat.id, PartialRes::new(res));
1411 PatKind::TupleStruct(ref path, ..) => {
1412 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1415 PatKind::Path(ref qself, ref path) => {
1416 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1419 PatKind::Struct(ref path, ..) => {
1420 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1428 visit::walk_pat(self, pat);
1431 // High-level and context dependent path resolution routine.
1432 // Resolves the path and records the resolution into definition map.
1433 // If resolution fails tries several techniques to find likely
1434 // resolution candidates, suggest imports or other help, and report
1435 // errors in user friendly way.
1436 fn smart_resolve_path(&mut self,
1438 qself: Option<&QSelf>,
1440 source: PathSource<'_>) {
1441 self.smart_resolve_path_fragment(
1444 &Segment::from_path(path),
1447 CrateLint::SimplePath(id),
1451 fn smart_resolve_path_fragment(&mut self,
1453 qself: Option<&QSelf>,
1456 source: PathSource<'_>,
1457 crate_lint: CrateLint)
1459 let ns = source.namespace();
1460 let is_expected = &|res| source.is_expected(res);
1462 let report_errors = |this: &mut Self, res: Option<Res>| {
1463 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1464 let def_id = this.parent_scope.module.normal_ancestor_id;
1465 let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1466 let better = res.is_some();
1467 this.r.use_injections.push(UseError { err, candidates, node_id, better });
1468 PartialRes::new(Res::Err)
1471 let partial_res = match self.resolve_qpath_anywhere(
1477 source.defer_to_typeck(),
1480 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1481 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1484 // Add a temporary hack to smooth the transition to new struct ctor
1485 // visibility rules. See #38932 for more details.
1487 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1488 if let Some((ctor_res, ctor_vis))
1489 = self.r.struct_constructors.get(&def_id).cloned() {
1490 if is_expected(ctor_res) &&
1491 self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1492 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1493 self.r.session.buffer_lint(lint, id, span,
1494 "private struct constructors are not usable through \
1495 re-exports in outer modules",
1497 res = Some(PartialRes::new(ctor_res));
1502 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1505 Some(partial_res) if source.defer_to_typeck() => {
1506 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1507 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1508 // it needs to be added to the trait map.
1510 let item_name = path.last().unwrap().ident;
1511 let traits = self.get_traits_containing_item(item_name, ns);
1512 self.r.trait_map.insert(id, traits);
1515 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1516 std_path.extend(path);
1517 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1518 let cl = CrateLint::No;
1520 if let PathResult::Module(_) | PathResult::NonModule(_) =
1521 self.resolve_path(&std_path, ns, false, span, cl) {
1522 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1523 let item_span = path.iter().last().map(|segment| segment.ident.span)
1525 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1526 let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1527 hm.insert(item_span, span);
1528 // In some places (E0223) we only have access to the full path
1529 hm.insert(span, span);
1534 _ => report_errors(self, None)
1537 if let PathSource::TraitItem(..) = source {} else {
1538 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1539 self.r.record_partial_res(id, partial_res);
1544 fn self_type_is_available(&mut self, span: Span) -> bool {
1545 let binding = self.resolve_ident_in_lexical_scope(
1546 Ident::with_dummy_span(kw::SelfUpper),
1551 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1554 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1555 let ident = Ident::new(kw::SelfLower, self_span);
1556 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1557 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1560 // Resolve in alternative namespaces if resolution in the primary namespace fails.
1561 fn resolve_qpath_anywhere(
1564 qself: Option<&QSelf>,
1566 primary_ns: Namespace,
1568 defer_to_typeck: bool,
1569 crate_lint: CrateLint,
1570 ) -> Option<PartialRes> {
1571 let mut fin_res = None;
1572 for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1573 if i == 0 || ns != primary_ns {
1574 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1575 // If defer_to_typeck, then resolution > no resolution,
1576 // otherwise full resolution > partial resolution > no resolution.
1577 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1579 return Some(partial_res),
1580 partial_res => if fin_res.is_none() { fin_res = partial_res },
1586 assert!(primary_ns != MacroNS);
1587 if qself.is_none() {
1588 let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1589 let path = Path { segments: path.iter().map(path_seg).collect(), span };
1590 if let Ok((_, res)) = self.r.resolve_macro_path(
1591 &path, None, &self.parent_scope, false, false
1593 return Some(PartialRes::new(res));
1600 /// Handles paths that may refer to associated items.
1604 qself: Option<&QSelf>,
1608 crate_lint: CrateLint,
1609 ) -> Option<PartialRes> {
1611 "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1619 if let Some(qself) = qself {
1620 if qself.position == 0 {
1621 // This is a case like `<T>::B`, where there is no
1622 // trait to resolve. In that case, we leave the `B`
1623 // segment to be resolved by type-check.
1624 return Some(PartialRes::with_unresolved_segments(
1625 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1629 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1631 // Currently, `path` names the full item (`A::B::C`, in
1632 // our example). so we extract the prefix of that that is
1633 // the trait (the slice upto and including
1634 // `qself.position`). And then we recursively resolve that,
1635 // but with `qself` set to `None`.
1637 // However, setting `qself` to none (but not changing the
1638 // span) loses the information about where this path
1639 // *actually* appears, so for the purposes of the crate
1640 // lint we pass along information that this is the trait
1641 // name from a fully qualified path, and this also
1642 // contains the full span (the `CrateLint::QPathTrait`).
1643 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1644 let partial_res = self.smart_resolve_path_fragment(
1647 &path[..=qself.position],
1649 PathSource::TraitItem(ns),
1650 CrateLint::QPathTrait {
1652 qpath_span: qself.path_span,
1656 // The remaining segments (the `C` in our example) will
1657 // have to be resolved by type-check, since that requires doing
1658 // trait resolution.
1659 return Some(PartialRes::with_unresolved_segments(
1660 partial_res.base_res(),
1661 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1665 let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1666 PathResult::NonModule(path_res) => path_res,
1667 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1668 PartialRes::new(module.res().unwrap())
1670 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1671 // don't report an error right away, but try to fallback to a primitive type.
1672 // So, we are still able to successfully resolve something like
1674 // use std::u8; // bring module u8 in scope
1675 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1676 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
1677 // // not to non-existent std::u8::max_value
1680 // Such behavior is required for backward compatibility.
1681 // The same fallback is used when `a` resolves to nothing.
1682 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1683 PathResult::Failed { .. }
1684 if (ns == TypeNS || path.len() > 1) &&
1685 self.r.primitive_type_table.primitive_types
1686 .contains_key(&path[0].ident.name) => {
1687 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1688 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1690 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1691 PartialRes::new(module.res().unwrap()),
1692 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1693 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1694 PartialRes::new(Res::Err)
1696 PathResult::Module(..) | PathResult::Failed { .. } => return None,
1697 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1700 if path.len() > 1 && result.base_res() != Res::Err &&
1701 path[0].ident.name != kw::PathRoot &&
1702 path[0].ident.name != kw::DollarCrate {
1703 let unqualified_result = {
1704 match self.resolve_path(
1705 &[*path.last().unwrap()],
1711 PathResult::NonModule(path_res) => path_res.base_res(),
1712 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1713 module.res().unwrap(),
1714 _ => return Some(result),
1717 if result.base_res() == unqualified_result {
1718 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1719 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1726 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
1727 where F: FnOnce(&mut LateResolutionVisitor<'_, '_>)
1729 if let Some(label) = label {
1730 self.unused_labels.insert(id, label.ident.span);
1731 self.with_label_rib(|this| {
1732 let ident = label.ident.modern_and_legacy();
1733 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1741 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1742 self.with_resolved_label(label, id, |this| this.visit_block(block));
1745 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1746 // First, record candidate traits for this expression if it could
1747 // result in the invocation of a method call.
1749 self.record_candidate_traits_for_expr_if_necessary(expr);
1751 // Next, resolve the node.
1753 ExprKind::Path(ref qself, ref path) => {
1754 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1755 visit::walk_expr(self, expr);
1758 ExprKind::Struct(ref path, ..) => {
1759 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1760 visit::walk_expr(self, expr);
1763 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1764 let node_id = self.search_label(label.ident, |rib, ident| {
1765 rib.bindings.get(&ident.modern_and_legacy()).cloned()
1769 // Search again for close matches...
1770 // Picks the first label that is "close enough", which is not necessarily
1771 // the closest match
1772 let close_match = self.search_label(label.ident, |rib, ident| {
1773 let names = rib.bindings.iter().filter_map(|(id, _)| {
1774 if id.span.ctxt() == label.ident.span.ctxt() {
1780 find_best_match_for_name(names, &*ident.as_str(), None)
1782 self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1783 self.r.report_error(
1785 ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1789 // Since this res is a label, it is never read.
1790 self.r.label_res_map.insert(expr.id, node_id);
1791 self.unused_labels.remove(&node_id);
1795 // visit `break` argument if any
1796 visit::walk_expr(self, expr);
1799 ExprKind::Let(ref pats, ref scrutinee) => {
1800 self.visit_expr(scrutinee);
1801 self.resolve_pats(pats, PatternSource::Let);
1804 ExprKind::If(ref cond, ref then, ref opt_else) => {
1805 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1806 self.visit_expr(cond);
1807 self.visit_block(then);
1808 self.ribs[ValueNS].pop();
1810 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1813 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1815 ExprKind::While(ref subexpression, ref block, label) => {
1816 self.with_resolved_label(label, expr.id, |this| {
1817 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
1818 this.visit_expr(subexpression);
1819 this.visit_block(block);
1820 this.ribs[ValueNS].pop();
1824 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
1825 self.visit_expr(subexpression);
1826 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
1827 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
1829 self.resolve_labeled_block(label, expr.id, block);
1831 self.ribs[ValueNS].pop();
1834 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1836 // Equivalent to `visit::walk_expr` + passing some context to children.
1837 ExprKind::Field(ref subexpression, _) => {
1838 self.resolve_expr(subexpression, Some(expr));
1840 ExprKind::MethodCall(ref segment, ref arguments) => {
1841 let mut arguments = arguments.iter();
1842 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1843 for argument in arguments {
1844 self.resolve_expr(argument, None);
1846 self.visit_path_segment(expr.span, segment);
1849 ExprKind::Call(ref callee, ref arguments) => {
1850 self.resolve_expr(callee, Some(expr));
1851 for argument in arguments {
1852 self.resolve_expr(argument, None);
1855 ExprKind::Type(ref type_expr, _) => {
1856 self.current_type_ascription.push(type_expr.span);
1857 visit::walk_expr(self, expr);
1858 self.current_type_ascription.pop();
1860 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1861 // resolve the arguments within the proper scopes so that usages of them inside the
1862 // closure are detected as upvars rather than normal closure arg usages.
1864 _, IsAsync::Async { .. }, _,
1865 ref fn_decl, ref body, _span,
1867 let rib_kind = NormalRibKind;
1868 self.ribs[ValueNS].push(Rib::new(rib_kind));
1869 // Resolve arguments:
1870 let mut bindings_list = FxHashMap::default();
1871 for argument in &fn_decl.inputs {
1872 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
1873 self.visit_ty(&argument.ty);
1875 // No need to resolve return type-- the outer closure return type is
1876 // FunctionRetTy::Default
1878 // Now resolve the inner closure
1880 // No need to resolve arguments: the inner closure has none.
1881 // Resolve the return type:
1882 visit::walk_fn_ret_ty(self, &fn_decl.output);
1884 self.visit_expr(body);
1886 self.ribs[ValueNS].pop();
1889 visit::walk_expr(self, expr);
1894 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1896 ExprKind::Field(_, ident) => {
1897 // FIXME(#6890): Even though you can't treat a method like a
1898 // field, we need to add any trait methods we find that match
1899 // the field name so that we can do some nice error reporting
1900 // later on in typeck.
1901 let traits = self.get_traits_containing_item(ident, ValueNS);
1902 self.r.trait_map.insert(expr.id, traits);
1904 ExprKind::MethodCall(ref segment, ..) => {
1905 debug!("(recording candidate traits for expr) recording traits for {}",
1907 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1908 self.r.trait_map.insert(expr.id, traits);
1916 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1917 -> Vec<TraitCandidate> {
1918 debug!("(getting traits containing item) looking for '{}'", ident.name);
1920 let mut found_traits = Vec::new();
1921 // Look for the current trait.
1922 if let Some((module, _)) = self.current_trait_ref {
1923 if self.r.resolve_ident_in_module(
1924 ModuleOrUniformRoot::Module(module),
1931 let def_id = module.def_id().unwrap();
1932 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1936 ident.span = ident.span.modern();
1937 let mut search_module = self.parent_scope.module;
1939 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1940 search_module = unwrap_or!(
1941 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1945 if let Some(prelude) = self.r.prelude {
1946 if !search_module.no_implicit_prelude {
1947 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1954 fn get_traits_in_module_containing_item(&mut self,
1958 found_traits: &mut Vec<TraitCandidate>) {
1959 assert!(ns == TypeNS || ns == ValueNS);
1960 let mut traits = module.traits.borrow_mut();
1961 if traits.is_none() {
1962 let mut collected_traits = Vec::new();
1963 module.for_each_child(self.r, |_, name, ns, binding| {
1964 if ns != TypeNS { return }
1965 match binding.res() {
1966 Res::Def(DefKind::Trait, _) |
1967 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1971 *traits = Some(collected_traits.into_boxed_slice());
1974 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1975 // Traits have pseudo-modules that can be used to search for the given ident.
1976 if let Some(module) = binding.module() {
1977 let mut ident = ident;
1978 if ident.span.glob_adjust(
1984 if self.r.resolve_ident_in_module_unadjusted(
1985 ModuleOrUniformRoot::Module(module),
1992 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1993 let trait_def_id = module.def_id().unwrap();
1994 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1996 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1997 // For now, just treat all trait aliases as possible candidates, since we don't
1998 // know if the ident is somewhere in the transitive bounds.
1999 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
2000 let trait_def_id = binding.res().def_id();
2001 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
2003 bug!("candidate is not trait or trait alias?")
2008 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
2009 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
2010 let mut import_ids = smallvec![];
2011 while let NameBindingKind::Import { directive, binding, .. } = kind {
2012 self.r.maybe_unused_trait_imports.insert(directive.id);
2013 self.r.add_to_glob_map(&directive, trait_name);
2014 import_ids.push(directive.id);
2015 kind = &binding.kind;
2021 impl<'a> Resolver<'a> {
2022 pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2023 let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2024 visit::walk_crate(&mut late_resolution_visitor, krate);
2025 for (id, span) in late_resolution_visitor.unused_labels.iter() {
2026 self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");