5 use rustc::session::Session;
6 use rustc::ty::{self, DefIdTree};
7 use rustc_ast::ast::{self, Ident, Path};
8 use rustc_ast::util::lev_distance::find_best_match_for_name;
9 use rustc_ast_pretty::pprust;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
12 use rustc_feature::BUILTIN_ATTRIBUTES;
13 use rustc_hir::def::Namespace::{self, *};
14 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
15 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::source_map::SourceMap;
18 use rustc_span::symbol::{kw, Symbol};
19 use rustc_span::{BytePos, MultiSpan, Span};
21 use crate::imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver};
22 use crate::path_names_to_string;
23 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
24 use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot};
25 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
26 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
28 type Res = def::Res<ast::NodeId>;
30 /// A vector of spans and replacements, a message and applicability.
31 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
33 crate struct TypoSuggestion {
34 pub candidate: Symbol,
39 crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
40 TypoSuggestion { candidate, res }
44 /// A free importable items suggested in case of resolution failure.
45 crate struct ImportSuggestion {
46 pub did: Option<DefId>,
50 /// Adjust the impl span so that just the `impl` keyword is taken by removing
51 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
52 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
54 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
55 /// parser. If you need to use this function or something similar, please consider updating the
56 /// `source_map` functions and this function to something more robust.
57 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
58 let impl_span = sm.span_until_char(impl_span, '<');
59 let impl_span = sm.span_until_whitespace(impl_span);
63 impl<'a> Resolver<'a> {
64 crate fn add_module_candidates(
67 names: &mut Vec<TypoSuggestion>,
68 filter_fn: &impl Fn(Res) -> bool,
70 for (key, resolution) in self.resolutions(module).borrow().iter() {
71 if let Some(binding) = resolution.borrow().binding {
72 let res = binding.res();
74 names.push(TypoSuggestion::from_res(key.ident.name, res));
80 /// Combines an error with provided span and emits it.
82 /// This takes the error provided, combines it with the span and any additional spans inside the
83 /// error and emits it.
84 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
85 self.into_struct_error(span, resolution_error).emit();
88 crate fn into_struct_error(
91 resolution_error: ResolutionError<'_>,
92 ) -> DiagnosticBuilder<'_> {
93 match resolution_error {
94 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
95 let mut err = struct_span_err!(
99 "can't use generic parameters from outer function",
101 err.span_label(span, "use of generic parameter from outer function".to_string());
103 let sm = self.session.source_map();
105 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
106 if let Some(impl_span) =
107 maybe_impl_defid.and_then(|def_id| self.definitions.opt_span(def_id))
110 reduce_impl_span_to_impl_keyword(sm, impl_span),
111 "`Self` type implicitly declared here, by this `impl`",
114 match (maybe_trait_defid, maybe_impl_defid) {
116 err.span_label(span, "can't use `Self` here");
119 err.span_label(span, "use a type here instead");
121 (None, None) => bug!("`impl` without trait nor type?"),
125 Res::Def(DefKind::TyParam, def_id) => {
126 if let Some(span) = self.definitions.opt_span(def_id) {
127 err.span_label(span, "type parameter from outer function");
130 Res::Def(DefKind::ConstParam, def_id) => {
131 if let Some(span) = self.definitions.opt_span(def_id) {
132 err.span_label(span, "const parameter from outer function");
137 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
143 if has_generic_params == HasGenericParams::Yes {
144 // Try to retrieve the span of the function signature and generate a new
145 // message with a local type or const parameter.
146 let sugg_msg = "try using a local generic parameter instead";
147 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
148 // Suggest the modification to the user
153 Applicability::MachineApplicable,
155 } else if let Some(sp) = sm.generate_fn_name_span(span) {
158 "try adding a local generic parameter in this method instead"
162 err.help("try using a local generic parameter instead");
168 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
169 let mut err = struct_span_err!(
173 "the name `{}` is already used for a generic \
174 parameter in this item's generic parameters",
177 err.span_label(span, "already used");
178 err.span_label(first_use_span, format!("first use of `{}`", name));
181 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
182 let mut err = struct_span_err!(
186 "method `{}` is not a member of trait `{}`",
190 err.span_label(span, format!("not a member of trait `{}`", trait_));
193 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
194 let mut err = struct_span_err!(
198 "type `{}` is not a member of trait `{}`",
202 err.span_label(span, format!("not a member of trait `{}`", trait_));
205 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
206 let mut err = struct_span_err!(
210 "const `{}` is not a member of trait `{}`",
214 err.span_label(span, format!("not a member of trait `{}`", trait_));
217 ResolutionError::VariableNotBoundInPattern(binding_error) => {
218 let BindingError { name, target, origin, could_be_path } = binding_error;
220 let target_sp = target.iter().copied().collect::<Vec<_>>();
221 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
223 let msp = MultiSpan::from_spans(target_sp.clone());
224 let mut err = struct_span_err!(
228 "variable `{}` is not bound in all patterns",
231 for sp in target_sp {
232 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
234 for sp in origin_sp {
235 err.span_label(sp, "variable not in all patterns");
238 let help_msg = format!(
239 "if you meant to match on a variant or a `const` item, consider \
240 making the path in the pattern qualified: `?::{}`",
243 err.span_help(span, &help_msg);
247 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
248 let mut err = struct_span_err!(
252 "variable `{}` is bound in inconsistent \
253 ways within the same match arm",
256 err.span_label(span, "bound in different ways");
257 err.span_label(first_binding_span, "first binding");
260 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
261 let mut err = struct_span_err!(
265 "identifier `{}` is bound more than once in this parameter list",
268 err.span_label(span, "used as parameter more than once");
271 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
272 let mut err = struct_span_err!(
276 "identifier `{}` is bound more than once in the same pattern",
279 err.span_label(span, "used in a pattern more than once");
282 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
283 let mut err = struct_span_err!(
287 "use of undeclared label `{}`",
290 if let Some(lev_candidate) = lev_candidate {
293 "a label with a similar name exists in this scope",
294 lev_candidate.to_string(),
295 Applicability::MaybeIncorrect,
298 err.span_label(span, format!("undeclared label `{}`", name));
302 ResolutionError::SelfImportsOnlyAllowedWithin => struct_span_err!(
307 "`self` imports are only allowed within a { } list"
309 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
310 let mut err = struct_span_err!(
314 "`self` import can only appear once in an import list"
316 err.span_label(span, "can only appear once in an import list");
319 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
320 let mut err = struct_span_err!(
324 "`self` import can only appear in an import list with \
327 err.span_label(span, "can only appear in an import list with a non-empty prefix");
330 ResolutionError::FailedToResolve { label, suggestion } => {
332 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
333 err.span_label(span, label);
335 if let Some((suggestions, msg, applicability)) = suggestion {
336 err.multipart_suggestion(&msg, suggestions, applicability);
341 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
342 let mut err = struct_span_err!(
347 "can't capture dynamic environment in a fn item"
349 err.help("use the `|| { ... }` closure form instead");
352 ResolutionError::AttemptToUseNonConstantValueInConstant => {
353 let mut err = struct_span_err!(
357 "attempt to use a non-constant value in a constant"
359 err.span_label(span, "non-constant value");
362 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
363 let res = binding.res();
364 let shadows_what = res.descr();
365 let mut err = struct_span_err!(
369 "{}s cannot shadow {}s",
375 format!("cannot be named the same as {} {}", res.article(), shadows_what),
377 let participle = if binding.is_import() { "imported" } else { "defined" };
378 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
379 err.span_label(binding.span, msg);
382 ResolutionError::ForwardDeclaredTyParam => {
383 let mut err = struct_span_err!(
387 "type parameters with a default cannot use \
388 forward declared identifiers"
392 "defaulted type parameters cannot be forward declared".to_string(),
396 ResolutionError::SelfInTyParamDefault => {
397 let mut err = struct_span_err!(
401 "type parameters cannot use `Self` in their defaults"
403 err.span_label(span, "`Self` in type parameter default".to_string());
409 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
410 match vis_resolution_error {
411 VisResolutionError::Relative2018(span, path) => {
412 let mut err = self.session.struct_span_err(
414 "relative paths are not supported in visibilities on 2018 edition",
419 format!("crate::{}", pprust::path_to_string(&path)),
420 Applicability::MaybeIncorrect,
424 VisResolutionError::AncestorOnly(span) => struct_span_err!(
428 "visibilities can only be restricted to ancestor modules"
430 VisResolutionError::FailedToResolve(span, label, suggestion) => {
431 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
433 VisResolutionError::ExpectedFound(span, path_str, res) => {
434 let mut err = struct_span_err!(
438 "expected module, found {} `{}`",
442 err.span_label(span, "not a module");
445 VisResolutionError::Indeterminate(span) => struct_span_err!(
449 "cannot determine resolution for the visibility"
451 VisResolutionError::ModuleOnly(span) => {
452 self.session.struct_span_err(span, "visibility must resolve to a module")
458 /// Lookup typo candidate in scope for a macro or import.
459 fn early_lookup_typo_candidate(
462 parent_scope: &ParentScope<'a>,
464 filter_fn: &impl Fn(Res) -> bool,
465 ) -> Option<TypoSuggestion> {
466 let mut suggestions = Vec::new();
467 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
469 Scope::DeriveHelpers(expn_id) => {
470 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
477 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
481 Scope::DeriveHelpersCompat => {
482 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
484 for derive in parent_scope.derives {
485 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
486 if let Ok((Some(ext), _)) = this.resolve_macro_path(
488 Some(MacroKind::Derive),
496 .map(|name| TypoSuggestion::from_res(*name, res)),
502 Scope::MacroRules(legacy_scope) => {
503 if let LegacyScope::Binding(legacy_binding) = legacy_scope {
504 let res = legacy_binding.binding.res();
507 .push(TypoSuggestion::from_res(legacy_binding.ident.name, res))
511 Scope::CrateRoot => {
512 let root_ident = Ident::new(kw::PathRoot, ident.span);
513 let root_module = this.resolve_crate_root(root_ident);
514 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
516 Scope::Module(module) => {
517 this.add_module_candidates(module, &mut suggestions, filter_fn);
519 Scope::RegisteredAttrs => {
520 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
523 this.registered_attrs
525 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
529 Scope::MacroUsePrelude => {
530 suggestions.extend(this.macro_use_prelude.iter().filter_map(
532 let res = binding.res();
533 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
537 Scope::BuiltinAttrs => {
538 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
543 .map(|(name, ..)| TypoSuggestion::from_res(*name, res)),
547 Scope::ExternPrelude => {
548 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
549 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
550 filter_fn(res).then_some(TypoSuggestion::from_res(ident.name, res))
553 Scope::ToolPrelude => {
554 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
556 this.registered_tools
558 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
561 Scope::StdLibPrelude => {
562 if let Some(prelude) = this.prelude {
563 let mut tmp_suggestions = Vec::new();
564 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
568 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
572 Scope::BuiltinTypes => {
573 let primitive_types = &this.primitive_type_table.primitive_types;
574 suggestions.extend(primitive_types.iter().flat_map(|(name, prim_ty)| {
575 let res = Res::PrimTy(*prim_ty);
576 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
584 // Make sure error reporting is deterministic.
585 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
587 match find_best_match_for_name(
588 suggestions.iter().map(|suggestion| &suggestion.candidate),
592 Some(found) if found != ident.name => {
593 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
599 fn lookup_import_candidates_from_module<FilterFn>(
602 namespace: Namespace,
603 start_module: Module<'a>,
606 ) -> Vec<ImportSuggestion>
608 FilterFn: Fn(Res) -> bool,
610 let mut candidates = Vec::new();
611 let mut seen_modules = FxHashSet::default();
612 let not_local_module = crate_name.name != kw::Crate;
613 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
615 while let Some((in_module, path_segments, in_module_is_extern)) = worklist.pop() {
616 // We have to visit module children in deterministic order to avoid
617 // instabilities in reported imports (#43552).
618 in_module.for_each_child(self, |this, ident, ns, name_binding| {
619 // avoid imports entirely
620 if name_binding.is_import() && !name_binding.is_extern_crate() {
623 // avoid non-importable candidates as well
624 if !name_binding.is_importable() {
628 // collect results based on the filter function
629 if ident.name == lookup_ident.name && ns == namespace {
630 let res = name_binding.res();
633 let mut segms = path_segments.clone();
634 if lookup_ident.span.rust_2018() {
635 // crate-local absolute paths start with `crate::` in edition 2018
636 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
637 segms.insert(0, ast::PathSegment::from_ident(crate_name));
640 segms.push(ast::PathSegment::from_ident(ident));
641 let path = Path { span: name_binding.span, segments: segms };
642 // the entity is accessible in the following cases:
643 // 1. if it's defined in the same crate, it's always
644 // accessible (since private entities can be made public)
645 // 2. if it's defined in another crate, it's accessible
646 // only if both the module is public and the entity is
647 // declared as public (due to pruning, we don't explore
648 // outside crate private modules => no need to check this)
649 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
650 let did = match res {
651 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
652 _ => res.opt_def_id(),
654 candidates.push(ImportSuggestion { did, path });
659 // collect submodules to explore
660 if let Some(module) = name_binding.module() {
662 let mut path_segments = path_segments.clone();
663 path_segments.push(ast::PathSegment::from_ident(ident));
665 let is_extern_crate_that_also_appears_in_prelude =
666 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
668 let is_visible_to_user =
669 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
671 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
672 // add the module to the lookup
673 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
674 if seen_modules.insert(module.def_id().unwrap()) {
675 worklist.push((module, path_segments, is_extern));
685 /// When name resolution fails, this method can be used to look up candidate
686 /// entities with the expected name. It allows filtering them using the
687 /// supplied predicate (which should be used to only accept the types of
688 /// definitions expected, e.g., traits). The lookup spans across all crates.
690 /// N.B., the method does not look into imports, but this is not a problem,
691 /// since we report the definitions (thus, the de-aliased imports).
692 crate fn lookup_import_candidates<FilterFn>(
695 namespace: Namespace,
697 ) -> Vec<ImportSuggestion>
699 FilterFn: Fn(Res) -> bool,
701 let mut suggestions = self.lookup_import_candidates_from_module(
705 Ident::with_dummy_span(kw::Crate),
709 if lookup_ident.span.rust_2018() {
710 let extern_prelude_names = self.extern_prelude.clone();
711 for (ident, _) in extern_prelude_names.into_iter() {
712 if ident.span.from_expansion() {
713 // Idents are adjusted to the root context before being
714 // resolved in the extern prelude, so reporting this to the
715 // user is no help. This skips the injected
716 // `extern crate std` in the 2018 edition, which would
717 // otherwise cause duplicate suggestions.
720 if let Some(crate_id) =
721 self.crate_loader.maybe_process_path_extern(ident.name, ident.span)
724 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
725 suggestions.extend(self.lookup_import_candidates_from_module(
739 crate fn unresolved_macro_suggestions(
741 err: &mut DiagnosticBuilder<'a>,
742 macro_kind: MacroKind,
743 parent_scope: &ParentScope<'a>,
746 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
747 let suggestion = self.early_lookup_typo_candidate(
748 ScopeSet::Macro(macro_kind),
753 self.add_typo_suggestion(err, suggestion, ident.span);
755 if macro_kind == MacroKind::Derive && (ident.as_str() == "Send" || ident.as_str() == "Sync")
757 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
758 err.span_note(ident.span, &msg);
760 if self.macro_names.contains(&ident.modern()) {
761 err.help("have you added the `#[macro_use]` on the module/import?");
765 crate fn add_typo_suggestion(
767 err: &mut DiagnosticBuilder<'_>,
768 suggestion: Option<TypoSuggestion>,
771 if let Some(suggestion) = suggestion {
772 // We shouldn't suggest underscore.
773 if suggestion.candidate == kw::Underscore {
778 "{} {} with a similar name exists",
779 suggestion.res.article(),
780 suggestion.res.descr()
785 suggestion.candidate.to_string(),
786 Applicability::MaybeIncorrect,
788 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
789 LOCAL_CRATE => self.definitions.opt_span(def_id),
793 .def_span(self.cstore().get_span_untracked(def_id, self.session)),
796 if let Some(span) = def_span {
800 "similarly named {} `{}` defined here",
801 suggestion.res.descr(),
802 suggestion.candidate.as_str(),
811 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
813 if b.span.is_dummy() {
814 let add_built_in = match b.res() {
815 // These already contain the "built-in" prefix or look bad with it.
816 Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
819 let (built_in, from) = if from_prelude {
820 ("", " from prelude")
821 } else if b.is_extern_crate()
823 && self.session.opts.externs.get(&ident.as_str()).is_some()
825 ("", " passed with `--extern`")
826 } else if add_built_in {
832 let article = if built_in.is_empty() { res.article() } else { "a" };
834 "{a}{built_in} {thing}{from}",
841 let introduced = if b.is_import() { "imported" } else { "defined" };
842 format!("the {thing} {introduced} here", thing = res.descr(), introduced = introduced)
846 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
847 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
848 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
849 // We have to print the span-less alternative first, otherwise formatting looks bad.
850 (b2, b1, misc2, misc1, true)
852 (b1, b2, misc1, misc2, false)
855 let mut err = struct_span_err!(
859 "`{ident}` is ambiguous ({why})",
863 err.span_label(ident.span, "ambiguous name");
865 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
866 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
867 let note_msg = format!(
868 "`{ident}` could{also} refer to {what}",
874 let thing = b.res().descr();
875 let mut help_msgs = Vec::new();
876 if b.is_glob_import()
877 && (kind == AmbiguityKind::GlobVsGlob
878 || kind == AmbiguityKind::GlobVsExpanded
879 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
881 help_msgs.push(format!(
882 "consider adding an explicit import of \
883 `{ident}` to disambiguate",
887 if b.is_extern_crate() && ident.span.rust_2018() {
888 help_msgs.push(format!(
889 "use `::{ident}` to refer to this {thing} unambiguously",
894 if misc == AmbiguityErrorMisc::SuggestCrate {
895 help_msgs.push(format!(
896 "use `crate::{ident}` to refer to this {thing} unambiguously",
900 } else if misc == AmbiguityErrorMisc::SuggestSelf {
901 help_msgs.push(format!(
902 "use `self::{ident}` to refer to this {thing} unambiguously",
908 err.span_note(b.span, ¬e_msg);
909 for (i, help_msg) in help_msgs.iter().enumerate() {
910 let or = if i == 0 { "" } else { "or " };
911 err.help(&format!("{}{}", or, help_msg));
915 could_refer_to(b1, misc1, "");
916 could_refer_to(b2, misc2, " also");
920 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
921 let PrivacyError { ident, binding, .. } = *privacy_error;
922 let session = &self.session;
923 let mk_struct_span_error = |is_constructor| {
924 let mut descr = binding.res().descr().to_string();
926 descr += " constructor";
928 if binding.is_import() {
933 struct_span_err!(session, ident.span, E0603, "{} `{}` is private", descr, ident);
935 err.span_label(ident.span, &format!("this {} is private", descr));
937 session.source_map().def_span(binding.span),
938 &format!("the {} `{}` is defined here", descr, ident),
944 let mut err = if let NameBindingKind::Res(
945 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
949 let def_id = (&*self).parent(ctor_def_id).expect("no parent for a constructor");
950 if let Some(fields) = self.field_names.get(&def_id) {
951 let mut err = mk_struct_span_error(true);
952 let first_field = fields.first().expect("empty field list in the map");
954 fields.iter().fold(first_field.span, |acc, field| acc.to(field.span)),
955 "a constructor is private if any of the fields is private",
959 mk_struct_span_error(false)
962 mk_struct_span_error(false)
969 impl<'a, 'b> ImportResolver<'a, 'b> {
970 /// Adds suggestions for a path that cannot be resolved.
971 pub(crate) fn make_path_suggestion(
974 mut path: Vec<Segment>,
975 parent_scope: &ParentScope<'b>,
976 ) -> Option<(Vec<Segment>, Vec<String>)> {
977 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
979 match (path.get(0), path.get(1)) {
980 // `{{root}}::ident::...` on both editions.
981 // On 2015 `{{root}}` is usually added implicitly.
982 (Some(fst), Some(snd))
983 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
984 // `ident::...` on 2018.
986 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
988 // Insert a placeholder that's later replaced by `self`/`super`/etc.
989 path.insert(0, Segment::from_ident(Ident::invalid()));
994 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
995 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
996 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
997 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1000 /// Suggest a missing `self::` if that resolves to an correct module.
1004 /// LL | use foo::Bar;
1005 /// | ^^^ did you mean `self::foo`?
1007 fn make_missing_self_suggestion(
1010 mut path: Vec<Segment>,
1011 parent_scope: &ParentScope<'b>,
1012 ) -> Option<(Vec<Segment>, Vec<String>)> {
1013 // Replace first ident with `self` and check if that is valid.
1014 path[0].ident.name = kw::SelfLower;
1015 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1016 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1017 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1020 /// Suggests a missing `crate::` if that resolves to an correct module.
1024 /// LL | use foo::Bar;
1025 /// | ^^^ did you mean `crate::foo`?
1027 fn make_missing_crate_suggestion(
1030 mut path: Vec<Segment>,
1031 parent_scope: &ParentScope<'b>,
1032 ) -> Option<(Vec<Segment>, Vec<String>)> {
1033 // Replace first ident with `crate` and check if that is valid.
1034 path[0].ident.name = kw::Crate;
1035 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1036 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1037 if let PathResult::Module(..) = result {
1041 "`use` statements changed in Rust 2018; read more at \
1042 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1052 /// Suggests a missing `super::` if that resolves to an correct module.
1056 /// LL | use foo::Bar;
1057 /// | ^^^ did you mean `super::foo`?
1059 fn make_missing_super_suggestion(
1062 mut path: Vec<Segment>,
1063 parent_scope: &ParentScope<'b>,
1064 ) -> Option<(Vec<Segment>, Vec<String>)> {
1065 // Replace first ident with `crate` and check if that is valid.
1066 path[0].ident.name = kw::Super;
1067 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1068 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1069 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1072 /// Suggests a missing external crate name if that resolves to an correct module.
1076 /// LL | use foobar::Baz;
1077 /// | ^^^^^^ did you mean `baz::foobar`?
1080 /// Used when importing a submodule of an external crate but missing that crate's
1081 /// name as the first part of path.
1082 fn make_external_crate_suggestion(
1085 mut path: Vec<Segment>,
1086 parent_scope: &ParentScope<'b>,
1087 ) -> Option<(Vec<Segment>, Vec<String>)> {
1088 if path[1].ident.span.rust_2015() {
1092 // Sort extern crate names in reverse order to get
1093 // 1) some consistent ordering for emitted dignostics, and
1094 // 2) `std` suggestions before `core` suggestions.
1095 let mut extern_crate_names =
1096 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1097 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1099 for name in extern_crate_names.into_iter() {
1100 // Replace first ident with a crate name and check if that is valid.
1101 path[0].ident.name = name;
1102 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1104 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1107 if let PathResult::Module(..) = result {
1108 return Some((path, Vec::new()));
1115 /// Suggests importing a macro from the root of the crate rather than a module within
1119 /// help: a macro with this name exists at the root of the crate
1121 /// LL | use issue_59764::makro;
1122 /// | ^^^^^^^^^^^^^^^^^^
1124 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1125 /// at the root of the crate instead of the module where it is defined
1127 pub(crate) fn check_for_module_export_macro(
1129 directive: &'b ImportDirective<'b>,
1130 module: ModuleOrUniformRoot<'b>,
1132 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1133 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
1139 while let Some(parent) = crate_module.parent {
1140 crate_module = parent;
1143 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1144 // Don't make a suggestion if the import was already from the root of the
1149 let resolutions = self.r.resolutions(crate_module).borrow();
1150 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1151 let binding = resolution.borrow().binding()?;
1152 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1153 let module_name = crate_module.kind.name().unwrap();
1154 let import = match directive.subclass {
1155 ImportDirectiveSubclass::SingleImport { source, target, .. }
1156 if source != target =>
1158 format!("{} as {}", source, target)
1160 _ => format!("{}", ident),
1163 let mut corrections: Vec<(Span, String)> = Vec::new();
1164 if !directive.is_nested() {
1165 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1166 // intermediate segments.
1167 corrections.push((directive.span, format!("{}::{}", module_name, import)));
1169 // Find the binding span (and any trailing commas and spaces).
1170 // ie. `use a::b::{c, d, e};`
1172 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1178 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1179 found_closing_brace, binding_span
1182 let mut removal_span = binding_span;
1183 if found_closing_brace {
1184 // If the binding span ended with a closing brace, as in the below example:
1185 // ie. `use a::b::{c, d};`
1187 // Then expand the span of characters to remove to include the previous
1188 // binding's trailing comma.
1189 // ie. `use a::b::{c, d};`
1191 if let Some(previous_span) =
1192 extend_span_to_previous_binding(self.r.session, binding_span)
1194 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1195 removal_span = removal_span.with_lo(previous_span.lo());
1198 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1200 // Remove the `removal_span`.
1201 corrections.push((removal_span, "".to_string()));
1203 // Find the span after the crate name and if it has nested imports immediatately
1204 // after the crate name already.
1205 // ie. `use a::b::{c, d};`
1207 // or `use a::{b, c, d}};`
1209 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1215 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1216 has_nested, after_crate_name
1219 let source_map = self.r.session.source_map();
1221 // Add the import to the start, with a `{` if required.
1222 let start_point = source_map.start_point(after_crate_name);
1223 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1227 // In this case, `start_snippet` must equal '{'.
1228 format!("{}{}, ", start_snippet, import)
1230 // In this case, add a `{`, then the moved import, then whatever
1231 // was there before.
1232 format!("{{{}, {}", import, start_snippet)
1237 // Add a `};` to the end if nested, matching the `{` added at the start.
1239 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1243 let suggestion = Some((
1245 String::from("a macro with this name exists at the root of the crate"),
1246 Applicability::MaybeIncorrect,
1249 "this could be because a macro annotated with `#[macro_export]` will be exported \
1250 at the root of the crate instead of the module where it is defined"
1253 Some((suggestion, note))
1260 /// Given a `binding_span` of a binding within a use statement:
1263 /// use foo::{a, b, c};
1267 /// then return the span until the next binding or the end of the statement:
1270 /// use foo::{a, b, c};
1273 pub(crate) fn find_span_of_binding_until_next_binding(
1278 let source_map = sess.source_map();
1280 // Find the span of everything after the binding.
1281 // ie. `a, e};` or `a};`
1282 let binding_until_end = binding_span.with_hi(use_span.hi());
1284 // Find everything after the binding but not including the binding.
1285 // ie. `, e};` or `};`
1286 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1288 // Keep characters in the span until we encounter something that isn't a comma or
1292 // Also note whether a closing brace character was encountered. If there
1293 // was, then later go backwards to remove any trailing commas that are left.
1294 let mut found_closing_brace = false;
1295 let after_binding_until_next_binding =
1296 source_map.span_take_while(after_binding_until_end, |&ch| {
1298 found_closing_brace = true;
1300 ch == ' ' || ch == ','
1303 // Combine the two spans.
1304 // ie. `a, ` or `a`.
1306 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1307 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1309 (found_closing_brace, span)
1312 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1316 /// use foo::a::{a, b, c};
1317 /// ^^--- binding span
1321 /// use foo::{a, b, c};
1322 /// --- binding span
1324 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1325 let source_map = sess.source_map();
1327 // `prev_source` will contain all of the source that came before the span.
1328 // Then split based on a command and take the first (ie. closest to our span)
1329 // snippet. In the example, this is a space.
1330 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1332 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1333 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1334 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1338 let prev_comma = prev_comma.first().unwrap();
1339 let prev_starting_brace = prev_starting_brace.first().unwrap();
1341 // If the amount of source code before the comma is greater than
1342 // the amount of source code before the starting brace then we've only
1343 // got one item in the nested item (eg. `issue_52891::{self}`).
1344 if prev_comma.len() > prev_starting_brace.len() {
1348 Some(binding_span.with_lo(BytePos(
1349 // Take away the number of bytes for the characters we've found and an
1350 // extra for the comma.
1351 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1355 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1356 /// it is a nested use tree.
1359 /// use foo::a::{b, c};
1360 /// ^^^^^^^^^^ // false
1362 /// use foo::{a, b, c};
1363 /// ^^^^^^^^^^ // true
1365 /// use foo::{a, b::{c, d}};
1366 /// ^^^^^^^^^^^^^^^ // true
1368 fn find_span_immediately_after_crate_name(
1370 module_name: Symbol,
1374 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1375 module_name, use_span
1377 let source_map = sess.source_map();
1379 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1380 let mut num_colons = 0;
1381 // Find second colon.. `use issue_59764:`
1382 let until_second_colon = source_map.span_take_while(use_span, |c| {
1387 ':' if num_colons == 2 => false,
1391 // Find everything after the second colon.. `foo::{baz, makro};`
1392 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1394 let mut found_a_non_whitespace_character = false;
1395 // Find the first non-whitespace character in `from_second_colon`.. `f`
1396 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1397 if found_a_non_whitespace_character {
1400 if !c.is_whitespace() {
1401 found_a_non_whitespace_character = true;
1406 // Find the first `{` in from_second_colon.. `foo::{`
1407 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1409 (next_left_bracket == after_second_colon, from_second_colon)
1412 /// When an entity with a given name is not available in scope, we search for
1413 /// entities with that name in all crates. This method allows outputting the
1414 /// results of this search in a programmer-friendly way
1415 crate fn show_candidates(
1416 err: &mut DiagnosticBuilder<'_>,
1417 // This is `None` if all placement locations are inside expansions
1419 candidates: &[ImportSuggestion],
1423 if candidates.is_empty() {
1426 // we want consistent results across executions, but candidates are produced
1427 // by iterating through a hash map, so make sure they are ordered:
1428 let mut path_strings: Vec<_> =
1429 candidates.iter().map(|c| path_names_to_string(&c.path)).collect();
1430 path_strings.sort();
1431 path_strings.dedup();
1433 let better = if better { "better " } else { "" };
1434 let msg_diff = match path_strings.len() {
1435 1 => " is found in another module, you can import it",
1436 _ => "s are found in other modules, you can import them",
1438 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1440 if let Some(span) = span {
1441 for candidate in &mut path_strings {
1442 // produce an additional newline to separate the new use statement
1443 // from the directly following item.
1444 let additional_newline = if found_use { "" } else { "\n" };
1445 *candidate = format!("use {};\n{}", candidate, additional_newline);
1448 err.span_suggestions(span, &msg, path_strings.into_iter(), Applicability::Unspecified);
1452 for candidate in path_strings {
1454 msg.push_str(&candidate);