5 use rustc_ast::ast::{self, Ident, Path};
6 use rustc_ast::util::lev_distance::find_best_match_for_name;
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
10 use rustc_feature::BUILTIN_ATTRIBUTES;
11 use rustc_hir::def::Namespace::{self, *};
12 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
13 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
14 use rustc_middle::bug;
15 use rustc_middle::ty::{self, DefIdTree};
16 use rustc_session::Session;
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::symbol::{kw, Symbol};
20 use rustc_span::{BytePos, MultiSpan, Span};
22 use crate::imports::{Import, ImportKind, ImportResolver};
23 use crate::path_names_to_string;
24 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
26 BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
28 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
29 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
31 type Res = def::Res<ast::NodeId>;
33 /// A vector of spans and replacements, a message and applicability.
34 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
36 crate struct TypoSuggestion {
37 pub candidate: Symbol,
42 crate fn from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
43 TypoSuggestion { candidate, res }
47 /// A free importable items suggested in case of resolution failure.
48 crate struct ImportSuggestion {
49 pub did: Option<DefId>,
53 /// Adjust the impl span so that just the `impl` keyword is taken by removing
54 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
55 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
57 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
58 /// parser. If you need to use this function or something similar, please consider updating the
59 /// `source_map` functions and this function to something more robust.
60 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
61 let impl_span = sm.span_until_char(impl_span, '<');
62 sm.span_until_whitespace(impl_span)
65 impl<'a> Resolver<'a> {
66 crate fn add_module_candidates(
69 names: &mut Vec<TypoSuggestion>,
70 filter_fn: &impl Fn(Res) -> bool,
72 for (key, resolution) in self.resolutions(module).borrow().iter() {
73 if let Some(binding) = resolution.borrow().binding {
74 let res = binding.res();
76 names.push(TypoSuggestion::from_res(key.ident.name, res));
82 /// Combines an error with provided span and emits it.
84 /// This takes the error provided, combines it with the span and any additional spans inside the
85 /// error and emits it.
86 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
87 self.into_struct_error(span, resolution_error).emit();
90 crate fn into_struct_error(
93 resolution_error: ResolutionError<'_>,
94 ) -> DiagnosticBuilder<'_> {
95 match resolution_error {
96 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
97 let mut err = struct_span_err!(
101 "can't use generic parameters from outer function",
103 err.span_label(span, "use of generic parameter from outer function".to_string());
105 let sm = self.session.source_map();
107 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
108 if let Some(impl_span) =
109 maybe_impl_defid.and_then(|def_id| self.definitions.opt_span(def_id))
112 reduce_impl_span_to_impl_keyword(sm, impl_span),
113 "`Self` type implicitly declared here, by this `impl`",
116 match (maybe_trait_defid, maybe_impl_defid) {
118 err.span_label(span, "can't use `Self` here");
121 err.span_label(span, "use a type here instead");
123 (None, None) => bug!("`impl` without trait nor type?"),
127 Res::Def(DefKind::TyParam, def_id) => {
128 if let Some(span) = self.definitions.opt_span(def_id) {
129 err.span_label(span, "type parameter from outer function");
132 Res::Def(DefKind::ConstParam, def_id) => {
133 if let Some(span) = self.definitions.opt_span(def_id) {
134 err.span_label(span, "const parameter from outer function");
139 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
145 if has_generic_params == HasGenericParams::Yes {
146 // Try to retrieve the span of the function signature and generate a new
147 // message with a local type or const parameter.
148 let sugg_msg = "try using a local generic parameter instead";
149 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
150 // Suggest the modification to the user
155 Applicability::MachineApplicable,
157 } else if let Some(sp) = sm.generate_fn_name_span(span) {
160 "try adding a local generic parameter in this method instead"
164 err.help("try using a local generic parameter instead");
170 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
171 let mut err = struct_span_err!(
175 "the name `{}` is already used for a generic \
176 parameter in this item's generic parameters",
179 err.span_label(span, "already used");
180 err.span_label(first_use_span, format!("first use of `{}`", name));
183 ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
184 let mut err = struct_span_err!(
188 "method `{}` is not a member of trait `{}`",
192 err.span_label(span, format!("not a member of trait `{}`", trait_));
195 ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
196 let mut err = struct_span_err!(
200 "type `{}` is not a member of trait `{}`",
204 err.span_label(span, format!("not a member of trait `{}`", trait_));
207 ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
208 let mut err = struct_span_err!(
212 "const `{}` is not a member of trait `{}`",
216 err.span_label(span, format!("not a member of trait `{}`", trait_));
219 ResolutionError::VariableNotBoundInPattern(binding_error) => {
220 let BindingError { name, target, origin, could_be_path } = binding_error;
222 let target_sp = target.iter().copied().collect::<Vec<_>>();
223 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
225 let msp = MultiSpan::from_spans(target_sp.clone());
226 let mut err = struct_span_err!(
230 "variable `{}` is not bound in all patterns",
233 for sp in target_sp {
234 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
236 for sp in origin_sp {
237 err.span_label(sp, "variable not in all patterns");
240 let help_msg = format!(
241 "if you meant to match on a variant or a `const` item, consider \
242 making the path in the pattern qualified: `?::{}`",
245 err.span_help(span, &help_msg);
249 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
250 let mut err = struct_span_err!(
254 "variable `{}` is bound inconsistently across alternatives separated by `|`",
257 err.span_label(span, "bound in different ways");
258 err.span_label(first_binding_span, "first binding");
261 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
262 let mut err = struct_span_err!(
266 "identifier `{}` is bound more than once in this parameter list",
269 err.span_label(span, "used as parameter more than once");
272 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
273 let mut err = struct_span_err!(
277 "identifier `{}` is bound more than once in the same pattern",
280 err.span_label(span, "used in a pattern more than once");
283 ResolutionError::UndeclaredLabel(name, lev_candidate) => {
284 let mut err = struct_span_err!(
288 "use of undeclared label `{}`",
291 if let Some(lev_candidate) = lev_candidate {
294 "a label with a similar name exists in this scope",
295 lev_candidate.to_string(),
296 Applicability::MaybeIncorrect,
299 err.span_label(span, format!("undeclared label `{}`", name));
303 ResolutionError::SelfImportsOnlyAllowedWithin => struct_span_err!(
308 "`self` imports are only allowed within a { } list"
310 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
311 let mut err = struct_span_err!(
315 "`self` import can only appear once in an import list"
317 err.span_label(span, "can only appear once in an import list");
320 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
321 let mut err = struct_span_err!(
325 "`self` import can only appear in an import list with \
328 err.span_label(span, "can only appear in an import list with a non-empty prefix");
331 ResolutionError::FailedToResolve { label, suggestion } => {
333 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
334 err.span_label(span, label);
336 if let Some((suggestions, msg, applicability)) = suggestion {
337 err.multipart_suggestion(&msg, suggestions, applicability);
342 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
343 let mut err = struct_span_err!(
348 "can't capture dynamic environment in a fn item"
350 err.help("use the `|| { ... }` closure form instead");
353 ResolutionError::AttemptToUseNonConstantValueInConstant => {
354 let mut err = struct_span_err!(
358 "attempt to use a non-constant value in a constant"
360 err.span_label(span, "non-constant value");
363 ResolutionError::BindingShadowsSomethingUnacceptable(what_binding, name, binding) => {
364 let res = binding.res();
365 let shadows_what = res.descr();
366 let mut err = struct_span_err!(
370 "{}s cannot shadow {}s",
376 format!("cannot be named the same as {} {}", res.article(), shadows_what),
378 let participle = if binding.is_import() { "imported" } else { "defined" };
379 let msg = format!("the {} `{}` is {} here", shadows_what, name, participle);
380 err.span_label(binding.span, msg);
383 ResolutionError::ForwardDeclaredTyParam => {
384 let mut err = struct_span_err!(
388 "type parameters with a default cannot use \
389 forward declared identifiers"
393 "defaulted type parameters cannot be forward declared".to_string(),
397 ResolutionError::SelfInTyParamDefault => {
398 let mut err = struct_span_err!(
402 "type parameters cannot use `Self` in their defaults"
404 err.span_label(span, "`Self` in type parameter default".to_string());
410 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
411 match vis_resolution_error {
412 VisResolutionError::Relative2018(span, path) => {
413 let mut err = self.session.struct_span_err(
415 "relative paths are not supported in visibilities on 2018 edition",
420 format!("crate::{}", pprust::path_to_string(&path)),
421 Applicability::MaybeIncorrect,
425 VisResolutionError::AncestorOnly(span) => struct_span_err!(
429 "visibilities can only be restricted to ancestor modules"
431 VisResolutionError::FailedToResolve(span, label, suggestion) => {
432 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
434 VisResolutionError::ExpectedFound(span, path_str, res) => {
435 let mut err = struct_span_err!(
439 "expected module, found {} `{}`",
443 err.span_label(span, "not a module");
446 VisResolutionError::Indeterminate(span) => struct_span_err!(
450 "cannot determine resolution for the visibility"
452 VisResolutionError::ModuleOnly(span) => {
453 self.session.struct_span_err(span, "visibility must resolve to a module")
459 /// Lookup typo candidate in scope for a macro or import.
460 fn early_lookup_typo_candidate(
463 parent_scope: &ParentScope<'a>,
465 filter_fn: &impl Fn(Res) -> bool,
466 ) -> Option<TypoSuggestion> {
467 let mut suggestions = Vec::new();
468 self.visit_scopes(scope_set, parent_scope, ident, |this, scope, use_prelude, _| {
470 Scope::DeriveHelpers(expn_id) => {
471 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
478 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
482 Scope::DeriveHelpersCompat => {
483 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
485 for derive in parent_scope.derives {
486 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
487 if let Ok((Some(ext), _)) = this.resolve_macro_path(
489 Some(MacroKind::Derive),
497 .map(|name| TypoSuggestion::from_res(*name, res)),
503 Scope::MacroRules(macro_rules_scope) => {
504 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope {
505 let res = macro_rules_binding.binding.res();
508 .push(TypoSuggestion::from_res(macro_rules_binding.ident.name, res))
512 Scope::CrateRoot => {
513 let root_ident = Ident::new(kw::PathRoot, ident.span);
514 let root_module = this.resolve_crate_root(root_ident);
515 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
517 Scope::Module(module) => {
518 this.add_module_candidates(module, &mut suggestions, filter_fn);
520 Scope::RegisteredAttrs => {
521 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
524 this.registered_attrs
526 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
530 Scope::MacroUsePrelude => {
531 suggestions.extend(this.macro_use_prelude.iter().filter_map(
533 let res = binding.res();
534 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
538 Scope::BuiltinAttrs => {
539 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
544 .map(|(name, ..)| TypoSuggestion::from_res(*name, res)),
548 Scope::ExternPrelude => {
549 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
550 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
551 filter_fn(res).then_some(TypoSuggestion::from_res(ident.name, res))
554 Scope::ToolPrelude => {
555 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
557 this.registered_tools
559 .map(|ident| TypoSuggestion::from_res(ident.name, res)),
562 Scope::StdLibPrelude => {
563 if let Some(prelude) = this.prelude {
564 let mut tmp_suggestions = Vec::new();
565 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
569 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
573 Scope::BuiltinTypes => {
574 let primitive_types = &this.primitive_type_table.primitive_types;
575 suggestions.extend(primitive_types.iter().flat_map(|(name, prim_ty)| {
576 let res = Res::PrimTy(*prim_ty);
577 filter_fn(res).then_some(TypoSuggestion::from_res(*name, res))
585 // Make sure error reporting is deterministic.
586 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
588 match find_best_match_for_name(
589 suggestions.iter().map(|suggestion| &suggestion.candidate),
593 Some(found) if found != ident.name => {
594 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
600 fn lookup_import_candidates_from_module<FilterFn>(
603 namespace: Namespace,
604 start_module: Module<'a>,
607 ) -> Vec<ImportSuggestion>
609 FilterFn: Fn(Res) -> bool,
611 let mut candidates = Vec::new();
612 let mut seen_modules = FxHashSet::default();
613 let not_local_module = crate_name.name != kw::Crate;
614 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), not_local_module)];
616 while let Some((in_module, path_segments, in_module_is_extern)) = worklist.pop() {
617 // We have to visit module children in deterministic order to avoid
618 // instabilities in reported imports (#43552).
619 in_module.for_each_child(self, |this, ident, ns, name_binding| {
620 // avoid imports entirely
621 if name_binding.is_import() && !name_binding.is_extern_crate() {
624 // avoid non-importable candidates as well
625 if !name_binding.is_importable() {
629 // collect results based on the filter function
630 if ident.name == lookup_ident.name && ns == namespace {
631 let res = name_binding.res();
634 let mut segms = path_segments.clone();
635 if lookup_ident.span.rust_2018() {
636 // crate-local absolute paths start with `crate::` in edition 2018
637 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
638 segms.insert(0, ast::PathSegment::from_ident(crate_name));
641 segms.push(ast::PathSegment::from_ident(ident));
642 let path = Path { span: name_binding.span, segments: segms };
643 // the entity is accessible in the following cases:
644 // 1. if it's defined in the same crate, it's always
645 // accessible (since private entities can be made public)
646 // 2. if it's defined in another crate, it's accessible
647 // only if both the module is public and the entity is
648 // declared as public (due to pruning, we don't explore
649 // outside crate private modules => no need to check this)
650 if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
651 let did = match res {
652 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
653 _ => res.opt_def_id(),
655 candidates.push(ImportSuggestion { did, path });
660 // collect submodules to explore
661 if let Some(module) = name_binding.module() {
663 let mut path_segments = path_segments.clone();
664 path_segments.push(ast::PathSegment::from_ident(ident));
666 let is_extern_crate_that_also_appears_in_prelude =
667 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
669 let is_visible_to_user =
670 !in_module_is_extern || name_binding.vis == ty::Visibility::Public;
672 if !is_extern_crate_that_also_appears_in_prelude && is_visible_to_user {
673 // add the module to the lookup
674 let is_extern = in_module_is_extern || name_binding.is_extern_crate();
675 if seen_modules.insert(module.def_id().unwrap()) {
676 worklist.push((module, path_segments, is_extern));
686 /// When name resolution fails, this method can be used to look up candidate
687 /// entities with the expected name. It allows filtering them using the
688 /// supplied predicate (which should be used to only accept the types of
689 /// definitions expected, e.g., traits). The lookup spans across all crates.
691 /// N.B., the method does not look into imports, but this is not a problem,
692 /// since we report the definitions (thus, the de-aliased imports).
693 crate fn lookup_import_candidates<FilterFn>(
696 namespace: Namespace,
698 ) -> Vec<ImportSuggestion>
700 FilterFn: Fn(Res) -> bool,
702 let mut suggestions = self.lookup_import_candidates_from_module(
706 Ident::with_dummy_span(kw::Crate),
710 if lookup_ident.span.rust_2018() {
711 let extern_prelude_names = self.extern_prelude.clone();
712 for (ident, _) in extern_prelude_names.into_iter() {
713 if ident.span.from_expansion() {
714 // Idents are adjusted to the root context before being
715 // resolved in the extern prelude, so reporting this to the
716 // user is no help. This skips the injected
717 // `extern crate std` in the 2018 edition, which would
718 // otherwise cause duplicate suggestions.
721 if let Some(crate_id) =
722 self.crate_loader.maybe_process_path_extern(ident.name, ident.span)
725 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
726 suggestions.extend(self.lookup_import_candidates_from_module(
740 crate fn unresolved_macro_suggestions(
742 err: &mut DiagnosticBuilder<'a>,
743 macro_kind: MacroKind,
744 parent_scope: &ParentScope<'a>,
747 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
748 let suggestion = self.early_lookup_typo_candidate(
749 ScopeSet::Macro(macro_kind),
754 self.add_typo_suggestion(err, suggestion, ident.span);
756 if macro_kind == MacroKind::Derive && (ident.as_str() == "Send" || ident.as_str() == "Sync")
758 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
759 err.span_note(ident.span, &msg);
761 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
762 err.help("have you added the `#[macro_use]` on the module/import?");
766 crate fn add_typo_suggestion(
768 err: &mut DiagnosticBuilder<'_>,
769 suggestion: Option<TypoSuggestion>,
772 if let Some(suggestion) = suggestion {
773 // We shouldn't suggest underscore.
774 if suggestion.candidate == kw::Underscore {
779 "{} {} with a similar name exists",
780 suggestion.res.article(),
781 suggestion.res.descr()
786 suggestion.candidate.to_string(),
787 Applicability::MaybeIncorrect,
789 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
790 LOCAL_CRATE => self.definitions.opt_span(def_id),
794 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
797 if let Some(span) = def_span {
799 self.session.source_map().guess_head_span(span),
801 "similarly named {} `{}` defined here",
802 suggestion.res.descr(),
803 suggestion.candidate.as_str(),
812 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
814 if b.span.is_dummy() {
815 let add_built_in = match b.res() {
816 // These already contain the "built-in" prefix or look bad with it.
817 Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
820 let (built_in, from) = if from_prelude {
821 ("", " from prelude")
822 } else if b.is_extern_crate()
824 && self.session.opts.externs.get(&ident.as_str()).is_some()
826 ("", " passed with `--extern`")
827 } else if add_built_in {
833 let article = if built_in.is_empty() { res.article() } else { "a" };
835 "{a}{built_in} {thing}{from}",
842 let introduced = if b.is_import() { "imported" } else { "defined" };
843 format!("the {thing} {introduced} here", thing = res.descr(), introduced = introduced)
847 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
848 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
849 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
850 // We have to print the span-less alternative first, otherwise formatting looks bad.
851 (b2, b1, misc2, misc1, true)
853 (b1, b2, misc1, misc2, false)
856 let mut err = struct_span_err!(
860 "`{ident}` is ambiguous ({why})",
864 err.span_label(ident.span, "ambiguous name");
866 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
867 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
868 let note_msg = format!(
869 "`{ident}` could{also} refer to {what}",
875 let thing = b.res().descr();
876 let mut help_msgs = Vec::new();
877 if b.is_glob_import()
878 && (kind == AmbiguityKind::GlobVsGlob
879 || kind == AmbiguityKind::GlobVsExpanded
880 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
882 help_msgs.push(format!(
883 "consider adding an explicit import of \
884 `{ident}` to disambiguate",
888 if b.is_extern_crate() && ident.span.rust_2018() {
889 help_msgs.push(format!(
890 "use `::{ident}` to refer to this {thing} unambiguously",
895 if misc == AmbiguityErrorMisc::SuggestCrate {
896 help_msgs.push(format!(
897 "use `crate::{ident}` to refer to this {thing} unambiguously",
901 } else if misc == AmbiguityErrorMisc::SuggestSelf {
902 help_msgs.push(format!(
903 "use `self::{ident}` to refer to this {thing} unambiguously",
909 err.span_note(b.span, ¬e_msg);
910 for (i, help_msg) in help_msgs.iter().enumerate() {
911 let or = if i == 0 { "" } else { "or " };
912 err.help(&format!("{}{}", or, help_msg));
916 could_refer_to(b1, misc1, "");
917 could_refer_to(b2, misc2, " also");
921 /// If the binding refers to a tuple struct constructor with fields,
922 /// returns the span of its fields.
923 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
924 if let NameBindingKind::Res(
925 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
929 let def_id = (&*self).parent(ctor_def_id).expect("no parent for a constructor");
930 if let Some(fields) = self.field_names.get(&def_id) {
931 let first_field = fields.first().expect("empty field list in the map");
932 return Some(fields.iter().fold(first_field.span, |acc, field| acc.to(field.span)));
938 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
939 let PrivacyError { ident, binding, .. } = *privacy_error;
941 let res = binding.res();
942 let ctor_fields_span = self.ctor_fields_span(binding);
943 let plain_descr = res.descr().to_string();
944 let nonimport_descr =
945 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
946 let import_descr = nonimport_descr.clone() + " import";
948 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
950 // Print the primary message.
951 let descr = get_descr(binding);
953 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
954 err.span_label(ident.span, &format!("private {}", descr));
955 if let Some(span) = ctor_fields_span {
956 err.span_label(span, "a constructor is private if any of the fields is private");
959 // Print the whole import chain to make it easier to see what happens.
960 let first_binding = binding;
961 let mut next_binding = Some(binding);
962 let mut next_ident = ident;
963 while let Some(binding) = next_binding {
964 let name = next_ident;
965 next_binding = match binding.kind {
966 _ if res == Res::Err => None,
967 NameBindingKind::Import { binding, import, .. } => match import.kind {
968 _ if binding.span.is_dummy() => None,
969 ImportKind::Single { source, .. } => {
973 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
974 ImportKind::ExternCrate { .. } => None,
979 let first = ptr::eq(binding, first_binding);
980 let descr = get_descr(binding);
982 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
983 and_refers_to = if first { "" } else { "...and refers to " },
986 which = if first { "" } else { " which" },
987 dots = if next_binding.is_some() { "..." } else { "" },
989 let def_span = self.session.source_map().guess_head_span(binding.span);
990 let mut note_span = MultiSpan::from_span(def_span);
991 if !first && binding.vis == ty::Visibility::Public {
992 note_span.push_span_label(def_span, "consider importing it directly".into());
994 err.span_note(note_span, &msg);
1001 impl<'a, 'b> ImportResolver<'a, 'b> {
1002 /// Adds suggestions for a path that cannot be resolved.
1003 pub(crate) fn make_path_suggestion(
1006 mut path: Vec<Segment>,
1007 parent_scope: &ParentScope<'b>,
1008 ) -> Option<(Vec<Segment>, Vec<String>)> {
1009 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1011 match (path.get(0), path.get(1)) {
1012 // `{{root}}::ident::...` on both editions.
1013 // On 2015 `{{root}}` is usually added implicitly.
1014 (Some(fst), Some(snd))
1015 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1016 // `ident::...` on 2018.
1018 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1020 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1021 path.insert(0, Segment::from_ident(Ident::invalid()));
1026 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1027 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1028 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1029 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1032 /// Suggest a missing `self::` if that resolves to an correct module.
1036 /// LL | use foo::Bar;
1037 /// | ^^^ did you mean `self::foo`?
1039 fn make_missing_self_suggestion(
1042 mut path: Vec<Segment>,
1043 parent_scope: &ParentScope<'b>,
1044 ) -> Option<(Vec<Segment>, Vec<String>)> {
1045 // Replace first ident with `self` and check if that is valid.
1046 path[0].ident.name = kw::SelfLower;
1047 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1048 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1049 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1052 /// Suggests a missing `crate::` if that resolves to an correct module.
1056 /// LL | use foo::Bar;
1057 /// | ^^^ did you mean `crate::foo`?
1059 fn make_missing_crate_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::Crate;
1067 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1068 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1069 if let PathResult::Module(..) = result {
1073 "`use` statements changed in Rust 2018; read more at \
1074 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1084 /// Suggests a missing `super::` if that resolves to an correct module.
1088 /// LL | use foo::Bar;
1089 /// | ^^^ did you mean `super::foo`?
1091 fn make_missing_super_suggestion(
1094 mut path: Vec<Segment>,
1095 parent_scope: &ParentScope<'b>,
1096 ) -> Option<(Vec<Segment>, Vec<String>)> {
1097 // Replace first ident with `crate` and check if that is valid.
1098 path[0].ident.name = kw::Super;
1099 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1100 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1101 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1104 /// Suggests a missing external crate name if that resolves to an correct module.
1108 /// LL | use foobar::Baz;
1109 /// | ^^^^^^ did you mean `baz::foobar`?
1112 /// Used when importing a submodule of an external crate but missing that crate's
1113 /// name as the first part of path.
1114 fn make_external_crate_suggestion(
1117 mut path: Vec<Segment>,
1118 parent_scope: &ParentScope<'b>,
1119 ) -> Option<(Vec<Segment>, Vec<String>)> {
1120 if path[1].ident.span.rust_2015() {
1124 // Sort extern crate names in reverse order to get
1125 // 1) some consistent ordering for emitted diagnostics, and
1126 // 2) `std` suggestions before `core` suggestions.
1127 let mut extern_crate_names =
1128 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1129 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1131 for name in extern_crate_names.into_iter() {
1132 // Replace first ident with a crate name and check if that is valid.
1133 path[0].ident.name = name;
1134 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1136 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1139 if let PathResult::Module(..) = result {
1140 return Some((path, Vec::new()));
1147 /// Suggests importing a macro from the root of the crate rather than a module within
1151 /// help: a macro with this name exists at the root of the crate
1153 /// LL | use issue_59764::makro;
1154 /// | ^^^^^^^^^^^^^^^^^^
1156 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1157 /// at the root of the crate instead of the module where it is defined
1159 pub(crate) fn check_for_module_export_macro(
1161 import: &'b Import<'b>,
1162 module: ModuleOrUniformRoot<'b>,
1164 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1165 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
1171 while let Some(parent) = crate_module.parent {
1172 crate_module = parent;
1175 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1176 // Don't make a suggestion if the import was already from the root of the
1181 let resolutions = self.r.resolutions(crate_module).borrow();
1182 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1183 let binding = resolution.borrow().binding()?;
1184 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1185 let module_name = crate_module.kind.name().unwrap();
1186 let import_snippet = match import.kind {
1187 ImportKind::Single { source, target, .. } if source != target => {
1188 format!("{} as {}", source, target)
1190 _ => format!("{}", ident),
1193 let mut corrections: Vec<(Span, String)> = Vec::new();
1194 if !import.is_nested() {
1195 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1196 // intermediate segments.
1197 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1199 // Find the binding span (and any trailing commas and spaces).
1200 // ie. `use a::b::{c, d, e};`
1202 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1208 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1209 found_closing_brace, binding_span
1212 let mut removal_span = binding_span;
1213 if found_closing_brace {
1214 // If the binding span ended with a closing brace, as in the below example:
1215 // ie. `use a::b::{c, d};`
1217 // Then expand the span of characters to remove to include the previous
1218 // binding's trailing comma.
1219 // ie. `use a::b::{c, d};`
1221 if let Some(previous_span) =
1222 extend_span_to_previous_binding(self.r.session, binding_span)
1224 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1225 removal_span = removal_span.with_lo(previous_span.lo());
1228 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1230 // Remove the `removal_span`.
1231 corrections.push((removal_span, "".to_string()));
1233 // Find the span after the crate name and if it has nested imports immediatately
1234 // after the crate name already.
1235 // ie. `use a::b::{c, d};`
1237 // or `use a::{b, c, d}};`
1239 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1245 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1246 has_nested, after_crate_name
1249 let source_map = self.r.session.source_map();
1251 // Add the import to the start, with a `{` if required.
1252 let start_point = source_map.start_point(after_crate_name);
1253 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1257 // In this case, `start_snippet` must equal '{'.
1258 format!("{}{}, ", start_snippet, import_snippet)
1260 // In this case, add a `{`, then the moved import, then whatever
1261 // was there before.
1262 format!("{{{}, {}", import_snippet, start_snippet)
1267 // Add a `};` to the end if nested, matching the `{` added at the start.
1269 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1273 let suggestion = Some((
1275 String::from("a macro with this name exists at the root of the crate"),
1276 Applicability::MaybeIncorrect,
1279 "this could be because a macro annotated with `#[macro_export]` will be exported \
1280 at the root of the crate instead of the module where it is defined"
1283 Some((suggestion, note))
1290 /// Given a `binding_span` of a binding within a use statement:
1293 /// use foo::{a, b, c};
1297 /// then return the span until the next binding or the end of the statement:
1300 /// use foo::{a, b, c};
1303 pub(crate) fn find_span_of_binding_until_next_binding(
1308 let source_map = sess.source_map();
1310 // Find the span of everything after the binding.
1311 // ie. `a, e};` or `a};`
1312 let binding_until_end = binding_span.with_hi(use_span.hi());
1314 // Find everything after the binding but not including the binding.
1315 // ie. `, e};` or `};`
1316 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1318 // Keep characters in the span until we encounter something that isn't a comma or
1322 // Also note whether a closing brace character was encountered. If there
1323 // was, then later go backwards to remove any trailing commas that are left.
1324 let mut found_closing_brace = false;
1325 let after_binding_until_next_binding =
1326 source_map.span_take_while(after_binding_until_end, |&ch| {
1328 found_closing_brace = true;
1330 ch == ' ' || ch == ','
1333 // Combine the two spans.
1334 // ie. `a, ` or `a`.
1336 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1337 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1339 (found_closing_brace, span)
1342 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1346 /// use foo::a::{a, b, c};
1347 /// ^^--- binding span
1351 /// use foo::{a, b, c};
1352 /// --- binding span
1354 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1355 let source_map = sess.source_map();
1357 // `prev_source` will contain all of the source that came before the span.
1358 // Then split based on a command and take the first (ie. closest to our span)
1359 // snippet. In the example, this is a space.
1360 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1362 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1363 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1364 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1368 let prev_comma = prev_comma.first().unwrap();
1369 let prev_starting_brace = prev_starting_brace.first().unwrap();
1371 // If the amount of source code before the comma is greater than
1372 // the amount of source code before the starting brace then we've only
1373 // got one item in the nested item (eg. `issue_52891::{self}`).
1374 if prev_comma.len() > prev_starting_brace.len() {
1378 Some(binding_span.with_lo(BytePos(
1379 // Take away the number of bytes for the characters we've found and an
1380 // extra for the comma.
1381 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1385 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1386 /// it is a nested use tree.
1389 /// use foo::a::{b, c};
1390 /// ^^^^^^^^^^ // false
1392 /// use foo::{a, b, c};
1393 /// ^^^^^^^^^^ // true
1395 /// use foo::{a, b::{c, d}};
1396 /// ^^^^^^^^^^^^^^^ // true
1398 fn find_span_immediately_after_crate_name(
1400 module_name: Symbol,
1404 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1405 module_name, use_span
1407 let source_map = sess.source_map();
1409 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1410 let mut num_colons = 0;
1411 // Find second colon.. `use issue_59764:`
1412 let until_second_colon = source_map.span_take_while(use_span, |c| {
1417 ':' if num_colons == 2 => false,
1421 // Find everything after the second colon.. `foo::{baz, makro};`
1422 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1424 let mut found_a_non_whitespace_character = false;
1425 // Find the first non-whitespace character in `from_second_colon`.. `f`
1426 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1427 if found_a_non_whitespace_character {
1430 if !c.is_whitespace() {
1431 found_a_non_whitespace_character = true;
1436 // Find the first `{` in from_second_colon.. `foo::{`
1437 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1439 (next_left_bracket == after_second_colon, from_second_colon)
1442 /// When an entity with a given name is not available in scope, we search for
1443 /// entities with that name in all crates. This method allows outputting the
1444 /// results of this search in a programmer-friendly way
1445 crate fn show_candidates(
1446 err: &mut DiagnosticBuilder<'_>,
1447 // This is `None` if all placement locations are inside expansions
1449 candidates: &[ImportSuggestion],
1453 if candidates.is_empty() {
1456 // we want consistent results across executions, but candidates are produced
1457 // by iterating through a hash map, so make sure they are ordered:
1458 let mut path_strings: Vec<_> =
1459 candidates.iter().map(|c| path_names_to_string(&c.path)).collect();
1460 path_strings.sort();
1461 path_strings.dedup();
1463 let better = if better { "better " } else { "" };
1464 let msg_diff = match path_strings.len() {
1465 1 => " is found in another module, you can import it",
1466 _ => "s are found in other modules, you can import them",
1468 let msg = format!("possible {}candidate{} into scope", better, msg_diff);
1470 if let Some(span) = span {
1471 for candidate in &mut path_strings {
1472 // produce an additional newline to separate the new use statement
1473 // from the directly following item.
1474 let additional_newline = if found_use { "" } else { "\n" };
1475 *candidate = format!("use {};\n{}", candidate, additional_newline);
1478 err.span_suggestions(span, &msg, path_strings.into_iter(), Applicability::Unspecified);
1482 for candidate in path_strings {
1484 msg.push_str(&candidate);