1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![feature(crate_visibility_modifier)]
4 #![feature(label_break_value)]
6 #![feature(rustc_diagnostic_macros)]
8 #![recursion_limit="256"]
10 #![deny(rust_2018_idioms)]
12 pub use rustc::hir::def::{Namespace, PerNS};
14 use GenericParameters::*;
17 use rustc::hir::map::{Definitions, DefCollector};
18 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
19 use rustc::middle::cstore::CrateStore;
20 use rustc::session::Session;
22 use rustc::hir::def::*;
23 use rustc::hir::def::Namespace::*;
24 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
25 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
26 use rustc::ty::{self, DefIdTree};
27 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
28 use rustc::{bug, span_bug};
30 use rustc_metadata::creader::CrateLoader;
31 use rustc_metadata::cstore::CStore;
33 use syntax::source_map::SourceMap;
34 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
35 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
36 use syntax::ext::base::SyntaxExtension;
37 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
38 use syntax::ext::base::MacroKind;
39 use syntax::symbol::{Symbol, keywords};
40 use syntax::util::lev_distance::find_best_match_for_name;
42 use syntax::visit::{self, FnKind, Visitor};
44 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
45 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
46 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
47 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
48 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
50 use syntax::{span_err, struct_span_err, unwrap_or, walk_list};
52 use syntax_pos::{BytePos, Span, DUMMY_SP, MultiSpan};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
57 use std::cell::{Cell, RefCell};
58 use std::{cmp, fmt, iter, mem, ptr};
59 use std::collections::BTreeSet;
60 use std::mem::replace;
61 use rustc_data_structures::ptr_key::PtrKey;
62 use rustc_data_structures::sync::Lrc;
64 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
65 use macros::{InvocationData, LegacyBinding, ParentScope};
67 // N.B., this module needs to be declared first so diagnostics are
68 // registered before they are used.
73 mod build_reduced_graph;
76 fn is_known_tool(name: Name) -> bool {
77 ["clippy", "rustfmt"].contains(&&*name.as_str())
87 AbsolutePath(Namespace),
92 /// A free importable items suggested in case of resolution failure.
93 struct ImportSuggestion {
98 /// A field or associated item from self type suggested in case of resolution failure.
99 enum AssocSuggestion {
106 struct BindingError {
108 origin: BTreeSet<Span>,
109 target: BTreeSet<Span>,
112 struct TypoSuggestion {
115 /// The kind of the binding ("crate", "module", etc.)
118 /// An appropriate article to refer to the binding ("a", "an", etc.)
119 article: &'static str,
122 impl PartialOrd for BindingError {
123 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
124 Some(self.cmp(other))
128 impl PartialEq for BindingError {
129 fn eq(&self, other: &BindingError) -> bool {
130 self.name == other.name
134 impl Ord for BindingError {
135 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
136 self.name.cmp(&other.name)
140 /// A span, message, replacement text, and applicability.
141 type Suggestion = (Span, String, String, Applicability);
143 enum ResolutionError<'a> {
144 /// Error E0401: can't use type or const parameters from outer function.
145 GenericParamsFromOuterFunction(Def),
146 /// Error E0403: the name is already used for a type or const parameter in this generic
148 NameAlreadyUsedInParameterList(Name, &'a Span),
149 /// Error E0407: method is not a member of trait.
150 MethodNotMemberOfTrait(Name, &'a str),
151 /// Error E0437: type is not a member of trait.
152 TypeNotMemberOfTrait(Name, &'a str),
153 /// Error E0438: const is not a member of trait.
154 ConstNotMemberOfTrait(Name, &'a str),
155 /// Error E0408: variable `{}` is not bound in all patterns.
156 VariableNotBoundInPattern(&'a BindingError),
157 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
158 VariableBoundWithDifferentMode(Name, Span),
159 /// Error E0415: identifier is bound more than once in this parameter list.
160 IdentifierBoundMoreThanOnceInParameterList(&'a str),
161 /// Error E0416: identifier is bound more than once in the same pattern.
162 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
163 /// Error E0426: use of undeclared label.
164 UndeclaredLabel(&'a str, Option<Name>),
165 /// Error E0429: `self` imports are only allowed within a `{ }` list.
166 SelfImportsOnlyAllowedWithin,
167 /// Error E0430: `self` import can only appear once in the list.
168 SelfImportCanOnlyAppearOnceInTheList,
169 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
170 SelfImportOnlyInImportListWithNonEmptyPrefix,
171 /// Error E0433: failed to resolve.
172 FailedToResolve { label: String, suggestion: Option<Suggestion> },
173 /// Error E0434: can't capture dynamic environment in a fn item.
174 CannotCaptureDynamicEnvironmentInFnItem,
175 /// Error E0435: attempt to use a non-constant value in a constant.
176 AttemptToUseNonConstantValueInConstant,
177 /// Error E0530: `X` bindings cannot shadow `Y`s.
178 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
179 /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
180 ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
183 /// Combines an error with provided span and emits it.
185 /// This takes the error provided, combines it with the span and any additional spans inside the
186 /// error and emits it.
187 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
189 resolution_error: ResolutionError<'a>) {
190 resolve_struct_error(resolver, span, resolution_error).emit();
193 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
195 resolution_error: ResolutionError<'a>)
196 -> DiagnosticBuilder<'sess> {
197 match resolution_error {
198 ResolutionError::GenericParamsFromOuterFunction(outer_def) => {
199 let mut err = struct_span_err!(resolver.session,
202 "can't use generic parameters from outer function",
204 err.span_label(span, format!("use of generic parameter from outer function"));
206 let cm = resolver.session.source_map();
208 Def::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
209 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
210 resolver.definitions.opt_span(def_id)
213 reduce_impl_span_to_impl_keyword(cm, impl_span),
214 "`Self` type implicitly declared here, by this `impl`",
217 match (maybe_trait_defid, maybe_impl_defid) {
219 err.span_label(span, "can't use `Self` here");
222 err.span_label(span, "use a type here instead");
224 (None, None) => bug!("`impl` without trait nor type?"),
228 Def::TyParam(def_id) => {
229 if let Some(span) = resolver.definitions.opt_span(def_id) {
230 err.span_label(span, "type variable from outer function");
233 Def::ConstParam(def_id) => {
234 if let Some(span) = resolver.definitions.opt_span(def_id) {
235 err.span_label(span, "const variable from outer function");
239 bug!("GenericParamsFromOuterFunction should only be used with Def::SelfTy, \
244 // Try to retrieve the span of the function signature and generate a new message with
245 // a local type or const parameter.
246 let sugg_msg = &format!("try using a local generic parameter instead");
247 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
248 // Suggest the modification to the user
253 Applicability::MachineApplicable,
255 } else if let Some(sp) = cm.generate_fn_name_span(span) {
257 format!("try adding a local generic parameter in this method instead"));
259 err.help(&format!("try using a local generic parameter instead"));
264 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
265 let mut err = struct_span_err!(resolver.session,
268 "the name `{}` is already used for a generic \
269 parameter in this list of generic parameters",
271 err.span_label(span, "already used");
272 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
275 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
276 let mut err = struct_span_err!(resolver.session,
279 "method `{}` is not a member of trait `{}`",
282 err.span_label(span, format!("not a member of trait `{}`", trait_));
285 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
286 let mut err = struct_span_err!(resolver.session,
289 "type `{}` is not a member of trait `{}`",
292 err.span_label(span, format!("not a member of trait `{}`", trait_));
295 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
296 let mut err = struct_span_err!(resolver.session,
299 "const `{}` is not a member of trait `{}`",
302 err.span_label(span, format!("not a member of trait `{}`", trait_));
305 ResolutionError::VariableNotBoundInPattern(binding_error) => {
306 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
307 let msp = MultiSpan::from_spans(target_sp.clone());
308 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
309 let mut err = resolver.session.struct_span_err_with_code(
312 DiagnosticId::Error("E0408".into()),
314 for sp in target_sp {
315 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
317 let origin_sp = binding_error.origin.iter().cloned();
318 for sp in origin_sp {
319 err.span_label(sp, "variable not in all patterns");
323 ResolutionError::VariableBoundWithDifferentMode(variable_name,
324 first_binding_span) => {
325 let mut err = struct_span_err!(resolver.session,
328 "variable `{}` is bound in inconsistent \
329 ways within the same match arm",
331 err.span_label(span, "bound in different ways");
332 err.span_label(first_binding_span, "first binding");
335 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
336 let mut err = struct_span_err!(resolver.session,
339 "identifier `{}` is bound more than once in this parameter list",
341 err.span_label(span, "used as parameter more than once");
344 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
345 let mut err = struct_span_err!(resolver.session,
348 "identifier `{}` is bound more than once in the same pattern",
350 err.span_label(span, "used in a pattern more than once");
353 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
354 let mut err = struct_span_err!(resolver.session,
357 "use of undeclared label `{}`",
359 if let Some(lev_candidate) = lev_candidate {
360 err.span_label(span, format!("did you mean `{}`?", lev_candidate));
362 err.span_label(span, format!("undeclared label `{}`", name));
366 ResolutionError::SelfImportsOnlyAllowedWithin => {
367 struct_span_err!(resolver.session,
371 "`self` imports are only allowed within a { } list")
373 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
374 let mut err = struct_span_err!(resolver.session, span, E0430,
375 "`self` import can only appear once in an import list");
376 err.span_label(span, "can only appear once in an import list");
379 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
380 let mut err = struct_span_err!(resolver.session, span, E0431,
381 "`self` import can only appear in an import list with \
382 a non-empty prefix");
383 err.span_label(span, "can only appear in an import list with a non-empty prefix");
386 ResolutionError::FailedToResolve { label, suggestion } => {
387 let mut err = struct_span_err!(resolver.session, span, E0433,
388 "failed to resolve: {}", &label);
389 err.span_label(span, label);
391 if let Some((span, msg, suggestion, applicability)) = suggestion {
392 err.span_suggestion(span, &msg, suggestion, applicability);
397 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
398 let mut err = struct_span_err!(resolver.session,
402 "can't capture dynamic environment in a fn item");
403 err.help("use the `|| { ... }` closure form instead");
406 ResolutionError::AttemptToUseNonConstantValueInConstant => {
407 let mut err = struct_span_err!(resolver.session, span, E0435,
408 "attempt to use a non-constant value in a constant");
409 err.span_label(span, "non-constant value");
412 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
413 let shadows_what = binding.descr();
414 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
415 what_binding, shadows_what);
416 err.span_label(span, format!("cannot be named the same as {} {}",
417 binding.article(), shadows_what));
418 let participle = if binding.is_import() { "imported" } else { "defined" };
419 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
420 err.span_label(binding.span, msg);
423 ResolutionError::ForwardDeclaredTyParam => {
424 let mut err = struct_span_err!(resolver.session, span, E0128,
425 "type parameters with a default cannot use \
426 forward declared identifiers");
428 span, "defaulted type parameters cannot be forward declared".to_string());
434 /// Adjust the impl span so that just the `impl` keyword is taken by removing
435 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
436 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
438 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
439 /// parser. If you need to use this function or something similar, please consider updating the
440 /// `source_map` functions and this function to something more robust.
441 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
442 let impl_span = cm.span_until_char(impl_span, '<');
443 let impl_span = cm.span_until_whitespace(impl_span);
447 #[derive(Copy, Clone, Debug)]
450 binding_mode: BindingMode,
453 /// Map from the name in a pattern to its binding mode.
454 type BindingMap = FxHashMap<Ident, BindingInfo>;
456 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
467 fn descr(self) -> &'static str {
469 PatternSource::Match => "match binding",
470 PatternSource::IfLet => "if let binding",
471 PatternSource::WhileLet => "while let binding",
472 PatternSource::Let => "let binding",
473 PatternSource::For => "for binding",
474 PatternSource::FnParam => "function parameter",
479 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
480 enum AliasPossibility {
485 #[derive(Copy, Clone, Debug)]
486 enum PathSource<'a> {
487 // Type paths `Path`.
489 // Trait paths in bounds or impls.
490 Trait(AliasPossibility),
491 // Expression paths `path`, with optional parent context.
492 Expr(Option<&'a Expr>),
493 // Paths in path patterns `Path`.
495 // Paths in struct expressions and patterns `Path { .. }`.
497 // Paths in tuple struct patterns `Path(..)`.
499 // `m::A::B` in `<T as m::A>::B::C`.
500 TraitItem(Namespace),
501 // Path in `pub(path)`
505 impl<'a> PathSource<'a> {
506 fn namespace(self) -> Namespace {
508 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
509 PathSource::Visibility => TypeNS,
510 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
511 PathSource::TraitItem(ns) => ns,
515 fn global_by_default(self) -> bool {
517 PathSource::Visibility => true,
518 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
519 PathSource::Struct | PathSource::TupleStruct |
520 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
524 fn defer_to_typeck(self) -> bool {
526 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
527 PathSource::Struct | PathSource::TupleStruct => true,
528 PathSource::Trait(_) | PathSource::TraitItem(..) |
529 PathSource::Visibility => false,
533 fn descr_expected(self) -> &'static str {
535 PathSource::Type => "type",
536 PathSource::Trait(_) => "trait",
537 PathSource::Pat => "unit struct/variant or constant",
538 PathSource::Struct => "struct, variant or union type",
539 PathSource::TupleStruct => "tuple struct/variant",
540 PathSource::Visibility => "module",
541 PathSource::TraitItem(ns) => match ns {
542 TypeNS => "associated type",
543 ValueNS => "method or associated constant",
544 MacroNS => bug!("associated macro"),
546 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
547 // "function" here means "anything callable" rather than `Def::Fn`,
548 // this is not precise but usually more helpful than just "value".
549 Some(&ExprKind::Call(..)) => "function",
555 fn is_expected(self, def: Def) -> bool {
557 PathSource::Type => match def {
558 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
559 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
560 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
561 Def::SelfTy(..) | Def::Existential(..) | Def::ForeignTy(..) => true,
564 PathSource::Trait(AliasPossibility::No) => match def {
565 Def::Trait(..) => true,
568 PathSource::Trait(AliasPossibility::Maybe) => match def {
569 Def::Trait(..) => true,
570 Def::TraitAlias(..) => true,
573 PathSource::Expr(..) => match def {
574 Def::Ctor(_, _, CtorKind::Const) | Def::Ctor(_, _, CtorKind::Fn) |
575 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
576 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
577 Def::SelfCtor(..) | Def::ConstParam(..) => true,
580 PathSource::Pat => match def {
581 Def::Ctor(_, _, CtorKind::Const) |
582 Def::Const(..) | Def::AssociatedConst(..) |
583 Def::SelfCtor(..) => true,
586 PathSource::TupleStruct => match def {
587 Def::Ctor(_, _, CtorKind::Fn) | Def::SelfCtor(..) => true,
590 PathSource::Struct => match def {
591 Def::Struct(..) | Def::Union(..) | Def::Variant(..) |
592 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => true,
595 PathSource::TraitItem(ns) => match def {
596 Def::AssociatedConst(..) | Def::Method(..) if ns == ValueNS => true,
597 Def::AssociatedTy(..) if ns == TypeNS => true,
600 PathSource::Visibility => match def {
601 Def::Mod(..) => true,
607 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
608 __diagnostic_used!(E0404);
609 __diagnostic_used!(E0405);
610 __diagnostic_used!(E0412);
611 __diagnostic_used!(E0422);
612 __diagnostic_used!(E0423);
613 __diagnostic_used!(E0425);
614 __diagnostic_used!(E0531);
615 __diagnostic_used!(E0532);
616 __diagnostic_used!(E0573);
617 __diagnostic_used!(E0574);
618 __diagnostic_used!(E0575);
619 __diagnostic_used!(E0576);
620 __diagnostic_used!(E0577);
621 __diagnostic_used!(E0578);
622 match (self, has_unexpected_resolution) {
623 (PathSource::Trait(_), true) => "E0404",
624 (PathSource::Trait(_), false) => "E0405",
625 (PathSource::Type, true) => "E0573",
626 (PathSource::Type, false) => "E0412",
627 (PathSource::Struct, true) => "E0574",
628 (PathSource::Struct, false) => "E0422",
629 (PathSource::Expr(..), true) => "E0423",
630 (PathSource::Expr(..), false) => "E0425",
631 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
632 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
633 (PathSource::TraitItem(..), true) => "E0575",
634 (PathSource::TraitItem(..), false) => "E0576",
635 (PathSource::Visibility, true) => "E0577",
636 (PathSource::Visibility, false) => "E0578",
641 // A minimal representation of a path segment. We use this in resolve because
642 // we synthesize 'path segments' which don't have the rest of an AST or HIR
644 #[derive(Clone, Copy, Debug)]
651 fn from_path(path: &Path) -> Vec<Segment> {
652 path.segments.iter().map(|s| s.into()).collect()
655 fn from_ident(ident: Ident) -> Segment {
662 fn names_to_string(segments: &[Segment]) -> String {
663 names_to_string(&segments.iter()
664 .map(|seg| seg.ident)
665 .collect::<Vec<_>>())
669 impl<'a> From<&'a ast::PathSegment> for Segment {
670 fn from(seg: &'a ast::PathSegment) -> Segment {
678 struct UsePlacementFinder {
679 target_module: NodeId,
684 impl UsePlacementFinder {
685 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
686 let mut finder = UsePlacementFinder {
691 visit::walk_crate(&mut finder, krate);
692 (finder.span, finder.found_use)
696 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
699 module: &'tcx ast::Mod,
701 _: &[ast::Attribute],
704 if self.span.is_some() {
707 if node_id != self.target_module {
708 visit::walk_mod(self, module);
711 // find a use statement
712 for item in &module.items {
714 ItemKind::Use(..) => {
715 // don't suggest placing a use before the prelude
716 // import or other generated ones
717 if item.span.ctxt().outer().expn_info().is_none() {
718 self.span = Some(item.span.shrink_to_lo());
719 self.found_use = true;
723 // don't place use before extern crate
724 ItemKind::ExternCrate(_) => {}
725 // but place them before the first other item
726 _ => if self.span.map_or(true, |span| item.span < span ) {
727 if item.span.ctxt().outer().expn_info().is_none() {
728 // don't insert between attributes and an item
729 if item.attrs.is_empty() {
730 self.span = Some(item.span.shrink_to_lo());
732 // find the first attribute on the item
733 for attr in &item.attrs {
734 if self.span.map_or(true, |span| attr.span < span) {
735 self.span = Some(attr.span.shrink_to_lo());
746 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
747 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
748 fn visit_item(&mut self, item: &'tcx Item) {
749 self.resolve_item(item);
751 fn visit_arm(&mut self, arm: &'tcx Arm) {
752 self.resolve_arm(arm);
754 fn visit_block(&mut self, block: &'tcx Block) {
755 self.resolve_block(block);
757 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
758 debug!("visit_anon_const {:?}", constant);
759 self.with_constant_rib(|this| {
760 visit::walk_anon_const(this, constant);
763 fn visit_expr(&mut self, expr: &'tcx Expr) {
764 self.resolve_expr(expr, None);
766 fn visit_local(&mut self, local: &'tcx Local) {
767 self.resolve_local(local);
769 fn visit_ty(&mut self, ty: &'tcx Ty) {
771 TyKind::Path(ref qself, ref path) => {
772 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
774 TyKind::ImplicitSelf => {
775 let self_ty = keywords::SelfUpper.ident();
776 let def = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
777 .map_or(Def::Err, |d| d.def());
778 self.record_def(ty.id, PathResolution::new(def));
782 visit::walk_ty(self, ty);
784 fn visit_poly_trait_ref(&mut self,
785 tref: &'tcx ast::PolyTraitRef,
786 m: &'tcx ast::TraitBoundModifier) {
787 self.smart_resolve_path(tref.trait_ref.ref_id, None,
788 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
789 visit::walk_poly_trait_ref(self, tref, m);
791 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
792 let generic_params = match foreign_item.node {
793 ForeignItemKind::Fn(_, ref generics) => {
794 HasGenericParams(generics, ItemRibKind)
796 ForeignItemKind::Static(..) => NoGenericParams,
797 ForeignItemKind::Ty => NoGenericParams,
798 ForeignItemKind::Macro(..) => NoGenericParams,
800 self.with_generic_param_rib(generic_params, |this| {
801 visit::walk_foreign_item(this, foreign_item);
804 fn visit_fn(&mut self,
805 function_kind: FnKind<'tcx>,
806 declaration: &'tcx FnDecl,
810 debug!("(resolving function) entering function");
811 let (rib_kind, asyncness) = match function_kind {
812 FnKind::ItemFn(_, ref header, ..) =>
813 (FnItemRibKind, header.asyncness.node),
814 FnKind::Method(_, ref sig, _, _) =>
815 (TraitOrImplItemRibKind, sig.header.asyncness.node),
816 FnKind::Closure(_) =>
817 // Async closures aren't resolved through `visit_fn`-- they're
818 // processed separately
819 (ClosureRibKind(node_id), IsAsync::NotAsync),
822 // Create a value rib for the function.
823 self.ribs[ValueNS].push(Rib::new(rib_kind));
825 // Create a label rib for the function.
826 self.label_ribs.push(Rib::new(rib_kind));
828 // Add each argument to the rib.
829 let mut bindings_list = FxHashMap::default();
830 for argument in &declaration.inputs {
831 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
833 self.visit_ty(&argument.ty);
835 debug!("(resolving function) recorded argument");
837 visit::walk_fn_ret_ty(self, &declaration.output);
839 // Resolve the function body, potentially inside the body of an async closure
840 if let IsAsync::Async { closure_id, .. } = asyncness {
841 let rib_kind = ClosureRibKind(closure_id);
842 self.ribs[ValueNS].push(Rib::new(rib_kind));
843 self.label_ribs.push(Rib::new(rib_kind));
846 match function_kind {
847 FnKind::ItemFn(.., body) |
848 FnKind::Method(.., body) => {
849 self.visit_block(body);
851 FnKind::Closure(body) => {
852 self.visit_expr(body);
856 // Leave the body of the async closure
857 if asyncness.is_async() {
858 self.label_ribs.pop();
859 self.ribs[ValueNS].pop();
862 debug!("(resolving function) leaving function");
864 self.label_ribs.pop();
865 self.ribs[ValueNS].pop();
868 fn visit_generics(&mut self, generics: &'tcx Generics) {
869 // For type parameter defaults, we have to ban access
870 // to following type parameters, as the InternalSubsts can only
871 // provide previous type parameters as they're built. We
872 // put all the parameters on the ban list and then remove
873 // them one by one as they are processed and become available.
874 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
875 let mut found_default = false;
876 default_ban_rib.bindings.extend(generics.params.iter()
877 .filter_map(|param| match param.kind {
878 GenericParamKind::Const { .. } |
879 GenericParamKind::Lifetime { .. } => None,
880 GenericParamKind::Type { ref default, .. } => {
881 found_default |= default.is_some();
883 Some((Ident::with_empty_ctxt(param.ident.name), Def::Err))
890 for param in &generics.params {
892 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
893 GenericParamKind::Type { ref default, .. } => {
894 for bound in ¶m.bounds {
895 self.visit_param_bound(bound);
898 if let Some(ref ty) = default {
899 self.ribs[TypeNS].push(default_ban_rib);
901 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
904 // Allow all following defaults to refer to this type parameter.
905 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
907 GenericParamKind::Const { ref ty } => {
908 for bound in ¶m.bounds {
909 self.visit_param_bound(bound);
916 for p in &generics.where_clause.predicates {
917 self.visit_where_predicate(p);
922 #[derive(Copy, Clone)]
923 enum GenericParameters<'a, 'b> {
925 HasGenericParams(// Type parameters.
928 // The kind of the rib used for type parameters.
932 /// The rib kind controls the translation of local
933 /// definitions (`Def::Local`) to upvars (`Def::Upvar`).
934 #[derive(Copy, Clone, Debug)]
936 /// No translation needs to be applied.
939 /// We passed through a closure scope at the given `NodeId`.
940 /// Translate upvars as appropriate.
941 ClosureRibKind(NodeId /* func id */),
943 /// We passed through an impl or trait and are now in one of its
944 /// methods or associated types. Allow references to ty params that impl or trait
945 /// binds. Disallow any other upvars (including other ty params that are
947 TraitOrImplItemRibKind,
949 /// We passed through a function definition. Disallow upvars.
950 /// Permit only those const parameters that are specified in the function's generics.
953 /// We passed through an item scope. Disallow upvars.
956 /// We're in a constant item. Can't refer to dynamic stuff.
959 /// We passed through a module.
960 ModuleRibKind(Module<'a>),
962 /// We passed through a `macro_rules!` statement
963 MacroDefinition(DefId),
965 /// All bindings in this rib are type parameters that can't be used
966 /// from the default of a type parameter because they're not declared
967 /// before said type parameter. Also see the `visit_generics` override.
968 ForwardTyParamBanRibKind,
971 /// A single local scope.
973 /// A rib represents a scope names can live in. Note that these appear in many places, not just
974 /// around braces. At any place where the list of accessible names (of the given namespace)
975 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
976 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
979 /// Different [rib kinds](enum.RibKind) are transparent for different names.
981 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
982 /// resolving, the name is looked up from inside out.
985 bindings: FxHashMap<Ident, Def>,
990 fn new(kind: RibKind<'a>) -> Rib<'a> {
992 bindings: Default::default(),
998 /// An intermediate resolution result.
1000 /// This refers to the thing referred by a name. The difference between `Def` and `Item` is that
1001 /// items are visible in their whole block, while defs only from the place they are defined
1003 enum LexicalScopeBinding<'a> {
1004 Item(&'a NameBinding<'a>),
1008 impl<'a> LexicalScopeBinding<'a> {
1009 fn item(self) -> Option<&'a NameBinding<'a>> {
1011 LexicalScopeBinding::Item(binding) => Some(binding),
1016 fn def(self) -> Def {
1018 LexicalScopeBinding::Item(binding) => binding.def(),
1019 LexicalScopeBinding::Def(def) => def,
1024 #[derive(Copy, Clone, Debug)]
1025 enum ModuleOrUniformRoot<'a> {
1029 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1030 CrateRootAndExternPrelude,
1032 /// Virtual module that denotes resolution in extern prelude.
1033 /// Used for paths starting with `::` on 2018 edition.
1036 /// Virtual module that denotes resolution in current scope.
1037 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1038 /// are always split into two parts, the first of which should be some kind of module.
1042 impl ModuleOrUniformRoot<'_> {
1043 fn same_def(lhs: Self, rhs: Self) -> bool {
1045 (ModuleOrUniformRoot::Module(lhs),
1046 ModuleOrUniformRoot::Module(rhs)) => lhs.def() == rhs.def(),
1047 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1048 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1049 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1050 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1056 #[derive(Clone, Debug)]
1057 enum PathResult<'a> {
1058 Module(ModuleOrUniformRoot<'a>),
1059 NonModule(PathResolution),
1064 suggestion: Option<Suggestion>,
1065 is_error_from_last_segment: bool,
1070 /// An anonymous module; e.g., just a block.
1074 /// fn f() {} // (1)
1075 /// { // This is an anonymous module
1076 /// f(); // This resolves to (2) as we are inside the block.
1077 /// fn f() {} // (2)
1079 /// f(); // Resolves to (1)
1083 /// Any module with a name.
1087 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1088 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1093 /// One node in the tree of modules.
1094 pub struct ModuleData<'a> {
1095 parent: Option<Module<'a>>,
1098 // The def id of the closest normal module (`mod`) ancestor (including this module).
1099 normal_ancestor_id: DefId,
1101 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1102 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1103 Option<&'a NameBinding<'a>>)>>,
1104 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1106 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1108 // Macro invocations that can expand into items in this module.
1109 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1111 no_implicit_prelude: bool,
1113 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1114 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1116 // Used to memoize the traits in this module for faster searches through all traits in scope.
1117 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1119 // Whether this module is populated. If not populated, any attempt to
1120 // access the children must be preceded with a
1121 // `populate_module_if_necessary` call.
1122 populated: Cell<bool>,
1124 /// Span of the module itself. Used for error reporting.
1130 type Module<'a> = &'a ModuleData<'a>;
1132 impl<'a> ModuleData<'a> {
1133 fn new(parent: Option<Module<'a>>,
1135 normal_ancestor_id: DefId,
1137 span: Span) -> Self {
1142 resolutions: Default::default(),
1143 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1144 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1145 builtin_attrs: RefCell::new(Vec::new()),
1146 unresolved_invocations: Default::default(),
1147 no_implicit_prelude: false,
1148 glob_importers: RefCell::new(Vec::new()),
1149 globs: RefCell::new(Vec::new()),
1150 traits: RefCell::new(None),
1151 populated: Cell::new(normal_ancestor_id.is_local()),
1157 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1158 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1159 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1163 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1164 let resolutions = self.resolutions.borrow();
1165 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1166 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1167 for &(&(ident, ns), &resolution) in resolutions.iter() {
1168 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1172 fn def(&self) -> Option<Def> {
1174 ModuleKind::Def(def, _) => Some(def),
1179 fn def_id(&self) -> Option<DefId> {
1180 self.def().as_ref().map(Def::def_id)
1183 // `self` resolves to the first module ancestor that `is_normal`.
1184 fn is_normal(&self) -> bool {
1186 ModuleKind::Def(Def::Mod(_), _) => true,
1191 fn is_trait(&self) -> bool {
1193 ModuleKind::Def(Def::Trait(_), _) => true,
1198 fn nearest_item_scope(&'a self) -> Module<'a> {
1199 if self.is_trait() { self.parent.unwrap() } else { self }
1202 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1203 while !ptr::eq(self, other) {
1204 if let Some(parent) = other.parent {
1214 impl<'a> fmt::Debug for ModuleData<'a> {
1215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216 write!(f, "{:?}", self.def())
1220 /// Records a possibly-private value, type, or module definition.
1221 #[derive(Clone, Debug)]
1222 pub struct NameBinding<'a> {
1223 kind: NameBindingKind<'a>,
1224 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
1227 vis: ty::Visibility,
1230 pub trait ToNameBinding<'a> {
1231 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1234 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1235 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1240 #[derive(Clone, Debug)]
1241 enum NameBindingKind<'a> {
1242 Def(Def, /* is_macro_export */ bool),
1245 binding: &'a NameBinding<'a>,
1246 directive: &'a ImportDirective<'a>,
1251 impl<'a> NameBindingKind<'a> {
1252 /// Is this a name binding of a import?
1253 fn is_import(&self) -> bool {
1255 NameBindingKind::Import { .. } => true,
1261 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1263 struct UseError<'a> {
1264 err: DiagnosticBuilder<'a>,
1265 /// Attach `use` statements for these candidates.
1266 candidates: Vec<ImportSuggestion>,
1267 /// The `NodeId` of the module to place the use-statements in.
1269 /// Whether the diagnostic should state that it's "better".
1273 #[derive(Clone, Copy, PartialEq, Debug)]
1274 enum AmbiguityKind {
1278 LegacyHelperVsPrelude,
1283 MoreExpandedVsOuter,
1286 impl AmbiguityKind {
1287 fn descr(self) -> &'static str {
1289 AmbiguityKind::Import =>
1290 "name vs any other name during import resolution",
1291 AmbiguityKind::BuiltinAttr =>
1292 "built-in attribute vs any other name",
1293 AmbiguityKind::DeriveHelper =>
1294 "derive helper attribute vs any other name",
1295 AmbiguityKind::LegacyHelperVsPrelude =>
1296 "legacy plugin helper attribute vs name from prelude",
1297 AmbiguityKind::LegacyVsModern =>
1298 "`macro_rules` vs non-`macro_rules` from other module",
1299 AmbiguityKind::GlobVsOuter =>
1300 "glob import vs any other name from outer scope during import/macro resolution",
1301 AmbiguityKind::GlobVsGlob =>
1302 "glob import vs glob import in the same module",
1303 AmbiguityKind::GlobVsExpanded =>
1304 "glob import vs macro-expanded name in the same \
1305 module during import/macro resolution",
1306 AmbiguityKind::MoreExpandedVsOuter =>
1307 "macro-expanded name vs less macro-expanded name \
1308 from outer scope during import/macro resolution",
1313 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1314 #[derive(Clone, Copy, PartialEq)]
1315 enum AmbiguityErrorMisc {
1322 struct AmbiguityError<'a> {
1323 kind: AmbiguityKind,
1325 b1: &'a NameBinding<'a>,
1326 b2: &'a NameBinding<'a>,
1327 misc1: AmbiguityErrorMisc,
1328 misc2: AmbiguityErrorMisc,
1331 impl<'a> NameBinding<'a> {
1332 fn module(&self) -> Option<Module<'a>> {
1334 NameBindingKind::Module(module) => Some(module),
1335 NameBindingKind::Import { binding, .. } => binding.module(),
1340 fn def(&self) -> Def {
1342 NameBindingKind::Def(def, _) => def,
1343 NameBindingKind::Module(module) => module.def().unwrap(),
1344 NameBindingKind::Import { binding, .. } => binding.def(),
1348 fn is_ambiguity(&self) -> bool {
1349 self.ambiguity.is_some() || match self.kind {
1350 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
1355 // We sometimes need to treat variants as `pub` for backwards compatibility
1356 fn pseudo_vis(&self) -> ty::Visibility {
1357 if self.is_variant() && self.def().def_id().is_local() {
1358 ty::Visibility::Public
1364 fn is_variant(&self) -> bool {
1366 NameBindingKind::Def(Def::Variant(..), _) |
1367 NameBindingKind::Def(Def::Ctor(_, CtorOf::Variant, ..), _) => true,
1372 fn is_extern_crate(&self) -> bool {
1374 NameBindingKind::Import {
1375 directive: &ImportDirective {
1376 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1379 NameBindingKind::Module(
1380 &ModuleData { kind: ModuleKind::Def(Def::Mod(def_id), _), .. }
1381 ) => def_id.index == CRATE_DEF_INDEX,
1386 fn is_import(&self) -> bool {
1388 NameBindingKind::Import { .. } => true,
1393 fn is_glob_import(&self) -> bool {
1395 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1400 fn is_importable(&self) -> bool {
1402 Def::AssociatedConst(..) | Def::Method(..) | Def::AssociatedTy(..) => false,
1407 fn is_macro_def(&self) -> bool {
1409 NameBindingKind::Def(Def::Macro(..), _) => true,
1414 fn macro_kind(&self) -> Option<MacroKind> {
1416 Def::Macro(_, kind) => Some(kind),
1417 Def::NonMacroAttr(..) => Some(MacroKind::Attr),
1422 fn descr(&self) -> &'static str {
1423 if self.is_extern_crate() { "extern crate" } else { self.def().kind_name() }
1426 fn article(&self) -> &'static str {
1427 if self.is_extern_crate() { "an" } else { self.def().article() }
1430 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1431 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1432 // Then this function returns `true` if `self` may emerge from a macro *after* that
1433 // in some later round and screw up our previously found resolution.
1434 // See more detailed explanation in
1435 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1436 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding<'_>) -> bool {
1437 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1438 // Expansions are partially ordered, so "may appear after" is an inversion of
1439 // "certainly appears before or simultaneously" and includes unordered cases.
1440 let self_parent_expansion = self.expansion;
1441 let other_parent_expansion = binding.expansion;
1442 let certainly_before_other_or_simultaneously =
1443 other_parent_expansion.is_descendant_of(self_parent_expansion);
1444 let certainly_before_invoc_or_simultaneously =
1445 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1446 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1450 /// Interns the names of the primitive types.
1452 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1453 /// special handling, since they have no place of origin.
1455 struct PrimitiveTypeTable {
1456 primitive_types: FxHashMap<Name, PrimTy>,
1459 impl PrimitiveTypeTable {
1460 fn new() -> PrimitiveTypeTable {
1461 let mut table = PrimitiveTypeTable::default();
1463 table.intern("bool", Bool);
1464 table.intern("char", Char);
1465 table.intern("f32", Float(FloatTy::F32));
1466 table.intern("f64", Float(FloatTy::F64));
1467 table.intern("isize", Int(IntTy::Isize));
1468 table.intern("i8", Int(IntTy::I8));
1469 table.intern("i16", Int(IntTy::I16));
1470 table.intern("i32", Int(IntTy::I32));
1471 table.intern("i64", Int(IntTy::I64));
1472 table.intern("i128", Int(IntTy::I128));
1473 table.intern("str", Str);
1474 table.intern("usize", Uint(UintTy::Usize));
1475 table.intern("u8", Uint(UintTy::U8));
1476 table.intern("u16", Uint(UintTy::U16));
1477 table.intern("u32", Uint(UintTy::U32));
1478 table.intern("u64", Uint(UintTy::U64));
1479 table.intern("u128", Uint(UintTy::U128));
1483 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
1484 self.primitive_types.insert(Symbol::intern(string), primitive_type);
1488 #[derive(Debug, Default, Clone)]
1489 pub struct ExternPreludeEntry<'a> {
1490 extern_crate_item: Option<&'a NameBinding<'a>>,
1491 pub introduced_by_item: bool,
1494 /// The main resolver class.
1496 /// This is the visitor that walks the whole crate.
1497 pub struct Resolver<'a> {
1498 session: &'a Session,
1501 pub definitions: Definitions,
1503 graph_root: Module<'a>,
1505 prelude: Option<Module<'a>>,
1506 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1508 /// N.B., this is used only for better diagnostics, not name resolution itself.
1509 has_self: FxHashSet<DefId>,
1511 /// Names of fields of an item `DefId` accessible with dot syntax.
1512 /// Used for hints during error reporting.
1513 field_names: FxHashMap<DefId, Vec<Name>>,
1515 /// All imports known to succeed or fail.
1516 determined_imports: Vec<&'a ImportDirective<'a>>,
1518 /// All non-determined imports.
1519 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1521 /// The module that represents the current item scope.
1522 current_module: Module<'a>,
1524 /// The current set of local scopes for types and values.
1525 /// FIXME #4948: Reuse ribs to avoid allocation.
1526 ribs: PerNS<Vec<Rib<'a>>>,
1528 /// The current set of local scopes, for labels.
1529 label_ribs: Vec<Rib<'a>>,
1531 /// The trait that the current context can refer to.
1532 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1534 /// The current self type if inside an impl (used for better errors).
1535 current_self_type: Option<Ty>,
1537 /// The current self item if inside an ADT (used for better errors).
1538 current_self_item: Option<NodeId>,
1540 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1541 /// We are resolving a last import segment during import validation.
1542 last_import_segment: bool,
1543 /// This binding should be ignored during in-module resolution, so that we don't get
1544 /// "self-confirming" import resolutions during import validation.
1545 blacklisted_binding: Option<&'a NameBinding<'a>>,
1547 /// The idents for the primitive types.
1548 primitive_type_table: PrimitiveTypeTable,
1551 import_map: ImportMap,
1552 pub freevars: FreevarMap,
1553 freevars_seen: NodeMap<NodeMap<usize>>,
1554 pub export_map: ExportMap,
1555 pub trait_map: TraitMap,
1557 /// A map from nodes to anonymous modules.
1558 /// Anonymous modules are pseudo-modules that are implicitly created around items
1559 /// contained within blocks.
1561 /// For example, if we have this:
1569 /// There will be an anonymous module created around `g` with the ID of the
1570 /// entry block for `f`.
1571 block_map: NodeMap<Module<'a>>,
1572 module_map: FxHashMap<DefId, Module<'a>>,
1573 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1574 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1576 /// Maps glob imports to the names of items actually imported.
1577 pub glob_map: GlobMap,
1579 used_imports: FxHashSet<(NodeId, Namespace)>,
1580 pub maybe_unused_trait_imports: NodeSet,
1581 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1583 /// A list of labels as of yet unused. Labels will be removed from this map when
1584 /// they are used (in a `break` or `continue` statement)
1585 pub unused_labels: FxHashMap<NodeId, Span>,
1587 /// Privacy errors are delayed until the end in order to deduplicate them.
1588 privacy_errors: Vec<PrivacyError<'a>>,
1589 /// Ambiguity errors are delayed for deduplication.
1590 ambiguity_errors: Vec<AmbiguityError<'a>>,
1591 /// `use` injections are delayed for better placement and deduplication.
1592 use_injections: Vec<UseError<'a>>,
1593 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1594 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1596 arenas: &'a ResolverArenas<'a>,
1597 dummy_binding: &'a NameBinding<'a>,
1599 crate_loader: &'a mut CrateLoader<'a>,
1600 macro_names: FxHashSet<Ident>,
1601 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1602 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1603 pub all_macros: FxHashMap<Name, Def>,
1604 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1605 macro_defs: FxHashMap<Mark, DefId>,
1606 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1608 /// List of crate local macros that we need to warn about as being unused.
1609 /// Right now this only includes macro_rules! macros, and macros 2.0.
1610 unused_macros: FxHashSet<DefId>,
1612 /// Maps the `Mark` of an expansion to its containing module or block.
1613 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1615 /// Avoid duplicated errors for "name already defined".
1616 name_already_seen: FxHashMap<Name, Span>,
1618 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1620 /// Table for mapping struct IDs into struct constructor IDs,
1621 /// it's not used during normal resolution, only for better error reporting.
1622 struct_constructors: DefIdMap<(Def, ty::Visibility)>,
1624 /// Only used for better errors on `fn(): fn()`.
1625 current_type_ascription: Vec<Span>,
1627 injected_crate: Option<Module<'a>>,
1630 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1632 pub struct ResolverArenas<'a> {
1633 modules: arena::TypedArena<ModuleData<'a>>,
1634 local_modules: RefCell<Vec<Module<'a>>>,
1635 name_bindings: arena::TypedArena<NameBinding<'a>>,
1636 import_directives: arena::TypedArena<ImportDirective<'a>>,
1637 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1638 invocation_data: arena::TypedArena<InvocationData<'a>>,
1639 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1642 impl<'a> ResolverArenas<'a> {
1643 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1644 let module = self.modules.alloc(module);
1645 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1646 self.local_modules.borrow_mut().push(module);
1650 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1651 self.local_modules.borrow()
1653 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1654 self.name_bindings.alloc(name_binding)
1656 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1657 -> &'a ImportDirective<'_> {
1658 self.import_directives.alloc(import_directive)
1660 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1661 self.name_resolutions.alloc(Default::default())
1663 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1664 -> &'a InvocationData<'a> {
1665 self.invocation_data.alloc(expansion_data)
1667 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1668 self.legacy_bindings.alloc(binding)
1672 impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> {
1673 fn parent(self, id: DefId) -> Option<DefId> {
1675 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1676 _ => self.cstore.def_key(id).parent,
1677 }.map(|index| DefId { index, ..id })
1681 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1682 /// the resolver is no longer needed as all the relevant information is inline.
1683 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1684 fn resolve_hir_path(
1689 self.resolve_hir_path_cb(path, is_value,
1690 |resolver, span, error| resolve_error(resolver, span, error))
1693 fn resolve_str_path(
1696 crate_root: Option<&str>,
1697 components: &[&str],
1700 let root = if crate_root.is_some() {
1705 let segments = iter::once(root.ident())
1707 crate_root.into_iter()
1708 .chain(components.iter().cloned())
1709 .map(Ident::from_str)
1710 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1713 let path = ast::Path {
1718 self.resolve_hir_path(&path, is_value)
1721 fn get_resolution(&mut self, id: NodeId) -> Option<PathResolution> {
1722 self.def_map.get(&id).cloned()
1725 fn get_import(&mut self, id: NodeId) -> PerNS<Option<PathResolution>> {
1726 self.import_map.get(&id).cloned().unwrap_or_default()
1729 fn definitions(&mut self) -> &mut Definitions {
1730 &mut self.definitions
1734 impl<'a> Resolver<'a> {
1735 /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
1736 /// isn't something that can be returned because it can't be made to live that long,
1737 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1738 /// just that an error occurred.
1739 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1740 -> Result<hir::Path, ()> {
1741 let mut errored = false;
1743 let path = if path_str.starts_with("::") {
1746 segments: iter::once(keywords::PathRoot.ident())
1748 path_str.split("::").skip(1).map(Ident::from_str)
1750 .map(|i| self.new_ast_path_segment(i))
1758 .map(Ident::from_str)
1759 .map(|i| self.new_ast_path_segment(i))
1763 let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true);
1764 if errored || path.def == Def::Err {
1771 /// Like `resolve_hir_path`, but takes a callback in case there was an error.
1772 fn resolve_hir_path_cb<F>(
1778 where F: for<'c, 'b> FnOnce(&'c mut Resolver<'_>, Span, ResolutionError<'b>)
1780 let namespace = if is_value { ValueNS } else { TypeNS };
1781 let span = path.span;
1782 let segments = &path.segments;
1783 let path = Segment::from_path(&path);
1784 // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
1785 let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1786 span, CrateLint::No) {
1787 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1788 module.def().unwrap(),
1789 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1790 path_res.base_def(),
1791 PathResult::NonModule(..) => {
1792 error_callback(self, span, ResolutionError::FailedToResolve {
1793 label: String::from("type-relative paths are not supported in this context"),
1798 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1799 PathResult::Failed { span, label, suggestion, .. } => {
1800 error_callback(self, span, ResolutionError::FailedToResolve {
1808 let segments: Vec<_> = segments.iter().map(|seg| {
1809 let mut hir_seg = hir::PathSegment::from_ident(seg.ident);
1810 hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def()));
1816 segments: segments.into(),
1820 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1821 let mut seg = ast::PathSegment::from_ident(ident);
1822 seg.id = self.session.next_node_id();
1827 impl<'a> Resolver<'a> {
1828 pub fn new(session: &'a Session,
1832 crate_loader: &'a mut CrateLoader<'a>,
1833 arenas: &'a ResolverArenas<'a>)
1835 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1836 let root_module_kind = ModuleKind::Def(Def::Mod(root_def_id), keywords::Invalid.name());
1837 let graph_root = arenas.alloc_module(ModuleData {
1838 no_implicit_prelude: attr::contains_name(&krate.attrs, "no_implicit_prelude"),
1839 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1841 let mut module_map = FxHashMap::default();
1842 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1844 let mut definitions = Definitions::new();
1845 DefCollector::new(&mut definitions, Mark::root())
1846 .collect_root(crate_name, session.local_crate_disambiguator());
1848 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> =
1849 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1852 if !attr::contains_name(&krate.attrs, "no_core") {
1853 extern_prelude.insert(Ident::from_str("core"), Default::default());
1854 if !attr::contains_name(&krate.attrs, "no_std") {
1855 extern_prelude.insert(Ident::from_str("std"), Default::default());
1856 if session.rust_2018() {
1857 extern_prelude.insert(Ident::from_str("meta"), Default::default());
1862 let mut invocations = FxHashMap::default();
1863 invocations.insert(Mark::root(),
1864 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1866 let mut macro_defs = FxHashMap::default();
1867 macro_defs.insert(Mark::root(), root_def_id);
1876 // The outermost module has def ID 0; this is not reflected in the
1882 has_self: FxHashSet::default(),
1883 field_names: FxHashMap::default(),
1885 determined_imports: Vec::new(),
1886 indeterminate_imports: Vec::new(),
1888 current_module: graph_root,
1890 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1891 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1892 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1894 label_ribs: Vec::new(),
1896 current_trait_ref: None,
1897 current_self_type: None,
1898 current_self_item: None,
1899 last_import_segment: false,
1900 blacklisted_binding: None,
1902 primitive_type_table: PrimitiveTypeTable::new(),
1904 def_map: Default::default(),
1905 import_map: Default::default(),
1906 freevars: Default::default(),
1907 freevars_seen: Default::default(),
1908 export_map: FxHashMap::default(),
1909 trait_map: Default::default(),
1911 block_map: Default::default(),
1912 extern_module_map: FxHashMap::default(),
1913 binding_parent_modules: FxHashMap::default(),
1915 glob_map: Default::default(),
1917 used_imports: FxHashSet::default(),
1918 maybe_unused_trait_imports: Default::default(),
1919 maybe_unused_extern_crates: Vec::new(),
1921 unused_labels: FxHashMap::default(),
1923 privacy_errors: Vec::new(),
1924 ambiguity_errors: Vec::new(),
1925 use_injections: Vec::new(),
1926 macro_expanded_macro_export_errors: BTreeSet::new(),
1929 dummy_binding: arenas.alloc_name_binding(NameBinding {
1930 kind: NameBindingKind::Def(Def::Err, false),
1932 expansion: Mark::root(),
1934 vis: ty::Visibility::Public,
1938 macro_names: FxHashSet::default(),
1939 builtin_macros: FxHashMap::default(),
1940 macro_use_prelude: FxHashMap::default(),
1941 all_macros: FxHashMap::default(),
1942 macro_map: FxHashMap::default(),
1945 local_macro_def_scopes: FxHashMap::default(),
1946 name_already_seen: FxHashMap::default(),
1947 potentially_unused_imports: Vec::new(),
1948 struct_constructors: Default::default(),
1949 unused_macros: FxHashSet::default(),
1950 current_type_ascription: Vec::new(),
1951 injected_crate: None,
1955 pub fn arenas() -> ResolverArenas<'a> {
1959 /// Runs the function on each namespace.
1960 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1966 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1968 match self.macro_defs.get(&ctxt.outer()) {
1969 Some(&def_id) => return def_id,
1970 None => ctxt.remove_mark(),
1975 /// Entry point to crate resolution.
1976 pub fn resolve_crate(&mut self, krate: &Crate) {
1977 ImportResolver { resolver: self }.finalize_imports();
1978 self.current_module = self.graph_root;
1979 self.finalize_current_module_macro_resolutions();
1981 visit::walk_crate(self, krate);
1983 check_unused::check_crate(self, krate);
1984 self.report_errors(krate);
1985 self.crate_loader.postprocess(krate);
1992 normal_ancestor_id: DefId,
1996 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
1997 self.arenas.alloc_module(module)
2000 fn record_use(&mut self, ident: Ident, ns: Namespace,
2001 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
2002 if let Some((b2, kind)) = used_binding.ambiguity {
2003 self.ambiguity_errors.push(AmbiguityError {
2004 kind, ident, b1: used_binding, b2,
2005 misc1: AmbiguityErrorMisc::None,
2006 misc2: AmbiguityErrorMisc::None,
2009 if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
2010 // Avoid marking `extern crate` items that refer to a name from extern prelude,
2011 // but not introduce it, as used if they are accessed from lexical scope.
2012 if is_lexical_scope {
2013 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
2014 if let Some(crate_item) = entry.extern_crate_item {
2015 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
2022 directive.used.set(true);
2023 self.used_imports.insert((directive.id, ns));
2024 self.add_to_glob_map(&directive, ident);
2025 self.record_use(ident, ns, binding, false);
2030 fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
2031 if directive.is_glob() {
2032 self.glob_map.entry(directive.id).or_default().insert(ident.name);
2036 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2037 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2038 /// `ident` in the first scope that defines it (or None if no scopes define it).
2040 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2041 /// the items are defined in the block. For example,
2044 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2047 /// g(); // This resolves to the local variable `g` since it shadows the item.
2051 /// Invariant: This must only be called during main resolution, not during
2052 /// import resolution.
2053 fn resolve_ident_in_lexical_scope(&mut self,
2056 record_used_id: Option<NodeId>,
2058 -> Option<LexicalScopeBinding<'a>> {
2059 assert!(ns == TypeNS || ns == ValueNS);
2060 if ident.name == keywords::Invalid.name() {
2061 return Some(LexicalScopeBinding::Def(Def::Err));
2063 ident.span = if ident.name == keywords::SelfUpper.name() {
2064 // FIXME(jseyfried) improve `Self` hygiene
2065 ident.span.with_ctxt(SyntaxContext::empty())
2066 } else if ns == TypeNS {
2069 ident.span.modern_and_legacy()
2072 // Walk backwards up the ribs in scope.
2073 let record_used = record_used_id.is_some();
2074 let mut module = self.graph_root;
2075 for i in (0 .. self.ribs[ns].len()).rev() {
2076 debug!("walk rib\n{:?}", self.ribs[ns][i].bindings);
2077 if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2078 // The ident resolves to a type parameter or local variable.
2079 return Some(LexicalScopeBinding::Def(
2080 self.adjust_local_def(ns, i, def, record_used, path_span)
2084 module = match self.ribs[ns][i].kind {
2085 ModuleRibKind(module) => module,
2086 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2087 // If an invocation of this macro created `ident`, give up on `ident`
2088 // and switch to `ident`'s source from the macro definition.
2089 ident.span.remove_mark();
2095 let item = self.resolve_ident_in_module_unadjusted(
2096 ModuleOrUniformRoot::Module(module),
2102 if let Ok(binding) = item {
2103 // The ident resolves to an item.
2104 return Some(LexicalScopeBinding::Item(binding));
2108 ModuleKind::Block(..) => {}, // We can see through blocks
2113 ident.span = ident.span.modern();
2114 let mut poisoned = None;
2116 let opt_module = if let Some(node_id) = record_used_id {
2117 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2118 node_id, &mut poisoned)
2120 self.hygienic_lexical_parent(module, &mut ident.span)
2122 module = unwrap_or!(opt_module, break);
2123 let orig_current_module = self.current_module;
2124 self.current_module = module; // Lexical resolutions can never be a privacy error.
2125 let result = self.resolve_ident_in_module_unadjusted(
2126 ModuleOrUniformRoot::Module(module),
2132 self.current_module = orig_current_module;
2136 if let Some(node_id) = poisoned {
2137 self.session.buffer_lint_with_diagnostic(
2138 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2139 node_id, ident.span,
2140 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2141 lint::builtin::BuiltinLintDiagnostics::
2142 ProcMacroDeriveResolutionFallback(ident.span),
2145 return Some(LexicalScopeBinding::Item(binding))
2147 Err(Determined) => continue,
2148 Err(Undetermined) =>
2149 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2153 if !module.no_implicit_prelude {
2155 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2156 return Some(LexicalScopeBinding::Item(binding));
2159 if ns == TypeNS && is_known_tool(ident.name) {
2160 let binding = (Def::ToolMod, ty::Visibility::Public,
2161 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2162 return Some(LexicalScopeBinding::Item(binding));
2164 if let Some(prelude) = self.prelude {
2165 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2166 ModuleOrUniformRoot::Module(prelude),
2172 return Some(LexicalScopeBinding::Item(binding));
2180 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2181 -> Option<Module<'a>> {
2182 if !module.expansion.is_descendant_of(span.ctxt().outer()) {
2183 return Some(self.macro_def_scope(span.remove_mark()));
2186 if let ModuleKind::Block(..) = module.kind {
2187 return Some(module.parent.unwrap());
2193 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2194 span: &mut Span, node_id: NodeId,
2195 poisoned: &mut Option<NodeId>)
2196 -> Option<Module<'a>> {
2197 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2201 // We need to support the next case under a deprecation warning
2204 // ---- begin: this comes from a proc macro derive
2205 // mod implementation_details {
2206 // // Note that `MyStruct` is not in scope here.
2207 // impl SomeTrait for MyStruct { ... }
2211 // So we have to fall back to the module's parent during lexical resolution in this case.
2212 if let Some(parent) = module.parent {
2213 // Inner module is inside the macro, parent module is outside of the macro.
2214 if module.expansion != parent.expansion &&
2215 module.expansion.is_descendant_of(parent.expansion) {
2216 // The macro is a proc macro derive
2217 if module.expansion.looks_like_proc_macro_derive() {
2218 if parent.expansion.is_descendant_of(span.ctxt().outer()) {
2219 *poisoned = Some(node_id);
2220 return module.parent;
2229 fn resolve_ident_in_module(
2231 module: ModuleOrUniformRoot<'a>,
2234 parent_scope: Option<&ParentScope<'a>>,
2237 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2238 self.resolve_ident_in_module_ext(
2239 module, ident, ns, parent_scope, record_used, path_span
2240 ).map_err(|(determinacy, _)| determinacy)
2243 fn resolve_ident_in_module_ext(
2245 module: ModuleOrUniformRoot<'a>,
2248 parent_scope: Option<&ParentScope<'a>>,
2251 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2252 let orig_current_module = self.current_module;
2254 ModuleOrUniformRoot::Module(module) => {
2255 ident.span = ident.span.modern();
2256 if let Some(def) = ident.span.adjust(module.expansion) {
2257 self.current_module = self.macro_def_scope(def);
2260 ModuleOrUniformRoot::ExternPrelude => {
2261 ident.span = ident.span.modern();
2262 ident.span.adjust(Mark::root());
2264 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2265 ModuleOrUniformRoot::CurrentScope => {
2269 let result = self.resolve_ident_in_module_unadjusted_ext(
2270 module, ident, ns, parent_scope, false, record_used, path_span,
2272 self.current_module = orig_current_module;
2276 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2277 let mut ctxt = ident.span.ctxt();
2278 let mark = if ident.name == keywords::DollarCrate.name() {
2279 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2280 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2281 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2282 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2283 // definitions actually produced by `macro` and `macro` definitions produced by
2284 // `macro_rules!`, but at least such configurations are not stable yet.
2285 ctxt = ctxt.modern_and_legacy();
2286 let mut iter = ctxt.marks().into_iter().rev().peekable();
2287 let mut result = None;
2288 // Find the last modern mark from the end if it exists.
2289 while let Some(&(mark, transparency)) = iter.peek() {
2290 if transparency == Transparency::Opaque {
2291 result = Some(mark);
2297 // Then find the last legacy mark from the end if it exists.
2298 for (mark, transparency) in iter {
2299 if transparency == Transparency::SemiTransparent {
2300 result = Some(mark);
2307 ctxt = ctxt.modern();
2308 ctxt.adjust(Mark::root())
2310 let module = match mark {
2311 Some(def) => self.macro_def_scope(def),
2312 None => return self.graph_root,
2314 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2317 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2318 let mut module = self.get_module(module.normal_ancestor_id);
2319 while module.span.ctxt().modern() != *ctxt {
2320 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2321 module = self.get_module(parent.normal_ancestor_id);
2328 // We maintain a list of value ribs and type ribs.
2330 // Simultaneously, we keep track of the current position in the module
2331 // graph in the `current_module` pointer. When we go to resolve a name in
2332 // the value or type namespaces, we first look through all the ribs and
2333 // then query the module graph. When we resolve a name in the module
2334 // namespace, we can skip all the ribs (since nested modules are not
2335 // allowed within blocks in Rust) and jump straight to the current module
2338 // Named implementations are handled separately. When we find a method
2339 // call, we consult the module node to find all of the implementations in
2340 // scope. This information is lazily cached in the module node. We then
2341 // generate a fake "implementation scope" containing all the
2342 // implementations thus found, for compatibility with old resolve pass.
2344 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2345 where F: FnOnce(&mut Resolver<'_>) -> T
2347 let id = self.definitions.local_def_id(id);
2348 let module = self.module_map.get(&id).cloned(); // clones a reference
2349 if let Some(module) = module {
2350 // Move down in the graph.
2351 let orig_module = replace(&mut self.current_module, module);
2352 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2353 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2355 self.finalize_current_module_macro_resolutions();
2358 self.current_module = orig_module;
2359 self.ribs[ValueNS].pop();
2360 self.ribs[TypeNS].pop();
2367 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
2368 /// is returned by the given predicate function
2370 /// Stops after meeting a closure.
2371 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2372 where P: Fn(&Rib<'_>, Ident) -> Option<R>
2374 for rib in self.label_ribs.iter().rev() {
2377 // If an invocation of this macro created `ident`, give up on `ident`
2378 // and switch to `ident`'s source from the macro definition.
2379 MacroDefinition(def) => {
2380 if def == self.macro_def(ident.span.ctxt()) {
2381 ident.span.remove_mark();
2385 // Do not resolve labels across function boundary
2389 let r = pred(rib, ident);
2397 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2398 debug!("resolve_adt");
2399 self.with_current_self_item(item, |this| {
2400 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2401 let item_def_id = this.definitions.local_def_id(item.id);
2402 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
2403 visit::walk_item(this, item);
2409 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2410 let segments = &use_tree.prefix.segments;
2411 if !segments.is_empty() {
2412 let ident = segments[0].ident;
2413 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2417 let nss = match use_tree.kind {
2418 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2421 let report_error = |this: &Self, ns| {
2422 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2423 this.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2427 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2428 Some(LexicalScopeBinding::Def(..)) => {
2429 report_error(self, ns);
2431 Some(LexicalScopeBinding::Item(binding)) => {
2432 let orig_blacklisted_binding =
2433 mem::replace(&mut self.blacklisted_binding, Some(binding));
2434 if let Some(LexicalScopeBinding::Def(..)) =
2435 self.resolve_ident_in_lexical_scope(ident, ns, None,
2436 use_tree.prefix.span) {
2437 report_error(self, ns);
2439 self.blacklisted_binding = orig_blacklisted_binding;
2444 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2445 for (use_tree, _) in use_trees {
2446 self.future_proof_import(use_tree);
2451 fn resolve_item(&mut self, item: &Item) {
2452 let name = item.ident.name;
2453 debug!("(resolving item) resolving {} ({:?})", name, item.node);
2456 ItemKind::Ty(_, ref generics) |
2457 ItemKind::Fn(_, _, ref generics, _) |
2458 ItemKind::Existential(_, ref generics) => {
2459 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind),
2460 |this| visit::walk_item(this, item));
2463 ItemKind::Enum(_, ref generics) |
2464 ItemKind::Struct(_, ref generics) |
2465 ItemKind::Union(_, ref generics) => {
2466 self.resolve_adt(item, generics);
2469 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2470 self.resolve_implementation(generics,
2476 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2477 // Create a new rib for the trait-wide type parameters.
2478 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2479 let local_def_id = this.definitions.local_def_id(item.id);
2480 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2481 this.visit_generics(generics);
2482 walk_list!(this, visit_param_bound, bounds);
2484 for trait_item in trait_items {
2485 let generic_params = HasGenericParams(&trait_item.generics,
2486 TraitOrImplItemRibKind);
2487 this.with_generic_param_rib(generic_params, |this| {
2488 match trait_item.node {
2489 TraitItemKind::Const(ref ty, ref default) => {
2492 // Only impose the restrictions of
2493 // ConstRibKind for an actual constant
2494 // expression in a provided default.
2495 if let Some(ref expr) = *default{
2496 this.with_constant_rib(|this| {
2497 this.visit_expr(expr);
2501 TraitItemKind::Method(_, _) => {
2502 visit::walk_trait_item(this, trait_item)
2504 TraitItemKind::Type(..) => {
2505 visit::walk_trait_item(this, trait_item)
2507 TraitItemKind::Macro(_) => {
2508 panic!("unexpanded macro in resolve!")
2517 ItemKind::TraitAlias(ref generics, ref bounds) => {
2518 // Create a new rib for the trait-wide type parameters.
2519 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2520 let local_def_id = this.definitions.local_def_id(item.id);
2521 this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
2522 this.visit_generics(generics);
2523 walk_list!(this, visit_param_bound, bounds);
2528 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2529 self.with_scope(item.id, |this| {
2530 visit::walk_item(this, item);
2534 ItemKind::Static(ref ty, _, ref expr) |
2535 ItemKind::Const(ref ty, ref expr) => {
2536 debug!("resolve_item ItemKind::Const");
2537 self.with_item_rib(|this| {
2539 this.with_constant_rib(|this| {
2540 this.visit_expr(expr);
2545 ItemKind::Use(ref use_tree) => {
2546 self.future_proof_import(use_tree);
2549 ItemKind::ExternCrate(..) |
2550 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2551 // do nothing, these are just around to be encoded
2554 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2558 fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F)
2559 where F: FnOnce(&mut Resolver<'_>)
2561 debug!("with_generic_param_rib");
2562 match generic_params {
2563 HasGenericParams(generics, rib_kind) => {
2564 let mut function_type_rib = Rib::new(rib_kind);
2565 let mut function_value_rib = Rib::new(rib_kind);
2566 let mut seen_bindings = FxHashMap::default();
2567 for param in &generics.params {
2569 GenericParamKind::Lifetime { .. } => {}
2570 GenericParamKind::Type { .. } => {
2571 let ident = param.ident.modern();
2572 debug!("with_generic_param_rib: {}", param.id);
2574 if seen_bindings.contains_key(&ident) {
2575 let span = seen_bindings.get(&ident).unwrap();
2576 let err = ResolutionError::NameAlreadyUsedInParameterList(
2580 resolve_error(self, param.ident.span, err);
2582 seen_bindings.entry(ident).or_insert(param.ident.span);
2584 // Plain insert (no renaming).
2585 let def = Def::TyParam(self.definitions.local_def_id(param.id));
2586 function_type_rib.bindings.insert(ident, def);
2587 self.record_def(param.id, PathResolution::new(def));
2589 GenericParamKind::Const { .. } => {
2590 let ident = param.ident.modern();
2591 debug!("with_generic_param_rib: {}", param.id);
2593 if seen_bindings.contains_key(&ident) {
2594 let span = seen_bindings.get(&ident).unwrap();
2595 let err = ResolutionError::NameAlreadyUsedInParameterList(
2599 resolve_error(self, param.ident.span, err);
2601 seen_bindings.entry(ident).or_insert(param.ident.span);
2603 let def = Def::ConstParam(self.definitions.local_def_id(param.id));
2604 function_value_rib.bindings.insert(ident, def);
2605 self.record_def(param.id, PathResolution::new(def));
2609 self.ribs[ValueNS].push(function_value_rib);
2610 self.ribs[TypeNS].push(function_type_rib);
2613 NoGenericParams => {
2620 if let HasGenericParams(..) = generic_params {
2621 self.ribs[TypeNS].pop();
2622 self.ribs[ValueNS].pop();
2626 fn with_label_rib<F>(&mut self, f: F)
2627 where F: FnOnce(&mut Resolver<'_>)
2629 self.label_ribs.push(Rib::new(NormalRibKind));
2631 self.label_ribs.pop();
2634 fn with_item_rib<F>(&mut self, f: F)
2635 where F: FnOnce(&mut Resolver<'_>)
2637 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2638 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2640 self.ribs[TypeNS].pop();
2641 self.ribs[ValueNS].pop();
2644 fn with_constant_rib<F>(&mut self, f: F)
2645 where F: FnOnce(&mut Resolver<'_>)
2647 debug!("with_constant_rib");
2648 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2649 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2651 self.label_ribs.pop();
2652 self.ribs[ValueNS].pop();
2655 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2656 where F: FnOnce(&mut Resolver<'_>) -> T
2658 // Handle nested impls (inside fn bodies)
2659 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2660 let result = f(self);
2661 self.current_self_type = previous_value;
2665 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2666 where F: FnOnce(&mut Resolver<'_>) -> T
2668 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2669 let result = f(self);
2670 self.current_self_item = previous_value;
2674 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2675 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2676 where F: FnOnce(&mut Resolver<'_>, Option<DefId>) -> T
2678 let mut new_val = None;
2679 let mut new_id = None;
2680 if let Some(trait_ref) = opt_trait_ref {
2681 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2682 let def = self.smart_resolve_path_fragment(
2686 trait_ref.path.span,
2687 PathSource::Trait(AliasPossibility::No),
2688 CrateLint::SimplePath(trait_ref.ref_id),
2690 if def != Def::Err {
2691 new_id = Some(def.def_id());
2692 let span = trait_ref.path.span;
2693 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2694 self.resolve_path_without_parent_scope(
2699 CrateLint::SimplePath(trait_ref.ref_id),
2702 new_val = Some((module, trait_ref.clone()));
2706 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2707 let result = f(self, new_id);
2708 self.current_trait_ref = original_trait_ref;
2712 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2713 where F: FnOnce(&mut Resolver<'_>)
2715 let mut self_type_rib = Rib::new(NormalRibKind);
2717 // plain insert (no renaming, types are not currently hygienic....)
2718 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2719 self.ribs[TypeNS].push(self_type_rib);
2721 self.ribs[TypeNS].pop();
2724 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2725 where F: FnOnce(&mut Resolver<'_>)
2727 let self_def = Def::SelfCtor(impl_id);
2728 let mut self_type_rib = Rib::new(NormalRibKind);
2729 self_type_rib.bindings.insert(keywords::SelfUpper.ident(), self_def);
2730 self.ribs[ValueNS].push(self_type_rib);
2732 self.ribs[ValueNS].pop();
2735 fn resolve_implementation(&mut self,
2736 generics: &Generics,
2737 opt_trait_reference: &Option<TraitRef>,
2740 impl_items: &[ImplItem]) {
2741 debug!("resolve_implementation");
2742 // If applicable, create a rib for the type parameters.
2743 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2744 // Dummy self type for better errors if `Self` is used in the trait path.
2745 this.with_self_rib(Def::SelfTy(None, None), |this| {
2746 // Resolve the trait reference, if necessary.
2747 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2748 let item_def_id = this.definitions.local_def_id(item_id);
2749 this.with_self_rib(Def::SelfTy(trait_id, Some(item_def_id)), |this| {
2750 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2751 // Resolve type arguments in the trait path.
2752 visit::walk_trait_ref(this, trait_ref);
2754 // Resolve the self type.
2755 this.visit_ty(self_type);
2756 // Resolve the generic parameters.
2757 this.visit_generics(generics);
2758 // Resolve the items within the impl.
2759 this.with_current_self_type(self_type, |this| {
2760 this.with_self_struct_ctor_rib(item_def_id, |this| {
2761 debug!("resolve_implementation with_self_struct_ctor_rib");
2762 for impl_item in impl_items {
2763 this.resolve_visibility(&impl_item.vis);
2765 // We also need a new scope for the impl item type parameters.
2766 let generic_params = HasGenericParams(&impl_item.generics,
2767 TraitOrImplItemRibKind);
2768 this.with_generic_param_rib(generic_params, |this| {
2769 use self::ResolutionError::*;
2770 match impl_item.node {
2771 ImplItemKind::Const(..) => {
2773 "resolve_implementation ImplItemKind::Const",
2775 // If this is a trait impl, ensure the const
2777 this.check_trait_item(
2781 |n, s| ConstNotMemberOfTrait(n, s),
2784 this.with_constant_rib(|this| {
2785 visit::walk_impl_item(this, impl_item)
2788 ImplItemKind::Method(..) => {
2789 // If this is a trait impl, ensure the method
2791 this.check_trait_item(impl_item.ident,
2794 |n, s| MethodNotMemberOfTrait(n, s));
2796 visit::walk_impl_item(this, impl_item);
2798 ImplItemKind::Type(ref ty) => {
2799 // If this is a trait impl, ensure the type
2801 this.check_trait_item(impl_item.ident,
2804 |n, s| TypeNotMemberOfTrait(n, s));
2808 ImplItemKind::Existential(ref bounds) => {
2809 // If this is a trait impl, ensure the type
2811 this.check_trait_item(impl_item.ident,
2814 |n, s| TypeNotMemberOfTrait(n, s));
2816 for bound in bounds {
2817 this.visit_param_bound(bound);
2820 ImplItemKind::Macro(_) =>
2821 panic!("unexpanded macro in resolve!"),
2833 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2834 where F: FnOnce(Name, &str) -> ResolutionError<'_>
2836 // If there is a TraitRef in scope for an impl, then the method must be in the
2838 if let Some((module, _)) = self.current_trait_ref {
2839 if self.resolve_ident_in_module(
2840 ModuleOrUniformRoot::Module(module),
2847 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2848 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2853 fn resolve_local(&mut self, local: &Local) {
2854 // Resolve the type.
2855 walk_list!(self, visit_ty, &local.ty);
2857 // Resolve the initializer.
2858 walk_list!(self, visit_expr, &local.init);
2860 // Resolve the pattern.
2861 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2864 // build a map from pattern identifiers to binding-info's.
2865 // this is done hygienically. This could arise for a macro
2866 // that expands into an or-pattern where one 'x' was from the
2867 // user and one 'x' came from the macro.
2868 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2869 let mut binding_map = FxHashMap::default();
2871 pat.walk(&mut |pat| {
2872 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2873 if sub_pat.is_some() || match self.def_map.get(&pat.id).map(|res| res.base_def()) {
2874 Some(Def::Local(..)) => true,
2877 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2878 binding_map.insert(ident, binding_info);
2887 // check that all of the arms in an or-pattern have exactly the
2888 // same set of bindings, with the same binding modes for each.
2889 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2890 if pats.is_empty() {
2894 let mut missing_vars = FxHashMap::default();
2895 let mut inconsistent_vars = FxHashMap::default();
2896 for (i, p) in pats.iter().enumerate() {
2897 let map_i = self.binding_mode_map(&p);
2899 for (j, q) in pats.iter().enumerate() {
2904 let map_j = self.binding_mode_map(&q);
2905 for (&key, &binding_i) in &map_i {
2906 if map_j.is_empty() { // Account for missing bindings when
2907 let binding_error = missing_vars // map_j has none.
2909 .or_insert(BindingError {
2911 origin: BTreeSet::new(),
2912 target: BTreeSet::new(),
2914 binding_error.origin.insert(binding_i.span);
2915 binding_error.target.insert(q.span);
2917 for (&key_j, &binding_j) in &map_j {
2918 match map_i.get(&key_j) {
2919 None => { // missing binding
2920 let binding_error = missing_vars
2922 .or_insert(BindingError {
2924 origin: BTreeSet::new(),
2925 target: BTreeSet::new(),
2927 binding_error.origin.insert(binding_j.span);
2928 binding_error.target.insert(p.span);
2930 Some(binding_i) => { // check consistent binding
2931 if binding_i.binding_mode != binding_j.binding_mode {
2934 .or_insert((binding_j.span, binding_i.span));
2942 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
2943 missing_vars.sort();
2944 for (_, v) in missing_vars {
2946 *v.origin.iter().next().unwrap(),
2947 ResolutionError::VariableNotBoundInPattern(v));
2949 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2950 inconsistent_vars.sort();
2951 for (name, v) in inconsistent_vars {
2952 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2956 fn resolve_arm(&mut self, arm: &Arm) {
2957 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2959 let mut bindings_list = FxHashMap::default();
2960 for pattern in &arm.pats {
2961 self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list);
2964 // This has to happen *after* we determine which pat_idents are variants.
2965 self.check_consistent_bindings(&arm.pats);
2967 if let Some(ast::Guard::If(ref expr)) = arm.guard {
2968 self.visit_expr(expr)
2970 self.visit_expr(&arm.body);
2972 self.ribs[ValueNS].pop();
2975 fn resolve_block(&mut self, block: &Block) {
2976 debug!("(resolving block) entering block");
2977 // Move down in the graph, if there's an anonymous module rooted here.
2978 let orig_module = self.current_module;
2979 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
2981 let mut num_macro_definition_ribs = 0;
2982 if let Some(anonymous_module) = anonymous_module {
2983 debug!("(resolving block) found anonymous module, moving down");
2984 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2985 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
2986 self.current_module = anonymous_module;
2987 self.finalize_current_module_macro_resolutions();
2989 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
2992 // Descend into the block.
2993 for stmt in &block.stmts {
2994 if let ast::StmtKind::Item(ref item) = stmt.node {
2995 if let ast::ItemKind::MacroDef(..) = item.node {
2996 num_macro_definition_ribs += 1;
2997 let def = self.definitions.local_def_id(item.id);
2998 self.ribs[ValueNS].push(Rib::new(MacroDefinition(def)));
2999 self.label_ribs.push(Rib::new(MacroDefinition(def)));
3003 self.visit_stmt(stmt);
3007 self.current_module = orig_module;
3008 for _ in 0 .. num_macro_definition_ribs {
3009 self.ribs[ValueNS].pop();
3010 self.label_ribs.pop();
3012 self.ribs[ValueNS].pop();
3013 if anonymous_module.is_some() {
3014 self.ribs[TypeNS].pop();
3016 debug!("(resolving block) leaving block");
3019 fn fresh_binding(&mut self,
3022 outer_pat_id: NodeId,
3023 pat_src: PatternSource,
3024 bindings: &mut FxHashMap<Ident, NodeId>)
3026 // Add the binding to the local ribs, if it
3027 // doesn't already exist in the bindings map. (We
3028 // must not add it if it's in the bindings map
3029 // because that breaks the assumptions later
3030 // passes make about or-patterns.)
3031 let ident = ident.modern_and_legacy();
3032 let mut def = Def::Local(pat_id);
3033 match bindings.get(&ident).cloned() {
3034 Some(id) if id == outer_pat_id => {
3035 // `Variant(a, a)`, error
3039 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
3043 Some(..) if pat_src == PatternSource::FnParam => {
3044 // `fn f(a: u8, a: u8)`, error
3048 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
3052 Some(..) if pat_src == PatternSource::Match ||
3053 pat_src == PatternSource::IfLet ||
3054 pat_src == PatternSource::WhileLet => {
3055 // `Variant1(a) | Variant2(a)`, ok
3056 // Reuse definition from the first `a`.
3057 def = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
3060 span_bug!(ident.span, "two bindings with the same name from \
3061 unexpected pattern source {:?}", pat_src);
3064 // A completely fresh binding, add to the lists if it's valid.
3065 if ident.name != keywords::Invalid.name() {
3066 bindings.insert(ident, outer_pat_id);
3067 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, def);
3072 PathResolution::new(def)
3075 fn resolve_pattern(&mut self,
3077 pat_src: PatternSource,
3078 // Maps idents to the node ID for the
3079 // outermost pattern that binds them.
3080 bindings: &mut FxHashMap<Ident, NodeId>) {
3081 // Visit all direct subpatterns of this pattern.
3082 let outer_pat_id = pat.id;
3083 pat.walk(&mut |pat| {
3084 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3086 PatKind::Ident(bmode, ident, ref opt_pat) => {
3087 // First try to resolve the identifier as some existing
3088 // entity, then fall back to a fresh binding.
3089 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3091 .and_then(LexicalScopeBinding::item);
3092 let resolution = binding.map(NameBinding::def).and_then(|def| {
3093 let is_syntactic_ambiguity = opt_pat.is_none() &&
3094 bmode == BindingMode::ByValue(Mutability::Immutable);
3096 Def::Ctor(_, _, CtorKind::Const) |
3097 Def::Const(..) if is_syntactic_ambiguity => {
3098 // Disambiguate in favor of a unit struct/variant
3099 // or constant pattern.
3100 self.record_use(ident, ValueNS, binding.unwrap(), false);
3101 Some(PathResolution::new(def))
3103 Def::Ctor(..) | Def::Const(..) | Def::Static(..) => {
3104 // This is unambiguously a fresh binding, either syntactically
3105 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3106 // to something unusable as a pattern (e.g., constructor function),
3107 // but we still conservatively report an error, see
3108 // issues/33118#issuecomment-233962221 for one reason why.
3112 ResolutionError::BindingShadowsSomethingUnacceptable(
3113 pat_src.descr(), ident.name, binding.unwrap())
3117 Def::Fn(..) | Def::Err => {
3118 // These entities are explicitly allowed
3119 // to be shadowed by fresh bindings.
3123 span_bug!(ident.span, "unexpected definition for an \
3124 identifier in pattern: {:?}", def);
3127 }).unwrap_or_else(|| {
3128 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3131 self.record_def(pat.id, resolution);
3134 PatKind::TupleStruct(ref path, ..) => {
3135 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3138 PatKind::Path(ref qself, ref path) => {
3139 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3142 PatKind::Struct(ref path, ..) => {
3143 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3151 visit::walk_pat(self, pat);
3154 // High-level and context dependent path resolution routine.
3155 // Resolves the path and records the resolution into definition map.
3156 // If resolution fails tries several techniques to find likely
3157 // resolution candidates, suggest imports or other help, and report
3158 // errors in user friendly way.
3159 fn smart_resolve_path(&mut self,
3161 qself: Option<&QSelf>,
3163 source: PathSource<'_>)
3165 self.smart_resolve_path_with_crate_lint(id, qself, path, source, CrateLint::SimplePath(id))
3168 /// A variant of `smart_resolve_path` where you also specify extra
3169 /// information about where the path came from; this extra info is
3170 /// sometimes needed for the lint that recommends rewriting
3171 /// absolute paths to `crate`, so that it knows how to frame the
3172 /// suggestion. If you are just resolving a path like `foo::bar`
3173 /// that appears in an arbitrary location, then you just want
3174 /// `CrateLint::SimplePath`, which is what `smart_resolve_path`
3175 /// already provides.
3176 fn smart_resolve_path_with_crate_lint(
3179 qself: Option<&QSelf>,
3181 source: PathSource<'_>,
3182 crate_lint: CrateLint
3183 ) -> PathResolution {
3184 self.smart_resolve_path_fragment(
3187 &Segment::from_path(path),
3194 fn smart_resolve_path_fragment(&mut self,
3196 qself: Option<&QSelf>,
3199 source: PathSource<'_>,
3200 crate_lint: CrateLint)
3202 let ns = source.namespace();
3203 let is_expected = &|def| source.is_expected(def);
3205 let report_errors = |this: &mut Self, def: Option<Def>| {
3206 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, def);
3207 let def_id = this.current_module.normal_ancestor_id;
3208 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3209 let better = def.is_some();
3210 this.use_injections.push(UseError { err, candidates, node_id, better });
3211 err_path_resolution()
3214 let resolution = match self.resolve_qpath_anywhere(
3220 source.defer_to_typeck(),
3221 source.global_by_default(),
3224 Some(resolution) if resolution.unresolved_segments() == 0 => {
3225 if is_expected(resolution.base_def()) || resolution.base_def() == Def::Err {
3228 // Add a temporary hack to smooth the transition to new struct ctor
3229 // visibility rules. See #38932 for more details.
3231 if let Def::Struct(def_id) = resolution.base_def() {
3232 if let Some((ctor_def, ctor_vis))
3233 = self.struct_constructors.get(&def_id).cloned() {
3234 if is_expected(ctor_def) && self.is_accessible(ctor_vis) {
3235 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3236 self.session.buffer_lint(lint, id, span,
3237 "private struct constructors are not usable through \
3238 re-exports in outer modules",
3240 res = Some(PathResolution::new(ctor_def));
3245 res.unwrap_or_else(|| report_errors(self, Some(resolution.base_def())))
3248 Some(resolution) if source.defer_to_typeck() => {
3249 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3250 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3251 // it needs to be added to the trait map.
3253 let item_name = path.last().unwrap().ident;
3254 let traits = self.get_traits_containing_item(item_name, ns);
3255 self.trait_map.insert(id, traits);
3259 _ => report_errors(self, None)
3262 if let PathSource::TraitItem(..) = source {} else {
3263 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3264 self.record_def(id, resolution);
3269 /// Only used in a specific case of type ascription suggestions
3271 fn get_colon_suggestion_span(&self, start: Span) -> Span {
3272 let cm = self.session.source_map();
3273 start.to(cm.next_point(start))
3276 fn type_ascription_suggestion(
3278 err: &mut DiagnosticBuilder<'_>,
3281 debug!("type_ascription_suggetion {:?}", base_span);
3282 let cm = self.session.source_map();
3283 let base_snippet = cm.span_to_snippet(base_span);
3284 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3285 if let Some(sp) = self.current_type_ascription.last() {
3288 // Try to find the `:`; bail on first non-':' / non-whitespace.
3289 sp = cm.next_point(sp);
3290 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3291 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3292 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3294 let mut show_label = true;
3295 if line_sp != line_base_sp {
3296 err.span_suggestion_short(
3298 "did you mean to use `;` here instead?",
3300 Applicability::MaybeIncorrect,
3303 let colon_sp = self.get_colon_suggestion_span(sp);
3304 let after_colon_sp = self.get_colon_suggestion_span(
3305 colon_sp.shrink_to_hi(),
3307 if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
3310 err.span_suggestion(
3312 "maybe you meant to write a path separator here",
3314 Applicability::MaybeIncorrect,
3318 if let Ok(base_snippet) = base_snippet {
3319 let mut sp = after_colon_sp;
3321 // Try to find an assignment
3322 sp = cm.next_point(sp);
3323 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
3325 Ok(ref x) if x.as_str() == "=" => {
3326 err.span_suggestion(
3328 "maybe you meant to write an assignment here",
3329 format!("let {}", base_snippet),
3330 Applicability::MaybeIncorrect,
3335 Ok(ref x) if x.as_str() == "\n" => break,
3343 err.span_label(base_span,
3344 "expecting a type here because of type ascription");
3347 } else if !snippet.trim().is_empty() {
3348 debug!("tried to find type ascription `:` token, couldn't find it");
3358 fn self_type_is_available(&mut self, span: Span) -> bool {
3359 let binding = self.resolve_ident_in_lexical_scope(keywords::SelfUpper.ident(),
3360 TypeNS, None, span);
3361 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3364 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3365 let ident = Ident::new(keywords::SelfLower.name(), self_span);
3366 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3367 if let Some(LexicalScopeBinding::Def(def)) = binding { def != Def::Err } else { false }
3370 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3371 fn resolve_qpath_anywhere(&mut self,
3373 qself: Option<&QSelf>,
3375 primary_ns: Namespace,
3377 defer_to_typeck: bool,
3378 global_by_default: bool,
3379 crate_lint: CrateLint)
3380 -> Option<PathResolution> {
3381 let mut fin_res = None;
3382 // FIXME: can't resolve paths in macro namespace yet, macros are
3383 // processed by the little special hack below.
3384 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3385 if i == 0 || ns != primary_ns {
3386 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3387 // If defer_to_typeck, then resolution > no resolution,
3388 // otherwise full resolution > partial resolution > no resolution.
3389 Some(res) if res.unresolved_segments() == 0 || defer_to_typeck =>
3391 res => if fin_res.is_none() { fin_res = res },
3395 if primary_ns != MacroNS &&
3396 (self.macro_names.contains(&path[0].ident.modern()) ||
3397 self.builtin_macros.get(&path[0].ident.name).cloned()
3398 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3399 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3400 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3401 // Return some dummy definition, it's enough for error reporting.
3403 PathResolution::new(Def::Macro(DefId::local(CRATE_DEF_INDEX), MacroKind::Bang))
3409 /// Handles paths that may refer to associated items.
3410 fn resolve_qpath(&mut self,
3412 qself: Option<&QSelf>,
3416 global_by_default: bool,
3417 crate_lint: CrateLint)
3418 -> Option<PathResolution> {
3420 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3421 ns={:?}, span={:?}, global_by_default={:?})",
3430 if let Some(qself) = qself {
3431 if qself.position == 0 {
3432 // This is a case like `<T>::B`, where there is no
3433 // trait to resolve. In that case, we leave the `B`
3434 // segment to be resolved by type-check.
3435 return Some(PathResolution::with_unresolved_segments(
3436 Def::Mod(DefId::local(CRATE_DEF_INDEX)), path.len()
3440 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3442 // Currently, `path` names the full item (`A::B::C`, in
3443 // our example). so we extract the prefix of that that is
3444 // the trait (the slice upto and including
3445 // `qself.position`). And then we recursively resolve that,
3446 // but with `qself` set to `None`.
3448 // However, setting `qself` to none (but not changing the
3449 // span) loses the information about where this path
3450 // *actually* appears, so for the purposes of the crate
3451 // lint we pass along information that this is the trait
3452 // name from a fully qualified path, and this also
3453 // contains the full span (the `CrateLint::QPathTrait`).
3454 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3455 let res = self.smart_resolve_path_fragment(
3458 &path[..=qself.position],
3460 PathSource::TraitItem(ns),
3461 CrateLint::QPathTrait {
3463 qpath_span: qself.path_span,
3467 // The remaining segments (the `C` in our example) will
3468 // have to be resolved by type-check, since that requires doing
3469 // trait resolution.
3470 return Some(PathResolution::with_unresolved_segments(
3471 res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1
3475 let result = match self.resolve_path_without_parent_scope(
3482 PathResult::NonModule(path_res) => path_res,
3483 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3484 PathResolution::new(module.def().unwrap())
3486 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3487 // don't report an error right away, but try to fallback to a primitive type.
3488 // So, we are still able to successfully resolve something like
3490 // use std::u8; // bring module u8 in scope
3491 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3492 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3493 // // not to non-existent std::u8::max_value
3496 // Such behavior is required for backward compatibility.
3497 // The same fallback is used when `a` resolves to nothing.
3498 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3499 PathResult::Failed { .. }
3500 if (ns == TypeNS || path.len() > 1) &&
3501 self.primitive_type_table.primitive_types
3502 .contains_key(&path[0].ident.name) => {
3503 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3504 PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1)
3506 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3507 PathResolution::new(module.def().unwrap()),
3508 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3509 resolve_error(self, span, ResolutionError::FailedToResolve { label, suggestion });
3510 err_path_resolution()
3512 PathResult::Module(..) | PathResult::Failed { .. } => return None,
3513 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3516 if path.len() > 1 && !global_by_default && result.base_def() != Def::Err &&
3517 path[0].ident.name != keywords::PathRoot.name() &&
3518 path[0].ident.name != keywords::DollarCrate.name() {
3519 let unqualified_result = {
3520 match self.resolve_path_without_parent_scope(
3521 &[*path.last().unwrap()],
3527 PathResult::NonModule(path_res) => path_res.base_def(),
3528 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3529 module.def().unwrap(),
3530 _ => return Some(result),
3533 if result.base_def() == unqualified_result {
3534 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3535 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3542 fn resolve_path_without_parent_scope(
3545 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3548 crate_lint: CrateLint,
3549 ) -> PathResult<'a> {
3550 // Macro and import paths must have full parent scope available during resolution,
3551 // other paths will do okay with parent module alone.
3552 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3553 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3554 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3560 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3561 parent_scope: &ParentScope<'a>,
3564 crate_lint: CrateLint,
3565 ) -> PathResult<'a> {
3566 let mut module = None;
3567 let mut allow_super = true;
3568 let mut second_binding = None;
3569 self.current_module = parent_scope.module;
3572 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3573 path_span={:?}, crate_lint={:?})",
3581 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3582 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3583 let record_segment_def = |this: &mut Self, def| {
3585 if let Some(id) = id {
3586 if !this.def_map.contains_key(&id) {
3587 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3588 this.record_def(id, PathResolution::new(def));
3594 let is_last = i == path.len() - 1;
3595 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3596 let name = ident.name;
3598 allow_super &= ns == TypeNS &&
3599 (name == keywords::SelfLower.name() ||
3600 name == keywords::Super.name());
3603 if allow_super && name == keywords::Super.name() {
3604 let mut ctxt = ident.span.ctxt().modern();
3605 let self_module = match i {
3606 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3608 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3612 if let Some(self_module) = self_module {
3613 if let Some(parent) = self_module.parent {
3614 module = Some(ModuleOrUniformRoot::Module(
3615 self.resolve_self(&mut ctxt, parent)));
3619 let msg = "there are too many initial `super`s.".to_string();
3620 return PathResult::Failed {
3624 is_error_from_last_segment: false,
3628 if name == keywords::SelfLower.name() {
3629 let mut ctxt = ident.span.ctxt().modern();
3630 module = Some(ModuleOrUniformRoot::Module(
3631 self.resolve_self(&mut ctxt, self.current_module)));
3634 if name == keywords::PathRoot.name() && ident.span.rust_2018() {
3635 module = Some(ModuleOrUniformRoot::ExternPrelude);
3638 if name == keywords::PathRoot.name() &&
3639 ident.span.rust_2015() && self.session.rust_2018() {
3640 // `::a::b` from 2015 macro on 2018 global edition
3641 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3644 if name == keywords::PathRoot.name() ||
3645 name == keywords::Crate.name() ||
3646 name == keywords::DollarCrate.name() {
3647 // `::a::b`, `crate::a::b` or `$crate::a::b`
3648 module = Some(ModuleOrUniformRoot::Module(
3649 self.resolve_crate_root(ident)));
3655 // Report special messages for path segment keywords in wrong positions.
3656 if ident.is_path_segment_keyword() && i != 0 {
3657 let name_str = if name == keywords::PathRoot.name() {
3658 "crate root".to_string()
3660 format!("`{}`", name)
3662 let label = if i == 1 && path[0].ident.name == keywords::PathRoot.name() {
3663 format!("global paths cannot start with {}", name_str)
3665 format!("{} in paths can only be used in start position", name_str)
3667 return PathResult::Failed {
3671 is_error_from_last_segment: false,
3675 let binding = if let Some(module) = module {
3676 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3677 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3678 assert!(ns == TypeNS);
3679 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3680 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3681 record_used, path_span)
3683 let record_used_id =
3684 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3685 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3686 // we found a locally-imported or available item/module
3687 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3688 // we found a local variable or type param
3689 Some(LexicalScopeBinding::Def(def))
3690 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3691 record_segment_def(self, def);
3692 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3696 _ => Err(Determinacy::determined(record_used)),
3703 second_binding = Some(binding);
3705 let def = binding.def();
3706 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def);
3707 if let Some(next_module) = binding.module() {
3708 module = Some(ModuleOrUniformRoot::Module(next_module));
3709 record_segment_def(self, def);
3710 } else if def == Def::ToolMod && i + 1 != path.len() {
3711 if binding.is_import() {
3712 self.session.struct_span_err(
3713 ident.span, "cannot use a tool module through an import"
3715 binding.span, "the tool module imported here"
3718 let def = Def::NonMacroAttr(NonMacroAttrKind::Tool);
3719 return PathResult::NonModule(PathResolution::new(def));
3720 } else if def == Def::Err {
3721 return PathResult::NonModule(err_path_resolution());
3722 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3723 self.lint_if_path_starts_with_module(
3729 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3730 def, path.len() - i - 1
3733 return PathResult::Failed {
3735 label: format!("not a module `{}`", ident),
3737 is_error_from_last_segment: is_last,
3741 Err(Undetermined) => return PathResult::Indeterminate,
3742 Err(Determined) => {
3743 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3744 if opt_ns.is_some() && !module.is_normal() {
3745 return PathResult::NonModule(PathResolution::with_unresolved_segments(
3746 module.def().unwrap(), path.len() - i
3750 let module_def = match module {
3751 Some(ModuleOrUniformRoot::Module(module)) => module.def(),
3754 let (label, suggestion) = if module_def == self.graph_root.def() {
3755 let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
3756 let mut candidates =
3757 self.lookup_import_candidates(ident, TypeNS, is_mod);
3758 candidates.sort_by_cached_key(|c| {
3759 (c.path.segments.len(), c.path.to_string())
3761 if let Some(candidate) = candidates.get(0) {
3763 String::from("unresolved import"),
3766 String::from("a similar path exists"),
3767 candidate.path.to_string(),
3768 Applicability::MaybeIncorrect,
3771 } else if !ident.is_reserved() {
3772 (format!("maybe a missing `extern crate {};`?", ident), None)
3774 // the parser will already have complained about the keyword being used
3775 return PathResult::NonModule(err_path_resolution());
3778 (format!("use of undeclared type or module `{}`", ident), None)
3780 (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
3782 return PathResult::Failed {
3786 is_error_from_last_segment: is_last,
3792 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3794 PathResult::Module(match module {
3795 Some(module) => module,
3796 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3797 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3801 fn lint_if_path_starts_with_module(
3803 crate_lint: CrateLint,
3806 second_binding: Option<&NameBinding<'_>>,
3808 let (diag_id, diag_span) = match crate_lint {
3809 CrateLint::No => return,
3810 CrateLint::SimplePath(id) => (id, path_span),
3811 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3812 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3815 let first_name = match path.get(0) {
3816 // In the 2018 edition this lint is a hard error, so nothing to do
3817 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3821 // We're only interested in `use` paths which should start with
3822 // `{{root}}` currently.
3823 if first_name != keywords::PathRoot.name() {
3828 // If this import looks like `crate::...` it's already good
3829 Some(Segment { ident, .. }) if ident.name == keywords::Crate.name() => return,
3830 // Otherwise go below to see if it's an extern crate
3832 // If the path has length one (and it's `PathRoot` most likely)
3833 // then we don't know whether we're gonna be importing a crate or an
3834 // item in our crate. Defer this lint to elsewhere
3838 // If the first element of our path was actually resolved to an
3839 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3840 // warning, this looks all good!
3841 if let Some(binding) = second_binding {
3842 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3843 // Careful: we still want to rewrite paths from
3844 // renamed extern crates.
3845 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
3851 let diag = lint::builtin::BuiltinLintDiagnostics
3852 ::AbsPathWithModule(diag_span);
3853 self.session.buffer_lint_with_diagnostic(
3854 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
3856 "absolute paths must start with `self`, `super`, \
3857 `crate`, or an external crate name in the 2018 edition",
3861 // Resolve a local definition, potentially adjusting for closures.
3862 fn adjust_local_def(&mut self,
3867 span: Span) -> Def {
3868 debug!("adjust_local_def");
3869 let ribs = &self.ribs[ns][rib_index + 1..];
3871 // An invalid forward use of a type parameter from a previous default.
3872 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3874 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3876 assert_eq!(def, Def::Err);
3882 span_bug!(span, "unexpected {:?} in bindings", def)
3884 Def::Local(node_id) => {
3885 use ResolutionError::*;
3886 let mut res_err = None;
3890 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
3891 ForwardTyParamBanRibKind => {
3892 // Nothing to do. Continue.
3894 ClosureRibKind(function_id) => {
3897 let seen = self.freevars_seen
3900 if let Some(&index) = seen.get(&node_id) {
3901 def = Def::Upvar(node_id, index, function_id);
3904 let vec = self.freevars
3907 let depth = vec.len();
3908 def = Def::Upvar(node_id, depth, function_id);
3915 seen.insert(node_id, depth);
3918 ItemRibKind | FnItemRibKind | TraitOrImplItemRibKind => {
3919 // This was an attempt to access an upvar inside a
3920 // named function item. This is not allowed, so we
3923 // We don't immediately trigger a resolve error, because
3924 // we want certain other resolution errors (namely those
3925 // emitted for `ConstantItemRibKind` below) to take
3927 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
3930 ConstantItemRibKind => {
3931 // Still doesn't deal with upvars
3933 resolve_error(self, span, AttemptToUseNonConstantValueInConstant);
3939 if let Some(res_err) = res_err {
3940 resolve_error(self, span, res_err);
3944 Def::TyParam(..) | Def::SelfTy(..) => {
3947 NormalRibKind | TraitOrImplItemRibKind | ClosureRibKind(..) |
3948 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
3949 ConstantItemRibKind => {
3950 // Nothing to do. Continue.
3952 ItemRibKind | FnItemRibKind => {
3953 // This was an attempt to use a type parameter outside its scope.
3958 ResolutionError::GenericParamsFromOuterFunction(def),
3966 Def::ConstParam(..) => {
3967 let mut ribs = ribs.iter().peekable();
3968 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
3969 // When declaring const parameters inside function signatures, the first rib
3970 // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
3971 // (spuriously) conflicting with the const param.
3975 if let ItemRibKind | FnItemRibKind = rib.kind {
3976 // This was an attempt to use a const parameter outside its scope.
3981 ResolutionError::GenericParamsFromOuterFunction(def),
3993 fn lookup_assoc_candidate<FilterFn>(&mut self,
3996 filter_fn: FilterFn)
3997 -> Option<AssocSuggestion>
3998 where FilterFn: Fn(Def) -> bool
4000 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4002 TyKind::Path(None, _) => Some(t.id),
4003 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4004 // This doesn't handle the remaining `Ty` variants as they are not
4005 // that commonly the self_type, it might be interesting to provide
4006 // support for those in future.
4011 // Fields are generally expected in the same contexts as locals.
4012 if filter_fn(Def::Local(ast::DUMMY_NODE_ID)) {
4013 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4014 // Look for a field with the same name in the current self_type.
4015 if let Some(resolution) = self.def_map.get(&node_id) {
4016 match resolution.base_def() {
4017 Def::Struct(did) | Def::Union(did)
4018 if resolution.unresolved_segments() == 0 => {
4019 if let Some(field_names) = self.field_names.get(&did) {
4020 if field_names.iter().any(|&field_name| ident.name == field_name) {
4021 return Some(AssocSuggestion::Field);
4031 // Look for associated items in the current trait.
4032 if let Some((module, _)) = self.current_trait_ref {
4033 if let Ok(binding) = self.resolve_ident_in_module(
4034 ModuleOrUniformRoot::Module(module),
4041 let def = binding.def();
4043 return Some(if self.has_self.contains(&def.def_id()) {
4044 AssocSuggestion::MethodWithSelf
4046 AssocSuggestion::AssocItem
4055 fn lookup_typo_candidate<FilterFn>(
4059 filter_fn: FilterFn,
4061 ) -> Option<TypoSuggestion>
4063 FilterFn: Fn(Def) -> bool,
4065 let add_module_candidates = |module: Module<'_>, names: &mut Vec<TypoSuggestion>| {
4066 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4067 if let Some(binding) = resolution.borrow().binding {
4068 if filter_fn(binding.def()) {
4069 names.push(TypoSuggestion {
4070 candidate: ident.name,
4071 article: binding.def().article(),
4072 kind: binding.def().kind_name(),
4079 let mut names = Vec::new();
4080 if path.len() == 1 {
4081 // Search in lexical scope.
4082 // Walk backwards up the ribs in scope and collect candidates.
4083 for rib in self.ribs[ns].iter().rev() {
4084 // Locals and type parameters
4085 for (ident, def) in &rib.bindings {
4086 if filter_fn(*def) {
4087 names.push(TypoSuggestion {
4088 candidate: ident.name,
4089 article: def.article(),
4090 kind: def.kind_name(),
4095 if let ModuleRibKind(module) = rib.kind {
4096 // Items from this module
4097 add_module_candidates(module, &mut names);
4099 if let ModuleKind::Block(..) = module.kind {
4100 // We can see through blocks
4102 // Items from the prelude
4103 if !module.no_implicit_prelude {
4104 names.extend(self.extern_prelude.clone().iter().flat_map(|(ident, _)| {
4106 .maybe_process_path_extern(ident.name, ident.span)
4107 .and_then(|crate_id| {
4108 let crate_mod = Def::Mod(DefId {
4110 index: CRATE_DEF_INDEX,
4113 if filter_fn(crate_mod) {
4114 Some(TypoSuggestion {
4115 candidate: ident.name,
4125 if let Some(prelude) = self.prelude {
4126 add_module_candidates(prelude, &mut names);
4133 // Add primitive types to the mix
4134 if filter_fn(Def::PrimTy(Bool)) {
4136 self.primitive_type_table.primitive_types.iter().map(|(name, _)| {
4140 kind: "primitive type",
4146 // Search in module.
4147 let mod_path = &path[..path.len() - 1];
4148 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4149 mod_path, Some(TypeNS), false, span, CrateLint::No
4151 if let ModuleOrUniformRoot::Module(module) = module {
4152 add_module_candidates(module, &mut names);
4157 let name = path[path.len() - 1].ident.name;
4158 // Make sure error reporting is deterministic.
4159 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
4161 match find_best_match_for_name(
4162 names.iter().map(|suggestion| &suggestion.candidate),
4166 Some(found) if found != name => names
4168 .find(|suggestion| suggestion.candidate == found),
4173 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4174 where F: FnOnce(&mut Resolver<'_>)
4176 if let Some(label) = label {
4177 self.unused_labels.insert(id, label.ident.span);
4178 let def = Def::Label(id);
4179 self.with_label_rib(|this| {
4180 let ident = label.ident.modern_and_legacy();
4181 this.label_ribs.last_mut().unwrap().bindings.insert(ident, def);
4189 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4190 self.with_resolved_label(label, id, |this| this.visit_block(block));
4193 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4194 // First, record candidate traits for this expression if it could
4195 // result in the invocation of a method call.
4197 self.record_candidate_traits_for_expr_if_necessary(expr);
4199 // Next, resolve the node.
4201 ExprKind::Path(ref qself, ref path) => {
4202 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4203 visit::walk_expr(self, expr);
4206 ExprKind::Struct(ref path, ..) => {
4207 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4208 visit::walk_expr(self, expr);
4211 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4212 let def = self.search_label(label.ident, |rib, ident| {
4213 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4217 // Search again for close matches...
4218 // Picks the first label that is "close enough", which is not necessarily
4219 // the closest match
4220 let close_match = self.search_label(label.ident, |rib, ident| {
4221 let names = rib.bindings.iter().map(|(id, _)| &id.name);
4222 find_best_match_for_name(names, &*ident.as_str(), None)
4224 self.record_def(expr.id, err_path_resolution());
4227 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4230 Some(Def::Label(id)) => {
4231 // Since this def is a label, it is never read.
4232 self.record_def(expr.id, PathResolution::new(Def::Label(id)));
4233 self.unused_labels.remove(&id);
4236 span_bug!(expr.span, "label wasn't mapped to a label def!");
4240 // visit `break` argument if any
4241 visit::walk_expr(self, expr);
4244 ExprKind::IfLet(ref pats, ref subexpression, ref if_block, ref optional_else) => {
4245 self.visit_expr(subexpression);
4247 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4248 let mut bindings_list = FxHashMap::default();
4250 self.resolve_pattern(pat, PatternSource::IfLet, &mut bindings_list);
4252 // This has to happen *after* we determine which pat_idents are variants
4253 self.check_consistent_bindings(pats);
4254 self.visit_block(if_block);
4255 self.ribs[ValueNS].pop();
4257 optional_else.as_ref().map(|expr| self.visit_expr(expr));
4260 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4262 ExprKind::While(ref subexpression, ref block, label) => {
4263 self.with_resolved_label(label, expr.id, |this| {
4264 this.visit_expr(subexpression);
4265 this.visit_block(block);
4269 ExprKind::WhileLet(ref pats, ref subexpression, ref block, label) => {
4270 self.with_resolved_label(label, expr.id, |this| {
4271 this.visit_expr(subexpression);
4272 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4273 let mut bindings_list = FxHashMap::default();
4275 this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list);
4277 // This has to happen *after* we determine which pat_idents are variants.
4278 this.check_consistent_bindings(pats);
4279 this.visit_block(block);
4280 this.ribs[ValueNS].pop();
4284 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4285 self.visit_expr(subexpression);
4286 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4287 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4289 self.resolve_labeled_block(label, expr.id, block);
4291 self.ribs[ValueNS].pop();
4294 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4296 // Equivalent to `visit::walk_expr` + passing some context to children.
4297 ExprKind::Field(ref subexpression, _) => {
4298 self.resolve_expr(subexpression, Some(expr));
4300 ExprKind::MethodCall(ref segment, ref arguments) => {
4301 let mut arguments = arguments.iter();
4302 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4303 for argument in arguments {
4304 self.resolve_expr(argument, None);
4306 self.visit_path_segment(expr.span, segment);
4309 ExprKind::Call(ref callee, ref arguments) => {
4310 self.resolve_expr(callee, Some(expr));
4311 for argument in arguments {
4312 self.resolve_expr(argument, None);
4315 ExprKind::Type(ref type_expr, _) => {
4316 self.current_type_ascription.push(type_expr.span);
4317 visit::walk_expr(self, expr);
4318 self.current_type_ascription.pop();
4320 // Resolve the body of async exprs inside the async closure to which they desugar
4321 ExprKind::Async(_, async_closure_id, ref block) => {
4322 let rib_kind = ClosureRibKind(async_closure_id);
4323 self.ribs[ValueNS].push(Rib::new(rib_kind));
4324 self.label_ribs.push(Rib::new(rib_kind));
4325 self.visit_block(&block);
4326 self.label_ribs.pop();
4327 self.ribs[ValueNS].pop();
4329 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4330 // resolve the arguments within the proper scopes so that usages of them inside the
4331 // closure are detected as upvars rather than normal closure arg usages.
4333 _, IsAsync::Async { closure_id: inner_closure_id, .. }, _,
4334 ref fn_decl, ref body, _span,
4336 let rib_kind = ClosureRibKind(expr.id);
4337 self.ribs[ValueNS].push(Rib::new(rib_kind));
4338 self.label_ribs.push(Rib::new(rib_kind));
4339 // Resolve arguments:
4340 let mut bindings_list = FxHashMap::default();
4341 for argument in &fn_decl.inputs {
4342 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4343 self.visit_ty(&argument.ty);
4345 // No need to resolve return type-- the outer closure return type is
4346 // FunctionRetTy::Default
4348 // Now resolve the inner closure
4350 let rib_kind = ClosureRibKind(inner_closure_id);
4351 self.ribs[ValueNS].push(Rib::new(rib_kind));
4352 self.label_ribs.push(Rib::new(rib_kind));
4353 // No need to resolve arguments: the inner closure has none.
4354 // Resolve the return type:
4355 visit::walk_fn_ret_ty(self, &fn_decl.output);
4357 self.visit_expr(body);
4358 self.label_ribs.pop();
4359 self.ribs[ValueNS].pop();
4361 self.label_ribs.pop();
4362 self.ribs[ValueNS].pop();
4365 visit::walk_expr(self, expr);
4370 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4372 ExprKind::Field(_, ident) => {
4373 // FIXME(#6890): Even though you can't treat a method like a
4374 // field, we need to add any trait methods we find that match
4375 // the field name so that we can do some nice error reporting
4376 // later on in typeck.
4377 let traits = self.get_traits_containing_item(ident, ValueNS);
4378 self.trait_map.insert(expr.id, traits);
4380 ExprKind::MethodCall(ref segment, ..) => {
4381 debug!("(recording candidate traits for expr) recording traits for {}",
4383 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4384 self.trait_map.insert(expr.id, traits);
4392 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4393 -> Vec<TraitCandidate> {
4394 debug!("(getting traits containing item) looking for '{}'", ident.name);
4396 let mut found_traits = Vec::new();
4397 // Look for the current trait.
4398 if let Some((module, _)) = self.current_trait_ref {
4399 if self.resolve_ident_in_module(
4400 ModuleOrUniformRoot::Module(module),
4407 let def_id = module.def_id().unwrap();
4408 found_traits.push(TraitCandidate { def_id: def_id, import_id: None });
4412 ident.span = ident.span.modern();
4413 let mut search_module = self.current_module;
4415 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4416 search_module = unwrap_or!(
4417 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4421 if let Some(prelude) = self.prelude {
4422 if !search_module.no_implicit_prelude {
4423 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4430 fn get_traits_in_module_containing_item(&mut self,
4434 found_traits: &mut Vec<TraitCandidate>) {
4435 assert!(ns == TypeNS || ns == ValueNS);
4436 let mut traits = module.traits.borrow_mut();
4437 if traits.is_none() {
4438 let mut collected_traits = Vec::new();
4439 module.for_each_child(|name, ns, binding| {
4440 if ns != TypeNS { return }
4441 if let Def::Trait(_) = binding.def() {
4442 collected_traits.push((name, binding));
4445 *traits = Some(collected_traits.into_boxed_slice());
4448 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4449 let module = binding.module().unwrap();
4450 let mut ident = ident;
4451 if ident.span.glob_adjust(module.expansion, binding.span.ctxt().modern()).is_none() {
4454 if self.resolve_ident_in_module_unadjusted(
4455 ModuleOrUniformRoot::Module(module),
4461 let import_id = match binding.kind {
4462 NameBindingKind::Import { directive, .. } => {
4463 self.maybe_unused_trait_imports.insert(directive.id);
4464 self.add_to_glob_map(&directive, trait_name);
4469 let trait_def_id = module.def_id().unwrap();
4470 found_traits.push(TraitCandidate { def_id: trait_def_id, import_id: import_id });
4475 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4476 lookup_ident: Ident,
4477 namespace: Namespace,
4478 start_module: &'a ModuleData<'a>,
4480 filter_fn: FilterFn)
4481 -> Vec<ImportSuggestion>
4482 where FilterFn: Fn(Def) -> bool
4484 let mut candidates = Vec::new();
4485 let mut seen_modules = FxHashSet::default();
4486 let not_local_module = crate_name != keywords::Crate.ident();
4487 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4489 while let Some((in_module,
4491 in_module_is_extern)) = worklist.pop() {
4492 self.populate_module_if_necessary(in_module);
4494 // We have to visit module children in deterministic order to avoid
4495 // instabilities in reported imports (#43552).
4496 in_module.for_each_child_stable(|ident, ns, name_binding| {
4497 // avoid imports entirely
4498 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4499 // avoid non-importable candidates as well
4500 if !name_binding.is_importable() { return; }
4502 // collect results based on the filter function
4503 if ident.name == lookup_ident.name && ns == namespace {
4504 let def = name_binding.def();
4507 let mut segms = path_segments.clone();
4508 if lookup_ident.span.rust_2018() {
4509 // crate-local absolute paths start with `crate::` in edition 2018
4510 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4512 0, ast::PathSegment::from_ident(crate_name)
4516 segms.push(ast::PathSegment::from_ident(ident));
4518 span: name_binding.span,
4521 // the entity is accessible in the following cases:
4522 // 1. if it's defined in the same crate, it's always
4523 // accessible (since private entities can be made public)
4524 // 2. if it's defined in another crate, it's accessible
4525 // only if both the module is public and the entity is
4526 // declared as public (due to pruning, we don't explore
4527 // outside crate private modules => no need to check this)
4528 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4529 let did = match def {
4530 Def::Ctor(did, ..) => self.parent(did),
4531 _ => def.opt_def_id(),
4533 candidates.push(ImportSuggestion { did, path });
4538 // collect submodules to explore
4539 if let Some(module) = name_binding.module() {
4541 let mut path_segments = path_segments.clone();
4542 path_segments.push(ast::PathSegment::from_ident(ident));
4544 let is_extern_crate_that_also_appears_in_prelude =
4545 name_binding.is_extern_crate() &&
4546 lookup_ident.span.rust_2018();
4548 let is_visible_to_user =
4549 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4551 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4552 // add the module to the lookup
4553 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4554 if seen_modules.insert(module.def_id().unwrap()) {
4555 worklist.push((module, path_segments, is_extern));
4565 /// When name resolution fails, this method can be used to look up candidate
4566 /// entities with the expected name. It allows filtering them using the
4567 /// supplied predicate (which should be used to only accept the types of
4568 /// definitions expected, e.g., traits). The lookup spans across all crates.
4570 /// N.B., the method does not look into imports, but this is not a problem,
4571 /// since we report the definitions (thus, the de-aliased imports).
4572 fn lookup_import_candidates<FilterFn>(&mut self,
4573 lookup_ident: Ident,
4574 namespace: Namespace,
4575 filter_fn: FilterFn)
4576 -> Vec<ImportSuggestion>
4577 where FilterFn: Fn(Def) -> bool
4579 let mut suggestions = self.lookup_import_candidates_from_module(
4580 lookup_ident, namespace, self.graph_root, keywords::Crate.ident(), &filter_fn);
4582 if lookup_ident.span.rust_2018() {
4583 let extern_prelude_names = self.extern_prelude.clone();
4584 for (ident, _) in extern_prelude_names.into_iter() {
4585 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4587 let crate_root = self.get_module(DefId {
4589 index: CRATE_DEF_INDEX,
4591 self.populate_module_if_necessary(&crate_root);
4593 suggestions.extend(self.lookup_import_candidates_from_module(
4594 lookup_ident, namespace, crate_root, ident, &filter_fn));
4602 fn find_module(&mut self,
4604 -> Option<(Module<'a>, ImportSuggestion)>
4606 let mut result = None;
4607 let mut seen_modules = FxHashSet::default();
4608 let mut worklist = vec![(self.graph_root, Vec::new())];
4610 while let Some((in_module, path_segments)) = worklist.pop() {
4611 // abort if the module is already found
4612 if result.is_some() { break; }
4614 self.populate_module_if_necessary(in_module);
4616 in_module.for_each_child_stable(|ident, _, name_binding| {
4617 // abort if the module is already found or if name_binding is private external
4618 if result.is_some() || !name_binding.vis.is_visible_locally() {
4621 if let Some(module) = name_binding.module() {
4623 let mut path_segments = path_segments.clone();
4624 path_segments.push(ast::PathSegment::from_ident(ident));
4625 if module.def() == Some(module_def) {
4627 span: name_binding.span,
4628 segments: path_segments,
4630 let did = module.def().and_then(|def| def.opt_def_id());
4631 result = Some((module, ImportSuggestion { did, path }));
4633 // add the module to the lookup
4634 if seen_modules.insert(module.def_id().unwrap()) {
4635 worklist.push((module, path_segments));
4645 fn collect_enum_variants(&mut self, enum_def: Def) -> Option<Vec<Path>> {
4646 if let Def::Enum(..) = enum_def {} else {
4647 panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def)
4650 self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| {
4651 self.populate_module_if_necessary(enum_module);
4653 let mut variants = Vec::new();
4654 enum_module.for_each_child_stable(|ident, _, name_binding| {
4655 if let Def::Variant(..) = name_binding.def() {
4656 let mut segms = enum_import_suggestion.path.segments.clone();
4657 segms.push(ast::PathSegment::from_ident(ident));
4658 variants.push(Path {
4659 span: name_binding.span,
4668 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
4669 debug!("(recording def) recording {:?} for {}", resolution, node_id);
4670 if let Some(prev_res) = self.def_map.insert(node_id, resolution) {
4671 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4675 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4677 ast::VisibilityKind::Public => ty::Visibility::Public,
4678 ast::VisibilityKind::Crate(..) => {
4679 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4681 ast::VisibilityKind::Inherited => {
4682 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4684 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4685 // For visibilities we are not ready to provide correct implementation of "uniform
4686 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4687 // On 2015 edition visibilities are resolved as crate-relative by default,
4688 // so we are prepending a root segment if necessary.
4689 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4690 let crate_root = if ident.is_path_segment_keyword() {
4692 } else if ident.span.rust_2018() {
4693 let msg = "relative paths are not supported in visibilities on 2018 edition";
4694 self.session.struct_span_err(ident.span, msg)
4698 format!("crate::{}", path),
4699 Applicability::MaybeIncorrect,
4702 return ty::Visibility::Public;
4704 let ctxt = ident.span.ctxt();
4705 Some(Segment::from_ident(Ident::new(
4706 keywords::PathRoot.name(), path.span.shrink_to_lo().with_ctxt(ctxt)
4710 let segments = crate_root.into_iter()
4711 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4712 let def = self.smart_resolve_path_fragment(
4717 PathSource::Visibility,
4718 CrateLint::SimplePath(id),
4720 if def == Def::Err {
4721 ty::Visibility::Public
4723 let vis = ty::Visibility::Restricted(def.def_id());
4724 if self.is_accessible(vis) {
4727 self.session.span_err(path.span, "visibilities can only be restricted \
4728 to ancestor modules");
4729 ty::Visibility::Public
4736 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4737 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4740 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4741 vis.is_accessible_from(module.normal_ancestor_id, self)
4744 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4745 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4746 if !ptr::eq(module, old_module) {
4747 span_bug!(binding.span, "parent module is reset for binding");
4752 fn disambiguate_legacy_vs_modern(
4754 legacy: &'a NameBinding<'a>,
4755 modern: &'a NameBinding<'a>,
4757 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4758 // is disambiguated to mitigate regressions from macro modularization.
4759 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4760 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4761 self.binding_parent_modules.get(&PtrKey(modern))) {
4762 (Some(legacy), Some(modern)) =>
4763 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4764 modern.is_ancestor_of(legacy),
4769 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
4770 if b.span.is_dummy() {
4771 let add_built_in = match b.def() {
4772 // These already contain the "built-in" prefix or look bad with it.
4773 Def::NonMacroAttr(..) | Def::PrimTy(..) | Def::ToolMod => false,
4776 let (built_in, from) = if from_prelude {
4777 ("", " from prelude")
4778 } else if b.is_extern_crate() && !b.is_import() &&
4779 self.session.opts.externs.get(&ident.as_str()).is_some() {
4780 ("", " passed with `--extern`")
4781 } else if add_built_in {
4787 let article = if built_in.is_empty() { b.article() } else { "a" };
4788 format!("{a}{built_in} {thing}{from}",
4789 a = article, thing = b.descr(), built_in = built_in, from = from)
4791 let introduced = if b.is_import() { "imported" } else { "defined" };
4792 format!("the {thing} {introduced} here",
4793 thing = b.descr(), introduced = introduced)
4797 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
4798 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4799 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4800 // We have to print the span-less alternative first, otherwise formatting looks bad.
4801 (b2, b1, misc2, misc1, true)
4803 (b1, b2, misc1, misc2, false)
4806 let mut err = struct_span_err!(self.session, ident.span, E0659,
4807 "`{ident}` is ambiguous ({why})",
4808 ident = ident, why = kind.descr());
4809 err.span_label(ident.span, "ambiguous name");
4811 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
4812 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4813 let note_msg = format!("`{ident}` could{also} refer to {what}",
4814 ident = ident, also = also, what = what);
4816 let mut help_msgs = Vec::new();
4817 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4818 kind == AmbiguityKind::GlobVsExpanded ||
4819 kind == AmbiguityKind::GlobVsOuter &&
4820 swapped != also.is_empty()) {
4821 help_msgs.push(format!("consider adding an explicit import of \
4822 `{ident}` to disambiguate", ident = ident))
4824 if b.is_extern_crate() && ident.span.rust_2018() {
4825 help_msgs.push(format!(
4826 "use `::{ident}` to refer to this {thing} unambiguously",
4827 ident = ident, thing = b.descr(),
4830 if misc == AmbiguityErrorMisc::SuggestCrate {
4831 help_msgs.push(format!(
4832 "use `crate::{ident}` to refer to this {thing} unambiguously",
4833 ident = ident, thing = b.descr(),
4835 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4836 help_msgs.push(format!(
4837 "use `self::{ident}` to refer to this {thing} unambiguously",
4838 ident = ident, thing = b.descr(),
4842 err.span_note(b.span, ¬e_msg);
4843 for (i, help_msg) in help_msgs.iter().enumerate() {
4844 let or = if i == 0 { "" } else { "or " };
4845 err.help(&format!("{}{}", or, help_msg));
4849 could_refer_to(b1, misc1, "");
4850 could_refer_to(b2, misc2, " also");
4854 fn report_errors(&mut self, krate: &Crate) {
4855 self.report_with_use_injections(krate);
4857 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4858 let msg = "macro-expanded `macro_export` macros from the current crate \
4859 cannot be referred to by absolute paths";
4860 self.session.buffer_lint_with_diagnostic(
4861 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4862 CRATE_NODE_ID, span_use, msg,
4863 lint::builtin::BuiltinLintDiagnostics::
4864 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4868 for ambiguity_error in &self.ambiguity_errors {
4869 self.report_ambiguity_error(ambiguity_error);
4872 let mut reported_spans = FxHashSet::default();
4873 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4874 if reported_spans.insert(dedup_span) {
4875 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4876 binding.descr(), ident.name);
4881 fn report_with_use_injections(&mut self, krate: &Crate) {
4882 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4883 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4884 if !candidates.is_empty() {
4885 show_candidates(&mut err, span, &candidates, better, found_use);
4891 fn report_conflict<'b>(&mut self,
4895 new_binding: &NameBinding<'b>,
4896 old_binding: &NameBinding<'b>) {
4897 // Error on the second of two conflicting names
4898 if old_binding.span.lo() > new_binding.span.lo() {
4899 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4902 let container = match parent.kind {
4903 ModuleKind::Def(Def::Mod(_), _) => "module",
4904 ModuleKind::Def(Def::Trait(_), _) => "trait",
4905 ModuleKind::Block(..) => "block",
4909 let old_noun = match old_binding.is_import() {
4911 false => "definition",
4914 let new_participle = match new_binding.is_import() {
4919 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4921 if let Some(s) = self.name_already_seen.get(&name) {
4927 let old_kind = match (ns, old_binding.module()) {
4928 (ValueNS, _) => "value",
4929 (MacroNS, _) => "macro",
4930 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
4931 (TypeNS, Some(module)) if module.is_normal() => "module",
4932 (TypeNS, Some(module)) if module.is_trait() => "trait",
4933 (TypeNS, _) => "type",
4936 let msg = format!("the name `{}` is defined multiple times", name);
4938 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
4939 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
4940 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
4941 true => struct_span_err!(self.session, span, E0254, "{}", msg),
4942 false => struct_span_err!(self.session, span, E0260, "{}", msg),
4944 _ => match (old_binding.is_import(), new_binding.is_import()) {
4945 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
4946 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
4947 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
4951 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
4956 err.span_label(span, format!("`{}` re{} here", name, new_participle));
4958 self.session.source_map().def_span(old_binding.span),
4959 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
4962 // See https://github.com/rust-lang/rust/issues/32354
4963 use NameBindingKind::Import;
4964 let directive = match (&new_binding.kind, &old_binding.kind) {
4965 // If there are two imports where one or both have attributes then prefer removing the
4966 // import without attributes.
4967 (Import { directive: new, .. }, Import { directive: old, .. }) if {
4968 !new_binding.span.is_dummy() && !old_binding.span.is_dummy() &&
4969 (new.has_attributes || old.has_attributes)
4971 if old.has_attributes {
4972 Some((new, new_binding.span, true))
4974 Some((old, old_binding.span, true))
4977 // Otherwise prioritize the new binding.
4978 (Import { directive, .. }, other) if !new_binding.span.is_dummy() =>
4979 Some((directive, new_binding.span, other.is_import())),
4980 (other, Import { directive, .. }) if !old_binding.span.is_dummy() =>
4981 Some((directive, old_binding.span, other.is_import())),
4985 // Check if the target of the use for both bindings is the same.
4986 let duplicate = new_binding.def().opt_def_id() == old_binding.def().opt_def_id();
4987 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
4988 let from_item = self.extern_prelude.get(&ident)
4989 .map(|entry| entry.introduced_by_item)
4991 // Only suggest removing an import if both bindings are to the same def, if both spans
4992 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
4993 // been introduced by a item.
4994 let should_remove_import = duplicate && !has_dummy_span &&
4995 ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
4998 Some((directive, span, true)) if should_remove_import && directive.is_nested() =>
4999 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span),
5000 Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
5001 // Simple case - remove the entire import. Due to the above match arm, this can
5002 // only be a single use so just remove it entirely.
5003 err.tool_only_span_suggestion(
5004 directive.use_span_with_attributes,
5005 "remove unnecessary import",
5007 Applicability::MaybeIncorrect,
5010 Some((directive, span, _)) =>
5011 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span),
5016 self.name_already_seen.insert(name, span);
5019 /// This function adds a suggestion to change the binding name of a new import that conflicts
5020 /// with an existing import.
5022 /// ```ignore (diagnostic)
5023 /// help: you can use `as` to change the binding name of the import
5025 /// LL | use foo::bar as other_bar;
5026 /// | ^^^^^^^^^^^^^^^^^^^^^
5028 fn add_suggestion_for_rename_of_use(
5030 err: &mut DiagnosticBuilder<'_>,
5032 directive: &ImportDirective<'_>,
5035 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5036 format!("Other{}", name)
5038 format!("other_{}", name)
5041 let mut suggestion = None;
5042 match directive.subclass {
5043 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5044 suggestion = Some(format!("self as {}", suggested_name)),
5045 ImportDirectiveSubclass::SingleImport { source, .. } => {
5046 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
5047 .map(|pos| pos as usize) {
5048 if let Ok(snippet) = self.session.source_map()
5049 .span_to_snippet(binding_span) {
5050 if pos <= snippet.len() {
5051 suggestion = Some(format!(
5055 if snippet.ends_with(";") { ";" } else { "" }
5061 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5062 suggestion = Some(format!(
5063 "extern crate {} as {};",
5064 source.unwrap_or(target.name),
5067 _ => unreachable!(),
5070 let rename_msg = "you can use `as` to change the binding name of the import";
5071 if let Some(suggestion) = suggestion {
5072 err.span_suggestion(
5076 Applicability::MaybeIncorrect,
5079 err.span_label(binding_span, rename_msg);
5083 /// This function adds a suggestion to remove a unnecessary binding from an import that is
5084 /// nested. In the following example, this function will be invoked to remove the `a` binding
5085 /// in the second use statement:
5087 /// ```ignore (diagnostic)
5088 /// use issue_52891::a;
5089 /// use issue_52891::{d, a, e};
5092 /// The following suggestion will be added:
5094 /// ```ignore (diagnostic)
5095 /// use issue_52891::{d, a, e};
5096 /// ^-- help: remove unnecessary import
5099 /// If the nested use contains only one import then the suggestion will remove the entire
5102 /// It is expected that the directive provided is a nested import - this isn't checked by the
5103 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
5104 /// as characters expected by span manipulations won't be present.
5105 fn add_suggestion_for_duplicate_nested_use(
5107 err: &mut DiagnosticBuilder<'_>,
5108 directive: &ImportDirective<'_>,
5111 assert!(directive.is_nested());
5112 let message = "remove unnecessary import";
5113 let source_map = self.session.source_map();
5115 // Two examples will be used to illustrate the span manipulations we're doing:
5117 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
5118 // `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
5119 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
5120 // `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
5122 // Find the span of everything after the binding.
5123 // ie. `a, e};` or `a};`
5124 let binding_until_end = binding_span.with_hi(directive.use_span.hi());
5126 // Find everything after the binding but not including the binding.
5127 // ie. `, e};` or `};`
5128 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
5130 // Keep characters in the span until we encounter something that isn't a comma or
5134 // Also note whether a closing brace character was encountered. If there
5135 // was, then later go backwards to remove any trailing commas that are left.
5136 let mut found_closing_brace = false;
5137 let after_binding_until_next_binding = source_map.span_take_while(
5138 after_binding_until_end,
5140 if ch == '}' { found_closing_brace = true; }
5141 ch == ' ' || ch == ','
5145 // Combine the two spans.
5146 // ie. `a, ` or `a`.
5148 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
5149 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
5151 // If there was a closing brace then identify the span to remove any trailing commas from
5152 // previous imports.
5153 if found_closing_brace {
5154 if let Ok(prev_source) = source_map.span_to_prev_source(span) {
5155 // `prev_source` will contain all of the source that came before the span.
5156 // Then split based on a command and take the first (ie. closest to our span)
5157 // snippet. In the example, this is a space.
5158 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
5159 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
5160 if prev_comma.len() > 1 && prev_starting_brace.len() > 1 {
5161 let prev_comma = prev_comma.first().unwrap();
5162 let prev_starting_brace = prev_starting_brace.first().unwrap();
5164 // If the amount of source code before the comma is greater than
5165 // the amount of source code before the starting brace then we've only
5166 // got one item in the nested item (eg. `issue_52891::{self}`).
5167 if prev_comma.len() > prev_starting_brace.len() {
5168 // So just remove the entire line...
5169 err.span_suggestion(
5170 directive.use_span_with_attributes,
5173 Applicability::MaybeIncorrect,
5178 let span = span.with_lo(BytePos(
5179 // Take away the number of bytes for the characters we've found and an
5180 // extra for the comma.
5181 span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1
5183 err.tool_only_span_suggestion(
5184 span, message, String::new(), Applicability::MaybeIncorrect,
5191 err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
5194 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5195 -> Option<&'a NameBinding<'a>> {
5196 if ident.is_path_segment_keyword() {
5197 // Make sure `self`, `super` etc produce an error when passed to here.
5200 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5201 if let Some(binding) = entry.extern_crate_item {
5202 if !speculative && entry.introduced_by_item {
5203 self.record_use(ident, TypeNS, binding, false);
5207 let crate_id = if !speculative {
5208 self.crate_loader.process_path_extern(ident.name, ident.span)
5209 } else if let Some(crate_id) =
5210 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5215 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5216 self.populate_module_if_necessary(&crate_root);
5217 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5218 .to_name_binding(self.arenas))
5224 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5225 namespace == TypeNS && path.len() == 1 && path[0].ident.name == keywords::SelfUpper.name()
5228 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5229 namespace == ValueNS && path.len() == 1 && path[0].ident.name == keywords::SelfLower.name()
5232 fn names_to_string(idents: &[Ident]) -> String {
5233 let mut result = String::new();
5234 for (i, ident) in idents.iter()
5235 .filter(|ident| ident.name != keywords::PathRoot.name())
5238 result.push_str("::");
5240 result.push_str(&ident.as_str());
5245 fn path_names_to_string(path: &Path) -> String {
5246 names_to_string(&path.segments.iter()
5247 .map(|seg| seg.ident)
5248 .collect::<Vec<_>>())
5251 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5252 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5253 let variant_path = &suggestion.path;
5254 let variant_path_string = path_names_to_string(variant_path);
5256 let path_len = suggestion.path.segments.len();
5257 let enum_path = ast::Path {
5258 span: suggestion.path.span,
5259 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5261 let enum_path_string = path_names_to_string(&enum_path);
5263 (variant_path_string, enum_path_string)
5266 /// When an entity with a given name is not available in scope, we search for
5267 /// entities with that name in all crates. This method allows outputting the
5268 /// results of this search in a programmer-friendly way
5269 fn show_candidates(err: &mut DiagnosticBuilder<'_>,
5270 // This is `None` if all placement locations are inside expansions
5272 candidates: &[ImportSuggestion],
5276 // we want consistent results across executions, but candidates are produced
5277 // by iterating through a hash map, so make sure they are ordered:
5278 let mut path_strings: Vec<_> =
5279 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5280 path_strings.sort();
5282 let better = if better { "better " } else { "" };
5283 let msg_diff = match path_strings.len() {
5284 1 => " is found in another module, you can import it",
5285 _ => "s are found in other modules, you can import them",
5287 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5289 if let Some(span) = span {
5290 for candidate in &mut path_strings {
5291 // produce an additional newline to separate the new use statement
5292 // from the directly following item.
5293 let additional_newline = if found_use {
5298 *candidate = format!("use {};\n{}", candidate, additional_newline);
5301 err.span_suggestions(
5304 path_strings.into_iter(),
5305 Applicability::Unspecified,
5310 for candidate in path_strings {
5312 msg.push_str(&candidate);
5317 /// A somewhat inefficient routine to obtain the name of a module.
5318 fn module_to_string(module: Module<'_>) -> Option<String> {
5319 let mut names = Vec::new();
5321 fn collect_mod(names: &mut Vec<Ident>, module: Module<'_>) {
5322 if let ModuleKind::Def(_, name) = module.kind {
5323 if let Some(parent) = module.parent {
5324 names.push(Ident::with_empty_ctxt(name));
5325 collect_mod(names, parent);
5328 // danger, shouldn't be ident?
5329 names.push(Ident::from_str("<opaque>"));
5330 collect_mod(names, module.parent.unwrap());
5333 collect_mod(&mut names, module);
5335 if names.is_empty() {
5338 Some(names_to_string(&names.into_iter()
5340 .collect::<Vec<_>>()))
5343 fn err_path_resolution() -> PathResolution {
5344 PathResolution::new(Def::Err)
5347 #[derive(Copy, Clone, Debug)]
5349 /// Do not issue the lint.
5352 /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
5353 /// In this case, we can take the span of that path.
5356 /// This lint comes from a `use` statement. In this case, what we
5357 /// care about really is the *root* `use` statement; e.g., if we
5358 /// have nested things like `use a::{b, c}`, we care about the
5360 UsePath { root_id: NodeId, root_span: Span },
5362 /// This is the "trait item" from a fully qualified path. For example,
5363 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5364 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5365 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5369 fn node_id(&self) -> Option<NodeId> {
5371 CrateLint::No => None,
5372 CrateLint::SimplePath(id) |
5373 CrateLint::UsePath { root_id: id, .. } |
5374 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5379 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }