1 // ignore-tidy-filelength
3 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
5 #![feature(crate_visibility_modifier)]
6 #![feature(label_break_value)]
8 #![feature(rustc_diagnostic_macros)]
9 #![feature(type_alias_enum_variants)]
11 #![recursion_limit="256"]
13 #![deny(rust_2018_idioms)]
15 #![deny(unused_lifetimes)]
17 pub use rustc::hir::def::{Namespace, PerNS};
19 use GenericParameters::*;
21 use smallvec::smallvec;
23 use rustc::hir::map::{Definitions, DefCollector};
24 use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str};
25 use rustc::middle::cstore::CrateStore;
26 use rustc::session::Session;
28 use rustc::hir::def::{
29 self, DefKind, PartialRes, CtorKind, CtorOf, NonMacroAttrKind, ExportMap
31 use rustc::hir::def::Namespace::*;
32 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
33 use rustc::hir::{TraitCandidate, TraitMap, GlobMap};
34 use rustc::ty::{self, DefIdTree};
35 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
36 use rustc::{bug, span_bug};
38 use rustc_metadata::creader::CrateLoader;
39 use rustc_metadata::cstore::CStore;
41 use syntax::source_map::SourceMap;
42 use syntax::ext::hygiene::{Mark, Transparency, SyntaxContext};
43 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
44 use syntax::ext::base::{SyntaxExtension, SyntaxExtensionKind};
45 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
46 use syntax::ext::base::MacroKind;
47 use syntax::symbol::{Symbol, kw, sym};
48 use syntax::util::lev_distance::find_best_match_for_name;
50 use syntax::visit::{self, FnKind, Visitor};
52 use syntax::ast::{CRATE_NODE_ID, Arm, IsAsync, BindingMode, Block, Crate, Expr, ExprKind};
53 use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
54 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
55 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
56 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
58 use syntax::{span_err, struct_span_err, unwrap_or, walk_list};
60 use syntax_pos::{Span, DUMMY_SP, MultiSpan};
61 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
65 use std::cell::{Cell, RefCell};
66 use std::{cmp, fmt, iter, mem, ptr};
67 use std::collections::BTreeSet;
68 use std::mem::replace;
69 use rustc_data_structures::ptr_key::PtrKey;
70 use rustc_data_structures::sync::Lrc;
71 use smallvec::SmallVec;
73 use diagnostics::{find_span_of_binding_until_next_binding, extend_span_to_previous_binding};
74 use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
75 use macros::{InvocationData, LegacyBinding, ParentScope};
77 type Res = def::Res<NodeId>;
79 // N.B., this module needs to be declared first so diagnostics are
80 // registered before they are used.
85 mod build_reduced_graph;
88 fn is_known_tool(name: Name) -> bool {
89 ["clippy", "rustfmt"].contains(&&*name.as_str())
99 AbsolutePath(Namespace),
104 /// A free importable items suggested in case of resolution failure.
105 struct ImportSuggestion {
110 /// A field or associated item from self type suggested in case of resolution failure.
111 enum AssocSuggestion {
118 struct BindingError {
120 origin: BTreeSet<Span>,
121 target: BTreeSet<Span>,
124 struct TypoSuggestion {
127 /// The kind of the binding ("crate", "module", etc.)
130 /// An appropriate article to refer to the binding ("a", "an", etc.)
131 article: &'static str,
134 impl PartialOrd for BindingError {
135 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
136 Some(self.cmp(other))
140 impl PartialEq for BindingError {
141 fn eq(&self, other: &BindingError) -> bool {
142 self.name == other.name
146 impl Ord for BindingError {
147 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
148 self.name.cmp(&other.name)
152 /// A vector of spans and replacements, a message and applicability.
153 type Suggestion = (Vec<(Span, String)>, String, Applicability);
155 enum ResolutionError<'a> {
156 /// Error E0401: can't use type or const parameters from outer function.
157 GenericParamsFromOuterFunction(Res),
158 /// Error E0403: the name is already used for a type or const parameter in this generic
160 NameAlreadyUsedInParameterList(Name, &'a Span),
161 /// Error E0407: method is not a member of trait.
162 MethodNotMemberOfTrait(Name, &'a str),
163 /// Error E0437: type is not a member of trait.
164 TypeNotMemberOfTrait(Name, &'a str),
165 /// Error E0438: const is not a member of trait.
166 ConstNotMemberOfTrait(Name, &'a str),
167 /// Error E0408: variable `{}` is not bound in all patterns.
168 VariableNotBoundInPattern(&'a BindingError),
169 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
170 VariableBoundWithDifferentMode(Name, Span),
171 /// Error E0415: identifier is bound more than once in this parameter list.
172 IdentifierBoundMoreThanOnceInParameterList(&'a str),
173 /// Error E0416: identifier is bound more than once in the same pattern.
174 IdentifierBoundMoreThanOnceInSamePattern(&'a str),
175 /// Error E0426: use of undeclared label.
176 UndeclaredLabel(&'a str, Option<Name>),
177 /// Error E0429: `self` imports are only allowed within a `{ }` list.
178 SelfImportsOnlyAllowedWithin,
179 /// Error E0430: `self` import can only appear once in the list.
180 SelfImportCanOnlyAppearOnceInTheList,
181 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
182 SelfImportOnlyInImportListWithNonEmptyPrefix,
183 /// Error E0433: failed to resolve.
184 FailedToResolve { label: String, suggestion: Option<Suggestion> },
185 /// Error E0434: can't capture dynamic environment in a fn item.
186 CannotCaptureDynamicEnvironmentInFnItem,
187 /// Error E0435: attempt to use a non-constant value in a constant.
188 AttemptToUseNonConstantValueInConstant,
189 /// Error E0530: `X` bindings cannot shadow `Y`s.
190 BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
191 /// Error E0128: type parameters with a default cannot use forward-declared identifiers.
192 ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
193 /// Error E0671: const parameter cannot depend on type parameter.
194 ConstParamDependentOnTypeParam,
197 /// Combines an error with provided span and emits it.
199 /// This takes the error provided, combines it with the span and any additional spans inside the
200 /// error and emits it.
201 fn resolve_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
203 resolution_error: ResolutionError<'a>) {
204 resolve_struct_error(resolver, span, resolution_error).emit();
207 fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>,
209 resolution_error: ResolutionError<'a>)
210 -> DiagnosticBuilder<'sess> {
211 match resolution_error {
212 ResolutionError::GenericParamsFromOuterFunction(outer_res) => {
213 let mut err = struct_span_err!(resolver.session,
216 "can't use generic parameters from outer function",
218 err.span_label(span, format!("use of generic parameter from outer function"));
220 let cm = resolver.session.source_map();
222 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
223 if let Some(impl_span) = maybe_impl_defid.and_then(|def_id| {
224 resolver.definitions.opt_span(def_id)
227 reduce_impl_span_to_impl_keyword(cm, impl_span),
228 "`Self` type implicitly declared here, by this `impl`",
231 match (maybe_trait_defid, maybe_impl_defid) {
233 err.span_label(span, "can't use `Self` here");
236 err.span_label(span, "use a type here instead");
238 (None, None) => bug!("`impl` without trait nor type?"),
242 Res::Def(DefKind::TyParam, def_id) => {
243 if let Some(span) = resolver.definitions.opt_span(def_id) {
244 err.span_label(span, "type parameter from outer function");
247 Res::Def(DefKind::ConstParam, def_id) => {
248 if let Some(span) = resolver.definitions.opt_span(def_id) {
249 err.span_label(span, "const parameter from outer function");
253 bug!("GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
258 // Try to retrieve the span of the function signature and generate a new message with
259 // a local type or const parameter.
260 let sugg_msg = &format!("try using a local generic parameter instead");
261 if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
262 // Suggest the modification to the user
267 Applicability::MachineApplicable,
269 } else if let Some(sp) = cm.generate_fn_name_span(span) {
271 format!("try adding a local generic parameter in this method instead"));
273 err.help(&format!("try using a local generic parameter instead"));
278 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
279 let mut err = struct_span_err!(resolver.session,
282 "the name `{}` is already used for a generic \
283 parameter in this list of generic parameters",
285 err.span_label(span, "already used");
286 err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
289 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
290 let mut err = struct_span_err!(resolver.session,
293 "method `{}` is not a member of trait `{}`",
296 err.span_label(span, format!("not a member of trait `{}`", trait_));
299 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
300 let mut err = struct_span_err!(resolver.session,
303 "type `{}` is not a member of trait `{}`",
306 err.span_label(span, format!("not a member of trait `{}`", trait_));
309 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
310 let mut err = struct_span_err!(resolver.session,
313 "const `{}` is not a member of trait `{}`",
316 err.span_label(span, format!("not a member of trait `{}`", trait_));
319 ResolutionError::VariableNotBoundInPattern(binding_error) => {
320 let target_sp = binding_error.target.iter().cloned().collect::<Vec<_>>();
321 let msp = MultiSpan::from_spans(target_sp.clone());
322 let msg = format!("variable `{}` is not bound in all patterns", binding_error.name);
323 let mut err = resolver.session.struct_span_err_with_code(
326 DiagnosticId::Error("E0408".into()),
328 for sp in target_sp {
329 err.span_label(sp, format!("pattern doesn't bind `{}`", binding_error.name));
331 let origin_sp = binding_error.origin.iter().cloned();
332 for sp in origin_sp {
333 err.span_label(sp, "variable not in all patterns");
337 ResolutionError::VariableBoundWithDifferentMode(variable_name,
338 first_binding_span) => {
339 let mut err = struct_span_err!(resolver.session,
342 "variable `{}` is bound in inconsistent \
343 ways within the same match arm",
345 err.span_label(span, "bound in different ways");
346 err.span_label(first_binding_span, "first binding");
349 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
350 let mut err = struct_span_err!(resolver.session,
353 "identifier `{}` is bound more than once in this parameter list",
355 err.span_label(span, "used as parameter more than once");
358 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
359 let mut err = struct_span_err!(resolver.session,
362 "identifier `{}` is bound more than once in the same pattern",
364 err.span_label(span, "used in a pattern more than once");
367 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
368 let mut err = struct_span_err!(resolver.session,
371 "use of undeclared label `{}`",
373 if let Some(lev_candidate) = lev_candidate {
376 "a label with a similar name exists in this scope",
377 lev_candidate.to_string(),
378 Applicability::MaybeIncorrect,
381 err.span_label(span, format!("undeclared label `{}`", name));
385 ResolutionError::SelfImportsOnlyAllowedWithin => {
386 struct_span_err!(resolver.session,
390 "`self` imports are only allowed within a { } list")
392 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
393 let mut err = struct_span_err!(resolver.session, span, E0430,
394 "`self` import can only appear once in an import list");
395 err.span_label(span, "can only appear once in an import list");
398 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
399 let mut err = struct_span_err!(resolver.session, span, E0431,
400 "`self` import can only appear in an import list with \
401 a non-empty prefix");
402 err.span_label(span, "can only appear in an import list with a non-empty prefix");
405 ResolutionError::FailedToResolve { label, suggestion } => {
406 let mut err = struct_span_err!(resolver.session, span, E0433,
407 "failed to resolve: {}", &label);
408 err.span_label(span, label);
410 if let Some((suggestions, msg, applicability)) = suggestion {
411 err.multipart_suggestion(&msg, suggestions, applicability);
416 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
417 let mut err = struct_span_err!(resolver.session,
421 "can't capture dynamic environment in a fn item");
422 err.help("use the `|| { ... }` closure form instead");
425 ResolutionError::AttemptToUseNonConstantValueInConstant => {
426 let mut err = struct_span_err!(resolver.session, span, E0435,
427 "attempt to use a non-constant value in a constant");
428 err.span_label(span, "non-constant value");
431 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
432 let shadows_what = binding.descr();
433 let mut err = struct_span_err!(resolver.session, span, E0530, "{}s cannot shadow {}s",
434 what_binding, shadows_what);
435 err.span_label(span, format!("cannot be named the same as {} {}",
436 binding.article(), shadows_what));
437 let participle = if binding.is_import() { "imported" } else { "defined" };
438 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
439 err.span_label(binding.span, msg);
442 ResolutionError::ForwardDeclaredTyParam => {
443 let mut err = struct_span_err!(resolver.session, span, E0128,
444 "type parameters with a default cannot use \
445 forward declared identifiers");
447 span, "defaulted type parameters cannot be forward declared".to_string());
450 ResolutionError::ConstParamDependentOnTypeParam => {
451 let mut err = struct_span_err!(
455 "const parameters cannot depend on type parameters"
457 err.span_label(span, format!("const parameter depends on type parameter"));
463 /// Adjust the impl span so that just the `impl` keyword is taken by removing
464 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
465 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
467 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
468 /// parser. If you need to use this function or something similar, please consider updating the
469 /// `source_map` functions and this function to something more robust.
470 fn reduce_impl_span_to_impl_keyword(cm: &SourceMap, impl_span: Span) -> Span {
471 let impl_span = cm.span_until_char(impl_span, '<');
472 let impl_span = cm.span_until_whitespace(impl_span);
476 #[derive(Copy, Clone, Debug)]
479 binding_mode: BindingMode,
482 /// Map from the name in a pattern to its binding mode.
483 type BindingMap = FxHashMap<Ident, BindingInfo>;
485 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
494 fn descr(self) -> &'static str {
496 PatternSource::Match => "match binding",
497 PatternSource::Let => "let binding",
498 PatternSource::For => "for binding",
499 PatternSource::FnParam => "function parameter",
504 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
505 enum AliasPossibility {
510 #[derive(Copy, Clone, Debug)]
511 enum PathSource<'a> {
512 // Type paths `Path`.
514 // Trait paths in bounds or impls.
515 Trait(AliasPossibility),
516 // Expression paths `path`, with optional parent context.
517 Expr(Option<&'a Expr>),
518 // Paths in path patterns `Path`.
520 // Paths in struct expressions and patterns `Path { .. }`.
522 // Paths in tuple struct patterns `Path(..)`.
524 // `m::A::B` in `<T as m::A>::B::C`.
525 TraitItem(Namespace),
526 // Path in `pub(path)`
530 impl<'a> PathSource<'a> {
531 fn namespace(self) -> Namespace {
533 PathSource::Type | PathSource::Trait(_) | PathSource::Struct |
534 PathSource::Visibility => TypeNS,
535 PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct => ValueNS,
536 PathSource::TraitItem(ns) => ns,
540 fn global_by_default(self) -> bool {
542 PathSource::Visibility => true,
543 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
544 PathSource::Struct | PathSource::TupleStruct |
545 PathSource::Trait(_) | PathSource::TraitItem(..) => false,
549 fn defer_to_typeck(self) -> bool {
551 PathSource::Type | PathSource::Expr(..) | PathSource::Pat |
552 PathSource::Struct | PathSource::TupleStruct => true,
553 PathSource::Trait(_) | PathSource::TraitItem(..) |
554 PathSource::Visibility => false,
558 fn descr_expected(self) -> &'static str {
560 PathSource::Type => "type",
561 PathSource::Trait(_) => "trait",
562 PathSource::Pat => "unit struct/variant or constant",
563 PathSource::Struct => "struct, variant or union type",
564 PathSource::TupleStruct => "tuple struct/variant",
565 PathSource::Visibility => "module",
566 PathSource::TraitItem(ns) => match ns {
567 TypeNS => "associated type",
568 ValueNS => "method or associated constant",
569 MacroNS => bug!("associated macro"),
571 PathSource::Expr(parent) => match parent.map(|p| &p.node) {
572 // "function" here means "anything callable" rather than `DefKind::Fn`,
573 // this is not precise but usually more helpful than just "value".
574 Some(&ExprKind::Call(..)) => "function",
580 fn is_expected(self, res: Res) -> bool {
582 PathSource::Type => match res {
583 Res::Def(DefKind::Struct, _)
584 | Res::Def(DefKind::Union, _)
585 | Res::Def(DefKind::Enum, _)
586 | Res::Def(DefKind::Trait, _)
587 | Res::Def(DefKind::TraitAlias, _)
588 | Res::Def(DefKind::TyAlias, _)
589 | Res::Def(DefKind::AssocTy, _)
591 | Res::Def(DefKind::TyParam, _)
593 | Res::Def(DefKind::Existential, _)
594 | Res::Def(DefKind::ForeignTy, _) => true,
597 PathSource::Trait(AliasPossibility::No) => match res {
598 Res::Def(DefKind::Trait, _) => true,
601 PathSource::Trait(AliasPossibility::Maybe) => match res {
602 Res::Def(DefKind::Trait, _) => true,
603 Res::Def(DefKind::TraitAlias, _) => true,
606 PathSource::Expr(..) => match res {
607 Res::Def(DefKind::Ctor(_, CtorKind::Const), _)
608 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
609 | Res::Def(DefKind::Const, _)
610 | Res::Def(DefKind::Static, _)
612 | Res::Def(DefKind::Fn, _)
613 | Res::Def(DefKind::Method, _)
614 | Res::Def(DefKind::AssocConst, _)
616 | Res::Def(DefKind::ConstParam, _) => true,
619 PathSource::Pat => match res {
620 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
621 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) |
622 Res::SelfCtor(..) => true,
625 PathSource::TupleStruct => match res {
626 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
629 PathSource::Struct => match res {
630 Res::Def(DefKind::Struct, _)
631 | Res::Def(DefKind::Union, _)
632 | Res::Def(DefKind::Variant, _)
633 | Res::Def(DefKind::TyAlias, _)
634 | Res::Def(DefKind::AssocTy, _)
635 | Res::SelfTy(..) => true,
638 PathSource::TraitItem(ns) => match res {
639 Res::Def(DefKind::AssocConst, _)
640 | Res::Def(DefKind::Method, _) if ns == ValueNS => true,
641 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
644 PathSource::Visibility => match res {
645 Res::Def(DefKind::Mod, _) => true,
651 fn error_code(self, has_unexpected_resolution: bool) -> &'static str {
652 __diagnostic_used!(E0404);
653 __diagnostic_used!(E0405);
654 __diagnostic_used!(E0412);
655 __diagnostic_used!(E0422);
656 __diagnostic_used!(E0423);
657 __diagnostic_used!(E0425);
658 __diagnostic_used!(E0531);
659 __diagnostic_used!(E0532);
660 __diagnostic_used!(E0573);
661 __diagnostic_used!(E0574);
662 __diagnostic_used!(E0575);
663 __diagnostic_used!(E0576);
664 __diagnostic_used!(E0577);
665 __diagnostic_used!(E0578);
666 match (self, has_unexpected_resolution) {
667 (PathSource::Trait(_), true) => "E0404",
668 (PathSource::Trait(_), false) => "E0405",
669 (PathSource::Type, true) => "E0573",
670 (PathSource::Type, false) => "E0412",
671 (PathSource::Struct, true) => "E0574",
672 (PathSource::Struct, false) => "E0422",
673 (PathSource::Expr(..), true) => "E0423",
674 (PathSource::Expr(..), false) => "E0425",
675 (PathSource::Pat, true) | (PathSource::TupleStruct, true) => "E0532",
676 (PathSource::Pat, false) | (PathSource::TupleStruct, false) => "E0531",
677 (PathSource::TraitItem(..), true) => "E0575",
678 (PathSource::TraitItem(..), false) => "E0576",
679 (PathSource::Visibility, true) => "E0577",
680 (PathSource::Visibility, false) => "E0578",
685 // A minimal representation of a path segment. We use this in resolve because
686 // we synthesize 'path segments' which don't have the rest of an AST or HIR
688 #[derive(Clone, Copy, Debug)]
695 fn from_path(path: &Path) -> Vec<Segment> {
696 path.segments.iter().map(|s| s.into()).collect()
699 fn from_ident(ident: Ident) -> Segment {
706 fn names_to_string(segments: &[Segment]) -> String {
707 names_to_string(&segments.iter()
708 .map(|seg| seg.ident)
709 .collect::<Vec<_>>())
713 impl<'a> From<&'a ast::PathSegment> for Segment {
714 fn from(seg: &'a ast::PathSegment) -> Segment {
722 struct UsePlacementFinder {
723 target_module: NodeId,
728 impl UsePlacementFinder {
729 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) {
730 let mut finder = UsePlacementFinder {
735 visit::walk_crate(&mut finder, krate);
736 (finder.span, finder.found_use)
740 impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
743 module: &'tcx ast::Mod,
745 _: &[ast::Attribute],
748 if self.span.is_some() {
751 if node_id != self.target_module {
752 visit::walk_mod(self, module);
755 // find a use statement
756 for item in &module.items {
758 ItemKind::Use(..) => {
759 // don't suggest placing a use before the prelude
760 // import or other generated ones
761 if item.span.ctxt().outer_expn_info().is_none() {
762 self.span = Some(item.span.shrink_to_lo());
763 self.found_use = true;
767 // don't place use before extern crate
768 ItemKind::ExternCrate(_) => {}
769 // but place them before the first other item
770 _ => if self.span.map_or(true, |span| item.span < span ) {
771 if item.span.ctxt().outer_expn_info().is_none() {
772 // don't insert between attributes and an item
773 if item.attrs.is_empty() {
774 self.span = Some(item.span.shrink_to_lo());
776 // find the first attribute on the item
777 for attr in &item.attrs {
778 if self.span.map_or(true, |span| attr.span < span) {
779 self.span = Some(attr.span.shrink_to_lo());
790 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
791 impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> {
792 fn visit_item(&mut self, item: &'tcx Item) {
793 self.resolve_item(item);
795 fn visit_arm(&mut self, arm: &'tcx Arm) {
796 self.resolve_arm(arm);
798 fn visit_block(&mut self, block: &'tcx Block) {
799 self.resolve_block(block);
801 fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
802 debug!("visit_anon_const {:?}", constant);
803 self.with_constant_rib(|this| {
804 visit::walk_anon_const(this, constant);
807 fn visit_expr(&mut self, expr: &'tcx Expr) {
808 self.resolve_expr(expr, None);
810 fn visit_local(&mut self, local: &'tcx Local) {
811 self.resolve_local(local);
813 fn visit_ty(&mut self, ty: &'tcx Ty) {
815 TyKind::Path(ref qself, ref path) => {
816 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
818 TyKind::ImplicitSelf => {
819 let self_ty = Ident::with_empty_ctxt(kw::SelfUpper);
820 let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
821 .map_or(Res::Err, |d| d.res());
822 self.record_partial_res(ty.id, PartialRes::new(res));
826 visit::walk_ty(self, ty);
828 fn visit_poly_trait_ref(&mut self,
829 tref: &'tcx ast::PolyTraitRef,
830 m: &'tcx ast::TraitBoundModifier) {
831 self.smart_resolve_path(tref.trait_ref.ref_id, None,
832 &tref.trait_ref.path, PathSource::Trait(AliasPossibility::Maybe));
833 visit::walk_poly_trait_ref(self, tref, m);
835 fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
836 let generic_params = match foreign_item.node {
837 ForeignItemKind::Fn(_, ref generics) => {
838 HasGenericParams(generics, ItemRibKind)
840 ForeignItemKind::Static(..) => NoGenericParams,
841 ForeignItemKind::Ty => NoGenericParams,
842 ForeignItemKind::Macro(..) => NoGenericParams,
844 self.with_generic_param_rib(generic_params, |this| {
845 visit::walk_foreign_item(this, foreign_item);
848 fn visit_fn(&mut self,
849 function_kind: FnKind<'tcx>,
850 declaration: &'tcx FnDecl,
854 debug!("(resolving function) entering function");
855 let rib_kind = match function_kind {
856 FnKind::ItemFn(..) => FnItemRibKind,
857 FnKind::Method(..) => AssocItemRibKind,
858 FnKind::Closure(_) => NormalRibKind,
861 // Create a value rib for the function.
862 self.ribs[ValueNS].push(Rib::new(rib_kind));
864 // Create a label rib for the function.
865 self.label_ribs.push(Rib::new(rib_kind));
867 // Add each argument to the rib.
868 let mut bindings_list = FxHashMap::default();
869 for argument in &declaration.inputs {
870 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
872 self.visit_ty(&argument.ty);
874 debug!("(resolving function) recorded argument");
876 visit::walk_fn_ret_ty(self, &declaration.output);
878 // Resolve the function body, potentially inside the body of an async closure
879 match function_kind {
880 FnKind::ItemFn(.., body) |
881 FnKind::Method(.., body) => {
882 self.visit_block(body);
884 FnKind::Closure(body) => {
885 self.visit_expr(body);
889 debug!("(resolving function) leaving function");
891 self.label_ribs.pop();
892 self.ribs[ValueNS].pop();
895 fn visit_generics(&mut self, generics: &'tcx Generics) {
896 // For type parameter defaults, we have to ban access
897 // to following type parameters, as the InternalSubsts can only
898 // provide previous type parameters as they're built. We
899 // put all the parameters on the ban list and then remove
900 // them one by one as they are processed and become available.
901 let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
902 let mut found_default = false;
903 default_ban_rib.bindings.extend(generics.params.iter()
904 .filter_map(|param| match param.kind {
905 GenericParamKind::Const { .. } |
906 GenericParamKind::Lifetime { .. } => None,
907 GenericParamKind::Type { ref default, .. } => {
908 found_default |= default.is_some();
910 Some((Ident::with_empty_ctxt(param.ident.name), Res::Err))
917 // We also ban access to type parameters for use as the types of const parameters.
918 let mut const_ty_param_ban_rib = Rib::new(TyParamAsConstParamTy);
919 const_ty_param_ban_rib.bindings.extend(generics.params.iter()
921 if let GenericParamKind::Type { .. } = param.kind {
927 .map(|param| (Ident::with_empty_ctxt(param.ident.name), Res::Err)));
929 for param in &generics.params {
931 GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
932 GenericParamKind::Type { ref default, .. } => {
933 for bound in ¶m.bounds {
934 self.visit_param_bound(bound);
937 if let Some(ref ty) = default {
938 self.ribs[TypeNS].push(default_ban_rib);
940 default_ban_rib = self.ribs[TypeNS].pop().unwrap();
943 // Allow all following defaults to refer to this type parameter.
944 default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
946 GenericParamKind::Const { ref ty } => {
947 self.ribs[TypeNS].push(const_ty_param_ban_rib);
949 for bound in ¶m.bounds {
950 self.visit_param_bound(bound);
955 const_ty_param_ban_rib = self.ribs[TypeNS].pop().unwrap();
959 for p in &generics.where_clause.predicates {
960 self.visit_where_predicate(p);
965 #[derive(Copy, Clone)]
966 enum GenericParameters<'a, 'b> {
968 HasGenericParams(// Type parameters.
971 // The kind of the rib used for type parameters.
975 /// The rib kind restricts certain accesses,
976 /// e.g. to a `Res::Local` of an outer item.
977 #[derive(Copy, Clone, Debug)]
979 /// No restriction needs to be applied.
982 /// We passed through an impl or trait and are now in one of its
983 /// methods or associated types. Allow references to ty params that impl or trait
984 /// binds. Disallow any other upvars (including other ty params that are
988 /// We passed through a function definition. Disallow upvars.
989 /// Permit only those const parameters that are specified in the function's generics.
992 /// We passed through an item scope. Disallow upvars.
995 /// We're in a constant item. Can't refer to dynamic stuff.
998 /// We passed through a module.
999 ModuleRibKind(Module<'a>),
1001 /// We passed through a `macro_rules!` statement
1002 MacroDefinition(DefId),
1004 /// All bindings in this rib are type parameters that can't be used
1005 /// from the default of a type parameter because they're not declared
1006 /// before said type parameter. Also see the `visit_generics` override.
1007 ForwardTyParamBanRibKind,
1009 /// We forbid the use of type parameters as the types of const parameters.
1010 TyParamAsConstParamTy,
1013 /// A single local scope.
1015 /// A rib represents a scope names can live in. Note that these appear in many places, not just
1016 /// around braces. At any place where the list of accessible names (of the given namespace)
1017 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
1018 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
1021 /// Different [rib kinds](enum.RibKind) are transparent for different names.
1023 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
1024 /// resolving, the name is looked up from inside out.
1026 struct Rib<'a, R = Res> {
1027 bindings: FxHashMap<Ident, R>,
1031 impl<'a, R> Rib<'a, R> {
1032 fn new(kind: RibKind<'a>) -> Rib<'a, R> {
1034 bindings: Default::default(),
1040 /// An intermediate resolution result.
1042 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
1043 /// items are visible in their whole block, while `Res`es only from the place they are defined
1045 enum LexicalScopeBinding<'a> {
1046 Item(&'a NameBinding<'a>),
1050 impl<'a> LexicalScopeBinding<'a> {
1051 fn item(self) -> Option<&'a NameBinding<'a>> {
1053 LexicalScopeBinding::Item(binding) => Some(binding),
1058 fn res(self) -> Res {
1060 LexicalScopeBinding::Item(binding) => binding.res(),
1061 LexicalScopeBinding::Res(res) => res,
1066 #[derive(Copy, Clone, Debug)]
1067 enum ModuleOrUniformRoot<'a> {
1071 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
1072 CrateRootAndExternPrelude,
1074 /// Virtual module that denotes resolution in extern prelude.
1075 /// Used for paths starting with `::` on 2018 edition.
1078 /// Virtual module that denotes resolution in current scope.
1079 /// Used only for resolving single-segment imports. The reason it exists is that import paths
1080 /// are always split into two parts, the first of which should be some kind of module.
1084 impl ModuleOrUniformRoot<'_> {
1085 fn same_def(lhs: Self, rhs: Self) -> bool {
1087 (ModuleOrUniformRoot::Module(lhs),
1088 ModuleOrUniformRoot::Module(rhs)) => lhs.def_id() == rhs.def_id(),
1089 (ModuleOrUniformRoot::CrateRootAndExternPrelude,
1090 ModuleOrUniformRoot::CrateRootAndExternPrelude) |
1091 (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) |
1092 (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
1098 #[derive(Clone, Debug)]
1099 enum PathResult<'a> {
1100 Module(ModuleOrUniformRoot<'a>),
1101 NonModule(PartialRes),
1106 suggestion: Option<Suggestion>,
1107 is_error_from_last_segment: bool,
1112 /// An anonymous module; e.g., just a block.
1116 /// fn f() {} // (1)
1117 /// { // This is an anonymous module
1118 /// f(); // This resolves to (2) as we are inside the block.
1119 /// fn f() {} // (2)
1121 /// f(); // Resolves to (1)
1125 /// Any module with a name.
1129 /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`.
1130 /// * A trait or an enum (it implicitly contains associated types, methods and variant
1132 Def(DefKind, DefId, Name),
1136 /// Get name of the module.
1137 pub fn name(&self) -> Option<Name> {
1139 ModuleKind::Block(..) => None,
1140 ModuleKind::Def(.., name) => Some(*name),
1145 /// One node in the tree of modules.
1146 pub struct ModuleData<'a> {
1147 parent: Option<Module<'a>>,
1150 // The def id of the closest normal module (`mod`) ancestor (including this module).
1151 normal_ancestor_id: DefId,
1153 resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
1154 single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
1155 Option<&'a NameBinding<'a>>)>>,
1156 multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
1158 builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
1160 // Macro invocations that can expand into items in this module.
1161 unresolved_invocations: RefCell<FxHashSet<Mark>>,
1163 no_implicit_prelude: bool,
1165 glob_importers: RefCell<Vec<&'a ImportDirective<'a>>>,
1166 globs: RefCell<Vec<&'a ImportDirective<'a>>>,
1168 // Used to memoize the traits in this module for faster searches through all traits in scope.
1169 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
1171 // Whether this module is populated. If not populated, any attempt to
1172 // access the children must be preceded with a
1173 // `populate_module_if_necessary` call.
1174 populated: Cell<bool>,
1176 /// Span of the module itself. Used for error reporting.
1182 type Module<'a> = &'a ModuleData<'a>;
1184 impl<'a> ModuleData<'a> {
1185 fn new(parent: Option<Module<'a>>,
1187 normal_ancestor_id: DefId,
1189 span: Span) -> Self {
1194 resolutions: Default::default(),
1195 single_segment_macro_resolutions: RefCell::new(Vec::new()),
1196 multi_segment_macro_resolutions: RefCell::new(Vec::new()),
1197 builtin_attrs: RefCell::new(Vec::new()),
1198 unresolved_invocations: Default::default(),
1199 no_implicit_prelude: false,
1200 glob_importers: RefCell::new(Vec::new()),
1201 globs: RefCell::new(Vec::new()),
1202 traits: RefCell::new(None),
1203 populated: Cell::new(normal_ancestor_id.is_local()),
1209 fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1210 for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
1211 name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1215 fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
1216 let resolutions = self.resolutions.borrow();
1217 let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1218 resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
1219 for &(&(ident, ns), &resolution) in resolutions.iter() {
1220 resolution.borrow().binding.map(|binding| f(ident, ns, binding));
1224 fn res(&self) -> Option<Res> {
1226 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
1231 fn def_kind(&self) -> Option<DefKind> {
1233 ModuleKind::Def(kind, ..) => Some(kind),
1238 fn def_id(&self) -> Option<DefId> {
1240 ModuleKind::Def(_, def_id, _) => Some(def_id),
1245 // `self` resolves to the first module ancestor that `is_normal`.
1246 fn is_normal(&self) -> bool {
1248 ModuleKind::Def(DefKind::Mod, _, _) => true,
1253 fn is_trait(&self) -> bool {
1255 ModuleKind::Def(DefKind::Trait, _, _) => true,
1260 fn nearest_item_scope(&'a self) -> Module<'a> {
1261 if self.is_trait() { self.parent.unwrap() } else { self }
1264 fn is_ancestor_of(&self, mut other: &Self) -> bool {
1265 while !ptr::eq(self, other) {
1266 if let Some(parent) = other.parent {
1276 impl<'a> fmt::Debug for ModuleData<'a> {
1277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1278 write!(f, "{:?}", self.res())
1282 /// Records a possibly-private value, type, or module definition.
1283 #[derive(Clone, Debug)]
1284 pub struct NameBinding<'a> {
1285 kind: NameBindingKind<'a>,
1286 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
1289 vis: ty::Visibility,
1292 pub trait ToNameBinding<'a> {
1293 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
1296 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
1297 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
1302 #[derive(Clone, Debug)]
1303 enum NameBindingKind<'a> {
1304 Res(Res, /* is_macro_export */ bool),
1307 binding: &'a NameBinding<'a>,
1308 directive: &'a ImportDirective<'a>,
1313 impl<'a> NameBindingKind<'a> {
1314 /// Is this a name binding of a import?
1315 fn is_import(&self) -> bool {
1317 NameBindingKind::Import { .. } => true,
1323 struct PrivacyError<'a>(Span, Ident, &'a NameBinding<'a>);
1325 struct UseError<'a> {
1326 err: DiagnosticBuilder<'a>,
1327 /// Attach `use` statements for these candidates.
1328 candidates: Vec<ImportSuggestion>,
1329 /// The `NodeId` of the module to place the use-statements in.
1331 /// Whether the diagnostic should state that it's "better".
1335 #[derive(Clone, Copy, PartialEq, Debug)]
1336 enum AmbiguityKind {
1340 LegacyHelperVsPrelude,
1345 MoreExpandedVsOuter,
1348 impl AmbiguityKind {
1349 fn descr(self) -> &'static str {
1351 AmbiguityKind::Import =>
1352 "name vs any other name during import resolution",
1353 AmbiguityKind::BuiltinAttr =>
1354 "built-in attribute vs any other name",
1355 AmbiguityKind::DeriveHelper =>
1356 "derive helper attribute vs any other name",
1357 AmbiguityKind::LegacyHelperVsPrelude =>
1358 "legacy plugin helper attribute vs name from prelude",
1359 AmbiguityKind::LegacyVsModern =>
1360 "`macro_rules` vs non-`macro_rules` from other module",
1361 AmbiguityKind::GlobVsOuter =>
1362 "glob import vs any other name from outer scope during import/macro resolution",
1363 AmbiguityKind::GlobVsGlob =>
1364 "glob import vs glob import in the same module",
1365 AmbiguityKind::GlobVsExpanded =>
1366 "glob import vs macro-expanded name in the same \
1367 module during import/macro resolution",
1368 AmbiguityKind::MoreExpandedVsOuter =>
1369 "macro-expanded name vs less macro-expanded name \
1370 from outer scope during import/macro resolution",
1375 /// Miscellaneous bits of metadata for better ambiguity error reporting.
1376 #[derive(Clone, Copy, PartialEq)]
1377 enum AmbiguityErrorMisc {
1384 struct AmbiguityError<'a> {
1385 kind: AmbiguityKind,
1387 b1: &'a NameBinding<'a>,
1388 b2: &'a NameBinding<'a>,
1389 misc1: AmbiguityErrorMisc,
1390 misc2: AmbiguityErrorMisc,
1393 impl<'a> NameBinding<'a> {
1394 fn module(&self) -> Option<Module<'a>> {
1396 NameBindingKind::Module(module) => Some(module),
1397 NameBindingKind::Import { binding, .. } => binding.module(),
1402 fn res(&self) -> Res {
1404 NameBindingKind::Res(res, _) => res,
1405 NameBindingKind::Module(module) => module.res().unwrap(),
1406 NameBindingKind::Import { binding, .. } => binding.res(),
1410 fn is_ambiguity(&self) -> bool {
1411 self.ambiguity.is_some() || match self.kind {
1412 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
1417 // We sometimes need to treat variants as `pub` for backwards compatibility.
1418 fn pseudo_vis(&self) -> ty::Visibility {
1419 if self.is_variant() && self.res().def_id().is_local() {
1420 ty::Visibility::Public
1426 fn is_variant(&self) -> bool {
1428 NameBindingKind::Res(Res::Def(DefKind::Variant, _), _) |
1429 NameBindingKind::Res(Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _), _) => true,
1434 fn is_extern_crate(&self) -> bool {
1436 NameBindingKind::Import {
1437 directive: &ImportDirective {
1438 subclass: ImportDirectiveSubclass::ExternCrate { .. }, ..
1441 NameBindingKind::Module(
1442 &ModuleData { kind: ModuleKind::Def(DefKind::Mod, def_id, _), .. }
1443 ) => def_id.index == CRATE_DEF_INDEX,
1448 fn is_import(&self) -> bool {
1450 NameBindingKind::Import { .. } => true,
1455 fn is_glob_import(&self) -> bool {
1457 NameBindingKind::Import { directive, .. } => directive.is_glob(),
1462 fn is_importable(&self) -> bool {
1464 Res::Def(DefKind::AssocConst, _)
1465 | Res::Def(DefKind::Method, _)
1466 | Res::Def(DefKind::AssocTy, _) => false,
1471 fn is_macro_def(&self) -> bool {
1473 NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true,
1478 fn macro_kind(&self) -> Option<MacroKind> {
1480 Res::Def(DefKind::Macro(kind), _) => Some(kind),
1481 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
1486 fn descr(&self) -> &'static str {
1487 if self.is_extern_crate() { "extern crate" } else { self.res().descr() }
1490 fn article(&self) -> &'static str {
1491 if self.is_extern_crate() { "an" } else { self.res().article() }
1494 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1495 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1496 // Then this function returns `true` if `self` may emerge from a macro *after* that
1497 // in some later round and screw up our previously found resolution.
1498 // See more detailed explanation in
1499 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1500 fn may_appear_after(&self, invoc_parent_expansion: Mark, binding: &NameBinding<'_>) -> bool {
1501 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1502 // Expansions are partially ordered, so "may appear after" is an inversion of
1503 // "certainly appears before or simultaneously" and includes unordered cases.
1504 let self_parent_expansion = self.expansion;
1505 let other_parent_expansion = binding.expansion;
1506 let certainly_before_other_or_simultaneously =
1507 other_parent_expansion.is_descendant_of(self_parent_expansion);
1508 let certainly_before_invoc_or_simultaneously =
1509 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1510 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1514 /// Interns the names of the primitive types.
1516 /// All other types are defined somewhere and possibly imported, but the primitive ones need
1517 /// special handling, since they have no place of origin.
1518 struct PrimitiveTypeTable {
1519 primitive_types: FxHashMap<Name, PrimTy>,
1522 impl PrimitiveTypeTable {
1523 fn new() -> PrimitiveTypeTable {
1524 let mut table = FxHashMap::default();
1526 table.insert(sym::bool, Bool);
1527 table.insert(sym::char, Char);
1528 table.insert(sym::f32, Float(FloatTy::F32));
1529 table.insert(sym::f64, Float(FloatTy::F64));
1530 table.insert(sym::isize, Int(IntTy::Isize));
1531 table.insert(sym::i8, Int(IntTy::I8));
1532 table.insert(sym::i16, Int(IntTy::I16));
1533 table.insert(sym::i32, Int(IntTy::I32));
1534 table.insert(sym::i64, Int(IntTy::I64));
1535 table.insert(sym::i128, Int(IntTy::I128));
1536 table.insert(sym::str, Str);
1537 table.insert(sym::usize, Uint(UintTy::Usize));
1538 table.insert(sym::u8, Uint(UintTy::U8));
1539 table.insert(sym::u16, Uint(UintTy::U16));
1540 table.insert(sym::u32, Uint(UintTy::U32));
1541 table.insert(sym::u64, Uint(UintTy::U64));
1542 table.insert(sym::u128, Uint(UintTy::U128));
1543 Self { primitive_types: table }
1547 #[derive(Debug, Default, Clone)]
1548 pub struct ExternPreludeEntry<'a> {
1549 extern_crate_item: Option<&'a NameBinding<'a>>,
1550 pub introduced_by_item: bool,
1553 /// The main resolver class.
1555 /// This is the visitor that walks the whole crate.
1556 pub struct Resolver<'a> {
1557 session: &'a Session,
1560 pub definitions: Definitions,
1562 graph_root: Module<'a>,
1564 prelude: Option<Module<'a>>,
1565 pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
1567 /// N.B., this is used only for better diagnostics, not name resolution itself.
1568 has_self: FxHashSet<DefId>,
1570 /// Names of fields of an item `DefId` accessible with dot syntax.
1571 /// Used for hints during error reporting.
1572 field_names: FxHashMap<DefId, Vec<Name>>,
1574 /// All imports known to succeed or fail.
1575 determined_imports: Vec<&'a ImportDirective<'a>>,
1577 /// All non-determined imports.
1578 indeterminate_imports: Vec<&'a ImportDirective<'a>>,
1580 /// The module that represents the current item scope.
1581 current_module: Module<'a>,
1583 /// The current set of local scopes for types and values.
1584 /// FIXME #4948: Reuse ribs to avoid allocation.
1585 ribs: PerNS<Vec<Rib<'a>>>,
1587 /// The current set of local scopes, for labels.
1588 label_ribs: Vec<Rib<'a, NodeId>>,
1590 /// The trait that the current context can refer to.
1591 current_trait_ref: Option<(Module<'a>, TraitRef)>,
1593 /// The current self type if inside an impl (used for better errors).
1594 current_self_type: Option<Ty>,
1596 /// The current self item if inside an ADT (used for better errors).
1597 current_self_item: Option<NodeId>,
1599 /// FIXME: Refactor things so that these fields are passed through arguments and not resolver.
1600 /// We are resolving a last import segment during import validation.
1601 last_import_segment: bool,
1602 /// This binding should be ignored during in-module resolution, so that we don't get
1603 /// "self-confirming" import resolutions during import validation.
1604 blacklisted_binding: Option<&'a NameBinding<'a>>,
1606 /// The idents for the primitive types.
1607 primitive_type_table: PrimitiveTypeTable,
1609 /// Resolutions for nodes that have a single resolution.
1610 partial_res_map: NodeMap<PartialRes>,
1611 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
1612 import_res_map: NodeMap<PerNS<Option<Res>>>,
1613 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
1614 label_res_map: NodeMap<NodeId>,
1616 pub export_map: ExportMap<NodeId>,
1617 pub trait_map: TraitMap,
1619 /// A map from nodes to anonymous modules.
1620 /// Anonymous modules are pseudo-modules that are implicitly created around items
1621 /// contained within blocks.
1623 /// For example, if we have this:
1631 /// There will be an anonymous module created around `g` with the ID of the
1632 /// entry block for `f`.
1633 block_map: NodeMap<Module<'a>>,
1634 module_map: FxHashMap<DefId, Module<'a>>,
1635 extern_module_map: FxHashMap<(DefId, bool /* MacrosOnly? */), Module<'a>>,
1636 binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>,
1638 /// Maps glob imports to the names of items actually imported.
1639 pub glob_map: GlobMap,
1641 used_imports: FxHashSet<(NodeId, Namespace)>,
1642 pub maybe_unused_trait_imports: NodeSet,
1643 pub maybe_unused_extern_crates: Vec<(NodeId, Span)>,
1645 /// A list of labels as of yet unused. Labels will be removed from this map when
1646 /// they are used (in a `break` or `continue` statement)
1647 pub unused_labels: FxHashMap<NodeId, Span>,
1649 /// Privacy errors are delayed until the end in order to deduplicate them.
1650 privacy_errors: Vec<PrivacyError<'a>>,
1651 /// Ambiguity errors are delayed for deduplication.
1652 ambiguity_errors: Vec<AmbiguityError<'a>>,
1653 /// `use` injections are delayed for better placement and deduplication.
1654 use_injections: Vec<UseError<'a>>,
1655 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1656 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1658 arenas: &'a ResolverArenas<'a>,
1659 dummy_binding: &'a NameBinding<'a>,
1661 crate_loader: &'a mut CrateLoader<'a>,
1662 macro_names: FxHashSet<Ident>,
1663 builtin_macros: FxHashMap<Name, &'a NameBinding<'a>>,
1664 macro_use_prelude: FxHashMap<Name, &'a NameBinding<'a>>,
1665 pub all_macros: FxHashMap<Name, Res>,
1666 macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>,
1667 non_macro_attrs: [Lrc<SyntaxExtension>; 2],
1668 macro_defs: FxHashMap<Mark, DefId>,
1669 local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
1671 /// List of crate local macros that we need to warn about as being unused.
1672 /// Right now this only includes macro_rules! macros, and macros 2.0.
1673 unused_macros: FxHashSet<DefId>,
1675 /// Maps the `Mark` of an expansion to its containing module or block.
1676 invocations: FxHashMap<Mark, &'a InvocationData<'a>>,
1678 /// Avoid duplicated errors for "name already defined".
1679 name_already_seen: FxHashMap<Name, Span>,
1681 potentially_unused_imports: Vec<&'a ImportDirective<'a>>,
1683 /// Table for mapping struct IDs into struct constructor IDs,
1684 /// it's not used during normal resolution, only for better error reporting.
1685 struct_constructors: DefIdMap<(Res, ty::Visibility)>,
1687 /// Only used for better errors on `fn(): fn()`.
1688 current_type_ascription: Vec<Span>,
1690 injected_crate: Option<Module<'a>>,
1693 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1695 pub struct ResolverArenas<'a> {
1696 modules: arena::TypedArena<ModuleData<'a>>,
1697 local_modules: RefCell<Vec<Module<'a>>>,
1698 name_bindings: arena::TypedArena<NameBinding<'a>>,
1699 import_directives: arena::TypedArena<ImportDirective<'a>>,
1700 name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
1701 invocation_data: arena::TypedArena<InvocationData<'a>>,
1702 legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
1705 impl<'a> ResolverArenas<'a> {
1706 fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> {
1707 let module = self.modules.alloc(module);
1708 if module.def_id().map(|def_id| def_id.is_local()).unwrap_or(true) {
1709 self.local_modules.borrow_mut().push(module);
1713 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1714 self.local_modules.borrow()
1716 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1717 self.name_bindings.alloc(name_binding)
1719 fn alloc_import_directive(&'a self, import_directive: ImportDirective<'a>)
1720 -> &'a ImportDirective<'_> {
1721 self.import_directives.alloc(import_directive)
1723 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1724 self.name_resolutions.alloc(Default::default())
1726 fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
1727 -> &'a InvocationData<'a> {
1728 self.invocation_data.alloc(expansion_data)
1730 fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
1731 self.legacy_bindings.alloc(binding)
1735 impl<'a, 'b> ty::DefIdTree for &'a Resolver<'b> {
1736 fn parent(self, id: DefId) -> Option<DefId> {
1738 LOCAL_CRATE => self.definitions.def_key(id.index).parent,
1739 _ => self.cstore.def_key(id).parent,
1740 }.map(|index| DefId { index, ..id })
1744 /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that
1745 /// the resolver is no longer needed as all the relevant information is inline.
1746 impl<'a> hir::lowering::Resolver for Resolver<'a> {
1747 fn resolve_ast_path(
1752 self.resolve_ast_path_cb(path, is_value,
1753 |resolver, span, error| resolve_error(resolver, span, error))
1756 fn resolve_str_path(
1759 crate_root: Option<Symbol>,
1760 components: &[Symbol],
1762 ) -> (ast::Path, Res) {
1763 let root = if crate_root.is_some() {
1768 let segments = iter::once(Ident::with_empty_ctxt(root))
1770 crate_root.into_iter()
1771 .chain(components.iter().cloned())
1772 .map(Ident::with_empty_ctxt)
1773 ).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
1775 let path = ast::Path {
1780 let res = self.resolve_ast_path(&path, is_value);
1784 fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes> {
1785 self.partial_res_map.get(&id).cloned()
1788 fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res>> {
1789 self.import_res_map.get(&id).cloned().unwrap_or_default()
1792 fn get_label_res(&mut self, id: NodeId) -> Option<NodeId> {
1793 self.label_res_map.get(&id).cloned()
1796 fn definitions(&mut self) -> &mut Definitions {
1797 &mut self.definitions
1801 impl<'a> Resolver<'a> {
1802 /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>`
1803 /// isn't something that can be returned because it can't be made to live that long,
1804 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1805 /// just that an error occurred.
1806 pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool)
1807 -> Result<(ast::Path, Res), ()> {
1808 let mut errored = false;
1810 let path = if path_str.starts_with("::") {
1813 segments: iter::once(Ident::with_empty_ctxt(kw::PathRoot))
1815 path_str.split("::").skip(1).map(Ident::from_str)
1817 .map(|i| self.new_ast_path_segment(i))
1825 .map(Ident::from_str)
1826 .map(|i| self.new_ast_path_segment(i))
1830 let res = self.resolve_ast_path_cb(&path, is_value, |_, _, _| errored = true);
1831 if errored || res == def::Res::Err {
1838 /// Like `resolve_ast_path`, but takes a callback in case there was an error.
1839 // FIXME(eddyb) use `Result` or something instead of callbacks.
1840 fn resolve_ast_path_cb<F>(
1846 where F: for<'c, 'b> FnOnce(&'c mut Resolver<'_>, Span, ResolutionError<'b>)
1848 let namespace = if is_value { ValueNS } else { TypeNS };
1849 let span = path.span;
1850 let path = Segment::from_path(&path);
1851 // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
1852 match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
1853 span, CrateLint::No) {
1854 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1855 module.res().unwrap(),
1856 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 =>
1857 path_res.base_res(),
1858 PathResult::NonModule(..) => {
1859 error_callback(self, span, ResolutionError::FailedToResolve {
1860 label: String::from("type-relative paths are not supported in this context"),
1865 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1866 PathResult::Failed { span, label, suggestion, .. } => {
1867 error_callback(self, span, ResolutionError::FailedToResolve {
1876 fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment {
1877 let mut seg = ast::PathSegment::from_ident(ident);
1878 seg.id = self.session.next_node_id();
1883 impl<'a> Resolver<'a> {
1884 pub fn new(session: &'a Session,
1888 crate_loader: &'a mut CrateLoader<'a>,
1889 arenas: &'a ResolverArenas<'a>)
1891 let root_def_id = DefId::local(CRATE_DEF_INDEX);
1892 let root_module_kind = ModuleKind::Def(
1897 let graph_root = arenas.alloc_module(ModuleData {
1898 no_implicit_prelude: attr::contains_name(&krate.attrs, sym::no_implicit_prelude),
1899 ..ModuleData::new(None, root_module_kind, root_def_id, Mark::root(), krate.span)
1901 let mut module_map = FxHashMap::default();
1902 module_map.insert(DefId::local(CRATE_DEF_INDEX), graph_root);
1904 let mut definitions = Definitions::default();
1905 DefCollector::new(&mut definitions, Mark::root())
1906 .collect_root(crate_name, session.local_crate_disambiguator());
1908 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> =
1909 session.opts.externs.iter().map(|kv| (Ident::from_str(kv.0), Default::default()))
1912 if !attr::contains_name(&krate.attrs, sym::no_core) {
1913 extern_prelude.insert(Ident::with_empty_ctxt(sym::core), Default::default());
1914 if !attr::contains_name(&krate.attrs, sym::no_std) {
1915 extern_prelude.insert(Ident::with_empty_ctxt(sym::std), Default::default());
1916 if session.rust_2018() {
1917 extern_prelude.insert(Ident::with_empty_ctxt(sym::meta), Default::default());
1922 let mut invocations = FxHashMap::default();
1923 invocations.insert(Mark::root(),
1924 arenas.alloc_invocation_data(InvocationData::root(graph_root)));
1926 let mut macro_defs = FxHashMap::default();
1927 macro_defs.insert(Mark::root(), root_def_id);
1929 let non_macro_attr = |mark_used| Lrc::new(SyntaxExtension::default(
1930 SyntaxExtensionKind::NonMacroAttr { mark_used }, session.edition()
1940 // The outermost module has def ID 0; this is not reflected in the
1946 has_self: FxHashSet::default(),
1947 field_names: FxHashMap::default(),
1949 determined_imports: Vec::new(),
1950 indeterminate_imports: Vec::new(),
1952 current_module: graph_root,
1954 value_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1955 type_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1956 macro_ns: vec![Rib::new(ModuleRibKind(graph_root))],
1958 label_ribs: Vec::new(),
1960 current_trait_ref: None,
1961 current_self_type: None,
1962 current_self_item: None,
1963 last_import_segment: false,
1964 blacklisted_binding: None,
1966 primitive_type_table: PrimitiveTypeTable::new(),
1968 partial_res_map: Default::default(),
1969 import_res_map: Default::default(),
1970 label_res_map: Default::default(),
1971 export_map: FxHashMap::default(),
1972 trait_map: Default::default(),
1974 block_map: Default::default(),
1975 extern_module_map: FxHashMap::default(),
1976 binding_parent_modules: FxHashMap::default(),
1978 glob_map: Default::default(),
1980 used_imports: FxHashSet::default(),
1981 maybe_unused_trait_imports: Default::default(),
1982 maybe_unused_extern_crates: Vec::new(),
1984 unused_labels: FxHashMap::default(),
1986 privacy_errors: Vec::new(),
1987 ambiguity_errors: Vec::new(),
1988 use_injections: Vec::new(),
1989 macro_expanded_macro_export_errors: BTreeSet::new(),
1992 dummy_binding: arenas.alloc_name_binding(NameBinding {
1993 kind: NameBindingKind::Res(Res::Err, false),
1995 expansion: Mark::root(),
1997 vis: ty::Visibility::Public,
2001 macro_names: FxHashSet::default(),
2002 builtin_macros: FxHashMap::default(),
2003 macro_use_prelude: FxHashMap::default(),
2004 all_macros: FxHashMap::default(),
2005 macro_map: FxHashMap::default(),
2006 non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
2009 local_macro_def_scopes: FxHashMap::default(),
2010 name_already_seen: FxHashMap::default(),
2011 potentially_unused_imports: Vec::new(),
2012 struct_constructors: Default::default(),
2013 unused_macros: FxHashSet::default(),
2014 current_type_ascription: Vec::new(),
2015 injected_crate: None,
2019 pub fn arenas() -> ResolverArenas<'a> {
2023 fn non_macro_attr(&self, mark_used: bool) -> Lrc<SyntaxExtension> {
2024 self.non_macro_attrs[mark_used as usize].clone()
2027 /// Runs the function on each namespace.
2028 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2034 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2036 match self.macro_defs.get(&ctxt.outer()) {
2037 Some(&def_id) => return def_id,
2038 None => ctxt.remove_mark(),
2043 /// Entry point to crate resolution.
2044 pub fn resolve_crate(&mut self, krate: &Crate) {
2045 ImportResolver { resolver: self }.finalize_imports();
2046 self.current_module = self.graph_root;
2047 self.finalize_current_module_macro_resolutions();
2049 visit::walk_crate(self, krate);
2051 check_unused::check_crate(self, krate);
2052 self.report_errors(krate);
2053 self.crate_loader.postprocess(krate);
2060 normal_ancestor_id: DefId,
2064 let module = ModuleData::new(Some(parent), kind, normal_ancestor_id, expansion, span);
2065 self.arenas.alloc_module(module)
2068 fn record_use(&mut self, ident: Ident, ns: Namespace,
2069 used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
2070 if let Some((b2, kind)) = used_binding.ambiguity {
2071 self.ambiguity_errors.push(AmbiguityError {
2072 kind, ident, b1: used_binding, b2,
2073 misc1: AmbiguityErrorMisc::None,
2074 misc2: AmbiguityErrorMisc::None,
2077 if let NameBindingKind::Import { directive, binding, ref used } = used_binding.kind {
2078 // Avoid marking `extern crate` items that refer to a name from extern prelude,
2079 // but not introduce it, as used if they are accessed from lexical scope.
2080 if is_lexical_scope {
2081 if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
2082 if let Some(crate_item) = entry.extern_crate_item {
2083 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
2090 directive.used.set(true);
2091 self.used_imports.insert((directive.id, ns));
2092 self.add_to_glob_map(&directive, ident);
2093 self.record_use(ident, ns, binding, false);
2098 fn add_to_glob_map(&mut self, directive: &ImportDirective<'_>, ident: Ident) {
2099 if directive.is_glob() {
2100 self.glob_map.entry(directive.id).or_default().insert(ident.name);
2104 /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
2105 /// More specifically, we proceed up the hierarchy of scopes and return the binding for
2106 /// `ident` in the first scope that defines it (or None if no scopes define it).
2108 /// A block's items are above its local variables in the scope hierarchy, regardless of where
2109 /// the items are defined in the block. For example,
2112 /// g(); // Since there are no local variables in scope yet, this resolves to the item.
2115 /// g(); // This resolves to the local variable `g` since it shadows the item.
2119 /// Invariant: This must only be called during main resolution, not during
2120 /// import resolution.
2121 fn resolve_ident_in_lexical_scope(&mut self,
2124 record_used_id: Option<NodeId>,
2126 -> Option<LexicalScopeBinding<'a>> {
2127 assert!(ns == TypeNS || ns == ValueNS);
2128 if ident.name == kw::Invalid {
2129 return Some(LexicalScopeBinding::Res(Res::Err));
2131 ident.span = if ident.name == kw::SelfUpper {
2132 // FIXME(jseyfried) improve `Self` hygiene
2133 ident.span.with_ctxt(SyntaxContext::empty())
2134 } else if ns == TypeNS {
2137 ident.span.modern_and_legacy()
2140 // Walk backwards up the ribs in scope.
2141 let record_used = record_used_id.is_some();
2142 let mut module = self.graph_root;
2143 for i in (0 .. self.ribs[ns].len()).rev() {
2144 debug!("walk rib\n{:?}", self.ribs[ns][i].bindings);
2145 if let Some(res) = self.ribs[ns][i].bindings.get(&ident).cloned() {
2146 // The ident resolves to a type parameter or local variable.
2147 return Some(LexicalScopeBinding::Res(
2148 self.validate_res_from_ribs(ns, i, res, record_used, path_span),
2152 module = match self.ribs[ns][i].kind {
2153 ModuleRibKind(module) => module,
2154 MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => {
2155 // If an invocation of this macro created `ident`, give up on `ident`
2156 // and switch to `ident`'s source from the macro definition.
2157 ident.span.remove_mark();
2163 let item = self.resolve_ident_in_module_unadjusted(
2164 ModuleOrUniformRoot::Module(module),
2170 if let Ok(binding) = item {
2171 // The ident resolves to an item.
2172 return Some(LexicalScopeBinding::Item(binding));
2176 ModuleKind::Block(..) => {}, // We can see through blocks
2181 ident.span = ident.span.modern();
2182 let mut poisoned = None;
2184 let opt_module = if let Some(node_id) = record_used_id {
2185 self.hygienic_lexical_parent_with_compatibility_fallback(module, &mut ident.span,
2186 node_id, &mut poisoned)
2188 self.hygienic_lexical_parent(module, &mut ident.span)
2190 module = unwrap_or!(opt_module, break);
2191 let orig_current_module = self.current_module;
2192 self.current_module = module; // Lexical resolutions can never be a privacy error.
2193 let result = self.resolve_ident_in_module_unadjusted(
2194 ModuleOrUniformRoot::Module(module),
2200 self.current_module = orig_current_module;
2204 if let Some(node_id) = poisoned {
2205 self.session.buffer_lint_with_diagnostic(
2206 lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
2207 node_id, ident.span,
2208 &format!("cannot find {} `{}` in this scope", ns.descr(), ident),
2209 lint::builtin::BuiltinLintDiagnostics::
2210 ProcMacroDeriveResolutionFallback(ident.span),
2213 return Some(LexicalScopeBinding::Item(binding))
2215 Err(Determined) => continue,
2216 Err(Undetermined) =>
2217 span_bug!(ident.span, "undetermined resolution during main resolution pass"),
2221 if !module.no_implicit_prelude {
2223 if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
2224 return Some(LexicalScopeBinding::Item(binding));
2227 if ns == TypeNS && is_known_tool(ident.name) {
2228 let binding = (Res::ToolMod, ty::Visibility::Public,
2229 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
2230 return Some(LexicalScopeBinding::Item(binding));
2232 if let Some(prelude) = self.prelude {
2233 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
2234 ModuleOrUniformRoot::Module(prelude),
2240 return Some(LexicalScopeBinding::Item(binding));
2248 fn hygienic_lexical_parent(&mut self, module: Module<'a>, span: &mut Span)
2249 -> Option<Module<'a>> {
2250 if !module.expansion.outer_is_descendant_of(span.ctxt()) {
2251 return Some(self.macro_def_scope(span.remove_mark()));
2254 if let ModuleKind::Block(..) = module.kind {
2255 return Some(module.parent.unwrap());
2261 fn hygienic_lexical_parent_with_compatibility_fallback(&mut self, module: Module<'a>,
2262 span: &mut Span, node_id: NodeId,
2263 poisoned: &mut Option<NodeId>)
2264 -> Option<Module<'a>> {
2265 if let module @ Some(..) = self.hygienic_lexical_parent(module, span) {
2269 // We need to support the next case under a deprecation warning
2272 // ---- begin: this comes from a proc macro derive
2273 // mod implementation_details {
2274 // // Note that `MyStruct` is not in scope here.
2275 // impl SomeTrait for MyStruct { ... }
2279 // So we have to fall back to the module's parent during lexical resolution in this case.
2280 if let Some(parent) = module.parent {
2281 // Inner module is inside the macro, parent module is outside of the macro.
2282 if module.expansion != parent.expansion &&
2283 module.expansion.is_descendant_of(parent.expansion) {
2284 // The macro is a proc macro derive
2285 if module.expansion.looks_like_proc_macro_derive() {
2286 if parent.expansion.outer_is_descendant_of(span.ctxt()) {
2287 *poisoned = Some(node_id);
2288 return module.parent;
2297 fn resolve_ident_in_module(
2299 module: ModuleOrUniformRoot<'a>,
2302 parent_scope: Option<&ParentScope<'a>>,
2305 ) -> Result<&'a NameBinding<'a>, Determinacy> {
2306 self.resolve_ident_in_module_ext(
2307 module, ident, ns, parent_scope, record_used, path_span
2308 ).map_err(|(determinacy, _)| determinacy)
2311 fn resolve_ident_in_module_ext(
2313 module: ModuleOrUniformRoot<'a>,
2316 parent_scope: Option<&ParentScope<'a>>,
2319 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
2320 let orig_current_module = self.current_module;
2322 ModuleOrUniformRoot::Module(module) => {
2323 if let Some(def) = ident.span.modernize_and_adjust(module.expansion) {
2324 self.current_module = self.macro_def_scope(def);
2327 ModuleOrUniformRoot::ExternPrelude => {
2328 ident.span.modernize_and_adjust(Mark::root());
2330 ModuleOrUniformRoot::CrateRootAndExternPrelude |
2331 ModuleOrUniformRoot::CurrentScope => {
2335 let result = self.resolve_ident_in_module_unadjusted_ext(
2336 module, ident, ns, parent_scope, false, record_used, path_span,
2338 self.current_module = orig_current_module;
2342 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
2343 let mut ctxt = ident.span.ctxt();
2344 let mark = if ident.name == kw::DollarCrate {
2345 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2346 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2347 // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
2348 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2349 // definitions actually produced by `macro` and `macro` definitions produced by
2350 // `macro_rules!`, but at least such configurations are not stable yet.
2351 ctxt = ctxt.modern_and_legacy();
2352 let mut iter = ctxt.marks().into_iter().rev().peekable();
2353 let mut result = None;
2354 // Find the last modern mark from the end if it exists.
2355 while let Some(&(mark, transparency)) = iter.peek() {
2356 if transparency == Transparency::Opaque {
2357 result = Some(mark);
2363 // Then find the last legacy mark from the end if it exists.
2364 for (mark, transparency) in iter {
2365 if transparency == Transparency::SemiTransparent {
2366 result = Some(mark);
2373 ctxt = ctxt.modern();
2374 ctxt.adjust(Mark::root())
2376 let module = match mark {
2377 Some(def) => self.macro_def_scope(def),
2378 None => return self.graph_root,
2380 self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.normal_ancestor_id })
2383 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
2384 let mut module = self.get_module(module.normal_ancestor_id);
2385 while module.span.ctxt().modern() != *ctxt {
2386 let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
2387 module = self.get_module(parent.normal_ancestor_id);
2394 // We maintain a list of value ribs and type ribs.
2396 // Simultaneously, we keep track of the current position in the module
2397 // graph in the `current_module` pointer. When we go to resolve a name in
2398 // the value or type namespaces, we first look through all the ribs and
2399 // then query the module graph. When we resolve a name in the module
2400 // namespace, we can skip all the ribs (since nested modules are not
2401 // allowed within blocks in Rust) and jump straight to the current module
2404 // Named implementations are handled separately. When we find a method
2405 // call, we consult the module node to find all of the implementations in
2406 // scope. This information is lazily cached in the module node. We then
2407 // generate a fake "implementation scope" containing all the
2408 // implementations thus found, for compatibility with old resolve pass.
2410 pub fn with_scope<F, T>(&mut self, id: NodeId, f: F) -> T
2411 where F: FnOnce(&mut Resolver<'_>) -> T
2413 let id = self.definitions.local_def_id(id);
2414 let module = self.module_map.get(&id).cloned(); // clones a reference
2415 if let Some(module) = module {
2416 // Move down in the graph.
2417 let orig_module = replace(&mut self.current_module, module);
2418 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
2419 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
2421 self.finalize_current_module_macro_resolutions();
2424 self.current_module = orig_module;
2425 self.ribs[ValueNS].pop();
2426 self.ribs[TypeNS].pop();
2433 /// Searches the current set of local scopes for labels. Returns the first non-`None` label that
2434 /// is returned by the given predicate function
2436 /// Stops after meeting a closure.
2437 fn search_label<P, R>(&self, mut ident: Ident, pred: P) -> Option<R>
2438 where P: Fn(&Rib<'_, NodeId>, Ident) -> Option<R>
2440 for rib in self.label_ribs.iter().rev() {
2443 // If an invocation of this macro created `ident`, give up on `ident`
2444 // and switch to `ident`'s source from the macro definition.
2445 MacroDefinition(def) => {
2446 if def == self.macro_def(ident.span.ctxt()) {
2447 ident.span.remove_mark();
2451 // Do not resolve labels across function boundary
2455 let r = pred(rib, ident);
2463 fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
2464 debug!("resolve_adt");
2465 self.with_current_self_item(item, |this| {
2466 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2467 let item_def_id = this.definitions.local_def_id(item.id);
2468 this.with_self_rib(Res::SelfTy(None, Some(item_def_id)), |this| {
2469 visit::walk_item(this, item);
2475 fn future_proof_import(&mut self, use_tree: &ast::UseTree) {
2476 let segments = &use_tree.prefix.segments;
2477 if !segments.is_empty() {
2478 let ident = segments[0].ident;
2479 if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2483 let nss = match use_tree.kind {
2484 ast::UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2487 let report_error = |this: &Self, ns| {
2488 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2489 this.session.span_err(ident.span, &format!("imports cannot refer to {}", what));
2493 match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) {
2494 Some(LexicalScopeBinding::Res(..)) => {
2495 report_error(self, ns);
2497 Some(LexicalScopeBinding::Item(binding)) => {
2498 let orig_blacklisted_binding =
2499 mem::replace(&mut self.blacklisted_binding, Some(binding));
2500 if let Some(LexicalScopeBinding::Res(..)) =
2501 self.resolve_ident_in_lexical_scope(ident, ns, None,
2502 use_tree.prefix.span) {
2503 report_error(self, ns);
2505 self.blacklisted_binding = orig_blacklisted_binding;
2510 } else if let ast::UseTreeKind::Nested(use_trees) = &use_tree.kind {
2511 for (use_tree, _) in use_trees {
2512 self.future_proof_import(use_tree);
2517 fn resolve_item(&mut self, item: &Item) {
2518 let name = item.ident.name;
2519 debug!("(resolving item) resolving {} ({:?})", name, item.node);
2522 ItemKind::Ty(_, ref generics) => {
2523 self.with_current_self_item(item, |this| {
2524 this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2525 let item_def_id = this.definitions.local_def_id(item.id);
2526 this.with_self_rib(Res::SelfTy(Some(item_def_id), None), |this| {
2527 visit::walk_item(this, item)
2533 ItemKind::Existential(_, ref generics) |
2534 ItemKind::Fn(_, _, ref generics, _) => {
2535 self.with_generic_param_rib(
2536 HasGenericParams(generics, ItemRibKind),
2537 |this| visit::walk_item(this, item)
2541 ItemKind::Enum(_, ref generics) |
2542 ItemKind::Struct(_, ref generics) |
2543 ItemKind::Union(_, ref generics) => {
2544 self.resolve_adt(item, generics);
2547 ItemKind::Impl(.., ref generics, ref opt_trait_ref, ref self_type, ref impl_items) =>
2548 self.resolve_implementation(generics,
2554 ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
2555 // Create a new rib for the trait-wide type parameters.
2556 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2557 let local_def_id = this.definitions.local_def_id(item.id);
2558 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
2559 this.visit_generics(generics);
2560 walk_list!(this, visit_param_bound, bounds);
2562 for trait_item in trait_items {
2563 let generic_params = HasGenericParams(&trait_item.generics,
2565 this.with_generic_param_rib(generic_params, |this| {
2566 match trait_item.node {
2567 TraitItemKind::Const(ref ty, ref default) => {
2570 // Only impose the restrictions of
2571 // ConstRibKind for an actual constant
2572 // expression in a provided default.
2573 if let Some(ref expr) = *default{
2574 this.with_constant_rib(|this| {
2575 this.visit_expr(expr);
2579 TraitItemKind::Method(_, _) => {
2580 visit::walk_trait_item(this, trait_item)
2582 TraitItemKind::Type(..) => {
2583 visit::walk_trait_item(this, trait_item)
2585 TraitItemKind::Macro(_) => {
2586 panic!("unexpanded macro in resolve!")
2595 ItemKind::TraitAlias(ref generics, ref bounds) => {
2596 // Create a new rib for the trait-wide type parameters.
2597 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2598 let local_def_id = this.definitions.local_def_id(item.id);
2599 this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| {
2600 this.visit_generics(generics);
2601 walk_list!(this, visit_param_bound, bounds);
2606 ItemKind::Mod(_) | ItemKind::ForeignMod(_) => {
2607 self.with_scope(item.id, |this| {
2608 visit::walk_item(this, item);
2612 ItemKind::Static(ref ty, _, ref expr) |
2613 ItemKind::Const(ref ty, ref expr) => {
2614 debug!("resolve_item ItemKind::Const");
2615 self.with_item_rib(|this| {
2617 this.with_constant_rib(|this| {
2618 this.visit_expr(expr);
2623 ItemKind::Use(ref use_tree) => {
2624 self.future_proof_import(use_tree);
2627 ItemKind::ExternCrate(..) |
2628 ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => {
2629 // do nothing, these are just around to be encoded
2632 ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"),
2636 fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F)
2637 where F: FnOnce(&mut Resolver<'_>)
2639 debug!("with_generic_param_rib");
2640 match generic_params {
2641 HasGenericParams(generics, rib_kind) => {
2642 let mut function_type_rib = Rib::new(rib_kind);
2643 let mut function_value_rib = Rib::new(rib_kind);
2644 let mut seen_bindings = FxHashMap::default();
2645 for param in &generics.params {
2647 GenericParamKind::Lifetime { .. } => {}
2648 GenericParamKind::Type { .. } => {
2649 let ident = param.ident.modern();
2650 debug!("with_generic_param_rib: {}", param.id);
2652 if seen_bindings.contains_key(&ident) {
2653 let span = seen_bindings.get(&ident).unwrap();
2654 let err = ResolutionError::NameAlreadyUsedInParameterList(
2658 resolve_error(self, param.ident.span, err);
2660 seen_bindings.entry(ident).or_insert(param.ident.span);
2662 // Plain insert (no renaming).
2665 self.definitions.local_def_id(param.id),
2667 function_type_rib.bindings.insert(ident, res);
2668 self.record_partial_res(param.id, PartialRes::new(res));
2670 GenericParamKind::Const { .. } => {
2671 let ident = param.ident.modern();
2672 debug!("with_generic_param_rib: {}", param.id);
2674 if seen_bindings.contains_key(&ident) {
2675 let span = seen_bindings.get(&ident).unwrap();
2676 let err = ResolutionError::NameAlreadyUsedInParameterList(
2680 resolve_error(self, param.ident.span, err);
2682 seen_bindings.entry(ident).or_insert(param.ident.span);
2685 DefKind::ConstParam,
2686 self.definitions.local_def_id(param.id),
2688 function_value_rib.bindings.insert(ident, res);
2689 self.record_partial_res(param.id, PartialRes::new(res));
2693 self.ribs[ValueNS].push(function_value_rib);
2694 self.ribs[TypeNS].push(function_type_rib);
2697 NoGenericParams => {
2704 if let HasGenericParams(..) = generic_params {
2705 self.ribs[TypeNS].pop();
2706 self.ribs[ValueNS].pop();
2710 fn with_label_rib<F>(&mut self, f: F)
2711 where F: FnOnce(&mut Resolver<'_>)
2713 self.label_ribs.push(Rib::new(NormalRibKind));
2715 self.label_ribs.pop();
2718 fn with_item_rib<F>(&mut self, f: F)
2719 where F: FnOnce(&mut Resolver<'_>)
2721 self.ribs[ValueNS].push(Rib::new(ItemRibKind));
2722 self.ribs[TypeNS].push(Rib::new(ItemRibKind));
2724 self.ribs[TypeNS].pop();
2725 self.ribs[ValueNS].pop();
2728 fn with_constant_rib<F>(&mut self, f: F)
2729 where F: FnOnce(&mut Resolver<'_>)
2731 debug!("with_constant_rib");
2732 self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
2733 self.label_ribs.push(Rib::new(ConstantItemRibKind));
2735 self.label_ribs.pop();
2736 self.ribs[ValueNS].pop();
2739 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2740 where F: FnOnce(&mut Resolver<'_>) -> T
2742 // Handle nested impls (inside fn bodies)
2743 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2744 let result = f(self);
2745 self.current_self_type = previous_value;
2749 fn with_current_self_item<T, F>(&mut self, self_item: &Item, f: F) -> T
2750 where F: FnOnce(&mut Resolver<'_>) -> T
2752 let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
2753 let result = f(self);
2754 self.current_self_item = previous_value;
2758 /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2759 fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
2760 where F: FnOnce(&mut Resolver<'_>, Option<DefId>) -> T
2762 let mut new_val = None;
2763 let mut new_id = None;
2764 if let Some(trait_ref) = opt_trait_ref {
2765 let path: Vec<_> = Segment::from_path(&trait_ref.path);
2766 let res = self.smart_resolve_path_fragment(
2770 trait_ref.path.span,
2771 PathSource::Trait(AliasPossibility::No),
2772 CrateLint::SimplePath(trait_ref.ref_id),
2774 if res != Res::Err {
2775 new_id = Some(res.def_id());
2776 let span = trait_ref.path.span;
2777 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2778 self.resolve_path_without_parent_scope(
2783 CrateLint::SimplePath(trait_ref.ref_id),
2786 new_val = Some((module, trait_ref.clone()));
2790 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2791 let result = f(self, new_id);
2792 self.current_trait_ref = original_trait_ref;
2796 fn with_self_rib<F>(&mut self, self_res: Res, f: F)
2797 where F: FnOnce(&mut Resolver<'_>)
2799 let mut self_type_rib = Rib::new(NormalRibKind);
2801 // Plain insert (no renaming, since types are not currently hygienic)
2802 self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
2803 self.ribs[TypeNS].push(self_type_rib);
2805 self.ribs[TypeNS].pop();
2808 fn with_self_struct_ctor_rib<F>(&mut self, impl_id: DefId, f: F)
2809 where F: FnOnce(&mut Resolver<'_>)
2811 let self_res = Res::SelfCtor(impl_id);
2812 let mut self_type_rib = Rib::new(NormalRibKind);
2813 self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
2814 self.ribs[ValueNS].push(self_type_rib);
2816 self.ribs[ValueNS].pop();
2819 fn resolve_implementation(&mut self,
2820 generics: &Generics,
2821 opt_trait_reference: &Option<TraitRef>,
2824 impl_items: &[ImplItem]) {
2825 debug!("resolve_implementation");
2826 // If applicable, create a rib for the type parameters.
2827 self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
2828 // Dummy self type for better errors if `Self` is used in the trait path.
2829 this.with_self_rib(Res::SelfTy(None, None), |this| {
2830 // Resolve the trait reference, if necessary.
2831 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2832 let item_def_id = this.definitions.local_def_id(item_id);
2833 this.with_self_rib(Res::SelfTy(trait_id, Some(item_def_id)), |this| {
2834 if let Some(trait_ref) = opt_trait_reference.as_ref() {
2835 // Resolve type arguments in the trait path.
2836 visit::walk_trait_ref(this, trait_ref);
2838 // Resolve the self type.
2839 this.visit_ty(self_type);
2840 // Resolve the generic parameters.
2841 this.visit_generics(generics);
2842 // Resolve the items within the impl.
2843 this.with_current_self_type(self_type, |this| {
2844 this.with_self_struct_ctor_rib(item_def_id, |this| {
2845 debug!("resolve_implementation with_self_struct_ctor_rib");
2846 for impl_item in impl_items {
2847 this.resolve_visibility(&impl_item.vis);
2849 // We also need a new scope for the impl item type parameters.
2850 let generic_params = HasGenericParams(&impl_item.generics,
2852 this.with_generic_param_rib(generic_params, |this| {
2853 use self::ResolutionError::*;
2854 match impl_item.node {
2855 ImplItemKind::Const(..) => {
2857 "resolve_implementation ImplItemKind::Const",
2859 // If this is a trait impl, ensure the const
2861 this.check_trait_item(
2865 |n, s| ConstNotMemberOfTrait(n, s),
2868 this.with_constant_rib(|this| {
2869 visit::walk_impl_item(this, impl_item)
2872 ImplItemKind::Method(..) => {
2873 // If this is a trait impl, ensure the method
2875 this.check_trait_item(impl_item.ident,
2878 |n, s| MethodNotMemberOfTrait(n, s));
2880 visit::walk_impl_item(this, impl_item);
2882 ImplItemKind::Type(ref ty) => {
2883 // If this is a trait impl, ensure the type
2885 this.check_trait_item(impl_item.ident,
2888 |n, s| TypeNotMemberOfTrait(n, s));
2892 ImplItemKind::Existential(ref bounds) => {
2893 // If this is a trait impl, ensure the type
2895 this.check_trait_item(impl_item.ident,
2898 |n, s| TypeNotMemberOfTrait(n, s));
2900 for bound in bounds {
2901 this.visit_param_bound(bound);
2904 ImplItemKind::Macro(_) =>
2905 panic!("unexpanded macro in resolve!"),
2917 fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F)
2918 where F: FnOnce(Name, &str) -> ResolutionError<'_>
2920 // If there is a TraitRef in scope for an impl, then the method must be in the
2922 if let Some((module, _)) = self.current_trait_ref {
2923 if self.resolve_ident_in_module(
2924 ModuleOrUniformRoot::Module(module),
2931 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2932 resolve_error(self, span, err(ident.name, &path_names_to_string(path)));
2937 fn resolve_local(&mut self, local: &Local) {
2938 // Resolve the type.
2939 walk_list!(self, visit_ty, &local.ty);
2941 // Resolve the initializer.
2942 walk_list!(self, visit_expr, &local.init);
2944 // Resolve the pattern.
2945 self.resolve_pattern(&local.pat, PatternSource::Let, &mut FxHashMap::default());
2948 // build a map from pattern identifiers to binding-info's.
2949 // this is done hygienically. This could arise for a macro
2950 // that expands into an or-pattern where one 'x' was from the
2951 // user and one 'x' came from the macro.
2952 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2953 let mut binding_map = FxHashMap::default();
2955 pat.walk(&mut |pat| {
2956 if let PatKind::Ident(binding_mode, ident, ref sub_pat) = pat.node {
2957 if sub_pat.is_some() || match self.partial_res_map.get(&pat.id)
2958 .map(|res| res.base_res()) {
2959 Some(Res::Local(..)) => true,
2962 let binding_info = BindingInfo { span: ident.span, binding_mode: binding_mode };
2963 binding_map.insert(ident, binding_info);
2972 // Checks that all of the arms in an or-pattern have exactly the
2973 // same set of bindings, with the same binding modes for each.
2974 fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) {
2975 if pats.is_empty() {
2979 let mut missing_vars = FxHashMap::default();
2980 let mut inconsistent_vars = FxHashMap::default();
2981 for (i, p) in pats.iter().enumerate() {
2982 let map_i = self.binding_mode_map(&p);
2984 for (j, q) in pats.iter().enumerate() {
2989 let map_j = self.binding_mode_map(&q);
2990 for (&key, &binding_i) in &map_i {
2991 if map_j.is_empty() { // Account for missing bindings when
2992 let binding_error = missing_vars // `map_j` has none.
2994 .or_insert(BindingError {
2996 origin: BTreeSet::new(),
2997 target: BTreeSet::new(),
2999 binding_error.origin.insert(binding_i.span);
3000 binding_error.target.insert(q.span);
3002 for (&key_j, &binding_j) in &map_j {
3003 match map_i.get(&key_j) {
3004 None => { // missing binding
3005 let binding_error = missing_vars
3007 .or_insert(BindingError {
3009 origin: BTreeSet::new(),
3010 target: BTreeSet::new(),
3012 binding_error.origin.insert(binding_j.span);
3013 binding_error.target.insert(p.span);
3015 Some(binding_i) => { // check consistent binding
3016 if binding_i.binding_mode != binding_j.binding_mode {
3019 .or_insert((binding_j.span, binding_i.span));
3027 let mut missing_vars = missing_vars.iter().collect::<Vec<_>>();
3028 missing_vars.sort();
3029 for (_, v) in missing_vars {
3031 *v.origin.iter().next().unwrap(),
3032 ResolutionError::VariableNotBoundInPattern(v));
3034 let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
3035 inconsistent_vars.sort();
3036 for (name, v) in inconsistent_vars {
3037 resolve_error(self, v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
3041 fn resolve_arm(&mut self, arm: &Arm) {
3042 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3044 self.resolve_pats(&arm.pats, PatternSource::Match);
3046 if let Some(ref expr) = arm.guard {
3047 self.visit_expr(expr)
3049 self.visit_expr(&arm.body);
3051 self.ribs[ValueNS].pop();
3054 /// Arising from `source`, resolve a sequence of patterns (top level or-patterns).
3055 fn resolve_pats(&mut self, pats: &[P<Pat>], source: PatternSource) {
3056 let mut bindings_list = FxHashMap::default();
3058 self.resolve_pattern(pat, source, &mut bindings_list);
3060 // This has to happen *after* we determine which pat_idents are variants
3061 self.check_consistent_bindings(pats);
3064 fn resolve_block(&mut self, block: &Block) {
3065 debug!("(resolving block) entering block");
3066 // Move down in the graph, if there's an anonymous module rooted here.
3067 let orig_module = self.current_module;
3068 let anonymous_module = self.block_map.get(&block.id).cloned(); // clones a reference
3070 let mut num_macro_definition_ribs = 0;
3071 if let Some(anonymous_module) = anonymous_module {
3072 debug!("(resolving block) found anonymous module, moving down");
3073 self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3074 self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3075 self.current_module = anonymous_module;
3076 self.finalize_current_module_macro_resolutions();
3078 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3081 // Descend into the block.
3082 for stmt in &block.stmts {
3083 if let ast::StmtKind::Item(ref item) = stmt.node {
3084 if let ast::ItemKind::MacroDef(..) = item.node {
3085 num_macro_definition_ribs += 1;
3086 let res = self.definitions.local_def_id(item.id);
3087 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3088 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3092 self.visit_stmt(stmt);
3096 self.current_module = orig_module;
3097 for _ in 0 .. num_macro_definition_ribs {
3098 self.ribs[ValueNS].pop();
3099 self.label_ribs.pop();
3101 self.ribs[ValueNS].pop();
3102 if anonymous_module.is_some() {
3103 self.ribs[TypeNS].pop();
3105 debug!("(resolving block) leaving block");
3108 fn fresh_binding(&mut self,
3111 outer_pat_id: NodeId,
3112 pat_src: PatternSource,
3113 bindings: &mut FxHashMap<Ident, NodeId>)
3115 // Add the binding to the local ribs, if it
3116 // doesn't already exist in the bindings map. (We
3117 // must not add it if it's in the bindings map
3118 // because that breaks the assumptions later
3119 // passes make about or-patterns.)
3120 let ident = ident.modern_and_legacy();
3121 let mut res = Res::Local(pat_id);
3122 match bindings.get(&ident).cloned() {
3123 Some(id) if id == outer_pat_id => {
3124 // `Variant(a, a)`, error
3128 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(
3132 Some(..) if pat_src == PatternSource::FnParam => {
3133 // `fn f(a: u8, a: u8)`, error
3137 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
3141 Some(..) if pat_src == PatternSource::Match ||
3142 pat_src == PatternSource::Let => {
3143 // `Variant1(a) | Variant2(a)`, ok
3144 // Reuse definition from the first `a`.
3145 res = self.ribs[ValueNS].last_mut().unwrap().bindings[&ident];
3148 span_bug!(ident.span, "two bindings with the same name from \
3149 unexpected pattern source {:?}", pat_src);
3152 // A completely fresh binding, add to the lists if it's valid.
3153 if ident.name != kw::Invalid {
3154 bindings.insert(ident, outer_pat_id);
3155 self.ribs[ValueNS].last_mut().unwrap().bindings.insert(ident, res);
3163 fn resolve_pattern(&mut self,
3165 pat_src: PatternSource,
3166 // Maps idents to the node ID for the
3167 // outermost pattern that binds them.
3168 bindings: &mut FxHashMap<Ident, NodeId>) {
3169 // Visit all direct subpatterns of this pattern.
3170 let outer_pat_id = pat.id;
3171 pat.walk(&mut |pat| {
3172 debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
3174 PatKind::Ident(bmode, ident, ref opt_pat) => {
3175 // First try to resolve the identifier as some existing
3176 // entity, then fall back to a fresh binding.
3177 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS,
3179 .and_then(LexicalScopeBinding::item);
3180 let res = binding.map(NameBinding::res).and_then(|res| {
3181 let is_syntactic_ambiguity = opt_pat.is_none() &&
3182 bmode == BindingMode::ByValue(Mutability::Immutable);
3184 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
3185 Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
3186 // Disambiguate in favor of a unit struct/variant
3187 // or constant pattern.
3188 self.record_use(ident, ValueNS, binding.unwrap(), false);
3191 Res::Def(DefKind::Ctor(..), _)
3192 | Res::Def(DefKind::Const, _)
3193 | Res::Def(DefKind::Static, _) => {
3194 // This is unambiguously a fresh binding, either syntactically
3195 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3196 // to something unusable as a pattern (e.g., constructor function),
3197 // but we still conservatively report an error, see
3198 // issues/33118#issuecomment-233962221 for one reason why.
3202 ResolutionError::BindingShadowsSomethingUnacceptable(
3203 pat_src.descr(), ident.name, binding.unwrap())
3207 Res::Def(DefKind::Fn, _) | Res::Err => {
3208 // These entities are explicitly allowed
3209 // to be shadowed by fresh bindings.
3213 span_bug!(ident.span, "unexpected resolution for an \
3214 identifier in pattern: {:?}", res);
3217 }).unwrap_or_else(|| {
3218 self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
3221 self.record_partial_res(pat.id, PartialRes::new(res));
3224 PatKind::TupleStruct(ref path, ..) => {
3225 self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
3228 PatKind::Path(ref qself, ref path) => {
3229 self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3232 PatKind::Struct(ref path, ..) => {
3233 self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
3241 visit::walk_pat(self, pat);
3244 // High-level and context dependent path resolution routine.
3245 // Resolves the path and records the resolution into definition map.
3246 // If resolution fails tries several techniques to find likely
3247 // resolution candidates, suggest imports or other help, and report
3248 // errors in user friendly way.
3249 fn smart_resolve_path(&mut self,
3251 qself: Option<&QSelf>,
3253 source: PathSource<'_>) {
3254 self.smart_resolve_path_fragment(
3257 &Segment::from_path(path),
3260 CrateLint::SimplePath(id),
3264 fn smart_resolve_path_fragment(&mut self,
3266 qself: Option<&QSelf>,
3269 source: PathSource<'_>,
3270 crate_lint: CrateLint)
3272 let ns = source.namespace();
3273 let is_expected = &|res| source.is_expected(res);
3275 let report_errors = |this: &mut Self, res: Option<Res>| {
3276 let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
3277 let def_id = this.current_module.normal_ancestor_id;
3278 let node_id = this.definitions.as_local_node_id(def_id).unwrap();
3279 let better = res.is_some();
3280 this.use_injections.push(UseError { err, candidates, node_id, better });
3281 PartialRes::new(Res::Err)
3284 let partial_res = match self.resolve_qpath_anywhere(
3290 source.defer_to_typeck(),
3291 source.global_by_default(),
3294 Some(partial_res) if partial_res.unresolved_segments() == 0 => {
3295 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
3298 // Add a temporary hack to smooth the transition to new struct ctor
3299 // visibility rules. See #38932 for more details.
3301 if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
3302 if let Some((ctor_res, ctor_vis))
3303 = self.struct_constructors.get(&def_id).cloned() {
3304 if is_expected(ctor_res) && self.is_accessible(ctor_vis) {
3305 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
3306 self.session.buffer_lint(lint, id, span,
3307 "private struct constructors are not usable through \
3308 re-exports in outer modules",
3310 res = Some(PartialRes::new(ctor_res));
3315 res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
3318 Some(partial_res) if source.defer_to_typeck() => {
3319 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3320 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3321 // it needs to be added to the trait map.
3323 let item_name = path.last().unwrap().ident;
3324 let traits = self.get_traits_containing_item(item_name, ns);
3325 self.trait_map.insert(id, traits);
3328 let mut std_path = vec![Segment::from_ident(Ident::with_empty_ctxt(sym::std))];
3329 std_path.extend(path);
3330 if self.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
3331 let cl = CrateLint::No;
3333 if let PathResult::Module(_) | PathResult::NonModule(_) =
3334 self.resolve_path_without_parent_scope(&std_path, ns, false, span, cl)
3336 // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3337 let item_span = path.iter().last().map(|segment| segment.ident.span)
3339 debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
3340 let mut hm = self.session.confused_type_with_std_module.borrow_mut();
3341 hm.insert(item_span, span);
3342 // In some places (E0223) we only have access to the full path
3343 hm.insert(span, span);
3348 _ => report_errors(self, None)
3351 if let PathSource::TraitItem(..) = source {} else {
3352 // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3353 self.record_partial_res(id, partial_res);
3358 /// Only used in a specific case of type ascription suggestions
3360 fn get_colon_suggestion_span(&self, start: Span) -> Span {
3361 let cm = self.session.source_map();
3362 start.to(cm.next_point(start))
3365 fn type_ascription_suggestion(
3367 err: &mut DiagnosticBuilder<'_>,
3370 debug!("type_ascription_suggetion {:?}", base_span);
3371 let cm = self.session.source_map();
3372 let base_snippet = cm.span_to_snippet(base_span);
3373 debug!("self.current_type_ascription {:?}", self.current_type_ascription);
3374 if let Some(sp) = self.current_type_ascription.last() {
3377 // Try to find the `:`; bail on first non-':' / non-whitespace.
3378 sp = cm.next_point(sp);
3379 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
3380 let line_sp = cm.lookup_char_pos(sp.hi()).line;
3381 let line_base_sp = cm.lookup_char_pos(base_span.lo()).line;
3383 let mut show_label = true;
3384 if line_sp != line_base_sp {
3385 err.span_suggestion_short(
3387 "did you mean to use `;` here instead?",
3389 Applicability::MaybeIncorrect,
3392 let colon_sp = self.get_colon_suggestion_span(sp);
3393 let after_colon_sp = self.get_colon_suggestion_span(
3394 colon_sp.shrink_to_hi(),
3396 if !cm.span_to_snippet(after_colon_sp).map(|s| s == " ")
3399 err.span_suggestion(
3401 "maybe you meant to write a path separator here",
3403 Applicability::MaybeIncorrect,
3407 if let Ok(base_snippet) = base_snippet {
3408 let mut sp = after_colon_sp;
3410 // Try to find an assignment
3411 sp = cm.next_point(sp);
3412 let snippet = cm.span_to_snippet(sp.to(cm.next_point(sp)));
3414 Ok(ref x) if x.as_str() == "=" => {
3415 err.span_suggestion(
3417 "maybe you meant to write an assignment here",
3418 format!("let {}", base_snippet),
3419 Applicability::MaybeIncorrect,
3424 Ok(ref x) if x.as_str() == "\n" => break,
3432 err.span_label(base_span,
3433 "expecting a type here because of type ascription");
3436 } else if !snippet.trim().is_empty() {
3437 debug!("tried to find type ascription `:` token, couldn't find it");
3447 fn self_type_is_available(&mut self, span: Span) -> bool {
3448 let binding = self.resolve_ident_in_lexical_scope(Ident::with_empty_ctxt(kw::SelfUpper),
3449 TypeNS, None, span);
3450 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3453 fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
3454 let ident = Ident::new(kw::SelfLower, self_span);
3455 let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
3456 if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3459 // Resolve in alternative namespaces if resolution in the primary namespace fails.
3460 fn resolve_qpath_anywhere(
3463 qself: Option<&QSelf>,
3465 primary_ns: Namespace,
3467 defer_to_typeck: bool,
3468 global_by_default: bool,
3469 crate_lint: CrateLint,
3470 ) -> Option<PartialRes> {
3471 let mut fin_res = None;
3472 // FIXME: can't resolve paths in macro namespace yet, macros are
3473 // processed by the little special hack below.
3474 for (i, ns) in [primary_ns, TypeNS, ValueNS, /*MacroNS*/].iter().cloned().enumerate() {
3475 if i == 0 || ns != primary_ns {
3476 match self.resolve_qpath(id, qself, path, ns, span, global_by_default, crate_lint) {
3477 // If defer_to_typeck, then resolution > no resolution,
3478 // otherwise full resolution > partial resolution > no resolution.
3479 Some(partial_res) if partial_res.unresolved_segments() == 0 ||
3481 return Some(partial_res),
3482 partial_res => if fin_res.is_none() { fin_res = partial_res },
3486 if primary_ns != MacroNS &&
3487 (self.macro_names.contains(&path[0].ident.modern()) ||
3488 self.builtin_macros.get(&path[0].ident.name).cloned()
3489 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) ||
3490 self.macro_use_prelude.get(&path[0].ident.name).cloned()
3491 .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) {
3492 // Return some dummy definition, it's enough for error reporting.
3493 return Some(PartialRes::new(Res::Def(
3494 DefKind::Macro(MacroKind::Bang),
3495 DefId::local(CRATE_DEF_INDEX),
3501 /// Handles paths that may refer to associated items.
3505 qself: Option<&QSelf>,
3509 global_by_default: bool,
3510 crate_lint: CrateLint,
3511 ) -> Option<PartialRes> {
3513 "resolve_qpath(id={:?}, qself={:?}, path={:?}, \
3514 ns={:?}, span={:?}, global_by_default={:?})",
3523 if let Some(qself) = qself {
3524 if qself.position == 0 {
3525 // This is a case like `<T>::B`, where there is no
3526 // trait to resolve. In that case, we leave the `B`
3527 // segment to be resolved by type-check.
3528 return Some(PartialRes::with_unresolved_segments(
3529 Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
3533 // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3535 // Currently, `path` names the full item (`A::B::C`, in
3536 // our example). so we extract the prefix of that that is
3537 // the trait (the slice upto and including
3538 // `qself.position`). And then we recursively resolve that,
3539 // but with `qself` set to `None`.
3541 // However, setting `qself` to none (but not changing the
3542 // span) loses the information about where this path
3543 // *actually* appears, so for the purposes of the crate
3544 // lint we pass along information that this is the trait
3545 // name from a fully qualified path, and this also
3546 // contains the full span (the `CrateLint::QPathTrait`).
3547 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3548 let partial_res = self.smart_resolve_path_fragment(
3551 &path[..=qself.position],
3553 PathSource::TraitItem(ns),
3554 CrateLint::QPathTrait {
3556 qpath_span: qself.path_span,
3560 // The remaining segments (the `C` in our example) will
3561 // have to be resolved by type-check, since that requires doing
3562 // trait resolution.
3563 return Some(PartialRes::with_unresolved_segments(
3564 partial_res.base_res(),
3565 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3569 let result = match self.resolve_path_without_parent_scope(
3576 PathResult::NonModule(path_res) => path_res,
3577 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3578 PartialRes::new(module.res().unwrap())
3580 // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3581 // don't report an error right away, but try to fallback to a primitive type.
3582 // So, we are still able to successfully resolve something like
3584 // use std::u8; // bring module u8 in scope
3585 // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3586 // u8::max_value() // OK, resolves to associated function <u8>::max_value,
3587 // // not to non-existent std::u8::max_value
3590 // Such behavior is required for backward compatibility.
3591 // The same fallback is used when `a` resolves to nothing.
3592 PathResult::Module(ModuleOrUniformRoot::Module(_)) |
3593 PathResult::Failed { .. }
3594 if (ns == TypeNS || path.len() > 1) &&
3595 self.primitive_type_table.primitive_types
3596 .contains_key(&path[0].ident.name) => {
3597 let prim = self.primitive_type_table.primitive_types[&path[0].ident.name];
3598 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3600 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3601 PartialRes::new(module.res().unwrap()),
3602 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3603 resolve_error(self, span, ResolutionError::FailedToResolve { label, suggestion });
3604 PartialRes::new(Res::Err)
3606 PathResult::Module(..) | PathResult::Failed { .. } => return None,
3607 PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
3610 if path.len() > 1 && !global_by_default && result.base_res() != Res::Err &&
3611 path[0].ident.name != kw::PathRoot &&
3612 path[0].ident.name != kw::DollarCrate {
3613 let unqualified_result = {
3614 match self.resolve_path_without_parent_scope(
3615 &[*path.last().unwrap()],
3621 PathResult::NonModule(path_res) => path_res.base_res(),
3622 PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
3623 module.res().unwrap(),
3624 _ => return Some(result),
3627 if result.base_res() == unqualified_result {
3628 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3629 self.session.buffer_lint(lint, id, span, "unnecessary qualification")
3636 fn resolve_path_without_parent_scope(
3639 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3642 crate_lint: CrateLint,
3643 ) -> PathResult<'a> {
3644 // Macro and import paths must have full parent scope available during resolution,
3645 // other paths will do okay with parent module alone.
3646 assert!(opt_ns != None && opt_ns != Some(MacroNS));
3647 let parent_scope = ParentScope { module: self.current_module, ..self.dummy_parent_scope() };
3648 self.resolve_path(path, opt_ns, &parent_scope, record_used, path_span, crate_lint)
3654 opt_ns: Option<Namespace>, // `None` indicates a module path in import
3655 parent_scope: &ParentScope<'a>,
3658 crate_lint: CrateLint,
3659 ) -> PathResult<'a> {
3660 let mut module = None;
3661 let mut allow_super = true;
3662 let mut second_binding = None;
3663 self.current_module = parent_scope.module;
3666 "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \
3667 path_span={:?}, crate_lint={:?})",
3675 for (i, &Segment { ident, id }) in path.iter().enumerate() {
3676 debug!("resolve_path ident {} {:?} {:?}", i, ident, id);
3677 let record_segment_res = |this: &mut Self, res| {
3679 if let Some(id) = id {
3680 if !this.partial_res_map.contains_key(&id) {
3681 assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
3682 this.record_partial_res(id, PartialRes::new(res));
3688 let is_last = i == path.len() - 1;
3689 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
3690 let name = ident.name;
3692 allow_super &= ns == TypeNS &&
3693 (name == kw::SelfLower ||
3697 if allow_super && name == kw::Super {
3698 let mut ctxt = ident.span.ctxt().modern();
3699 let self_module = match i {
3700 0 => Some(self.resolve_self(&mut ctxt, self.current_module)),
3702 Some(ModuleOrUniformRoot::Module(module)) => Some(module),
3706 if let Some(self_module) = self_module {
3707 if let Some(parent) = self_module.parent {
3708 module = Some(ModuleOrUniformRoot::Module(
3709 self.resolve_self(&mut ctxt, parent)));
3713 let msg = "there are too many initial `super`s.".to_string();
3714 return PathResult::Failed {
3718 is_error_from_last_segment: false,
3722 if name == kw::SelfLower {
3723 let mut ctxt = ident.span.ctxt().modern();
3724 module = Some(ModuleOrUniformRoot::Module(
3725 self.resolve_self(&mut ctxt, self.current_module)));
3728 if name == kw::PathRoot && ident.span.rust_2018() {
3729 module = Some(ModuleOrUniformRoot::ExternPrelude);
3732 if name == kw::PathRoot &&
3733 ident.span.rust_2015() && self.session.rust_2018() {
3734 // `::a::b` from 2015 macro on 2018 global edition
3735 module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude);
3738 if name == kw::PathRoot ||
3739 name == kw::Crate ||
3740 name == kw::DollarCrate {
3741 // `::a::b`, `crate::a::b` or `$crate::a::b`
3742 module = Some(ModuleOrUniformRoot::Module(
3743 self.resolve_crate_root(ident)));
3749 // Report special messages for path segment keywords in wrong positions.
3750 if ident.is_path_segment_keyword() && i != 0 {
3751 let name_str = if name == kw::PathRoot {
3752 "crate root".to_string()
3754 format!("`{}`", name)
3756 let label = if i == 1 && path[0].ident.name == kw::PathRoot {
3757 format!("global paths cannot start with {}", name_str)
3759 format!("{} in paths can only be used in start position", name_str)
3761 return PathResult::Failed {
3765 is_error_from_last_segment: false,
3769 let binding = if let Some(module) = module {
3770 self.resolve_ident_in_module(module, ident, ns, None, record_used, path_span)
3771 } else if opt_ns.is_none() || opt_ns == Some(MacroNS) {
3772 assert!(ns == TypeNS);
3773 let scopes = if opt_ns.is_none() { ScopeSet::Import(ns) } else { ScopeSet::Module };
3774 self.early_resolve_ident_in_lexical_scope(ident, scopes, parent_scope, record_used,
3775 record_used, path_span)
3777 let record_used_id =
3778 if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
3779 match self.resolve_ident_in_lexical_scope(ident, ns, record_used_id, path_span) {
3780 // we found a locally-imported or available item/module
3781 Some(LexicalScopeBinding::Item(binding)) => Ok(binding),
3782 // we found a local variable or type param
3783 Some(LexicalScopeBinding::Res(res))
3784 if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => {
3785 record_segment_res(self, res);
3786 return PathResult::NonModule(PartialRes::with_unresolved_segments(
3790 _ => Err(Determinacy::determined(record_used)),
3797 second_binding = Some(binding);
3799 let res = binding.res();
3800 let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
3801 if let Some(next_module) = binding.module() {
3802 module = Some(ModuleOrUniformRoot::Module(next_module));
3803 record_segment_res(self, res);
3804 } else if res == Res::ToolMod && i + 1 != path.len() {
3805 if binding.is_import() {
3806 self.session.struct_span_err(
3807 ident.span, "cannot use a tool module through an import"
3809 binding.span, "the tool module imported here"
3812 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
3813 return PathResult::NonModule(PartialRes::new(res));
3814 } else if res == Res::Err {
3815 return PathResult::NonModule(PartialRes::new(Res::Err));
3816 } else if opt_ns.is_some() && (is_last || maybe_assoc) {
3817 self.lint_if_path_starts_with_module(
3823 return PathResult::NonModule(PartialRes::with_unresolved_segments(
3824 res, path.len() - i - 1
3827 let label = format!(
3828 "`{}` is {} {}, not a module",
3834 return PathResult::Failed {
3838 is_error_from_last_segment: is_last,
3842 Err(Undetermined) => return PathResult::Indeterminate,
3843 Err(Determined) => {
3844 if let Some(ModuleOrUniformRoot::Module(module)) = module {
3845 if opt_ns.is_some() && !module.is_normal() {
3846 return PathResult::NonModule(PartialRes::with_unresolved_segments(
3847 module.res().unwrap(), path.len() - i
3851 let module_res = match module {
3852 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
3855 let (label, suggestion) = if module_res == self.graph_root.res() {
3856 let is_mod = |res| {
3857 match res { Res::Def(DefKind::Mod, _) => true, _ => false }
3859 let mut candidates =
3860 self.lookup_import_candidates(ident, TypeNS, is_mod);
3861 candidates.sort_by_cached_key(|c| {
3862 (c.path.segments.len(), c.path.to_string())
3864 if let Some(candidate) = candidates.get(0) {
3866 String::from("unresolved import"),
3868 vec![(ident.span, candidate.path.to_string())],
3869 String::from("a similar path exists"),
3870 Applicability::MaybeIncorrect,
3873 } else if !ident.is_reserved() {
3874 (format!("maybe a missing `extern crate {};`?", ident), None)
3876 // the parser will already have complained about the keyword being used
3877 return PathResult::NonModule(PartialRes::new(Res::Err));
3880 (format!("use of undeclared type or module `{}`", ident), None)
3882 (format!("could not find `{}` in `{}`", ident, path[i - 1].ident), None)
3884 return PathResult::Failed {
3888 is_error_from_last_segment: is_last,
3894 self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding);
3896 PathResult::Module(match module {
3897 Some(module) => module,
3898 None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
3899 _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path),
3903 fn lint_if_path_starts_with_module(
3905 crate_lint: CrateLint,
3908 second_binding: Option<&NameBinding<'_>>,
3910 let (diag_id, diag_span) = match crate_lint {
3911 CrateLint::No => return,
3912 CrateLint::SimplePath(id) => (id, path_span),
3913 CrateLint::UsePath { root_id, root_span } => (root_id, root_span),
3914 CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span),
3917 let first_name = match path.get(0) {
3918 // In the 2018 edition this lint is a hard error, so nothing to do
3919 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
3923 // We're only interested in `use` paths which should start with
3924 // `{{root}}` currently.
3925 if first_name != kw::PathRoot {
3930 // If this import looks like `crate::...` it's already good
3931 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
3932 // Otherwise go below to see if it's an extern crate
3934 // If the path has length one (and it's `PathRoot` most likely)
3935 // then we don't know whether we're gonna be importing a crate or an
3936 // item in our crate. Defer this lint to elsewhere
3940 // If the first element of our path was actually resolved to an
3941 // `ExternCrate` (also used for `crate::...`) then no need to issue a
3942 // warning, this looks all good!
3943 if let Some(binding) = second_binding {
3944 if let NameBindingKind::Import { directive: d, .. } = binding.kind {
3945 // Careful: we still want to rewrite paths from
3946 // renamed extern crates.
3947 if let ImportDirectiveSubclass::ExternCrate { source: None, .. } = d.subclass {
3953 let diag = lint::builtin::BuiltinLintDiagnostics
3954 ::AbsPathWithModule(diag_span);
3955 self.session.buffer_lint_with_diagnostic(
3956 lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
3958 "absolute paths must start with `self`, `super`, \
3959 `crate`, or an external crate name in the 2018 edition",
3963 // Validate a local resolution (from ribs).
3964 fn validate_res_from_ribs(
3972 debug!("validate_res_from_ribs({:?})", res);
3973 let ribs = &self.ribs[ns][rib_index + 1..];
3975 // An invalid forward use of a type parameter from a previous default.
3976 if let ForwardTyParamBanRibKind = self.ribs[ns][rib_index].kind {
3978 resolve_error(self, span, ResolutionError::ForwardDeclaredTyParam);
3980 assert_eq!(res, Res::Err);
3984 // An invalid use of a type parameter as the type of a const parameter.
3985 if let TyParamAsConstParamTy = self.ribs[ns][rib_index].kind {
3987 resolve_error(self, span, ResolutionError::ConstParamDependentOnTypeParam);
3989 assert_eq!(res, Res::Err);
3995 use ResolutionError::*;
3996 let mut res_err = None;
4000 NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
4001 ForwardTyParamBanRibKind | TyParamAsConstParamTy => {
4002 // Nothing to do. Continue.
4004 ItemRibKind | FnItemRibKind | AssocItemRibKind => {
4005 // This was an attempt to access an upvar inside a
4006 // named function item. This is not allowed, so we
4009 // We don't immediately trigger a resolve error, because
4010 // we want certain other resolution errors (namely those
4011 // emitted for `ConstantItemRibKind` below) to take
4013 res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
4016 ConstantItemRibKind => {
4017 // Still doesn't deal with upvars
4019 resolve_error(self, span, AttemptToUseNonConstantValueInConstant);
4025 if let Some(res_err) = res_err {
4026 resolve_error(self, span, res_err);
4030 Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => {
4033 NormalRibKind | AssocItemRibKind |
4034 ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind |
4035 ConstantItemRibKind | TyParamAsConstParamTy => {
4036 // Nothing to do. Continue.
4038 ItemRibKind | FnItemRibKind => {
4039 // This was an attempt to use a type parameter outside its scope.
4044 ResolutionError::GenericParamsFromOuterFunction(res),
4052 Res::Def(DefKind::ConstParam, _) => {
4053 let mut ribs = ribs.iter().peekable();
4054 if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() {
4055 // When declaring const parameters inside function signatures, the first rib
4056 // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it
4057 // (spuriously) conflicting with the const param.
4061 if let ItemRibKind | FnItemRibKind = rib.kind {
4062 // This was an attempt to use a const parameter outside its scope.
4067 ResolutionError::GenericParamsFromOuterFunction(res),
4079 fn lookup_assoc_candidate<FilterFn>(&mut self,
4082 filter_fn: FilterFn)
4083 -> Option<AssocSuggestion>
4084 where FilterFn: Fn(Res) -> bool
4086 fn extract_node_id(t: &Ty) -> Option<NodeId> {
4088 TyKind::Path(None, _) => Some(t.id),
4089 TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
4090 // This doesn't handle the remaining `Ty` variants as they are not
4091 // that commonly the self_type, it might be interesting to provide
4092 // support for those in future.
4097 // Fields are generally expected in the same contexts as locals.
4098 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
4099 if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
4100 // Look for a field with the same name in the current self_type.
4101 if let Some(resolution) = self.partial_res_map.get(&node_id) {
4102 match resolution.base_res() {
4103 Res::Def(DefKind::Struct, did) | Res::Def(DefKind::Union, did)
4104 if resolution.unresolved_segments() == 0 => {
4105 if let Some(field_names) = self.field_names.get(&did) {
4106 if field_names.iter().any(|&field_name| ident.name == field_name) {
4107 return Some(AssocSuggestion::Field);
4117 // Look for associated items in the current trait.
4118 if let Some((module, _)) = self.current_trait_ref {
4119 if let Ok(binding) = self.resolve_ident_in_module(
4120 ModuleOrUniformRoot::Module(module),
4127 let res = binding.res();
4129 return Some(if self.has_self.contains(&res.def_id()) {
4130 AssocSuggestion::MethodWithSelf
4132 AssocSuggestion::AssocItem
4141 fn lookup_typo_candidate<FilterFn>(
4145 filter_fn: FilterFn,
4147 ) -> Option<TypoSuggestion>
4149 FilterFn: Fn(Res) -> bool,
4151 let add_module_candidates = |module: Module<'_>, names: &mut Vec<TypoSuggestion>| {
4152 for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
4153 if let Some(binding) = resolution.borrow().binding {
4154 if filter_fn(binding.res()) {
4155 names.push(TypoSuggestion {
4156 candidate: ident.name,
4157 article: binding.res().article(),
4158 kind: binding.res().descr(),
4165 let mut names = Vec::new();
4166 if path.len() == 1 {
4167 // Search in lexical scope.
4168 // Walk backwards up the ribs in scope and collect candidates.
4169 for rib in self.ribs[ns].iter().rev() {
4170 // Locals and type parameters
4171 for (ident, &res) in &rib.bindings {
4173 names.push(TypoSuggestion {
4174 candidate: ident.name,
4175 article: res.article(),
4181 if let ModuleRibKind(module) = rib.kind {
4182 // Items from this module
4183 add_module_candidates(module, &mut names);
4185 if let ModuleKind::Block(..) = module.kind {
4186 // We can see through blocks
4188 // Items from the prelude
4189 if !module.no_implicit_prelude {
4190 names.extend(self.extern_prelude.clone().iter().flat_map(|(ident, _)| {
4192 .maybe_process_path_extern(ident.name, ident.span)
4193 .and_then(|crate_id| {
4194 let crate_mod = Res::Def(
4198 index: CRATE_DEF_INDEX,
4202 if filter_fn(crate_mod) {
4203 Some(TypoSuggestion {
4204 candidate: ident.name,
4214 if let Some(prelude) = self.prelude {
4215 add_module_candidates(prelude, &mut names);
4222 // Add primitive types to the mix
4223 if filter_fn(Res::PrimTy(Bool)) {
4225 self.primitive_type_table.primitive_types.iter().map(|(name, _)| {
4229 kind: "primitive type",
4235 // Search in module.
4236 let mod_path = &path[..path.len() - 1];
4237 if let PathResult::Module(module) = self.resolve_path_without_parent_scope(
4238 mod_path, Some(TypeNS), false, span, CrateLint::No
4240 if let ModuleOrUniformRoot::Module(module) = module {
4241 add_module_candidates(module, &mut names);
4246 let name = path[path.len() - 1].ident.name;
4247 // Make sure error reporting is deterministic.
4248 names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
4250 match find_best_match_for_name(
4251 names.iter().map(|suggestion| &suggestion.candidate),
4255 Some(found) if found != name => names
4257 .find(|suggestion| suggestion.candidate == found),
4262 fn with_resolved_label<F>(&mut self, label: Option<Label>, id: NodeId, f: F)
4263 where F: FnOnce(&mut Resolver<'_>)
4265 if let Some(label) = label {
4266 self.unused_labels.insert(id, label.ident.span);
4267 self.with_label_rib(|this| {
4268 let ident = label.ident.modern_and_legacy();
4269 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4277 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
4278 self.with_resolved_label(label, id, |this| this.visit_block(block));
4281 fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
4282 // First, record candidate traits for this expression if it could
4283 // result in the invocation of a method call.
4285 self.record_candidate_traits_for_expr_if_necessary(expr);
4287 // Next, resolve the node.
4289 ExprKind::Path(ref qself, ref path) => {
4290 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
4291 visit::walk_expr(self, expr);
4294 ExprKind::Struct(ref path, ..) => {
4295 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
4296 visit::walk_expr(self, expr);
4299 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
4300 let node_id = self.search_label(label.ident, |rib, ident| {
4301 rib.bindings.get(&ident.modern_and_legacy()).cloned()
4305 // Search again for close matches...
4306 // Picks the first label that is "close enough", which is not necessarily
4307 // the closest match
4308 let close_match = self.search_label(label.ident, |rib, ident| {
4309 let names = rib.bindings.iter().filter_map(|(id, _)| {
4310 if id.span.ctxt() == label.ident.span.ctxt() {
4316 find_best_match_for_name(names, &*ident.as_str(), None)
4318 self.record_partial_res(expr.id, PartialRes::new(Res::Err));
4321 ResolutionError::UndeclaredLabel(&label.ident.as_str(),
4325 // Since this res is a label, it is never read.
4326 self.label_res_map.insert(expr.id, node_id);
4327 self.unused_labels.remove(&node_id);
4331 // visit `break` argument if any
4332 visit::walk_expr(self, expr);
4335 ExprKind::Let(ref pats, ref scrutinee) => {
4336 self.visit_expr(scrutinee);
4337 self.resolve_pats(pats, PatternSource::Let);
4340 ExprKind::If(ref cond, ref then, ref opt_else) => {
4341 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4342 self.visit_expr(cond);
4343 self.visit_block(then);
4344 self.ribs[ValueNS].pop();
4346 opt_else.as_ref().map(|expr| self.visit_expr(expr));
4349 ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
4351 ExprKind::While(ref subexpression, ref block, label) => {
4352 self.with_resolved_label(label, expr.id, |this| {
4353 this.ribs[ValueNS].push(Rib::new(NormalRibKind));
4354 this.visit_expr(subexpression);
4355 this.visit_block(block);
4356 this.ribs[ValueNS].pop();
4360 ExprKind::ForLoop(ref pattern, ref subexpression, ref block, label) => {
4361 self.visit_expr(subexpression);
4362 self.ribs[ValueNS].push(Rib::new(NormalRibKind));
4363 self.resolve_pattern(pattern, PatternSource::For, &mut FxHashMap::default());
4365 self.resolve_labeled_block(label, expr.id, block);
4367 self.ribs[ValueNS].pop();
4370 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
4372 // Equivalent to `visit::walk_expr` + passing some context to children.
4373 ExprKind::Field(ref subexpression, _) => {
4374 self.resolve_expr(subexpression, Some(expr));
4376 ExprKind::MethodCall(ref segment, ref arguments) => {
4377 let mut arguments = arguments.iter();
4378 self.resolve_expr(arguments.next().unwrap(), Some(expr));
4379 for argument in arguments {
4380 self.resolve_expr(argument, None);
4382 self.visit_path_segment(expr.span, segment);
4385 ExprKind::Call(ref callee, ref arguments) => {
4386 self.resolve_expr(callee, Some(expr));
4387 for argument in arguments {
4388 self.resolve_expr(argument, None);
4391 ExprKind::Type(ref type_expr, _) => {
4392 self.current_type_ascription.push(type_expr.span);
4393 visit::walk_expr(self, expr);
4394 self.current_type_ascription.pop();
4396 // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
4397 // resolve the arguments within the proper scopes so that usages of them inside the
4398 // closure are detected as upvars rather than normal closure arg usages.
4400 _, IsAsync::Async { .. }, _,
4401 ref fn_decl, ref body, _span,
4403 let rib_kind = NormalRibKind;
4404 self.ribs[ValueNS].push(Rib::new(rib_kind));
4405 // Resolve arguments:
4406 let mut bindings_list = FxHashMap::default();
4407 for argument in &fn_decl.inputs {
4408 self.resolve_pattern(&argument.pat, PatternSource::FnParam, &mut bindings_list);
4409 self.visit_ty(&argument.ty);
4411 // No need to resolve return type-- the outer closure return type is
4412 // FunctionRetTy::Default
4414 // Now resolve the inner closure
4416 // No need to resolve arguments: the inner closure has none.
4417 // Resolve the return type:
4418 visit::walk_fn_ret_ty(self, &fn_decl.output);
4420 self.visit_expr(body);
4422 self.ribs[ValueNS].pop();
4425 visit::walk_expr(self, expr);
4430 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
4432 ExprKind::Field(_, ident) => {
4433 // FIXME(#6890): Even though you can't treat a method like a
4434 // field, we need to add any trait methods we find that match
4435 // the field name so that we can do some nice error reporting
4436 // later on in typeck.
4437 let traits = self.get_traits_containing_item(ident, ValueNS);
4438 self.trait_map.insert(expr.id, traits);
4440 ExprKind::MethodCall(ref segment, ..) => {
4441 debug!("(recording candidate traits for expr) recording traits for {}",
4443 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
4444 self.trait_map.insert(expr.id, traits);
4452 fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
4453 -> Vec<TraitCandidate> {
4454 debug!("(getting traits containing item) looking for '{}'", ident.name);
4456 let mut found_traits = Vec::new();
4457 // Look for the current trait.
4458 if let Some((module, _)) = self.current_trait_ref {
4459 if self.resolve_ident_in_module(
4460 ModuleOrUniformRoot::Module(module),
4467 let def_id = module.def_id().unwrap();
4468 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
4472 ident.span = ident.span.modern();
4473 let mut search_module = self.current_module;
4475 self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
4476 search_module = unwrap_or!(
4477 self.hygienic_lexical_parent(search_module, &mut ident.span), break
4481 if let Some(prelude) = self.prelude {
4482 if !search_module.no_implicit_prelude {
4483 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
4490 fn get_traits_in_module_containing_item(&mut self,
4494 found_traits: &mut Vec<TraitCandidate>) {
4495 assert!(ns == TypeNS || ns == ValueNS);
4496 let mut traits = module.traits.borrow_mut();
4497 if traits.is_none() {
4498 let mut collected_traits = Vec::new();
4499 module.for_each_child(|name, ns, binding| {
4500 if ns != TypeNS { return }
4501 match binding.res() {
4502 Res::Def(DefKind::Trait, _) |
4503 Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
4507 *traits = Some(collected_traits.into_boxed_slice());
4510 for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
4511 // Traits have pseudo-modules that can be used to search for the given ident.
4512 if let Some(module) = binding.module() {
4513 let mut ident = ident;
4514 if ident.span.glob_adjust(
4520 if self.resolve_ident_in_module_unadjusted(
4521 ModuleOrUniformRoot::Module(module),
4527 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
4528 let trait_def_id = module.def_id().unwrap();
4529 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
4531 } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
4532 // For now, just treat all trait aliases as possible candidates, since we don't
4533 // know if the ident is somewhere in the transitive bounds.
4534 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
4535 let trait_def_id = binding.res().def_id();
4536 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
4538 bug!("candidate is not trait or trait alias?")
4543 fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
4544 trait_name: Ident) -> SmallVec<[NodeId; 1]> {
4545 let mut import_ids = smallvec![];
4546 while let NameBindingKind::Import { directive, binding, .. } = kind {
4547 self.maybe_unused_trait_imports.insert(directive.id);
4548 self.add_to_glob_map(&directive, trait_name);
4549 import_ids.push(directive.id);
4550 kind = &binding.kind;
4555 fn lookup_import_candidates_from_module<FilterFn>(&mut self,
4556 lookup_ident: Ident,
4557 namespace: Namespace,
4558 start_module: &'a ModuleData<'a>,
4560 filter_fn: FilterFn)
4561 -> Vec<ImportSuggestion>
4562 where FilterFn: Fn(Res) -> bool
4564 let mut candidates = Vec::new();
4565 let mut seen_modules = FxHashSet::default();
4566 let not_local_module = crate_name.name != kw::Crate;
4567 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
4569 while let Some((in_module,
4571 in_module_is_extern)) = worklist.pop() {
4572 self.populate_module_if_necessary(in_module);
4574 // We have to visit module children in deterministic order to avoid
4575 // instabilities in reported imports (#43552).
4576 in_module.for_each_child_stable(|ident, ns, name_binding| {
4577 // avoid imports entirely
4578 if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
4579 // avoid non-importable candidates as well
4580 if !name_binding.is_importable() { return; }
4582 // collect results based on the filter function
4583 if ident.name == lookup_ident.name && ns == namespace {
4584 let res = name_binding.res();
4587 let mut segms = path_segments.clone();
4588 if lookup_ident.span.rust_2018() {
4589 // crate-local absolute paths start with `crate::` in edition 2018
4590 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
4592 0, ast::PathSegment::from_ident(crate_name)
4596 segms.push(ast::PathSegment::from_ident(ident));
4598 span: name_binding.span,
4601 // the entity is accessible in the following cases:
4602 // 1. if it's defined in the same crate, it's always
4603 // accessible (since private entities can be made public)
4604 // 2. if it's defined in another crate, it's accessible
4605 // only if both the module is public and the entity is
4606 // declared as public (due to pruning, we don't explore
4607 // outside crate private modules => no need to check this)
4608 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
4609 let did = match res {
4610 Res::Def(DefKind::Ctor(..), did) => self.parent(did),
4611 _ => res.opt_def_id(),
4613 candidates.push(ImportSuggestion { did, path });
4618 // collect submodules to explore
4619 if let Some(module) = name_binding.module() {
4621 let mut path_segments = path_segments.clone();
4622 path_segments.push(ast::PathSegment::from_ident(ident));
4624 let is_extern_crate_that_also_appears_in_prelude =
4625 name_binding.is_extern_crate() &&
4626 lookup_ident.span.rust_2018();
4628 let is_visible_to_user =
4629 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
4631 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
4632 // add the module to the lookup
4633 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
4634 if seen_modules.insert(module.def_id().unwrap()) {
4635 worklist.push((module, path_segments, is_extern));
4645 /// When name resolution fails, this method can be used to look up candidate
4646 /// entities with the expected name. It allows filtering them using the
4647 /// supplied predicate (which should be used to only accept the types of
4648 /// definitions expected, e.g., traits). The lookup spans across all crates.
4650 /// N.B., the method does not look into imports, but this is not a problem,
4651 /// since we report the definitions (thus, the de-aliased imports).
4652 fn lookup_import_candidates<FilterFn>(&mut self,
4653 lookup_ident: Ident,
4654 namespace: Namespace,
4655 filter_fn: FilterFn)
4656 -> Vec<ImportSuggestion>
4657 where FilterFn: Fn(Res) -> bool
4659 let mut suggestions = self.lookup_import_candidates_from_module(
4660 lookup_ident, namespace, self.graph_root, Ident::with_empty_ctxt(kw::Crate), &filter_fn
4663 if lookup_ident.span.rust_2018() {
4664 let extern_prelude_names = self.extern_prelude.clone();
4665 for (ident, _) in extern_prelude_names.into_iter() {
4666 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name,
4668 let crate_root = self.get_module(DefId {
4670 index: CRATE_DEF_INDEX,
4672 self.populate_module_if_necessary(&crate_root);
4674 suggestions.extend(self.lookup_import_candidates_from_module(
4675 lookup_ident, namespace, crate_root, ident, &filter_fn));
4683 fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {
4684 let mut result = None;
4685 let mut seen_modules = FxHashSet::default();
4686 let mut worklist = vec![(self.graph_root, Vec::new())];
4688 while let Some((in_module, path_segments)) = worklist.pop() {
4689 // abort if the module is already found
4690 if result.is_some() { break; }
4692 self.populate_module_if_necessary(in_module);
4694 in_module.for_each_child_stable(|ident, _, name_binding| {
4695 // abort if the module is already found or if name_binding is private external
4696 if result.is_some() || !name_binding.vis.is_visible_locally() {
4699 if let Some(module) = name_binding.module() {
4701 let mut path_segments = path_segments.clone();
4702 path_segments.push(ast::PathSegment::from_ident(ident));
4703 let module_def_id = module.def_id().unwrap();
4704 if module_def_id == def_id {
4706 span: name_binding.span,
4707 segments: path_segments,
4709 result = Some((module, ImportSuggestion { did: Some(def_id), path }));
4711 // add the module to the lookup
4712 if seen_modules.insert(module_def_id) {
4713 worklist.push((module, path_segments));
4723 fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
4724 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
4725 self.populate_module_if_necessary(enum_module);
4727 let mut variants = Vec::new();
4728 enum_module.for_each_child_stable(|ident, _, name_binding| {
4729 if let Res::Def(DefKind::Variant, _) = name_binding.res() {
4730 let mut segms = enum_import_suggestion.path.segments.clone();
4731 segms.push(ast::PathSegment::from_ident(ident));
4732 variants.push(Path {
4733 span: name_binding.span,
4742 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
4743 debug!("(recording res) recording {:?} for {}", resolution, node_id);
4744 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
4745 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
4749 fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
4751 ast::VisibilityKind::Public => ty::Visibility::Public,
4752 ast::VisibilityKind::Crate(..) => {
4753 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
4755 ast::VisibilityKind::Inherited => {
4756 ty::Visibility::Restricted(self.current_module.normal_ancestor_id)
4758 ast::VisibilityKind::Restricted { ref path, id, .. } => {
4759 // For visibilities we are not ready to provide correct implementation of "uniform
4760 // paths" right now, so on 2018 edition we only allow module-relative paths for now.
4761 // On 2015 edition visibilities are resolved as crate-relative by default,
4762 // so we are prepending a root segment if necessary.
4763 let ident = path.segments.get(0).expect("empty path in visibility").ident;
4764 let crate_root = if ident.is_path_segment_keyword() {
4766 } else if ident.span.rust_2018() {
4767 let msg = "relative paths are not supported in visibilities on 2018 edition";
4768 self.session.struct_span_err(ident.span, msg)
4772 format!("crate::{}", path),
4773 Applicability::MaybeIncorrect,
4776 return ty::Visibility::Public;
4778 let ctxt = ident.span.ctxt();
4779 Some(Segment::from_ident(Ident::new(
4780 kw::PathRoot, path.span.shrink_to_lo().with_ctxt(ctxt)
4784 let segments = crate_root.into_iter()
4785 .chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
4786 let res = self.smart_resolve_path_fragment(
4791 PathSource::Visibility,
4792 CrateLint::SimplePath(id),
4794 if res == Res::Err {
4795 ty::Visibility::Public
4797 let vis = ty::Visibility::Restricted(res.def_id());
4798 if self.is_accessible(vis) {
4801 self.session.span_err(path.span, "visibilities can only be restricted \
4802 to ancestor modules");
4803 ty::Visibility::Public
4810 fn is_accessible(&self, vis: ty::Visibility) -> bool {
4811 vis.is_accessible_from(self.current_module.normal_ancestor_id, self)
4814 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
4815 vis.is_accessible_from(module.normal_ancestor_id, self)
4818 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
4819 if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) {
4820 if !ptr::eq(module, old_module) {
4821 span_bug!(binding.span, "parent module is reset for binding");
4826 fn disambiguate_legacy_vs_modern(
4828 legacy: &'a NameBinding<'a>,
4829 modern: &'a NameBinding<'a>,
4831 // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
4832 // is disambiguated to mitigate regressions from macro modularization.
4833 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
4834 match (self.binding_parent_modules.get(&PtrKey(legacy)),
4835 self.binding_parent_modules.get(&PtrKey(modern))) {
4836 (Some(legacy), Some(modern)) =>
4837 legacy.normal_ancestor_id == modern.normal_ancestor_id &&
4838 modern.is_ancestor_of(legacy),
4843 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
4844 if b.span.is_dummy() {
4845 let add_built_in = match b.res() {
4846 // These already contain the "built-in" prefix or look bad with it.
4847 Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
4850 let (built_in, from) = if from_prelude {
4851 ("", " from prelude")
4852 } else if b.is_extern_crate() && !b.is_import() &&
4853 self.session.opts.externs.get(&ident.as_str()).is_some() {
4854 ("", " passed with `--extern`")
4855 } else if add_built_in {
4861 let article = if built_in.is_empty() { b.article() } else { "a" };
4862 format!("{a}{built_in} {thing}{from}",
4863 a = article, thing = b.descr(), built_in = built_in, from = from)
4865 let introduced = if b.is_import() { "imported" } else { "defined" };
4866 format!("the {thing} {introduced} here",
4867 thing = b.descr(), introduced = introduced)
4871 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
4872 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
4873 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
4874 // We have to print the span-less alternative first, otherwise formatting looks bad.
4875 (b2, b1, misc2, misc1, true)
4877 (b1, b2, misc1, misc2, false)
4880 let mut err = struct_span_err!(self.session, ident.span, E0659,
4881 "`{ident}` is ambiguous ({why})",
4882 ident = ident, why = kind.descr());
4883 err.span_label(ident.span, "ambiguous name");
4885 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
4886 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
4887 let note_msg = format!("`{ident}` could{also} refer to {what}",
4888 ident = ident, also = also, what = what);
4890 let mut help_msgs = Vec::new();
4891 if b.is_glob_import() && (kind == AmbiguityKind::GlobVsGlob ||
4892 kind == AmbiguityKind::GlobVsExpanded ||
4893 kind == AmbiguityKind::GlobVsOuter &&
4894 swapped != also.is_empty()) {
4895 help_msgs.push(format!("consider adding an explicit import of \
4896 `{ident}` to disambiguate", ident = ident))
4898 if b.is_extern_crate() && ident.span.rust_2018() {
4899 help_msgs.push(format!(
4900 "use `::{ident}` to refer to this {thing} unambiguously",
4901 ident = ident, thing = b.descr(),
4904 if misc == AmbiguityErrorMisc::SuggestCrate {
4905 help_msgs.push(format!(
4906 "use `crate::{ident}` to refer to this {thing} unambiguously",
4907 ident = ident, thing = b.descr(),
4909 } else if misc == AmbiguityErrorMisc::SuggestSelf {
4910 help_msgs.push(format!(
4911 "use `self::{ident}` to refer to this {thing} unambiguously",
4912 ident = ident, thing = b.descr(),
4916 err.span_note(b.span, ¬e_msg);
4917 for (i, help_msg) in help_msgs.iter().enumerate() {
4918 let or = if i == 0 { "" } else { "or " };
4919 err.help(&format!("{}{}", or, help_msg));
4923 could_refer_to(b1, misc1, "");
4924 could_refer_to(b2, misc2, " also");
4928 fn report_errors(&mut self, krate: &Crate) {
4929 self.report_with_use_injections(krate);
4931 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
4932 let msg = "macro-expanded `macro_export` macros from the current crate \
4933 cannot be referred to by absolute paths";
4934 self.session.buffer_lint_with_diagnostic(
4935 lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
4936 CRATE_NODE_ID, span_use, msg,
4937 lint::builtin::BuiltinLintDiagnostics::
4938 MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
4942 for ambiguity_error in &self.ambiguity_errors {
4943 self.report_ambiguity_error(ambiguity_error);
4946 let mut reported_spans = FxHashSet::default();
4947 for &PrivacyError(dedup_span, ident, binding) in &self.privacy_errors {
4948 if reported_spans.insert(dedup_span) {
4949 span_err!(self.session, ident.span, E0603, "{} `{}` is private",
4950 binding.descr(), ident.name);
4955 fn report_with_use_injections(&mut self, krate: &Crate) {
4956 for UseError { mut err, candidates, node_id, better } in self.use_injections.drain(..) {
4957 let (span, found_use) = UsePlacementFinder::check(krate, node_id);
4958 if !candidates.is_empty() {
4959 show_candidates(&mut err, span, &candidates, better, found_use);
4965 fn report_conflict<'b>(&mut self,
4969 new_binding: &NameBinding<'b>,
4970 old_binding: &NameBinding<'b>) {
4971 // Error on the second of two conflicting names
4972 if old_binding.span.lo() > new_binding.span.lo() {
4973 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
4976 let container = match parent.kind {
4977 ModuleKind::Def(DefKind::Mod, _, _) => "module",
4978 ModuleKind::Def(DefKind::Trait, _, _) => "trait",
4979 ModuleKind::Block(..) => "block",
4983 let old_noun = match old_binding.is_import() {
4985 false => "definition",
4988 let new_participle = match new_binding.is_import() {
4993 let (name, span) = (ident.name, self.session.source_map().def_span(new_binding.span));
4995 if let Some(s) = self.name_already_seen.get(&name) {
5001 let old_kind = match (ns, old_binding.module()) {
5002 (ValueNS, _) => "value",
5003 (MacroNS, _) => "macro",
5004 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
5005 (TypeNS, Some(module)) if module.is_normal() => "module",
5006 (TypeNS, Some(module)) if module.is_trait() => "trait",
5007 (TypeNS, _) => "type",
5010 let msg = format!("the name `{}` is defined multiple times", name);
5012 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
5013 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
5014 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
5015 true => struct_span_err!(self.session, span, E0254, "{}", msg),
5016 false => struct_span_err!(self.session, span, E0260, "{}", msg),
5018 _ => match (old_binding.is_import(), new_binding.is_import()) {
5019 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
5020 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
5021 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
5025 err.note(&format!("`{}` must be defined only once in the {} namespace of this {}",
5030 err.span_label(span, format!("`{}` re{} here", name, new_participle));
5032 self.session.source_map().def_span(old_binding.span),
5033 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
5036 // See https://github.com/rust-lang/rust/issues/32354
5037 use NameBindingKind::Import;
5038 let directive = match (&new_binding.kind, &old_binding.kind) {
5039 // If there are two imports where one or both have attributes then prefer removing the
5040 // import without attributes.
5041 (Import { directive: new, .. }, Import { directive: old, .. }) if {
5042 !new_binding.span.is_dummy() && !old_binding.span.is_dummy() &&
5043 (new.has_attributes || old.has_attributes)
5045 if old.has_attributes {
5046 Some((new, new_binding.span, true))
5048 Some((old, old_binding.span, true))
5051 // Otherwise prioritize the new binding.
5052 (Import { directive, .. }, other) if !new_binding.span.is_dummy() =>
5053 Some((directive, new_binding.span, other.is_import())),
5054 (other, Import { directive, .. }) if !old_binding.span.is_dummy() =>
5055 Some((directive, old_binding.span, other.is_import())),
5059 // Check if the target of the use for both bindings is the same.
5060 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
5061 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
5062 let from_item = self.extern_prelude.get(&ident)
5063 .map(|entry| entry.introduced_by_item)
5065 // Only suggest removing an import if both bindings are to the same def, if both spans
5066 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
5067 // been introduced by a item.
5068 let should_remove_import = duplicate && !has_dummy_span &&
5069 ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
5072 Some((directive, span, true)) if should_remove_import && directive.is_nested() =>
5073 self.add_suggestion_for_duplicate_nested_use(&mut err, directive, span),
5074 Some((directive, _, true)) if should_remove_import && !directive.is_glob() => {
5075 // Simple case - remove the entire import. Due to the above match arm, this can
5076 // only be a single use so just remove it entirely.
5077 err.tool_only_span_suggestion(
5078 directive.use_span_with_attributes,
5079 "remove unnecessary import",
5081 Applicability::MaybeIncorrect,
5084 Some((directive, span, _)) =>
5085 self.add_suggestion_for_rename_of_use(&mut err, name, directive, span),
5090 self.name_already_seen.insert(name, span);
5093 /// This function adds a suggestion to change the binding name of a new import that conflicts
5094 /// with an existing import.
5096 /// ```ignore (diagnostic)
5097 /// help: you can use `as` to change the binding name of the import
5099 /// LL | use foo::bar as other_bar;
5100 /// | ^^^^^^^^^^^^^^^^^^^^^
5102 fn add_suggestion_for_rename_of_use(
5104 err: &mut DiagnosticBuilder<'_>,
5106 directive: &ImportDirective<'_>,
5109 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
5110 format!("Other{}", name)
5112 format!("other_{}", name)
5115 let mut suggestion = None;
5116 match directive.subclass {
5117 ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } =>
5118 suggestion = Some(format!("self as {}", suggested_name)),
5119 ImportDirectiveSubclass::SingleImport { source, .. } => {
5120 if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
5121 .map(|pos| pos as usize) {
5122 if let Ok(snippet) = self.session.source_map()
5123 .span_to_snippet(binding_span) {
5124 if pos <= snippet.len() {
5125 suggestion = Some(format!(
5129 if snippet.ends_with(";") { ";" } else { "" }
5135 ImportDirectiveSubclass::ExternCrate { source, target, .. } =>
5136 suggestion = Some(format!(
5137 "extern crate {} as {};",
5138 source.unwrap_or(target.name),
5141 _ => unreachable!(),
5144 let rename_msg = "you can use `as` to change the binding name of the import";
5145 if let Some(suggestion) = suggestion {
5146 err.span_suggestion(
5150 Applicability::MaybeIncorrect,
5153 err.span_label(binding_span, rename_msg);
5157 /// This function adds a suggestion to remove a unnecessary binding from an import that is
5158 /// nested. In the following example, this function will be invoked to remove the `a` binding
5159 /// in the second use statement:
5161 /// ```ignore (diagnostic)
5162 /// use issue_52891::a;
5163 /// use issue_52891::{d, a, e};
5166 /// The following suggestion will be added:
5168 /// ```ignore (diagnostic)
5169 /// use issue_52891::{d, a, e};
5170 /// ^-- help: remove unnecessary import
5173 /// If the nested use contains only one import then the suggestion will remove the entire
5176 /// It is expected that the directive provided is a nested import - this isn't checked by the
5177 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
5178 /// as characters expected by span manipulations won't be present.
5179 fn add_suggestion_for_duplicate_nested_use(
5181 err: &mut DiagnosticBuilder<'_>,
5182 directive: &ImportDirective<'_>,
5185 assert!(directive.is_nested());
5186 let message = "remove unnecessary import";
5188 // Two examples will be used to illustrate the span manipulations we're doing:
5190 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
5191 // `a` and `directive.use_span` is `issue_52891::{d, a, e};`.
5192 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
5193 // `a` and `directive.use_span` is `issue_52891::{d, e, a};`.
5195 let (found_closing_brace, span) = find_span_of_binding_until_next_binding(
5196 self.session, binding_span, directive.use_span,
5199 // If there was a closing brace then identify the span to remove any trailing commas from
5200 // previous imports.
5201 if found_closing_brace {
5202 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
5203 err.tool_only_span_suggestion(span, message, String::new(),
5204 Applicability::MaybeIncorrect);
5206 // Remove the entire line if we cannot extend the span back, this indicates a
5207 // `issue_52891::{self}` case.
5208 err.span_suggestion(directive.use_span_with_attributes, message, String::new(),
5209 Applicability::MaybeIncorrect);
5215 err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
5218 fn extern_prelude_get(&mut self, ident: Ident, speculative: bool)
5219 -> Option<&'a NameBinding<'a>> {
5220 if ident.is_path_segment_keyword() {
5221 // Make sure `self`, `super` etc produce an error when passed to here.
5224 self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
5225 if let Some(binding) = entry.extern_crate_item {
5226 if !speculative && entry.introduced_by_item {
5227 self.record_use(ident, TypeNS, binding, false);
5231 let crate_id = if !speculative {
5232 self.crate_loader.process_path_extern(ident.name, ident.span)
5233 } else if let Some(crate_id) =
5234 self.crate_loader.maybe_process_path_extern(ident.name, ident.span) {
5239 let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
5240 self.populate_module_if_necessary(&crate_root);
5241 Some((crate_root, ty::Visibility::Public, DUMMY_SP, Mark::root())
5242 .to_name_binding(self.arenas))
5248 fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
5249 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
5252 fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
5253 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
5256 fn names_to_string(idents: &[Ident]) -> String {
5257 let mut result = String::new();
5258 for (i, ident) in idents.iter()
5259 .filter(|ident| ident.name != kw::PathRoot)
5262 result.push_str("::");
5264 result.push_str(&ident.as_str());
5269 fn path_names_to_string(path: &Path) -> String {
5270 names_to_string(&path.segments.iter()
5271 .map(|seg| seg.ident)
5272 .collect::<Vec<_>>())
5275 /// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant.
5276 fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
5277 let variant_path = &suggestion.path;
5278 let variant_path_string = path_names_to_string(variant_path);
5280 let path_len = suggestion.path.segments.len();
5281 let enum_path = ast::Path {
5282 span: suggestion.path.span,
5283 segments: suggestion.path.segments[0..path_len - 1].to_vec(),
5285 let enum_path_string = path_names_to_string(&enum_path);
5287 (variant_path_string, enum_path_string)
5290 /// When an entity with a given name is not available in scope, we search for
5291 /// entities with that name in all crates. This method allows outputting the
5292 /// results of this search in a programmer-friendly way
5293 fn show_candidates(err: &mut DiagnosticBuilder<'_>,
5294 // This is `None` if all placement locations are inside expansions
5296 candidates: &[ImportSuggestion],
5300 // we want consistent results across executions, but candidates are produced
5301 // by iterating through a hash map, so make sure they are ordered:
5302 let mut path_strings: Vec<_> =
5303 candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
5304 path_strings.sort();
5306 let better = if better { "better " } else { "" };
5307 let msg_diff = match path_strings.len() {
5308 1 => " is found in another module, you can import it",
5309 _ => "s are found in other modules, you can import them",
5311 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
5313 if let Some(span) = span {
5314 for candidate in &mut path_strings {
5315 // produce an additional newline to separate the new use statement
5316 // from the directly following item.
5317 let additional_newline = if found_use {
5322 *candidate = format!("use {};\n{}", candidate, additional_newline);
5325 err.span_suggestions(
5328 path_strings.into_iter(),
5329 Applicability::Unspecified,
5334 for candidate in path_strings {
5336 msg.push_str(&candidate);
5341 /// A somewhat inefficient routine to obtain the name of a module.
5342 fn module_to_string(module: Module<'_>) -> Option<String> {
5343 let mut names = Vec::new();
5345 fn collect_mod(names: &mut Vec<Ident>, module: Module<'_>) {
5346 if let ModuleKind::Def(.., name) = module.kind {
5347 if let Some(parent) = module.parent {
5348 names.push(Ident::with_empty_ctxt(name));
5349 collect_mod(names, parent);
5352 // danger, shouldn't be ident?
5353 names.push(Ident::from_str("<opaque>"));
5354 collect_mod(names, module.parent.unwrap());
5357 collect_mod(&mut names, module);
5359 if names.is_empty() {
5362 Some(names_to_string(&names.into_iter()
5364 .collect::<Vec<_>>()))
5367 #[derive(Copy, Clone, Debug)]
5369 /// Do not issue the lint.
5372 /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`.
5373 /// In this case, we can take the span of that path.
5376 /// This lint comes from a `use` statement. In this case, what we
5377 /// care about really is the *root* `use` statement; e.g., if we
5378 /// have nested things like `use a::{b, c}`, we care about the
5380 UsePath { root_id: NodeId, root_span: Span },
5382 /// This is the "trait item" from a fully qualified path. For example,
5383 /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`.
5384 /// The `path_span` is the span of the to the trait itself (`X::Y`).
5385 QPathTrait { qpath_id: NodeId, qpath_span: Span },
5389 fn node_id(&self) -> Option<NodeId> {
5391 CrateLint::No => None,
5392 CrateLint::SimplePath(id) |
5393 CrateLint::UsePath { root_id: id, .. } |
5394 CrateLint::QPathTrait { qpath_id: id, .. } => Some(id),
5399 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }