4 use rustc_ast::{self as ast, Path};
5 use rustc_ast_pretty::pprust;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
8 use rustc_feature::BUILTIN_ATTRIBUTES;
9 use rustc_hir::def::Namespace::{self, *};
10 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
11 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::PrimTy;
13 use rustc_middle::bug;
14 use rustc_middle::ty::{self, DefIdTree};
15 use rustc_session::Session;
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::lev_distance::find_best_match_for_name;
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{BytePos, MultiSpan, Span};
23 use crate::imports::{Import, ImportKind, ImportResolver};
24 use crate::path_names_to_string;
25 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
27 BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
29 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
30 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
32 type Res = def::Res<ast::NodeId>;
34 /// A vector of spans and replacements, a message and applicability.
35 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
37 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
38 /// similarly named label and whether or not it is reachable.
39 crate type LabelSuggestion = (Ident, bool);
41 crate enum SuggestionTarget {
42 /// The target has a similar name as the name used by the programmer (probably a typo)
44 /// The target is the only valid item that can be used in the corresponding context
48 crate struct TypoSuggestion {
49 pub candidate: Symbol,
51 pub target: SuggestionTarget,
55 crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
56 Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
58 crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
59 Self { candidate, res, target: SuggestionTarget::SingleItem }
63 /// A free importable items suggested in case of resolution failure.
64 crate struct ImportSuggestion {
65 pub did: Option<DefId>,
66 pub descr: &'static str,
69 /// An extra note that should be issued if this item is suggested
70 pub note: Option<String>,
73 /// Adjust the impl span so that just the `impl` keyword is taken by removing
74 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
75 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
77 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
78 /// parser. If you need to use this function or something similar, please consider updating the
79 /// `source_map` functions and this function to something more robust.
80 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
81 let impl_span = sm.span_until_char(impl_span, '<');
82 sm.span_until_whitespace(impl_span)
85 impl<'a> Resolver<'a> {
86 crate fn add_module_candidates(
89 names: &mut Vec<TypoSuggestion>,
90 filter_fn: &impl Fn(Res) -> bool,
92 for (key, resolution) in self.resolutions(module).borrow().iter() {
93 if let Some(binding) = resolution.borrow().binding {
94 let res = binding.res();
96 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
102 /// Combines an error with provided span and emits it.
104 /// This takes the error provided, combines it with the span and any additional spans inside the
105 /// error and emits it.
106 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
107 self.into_struct_error(span, resolution_error).emit();
110 crate fn into_struct_error(
113 resolution_error: ResolutionError<'_>,
114 ) -> DiagnosticBuilder<'_> {
115 match resolution_error {
116 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
117 let mut err = struct_span_err!(
121 "can't use generic parameters from outer function",
123 err.span_label(span, "use of generic parameter from outer function".to_string());
125 let sm = self.session.source_map();
127 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
128 if let Some(impl_span) =
129 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
132 reduce_impl_span_to_impl_keyword(sm, impl_span),
133 "`Self` type implicitly declared here, by this `impl`",
136 match (maybe_trait_defid, maybe_impl_defid) {
138 err.span_label(span, "can't use `Self` here");
141 err.span_label(span, "use a type here instead");
143 (None, None) => bug!("`impl` without trait nor type?"),
147 Res::Def(DefKind::TyParam, def_id) => {
148 if let Some(span) = self.opt_span(def_id) {
149 err.span_label(span, "type parameter from outer function");
152 Res::Def(DefKind::ConstParam, def_id) => {
153 if let Some(span) = self.opt_span(def_id) {
154 err.span_label(span, "const parameter from outer function");
159 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
160 DefKind::TyParam or DefKind::ConstParam"
165 if has_generic_params == HasGenericParams::Yes {
166 // Try to retrieve the span of the function signature and generate a new
167 // message with a local type or const parameter.
168 let sugg_msg = "try using a local generic parameter instead";
169 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
170 // Suggest the modification to the user
175 Applicability::MachineApplicable,
177 } else if let Some(sp) = sm.generate_fn_name_span(span) {
180 "try adding a local generic parameter in this method instead"
184 err.help("try using a local generic parameter instead");
190 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
191 let mut err = struct_span_err!(
195 "the name `{}` is already used for a generic \
196 parameter in this item's generic parameters",
199 err.span_label(span, "already used");
200 err.span_label(first_use_span, format!("first use of `{}`", name));
203 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
204 let mut err = struct_span_err!(
208 "method `{}` is not a member of trait `{}`",
212 err.span_label(span, format!("not a member of trait `{}`", trait_));
213 if let Some(candidate) = candidate {
216 "there is an associated function with a similar name",
217 candidate.to_ident_string(),
218 Applicability::MaybeIncorrect,
223 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
224 let mut err = struct_span_err!(
228 "type `{}` is not a member of trait `{}`",
232 err.span_label(span, format!("not a member of trait `{}`", trait_));
233 if let Some(candidate) = candidate {
236 "there is an associated type with a similar name",
237 candidate.to_ident_string(),
238 Applicability::MaybeIncorrect,
243 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
244 let mut err = struct_span_err!(
248 "const `{}` is not a member of trait `{}`",
252 err.span_label(span, format!("not a member of trait `{}`", trait_));
253 if let Some(candidate) = candidate {
256 "there is an associated constant with a similar name",
257 candidate.to_ident_string(),
258 Applicability::MaybeIncorrect,
263 ResolutionError::VariableNotBoundInPattern(binding_error) => {
264 let BindingError { name, target, origin, could_be_path } = binding_error;
266 let target_sp = target.iter().copied().collect::<Vec<_>>();
267 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
269 let msp = MultiSpan::from_spans(target_sp.clone());
270 let mut err = struct_span_err!(
274 "variable `{}` is not bound in all patterns",
277 for sp in target_sp {
278 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
280 for sp in origin_sp {
281 err.span_label(sp, "variable not in all patterns");
284 let help_msg = format!(
285 "if you meant to match on a variant or a `const` item, consider \
286 making the path in the pattern qualified: `?::{}`",
289 err.span_help(span, &help_msg);
293 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
294 let mut err = struct_span_err!(
298 "variable `{}` is bound inconsistently across alternatives separated by `|`",
301 err.span_label(span, "bound in different ways");
302 err.span_label(first_binding_span, "first binding");
305 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
306 let mut err = struct_span_err!(
310 "identifier `{}` is bound more than once in this parameter list",
313 err.span_label(span, "used as parameter more than once");
316 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
317 let mut err = struct_span_err!(
321 "identifier `{}` is bound more than once in the same pattern",
324 err.span_label(span, "used in a pattern more than once");
327 ResolutionError::UndeclaredLabel { name, suggestion } => {
328 let mut err = struct_span_err!(
332 "use of undeclared label `{}`",
336 err.span_label(span, format!("undeclared label `{}`", name));
339 // A reachable label with a similar name exists.
340 Some((ident, true)) => {
341 err.span_label(ident.span, "a label with a similar name is reachable");
344 "try using similarly named label",
345 ident.name.to_string(),
346 Applicability::MaybeIncorrect,
349 // An unreachable label with a similar name exists.
350 Some((ident, false)) => {
353 "a label with a similar name exists but is unreachable",
356 // No similarly-named labels exist.
362 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
363 let mut err = struct_span_err!(
368 "`self` imports are only allowed within a { } list"
371 // None of the suggestions below would help with a case like `use self`.
373 // use foo::bar::self -> foo::bar
374 // use foo::bar::self as abc -> foo::bar as abc
377 "consider importing the module directly",
379 Applicability::MachineApplicable,
382 // use foo::bar::self -> foo::bar::{self}
383 // use foo::bar::self as abc -> foo::bar::{self as abc}
385 (span_with_rename.shrink_to_lo(), "{".to_string()),
386 (span_with_rename.shrink_to_hi(), "}".to_string()),
388 err.multipart_suggestion(
389 "alternatively, use the multi-path `use` syntax to import `self`",
391 Applicability::MachineApplicable,
396 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
397 let mut err = struct_span_err!(
401 "`self` import can only appear once in an import list"
403 err.span_label(span, "can only appear once in an import list");
406 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
407 let mut err = struct_span_err!(
411 "`self` import can only appear in an import list with \
414 err.span_label(span, "can only appear in an import list with a non-empty prefix");
417 ResolutionError::FailedToResolve { label, suggestion } => {
419 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
420 err.span_label(span, label);
422 if let Some((suggestions, msg, applicability)) = suggestion {
423 if suggestions.is_empty() {
427 err.multipart_suggestion(&msg, suggestions, applicability);
432 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
433 let mut err = struct_span_err!(
438 "can't capture dynamic environment in a fn item"
440 err.help("use the `|| { ... }` closure form instead");
443 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
444 let mut err = struct_span_err!(
448 "attempt to use a non-constant value in a constant"
451 // ^^^ given this Span
452 // ------- get this Span to have an applicable suggestion
454 self.session.source_map().span_extend_to_prev_str(ident.span, current, true);
456 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
458 let sp = sp.with_lo(BytePos(sp.lo().0 - current.len() as u32));
461 &format!("consider using `{}` instead of `{}`", sugg, current),
462 format!("{} {}", sugg, ident),
463 Applicability::MaybeIncorrect,
465 err.span_label(span, "non-constant value");
469 ResolutionError::BindingShadowsSomethingUnacceptable {
470 shadowing_binding_descr,
474 shadowed_binding_descr,
475 shadowed_binding_span,
477 let mut err = struct_span_err!(
481 "{}s cannot shadow {}s",
482 shadowing_binding_descr,
483 shadowed_binding_descr,
487 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
490 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
491 err.span_label(shadowed_binding_span, msg);
494 ResolutionError::ForwardDeclaredGenericParam => {
495 let mut err = struct_span_err!(
499 "generic parameters with a default cannot use \
500 forward declared identifiers"
504 "defaulted generic parameters cannot be forward declared".to_string(),
508 ResolutionError::ParamInTyOfConstParam(name) => {
509 let mut err = struct_span_err!(
513 "the type of const parameters must not depend on other generic parameters"
517 format!("the type must not depend on the parameter `{}`", name),
521 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
522 let mut err = self.session.struct_span_err(
524 "generic parameters may not be used in const operations",
526 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
529 err.note("type parameters may not be used in const expressions");
532 "const parameters may only be used as standalone arguments, i.e. `{}`",
537 if self.session.is_nightly_build() {
539 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
545 ResolutionError::SelfInGenericParamDefault => {
546 let mut err = struct_span_err!(
550 "generic parameters cannot use `Self` in their defaults"
552 err.span_label(span, "`Self` in generic parameter default".to_string());
555 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
556 let mut err = struct_span_err!(
560 "use of unreachable label `{}`",
564 err.span_label(definition_span, "unreachable label defined here");
565 err.span_label(span, format!("unreachable label `{}`", name));
567 "labels are unreachable through functions, closures, async blocks and modules",
571 // A reachable label with a similar name exists.
572 Some((ident, true)) => {
573 err.span_label(ident.span, "a label with a similar name is reachable");
576 "try using similarly named label",
577 ident.name.to_string(),
578 Applicability::MaybeIncorrect,
581 // An unreachable label with a similar name exists.
582 Some((ident, false)) => {
585 "a label with a similar name exists but is also unreachable",
588 // No similarly-named labels exist.
597 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
598 match vis_resolution_error {
599 VisResolutionError::Relative2018(span, path) => {
600 let mut err = self.session.struct_span_err(
602 "relative paths are not supported in visibilities on 2018 edition",
607 format!("crate::{}", pprust::path_to_string(&path)),
608 Applicability::MaybeIncorrect,
612 VisResolutionError::AncestorOnly(span) => struct_span_err!(
616 "visibilities can only be restricted to ancestor modules"
618 VisResolutionError::FailedToResolve(span, label, suggestion) => {
619 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
621 VisResolutionError::ExpectedFound(span, path_str, res) => {
622 let mut err = struct_span_err!(
626 "expected module, found {} `{}`",
630 err.span_label(span, "not a module");
633 VisResolutionError::Indeterminate(span) => struct_span_err!(
637 "cannot determine resolution for the visibility"
639 VisResolutionError::ModuleOnly(span) => {
640 self.session.struct_span_err(span, "visibility must resolve to a module")
646 /// Lookup typo candidate in scope for a macro or import.
647 fn early_lookup_typo_candidate(
649 scope_set: ScopeSet<'a>,
650 parent_scope: &ParentScope<'a>,
652 filter_fn: &impl Fn(Res) -> bool,
653 ) -> Option<TypoSuggestion> {
654 let mut suggestions = Vec::new();
655 let ctxt = ident.span.ctxt();
656 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
658 Scope::DeriveHelpers(expn_id) => {
659 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
666 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
670 Scope::DeriveHelpersCompat => {
671 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
673 for derive in parent_scope.derives {
674 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
675 if let Ok((Some(ext), _)) = this.resolve_macro_path(
677 Some(MacroKind::Derive),
685 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
691 Scope::MacroRules(macro_rules_scope) => {
692 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
693 let res = macro_rules_binding.binding.res();
695 suggestions.push(TypoSuggestion::typo_from_res(
696 macro_rules_binding.ident.name,
702 Scope::CrateRoot => {
703 let root_ident = Ident::new(kw::PathRoot, ident.span);
704 let root_module = this.resolve_crate_root(root_ident);
705 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
707 Scope::Module(module, _) => {
708 this.add_module_candidates(module, &mut suggestions, filter_fn);
710 Scope::RegisteredAttrs => {
711 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
714 this.registered_attrs
716 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
720 Scope::MacroUsePrelude => {
721 suggestions.extend(this.macro_use_prelude.iter().filter_map(
723 let res = binding.res();
724 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
728 Scope::BuiltinAttrs => {
729 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
734 .map(|(name, ..)| TypoSuggestion::typo_from_res(*name, res)),
738 Scope::ExternPrelude => {
739 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
740 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
741 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
744 Scope::ToolPrelude => {
745 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
747 this.registered_tools
749 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
752 Scope::StdLibPrelude => {
753 if let Some(prelude) = this.prelude {
754 let mut tmp_suggestions = Vec::new();
755 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
759 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
763 Scope::BuiltinTypes => {
764 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
765 let res = Res::PrimTy(*prim_ty);
766 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
774 // Make sure error reporting is deterministic.
775 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
777 match find_best_match_for_name(
778 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
782 Some(found) if found != ident.name => {
783 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
789 fn lookup_import_candidates_from_module<FilterFn>(
792 namespace: Namespace,
793 parent_scope: &ParentScope<'a>,
794 start_module: Module<'a>,
797 ) -> Vec<ImportSuggestion>
799 FilterFn: Fn(Res) -> bool,
801 let mut candidates = Vec::new();
802 let mut seen_modules = FxHashSet::default();
803 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
804 let mut worklist_via_import = vec![];
806 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
807 None => worklist_via_import.pop(),
810 let in_module_is_extern = !in_module.def_id().is_local();
811 // We have to visit module children in deterministic order to avoid
812 // instabilities in reported imports (#43552).
813 in_module.for_each_child(self, |this, ident, ns, name_binding| {
814 // avoid non-importable candidates
815 if !name_binding.is_importable() {
819 let child_accessible =
820 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
822 // do not venture inside inaccessible items of other crates
823 if in_module_is_extern && !child_accessible {
827 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
829 // There is an assumption elsewhere that paths of variants are in the enum's
830 // declaration and not imported. With this assumption, the variant component is
831 // chopped and the rest of the path is assumed to be the enum's own path. For
832 // errors where a variant is used as the type instead of the enum, this causes
833 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
834 if via_import && name_binding.is_possibly_imported_variant() {
838 // #90113: Do not count an inaccessible reexported item as a candidate.
839 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
840 if this.is_accessible_from(binding.vis, parent_scope.module)
841 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
847 // collect results based on the filter function
848 // avoid suggesting anything from the same module in which we are resolving
849 // avoid suggesting anything with a hygienic name
850 if ident.name == lookup_ident.name
852 && !ptr::eq(in_module, parent_scope.module)
853 && !ident.span.normalize_to_macros_2_0().from_expansion()
855 let res = name_binding.res();
858 let mut segms = path_segments.clone();
859 if lookup_ident.span.rust_2018() {
860 // crate-local absolute paths start with `crate::` in edition 2018
861 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
862 segms.insert(0, ast::PathSegment::from_ident(crate_name));
865 segms.push(ast::PathSegment::from_ident(ident));
866 let path = Path { span: name_binding.span, segments: segms, tokens: None };
867 let did = match res {
868 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
869 _ => res.opt_def_id(),
872 if child_accessible {
873 // Remove invisible match if exists
874 if let Some(idx) = candidates
876 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
878 candidates.remove(idx);
882 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
883 // See if we're recommending TryFrom, TryInto, or FromIterator and add
884 // a note about editions
885 let note = if let Some(did) = did {
886 let requires_note = !did.is_local()
887 && this.cstore().item_attrs(did, this.session).iter().any(
889 if attr.has_name(sym::rustc_diagnostic_item) {
890 [sym::TryInto, sym::TryFrom, sym::FromIterator]
892 .contains(&attr.value_str())
899 requires_note.then(|| {
901 "'{}' is included in the prelude starting in Edition 2021",
902 path_names_to_string(&path)
909 candidates.push(ImportSuggestion {
913 accessible: child_accessible,
920 // collect submodules to explore
921 if let Some(module) = name_binding.module() {
923 let mut path_segments = path_segments.clone();
924 path_segments.push(ast::PathSegment::from_ident(ident));
926 let is_extern_crate_that_also_appears_in_prelude =
927 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
929 if !is_extern_crate_that_also_appears_in_prelude {
930 // add the module to the lookup
931 if seen_modules.insert(module.def_id()) {
932 if via_import { &mut worklist_via_import } else { &mut worklist }
933 .push((module, path_segments, child_accessible));
940 // If only some candidates are accessible, take just them
941 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
942 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
948 /// When name resolution fails, this method can be used to look up candidate
949 /// entities with the expected name. It allows filtering them using the
950 /// supplied predicate (which should be used to only accept the types of
951 /// definitions expected, e.g., traits). The lookup spans across all crates.
953 /// N.B., the method does not look into imports, but this is not a problem,
954 /// since we report the definitions (thus, the de-aliased imports).
955 crate fn lookup_import_candidates<FilterFn>(
958 namespace: Namespace,
959 parent_scope: &ParentScope<'a>,
961 ) -> Vec<ImportSuggestion>
963 FilterFn: Fn(Res) -> bool,
965 let mut suggestions = self.lookup_import_candidates_from_module(
970 Ident::with_dummy_span(kw::Crate),
974 if lookup_ident.span.rust_2018() {
975 let extern_prelude_names = self.extern_prelude.clone();
976 for (ident, _) in extern_prelude_names.into_iter() {
977 if ident.span.from_expansion() {
978 // Idents are adjusted to the root context before being
979 // resolved in the extern prelude, so reporting this to the
980 // user is no help. This skips the injected
981 // `extern crate std` in the 2018 edition, which would
982 // otherwise cause duplicate suggestions.
985 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
986 let crate_root = self.expect_module(crate_id.as_def_id());
987 suggestions.extend(self.lookup_import_candidates_from_module(
1002 crate fn unresolved_macro_suggestions(
1004 err: &mut DiagnosticBuilder<'a>,
1005 macro_kind: MacroKind,
1006 parent_scope: &ParentScope<'a>,
1009 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1010 let suggestion = self.early_lookup_typo_candidate(
1011 ScopeSet::Macro(macro_kind),
1016 self.add_typo_suggestion(err, suggestion, ident.span);
1018 let import_suggestions =
1019 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1025 &import_suggestions,
1030 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1031 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1032 err.span_note(ident.span, &msg);
1035 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1036 err.help("have you added the `#[macro_use]` on the module/import?");
1039 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1040 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1042 ScopeSet::All(ns, false),
1048 let desc = match binding.res() {
1049 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1050 "a function-like macro".to_string()
1052 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1053 format!("an attribute: `#[{}]`", ident)
1055 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1056 format!("a derive macro: `#[derive({})]`", ident)
1059 // Don't confuse the user with tool modules.
1062 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1063 "only a trait, without a derive macro".to_string()
1069 macro_kind.article(),
1070 macro_kind.descr_expected(),
1073 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1074 if !import.span.is_dummy() {
1077 &format!("`{}` is imported here, but it is {}", ident, desc),
1079 // Silence the 'unused import' warning we might get,
1080 // since this diagnostic already covers that import.
1081 self.record_use(ident, binding, false);
1085 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1091 crate fn add_typo_suggestion(
1093 err: &mut DiagnosticBuilder<'_>,
1094 suggestion: Option<TypoSuggestion>,
1097 let suggestion = match suggestion {
1098 None => return false,
1099 // We shouldn't suggest underscore.
1100 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1101 Some(suggestion) => suggestion,
1103 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1104 LOCAL_CRATE => self.opt_span(def_id),
1108 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1111 if let Some(def_span) = def_span {
1112 if span.overlaps(def_span) {
1113 // Don't suggest typo suggestion for itself like in the following:
1114 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1115 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1118 // | ----------- `X` defined here
1120 // LL | const Y: X = X("ö");
1121 // | -------------^^^^^^- similarly named constant `Y` defined here
1123 // help: use struct literal syntax instead
1125 // LL | const Y: X = X {};
1127 // help: a constant with a similar name exists
1129 // LL | const Y: X = Y("ö");
1133 let prefix = match suggestion.target {
1134 SuggestionTarget::SimilarlyNamed => "similarly named ",
1135 SuggestionTarget::SingleItem => "",
1139 self.session.source_map().guess_head_span(def_span),
1141 "{}{} `{}` defined here",
1143 suggestion.res.descr(),
1144 suggestion.candidate.as_str(),
1148 let msg = match suggestion.target {
1149 SuggestionTarget::SimilarlyNamed => format!(
1150 "{} {} with a similar name exists",
1151 suggestion.res.article(),
1152 suggestion.res.descr()
1154 SuggestionTarget::SingleItem => {
1155 format!("maybe you meant this {}", suggestion.res.descr())
1158 err.span_suggestion(
1161 suggestion.candidate.to_string(),
1162 Applicability::MaybeIncorrect,
1167 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1169 if b.span.is_dummy() {
1170 // These already contain the "built-in" prefix or look bad with it.
1172 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1173 let (built_in, from) = if from_prelude {
1174 ("", " from prelude")
1175 } else if b.is_extern_crate()
1177 && self.session.opts.externs.get(&ident.as_str()).is_some()
1179 ("", " passed with `--extern`")
1180 } else if add_built_in {
1186 let a = if built_in.is_empty() { res.article() } else { "a" };
1187 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1189 let introduced = if b.is_import() { "imported" } else { "defined" };
1190 format!("the {thing} {introduced} here", thing = res.descr())
1194 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1195 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1196 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1197 // We have to print the span-less alternative first, otherwise formatting looks bad.
1198 (b2, b1, misc2, misc1, true)
1200 (b1, b2, misc1, misc2, false)
1203 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1204 err.span_label(ident.span, "ambiguous name");
1205 err.note(&format!("ambiguous because of {}", kind.descr()));
1207 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1208 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1209 let note_msg = format!("`{ident}` could{also} refer to {what}");
1211 let thing = b.res().descr();
1212 let mut help_msgs = Vec::new();
1213 if b.is_glob_import()
1214 && (kind == AmbiguityKind::GlobVsGlob
1215 || kind == AmbiguityKind::GlobVsExpanded
1216 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1218 help_msgs.push(format!(
1219 "consider adding an explicit import of `{ident}` to disambiguate"
1222 if b.is_extern_crate() && ident.span.rust_2018() {
1223 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1225 if misc == AmbiguityErrorMisc::SuggestCrate {
1227 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1228 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1230 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1233 err.span_note(b.span, ¬e_msg);
1234 for (i, help_msg) in help_msgs.iter().enumerate() {
1235 let or = if i == 0 { "" } else { "or " };
1236 err.help(&format!("{}{}", or, help_msg));
1240 could_refer_to(b1, misc1, "");
1241 could_refer_to(b2, misc2, " also");
1245 /// If the binding refers to a tuple struct constructor with fields,
1246 /// returns the span of its fields.
1247 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1248 if let NameBindingKind::Res(
1249 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1253 let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1254 let fields = self.field_names.get(&def_id)?;
1255 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1260 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1261 let PrivacyError { ident, binding, .. } = *privacy_error;
1263 let res = binding.res();
1264 let ctor_fields_span = self.ctor_fields_span(binding);
1265 let plain_descr = res.descr().to_string();
1266 let nonimport_descr =
1267 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1268 let import_descr = nonimport_descr.clone() + " import";
1270 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1272 // Print the primary message.
1273 let descr = get_descr(binding);
1275 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1276 err.span_label(ident.span, &format!("private {}", descr));
1277 if let Some(span) = ctor_fields_span {
1278 err.span_label(span, "a constructor is private if any of the fields is private");
1281 // Print the whole import chain to make it easier to see what happens.
1282 let first_binding = binding;
1283 let mut next_binding = Some(binding);
1284 let mut next_ident = ident;
1285 while let Some(binding) = next_binding {
1286 let name = next_ident;
1287 next_binding = match binding.kind {
1288 _ if res == Res::Err => None,
1289 NameBindingKind::Import { binding, import, .. } => match import.kind {
1290 _ if binding.span.is_dummy() => None,
1291 ImportKind::Single { source, .. } => {
1292 next_ident = source;
1295 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1296 ImportKind::ExternCrate { .. } => None,
1301 let first = ptr::eq(binding, first_binding);
1303 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1304 and_refers_to = if first { "" } else { "...and refers to " },
1305 item = get_descr(binding),
1306 which = if first { "" } else { " which" },
1307 dots = if next_binding.is_some() { "..." } else { "" },
1309 let def_span = self.session.source_map().guess_head_span(binding.span);
1310 let mut note_span = MultiSpan::from_span(def_span);
1311 if !first && binding.vis == ty::Visibility::Public {
1312 note_span.push_span_label(def_span, "consider importing it directly".into());
1314 err.span_note(note_span, &msg);
1320 crate fn find_similarly_named_module_or_crate(
1323 current_module: &Module<'a>,
1324 ) -> Option<Symbol> {
1325 let mut candidates = self
1328 .map(|(ident, _)| ident.name)
1332 .filter(|(_, module)| {
1333 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1335 .map(|(_, module)| module.kind.name())
1338 .filter(|c| !c.to_string().is_empty())
1339 .collect::<Vec<_>>();
1342 match find_best_match_for_name(&candidates, ident, None) {
1343 Some(sugg) if sugg == ident => None,
1349 impl<'a, 'b> ImportResolver<'a, 'b> {
1350 /// Adds suggestions for a path that cannot be resolved.
1351 pub(crate) fn make_path_suggestion(
1354 mut path: Vec<Segment>,
1355 parent_scope: &ParentScope<'b>,
1356 ) -> Option<(Vec<Segment>, Vec<String>)> {
1357 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1359 match (path.get(0), path.get(1)) {
1360 // `{{root}}::ident::...` on both editions.
1361 // On 2015 `{{root}}` is usually added implicitly.
1362 (Some(fst), Some(snd))
1363 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1364 // `ident::...` on 2018.
1366 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1368 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1369 path.insert(0, Segment::from_ident(Ident::empty()));
1374 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1375 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1376 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1377 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1380 /// Suggest a missing `self::` if that resolves to an correct module.
1384 /// LL | use foo::Bar;
1385 /// | ^^^ did you mean `self::foo`?
1387 fn make_missing_self_suggestion(
1390 mut path: Vec<Segment>,
1391 parent_scope: &ParentScope<'b>,
1392 ) -> Option<(Vec<Segment>, Vec<String>)> {
1393 // Replace first ident with `self` and check if that is valid.
1394 path[0].ident.name = kw::SelfLower;
1395 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1396 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1397 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1400 /// Suggests a missing `crate::` if that resolves to an correct module.
1404 /// LL | use foo::Bar;
1405 /// | ^^^ did you mean `crate::foo`?
1407 fn make_missing_crate_suggestion(
1410 mut path: Vec<Segment>,
1411 parent_scope: &ParentScope<'b>,
1412 ) -> Option<(Vec<Segment>, Vec<String>)> {
1413 // Replace first ident with `crate` and check if that is valid.
1414 path[0].ident.name = kw::Crate;
1415 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1416 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1417 if let PathResult::Module(..) = result {
1421 "`use` statements changed in Rust 2018; read more at \
1422 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1432 /// Suggests a missing `super::` if that resolves to an correct module.
1436 /// LL | use foo::Bar;
1437 /// | ^^^ did you mean `super::foo`?
1439 fn make_missing_super_suggestion(
1442 mut path: Vec<Segment>,
1443 parent_scope: &ParentScope<'b>,
1444 ) -> Option<(Vec<Segment>, Vec<String>)> {
1445 // Replace first ident with `crate` and check if that is valid.
1446 path[0].ident.name = kw::Super;
1447 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1448 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1449 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1452 /// Suggests a missing external crate name if that resolves to an correct module.
1456 /// LL | use foobar::Baz;
1457 /// | ^^^^^^ did you mean `baz::foobar`?
1460 /// Used when importing a submodule of an external crate but missing that crate's
1461 /// name as the first part of path.
1462 fn make_external_crate_suggestion(
1465 mut path: Vec<Segment>,
1466 parent_scope: &ParentScope<'b>,
1467 ) -> Option<(Vec<Segment>, Vec<String>)> {
1468 if path[1].ident.span.rust_2015() {
1472 // Sort extern crate names in reverse order to get
1473 // 1) some consistent ordering for emitted diagnostics, and
1474 // 2) `std` suggestions before `core` suggestions.
1475 let mut extern_crate_names =
1476 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1477 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1479 for name in extern_crate_names.into_iter() {
1480 // Replace first ident with a crate name and check if that is valid.
1481 path[0].ident.name = name;
1482 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1484 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1487 if let PathResult::Module(..) = result {
1488 return Some((path, Vec::new()));
1495 /// Suggests importing a macro from the root of the crate rather than a module within
1499 /// help: a macro with this name exists at the root of the crate
1501 /// LL | use issue_59764::makro;
1502 /// | ^^^^^^^^^^^^^^^^^^
1504 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1505 /// at the root of the crate instead of the module where it is defined
1507 pub(crate) fn check_for_module_export_macro(
1509 import: &'b Import<'b>,
1510 module: ModuleOrUniformRoot<'b>,
1512 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1513 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
1517 while let Some(parent) = crate_module.parent {
1518 crate_module = parent;
1521 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1522 // Don't make a suggestion if the import was already from the root of the
1527 let resolutions = self.r.resolutions(crate_module).borrow();
1528 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1529 let binding = resolution.borrow().binding()?;
1530 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1531 let module_name = crate_module.kind.name().unwrap();
1532 let import_snippet = match import.kind {
1533 ImportKind::Single { source, target, .. } if source != target => {
1534 format!("{} as {}", source, target)
1536 _ => format!("{}", ident),
1539 let mut corrections: Vec<(Span, String)> = Vec::new();
1540 if !import.is_nested() {
1541 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1542 // intermediate segments.
1543 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1545 // Find the binding span (and any trailing commas and spaces).
1546 // ie. `use a::b::{c, d, e};`
1548 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1554 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1555 found_closing_brace, binding_span
1558 let mut removal_span = binding_span;
1559 if found_closing_brace {
1560 // If the binding span ended with a closing brace, as in the below example:
1561 // ie. `use a::b::{c, d};`
1563 // Then expand the span of characters to remove to include the previous
1564 // binding's trailing comma.
1565 // ie. `use a::b::{c, d};`
1567 if let Some(previous_span) =
1568 extend_span_to_previous_binding(self.r.session, binding_span)
1570 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1571 removal_span = removal_span.with_lo(previous_span.lo());
1574 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1576 // Remove the `removal_span`.
1577 corrections.push((removal_span, "".to_string()));
1579 // Find the span after the crate name and if it has nested imports immediatately
1580 // after the crate name already.
1581 // ie. `use a::b::{c, d};`
1583 // or `use a::{b, c, d}};`
1585 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1591 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1592 has_nested, after_crate_name
1595 let source_map = self.r.session.source_map();
1597 // Add the import to the start, with a `{` if required.
1598 let start_point = source_map.start_point(after_crate_name);
1599 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1603 // In this case, `start_snippet` must equal '{'.
1604 format!("{}{}, ", start_snippet, import_snippet)
1606 // In this case, add a `{`, then the moved import, then whatever
1607 // was there before.
1608 format!("{{{}, {}", import_snippet, start_snippet)
1613 // Add a `};` to the end if nested, matching the `{` added at the start.
1615 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1619 let suggestion = Some((
1621 String::from("a macro with this name exists at the root of the crate"),
1622 Applicability::MaybeIncorrect,
1625 "this could be because a macro annotated with `#[macro_export]` will be exported \
1626 at the root of the crate instead of the module where it is defined"
1629 Some((suggestion, note))
1636 /// Given a `binding_span` of a binding within a use statement:
1639 /// use foo::{a, b, c};
1643 /// then return the span until the next binding or the end of the statement:
1646 /// use foo::{a, b, c};
1649 pub(crate) fn find_span_of_binding_until_next_binding(
1654 let source_map = sess.source_map();
1656 // Find the span of everything after the binding.
1657 // ie. `a, e};` or `a};`
1658 let binding_until_end = binding_span.with_hi(use_span.hi());
1660 // Find everything after the binding but not including the binding.
1661 // ie. `, e};` or `};`
1662 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1664 // Keep characters in the span until we encounter something that isn't a comma or
1668 // Also note whether a closing brace character was encountered. If there
1669 // was, then later go backwards to remove any trailing commas that are left.
1670 let mut found_closing_brace = false;
1671 let after_binding_until_next_binding =
1672 source_map.span_take_while(after_binding_until_end, |&ch| {
1674 found_closing_brace = true;
1676 ch == ' ' || ch == ','
1679 // Combine the two spans.
1680 // ie. `a, ` or `a`.
1682 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1683 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1685 (found_closing_brace, span)
1688 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1692 /// use foo::a::{a, b, c};
1693 /// ^^--- binding span
1697 /// use foo::{a, b, c};
1698 /// --- binding span
1700 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1701 let source_map = sess.source_map();
1703 // `prev_source` will contain all of the source that came before the span.
1704 // Then split based on a command and take the first (ie. closest to our span)
1705 // snippet. In the example, this is a space.
1706 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1708 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1709 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1710 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1714 let prev_comma = prev_comma.first().unwrap();
1715 let prev_starting_brace = prev_starting_brace.first().unwrap();
1717 // If the amount of source code before the comma is greater than
1718 // the amount of source code before the starting brace then we've only
1719 // got one item in the nested item (eg. `issue_52891::{self}`).
1720 if prev_comma.len() > prev_starting_brace.len() {
1724 Some(binding_span.with_lo(BytePos(
1725 // Take away the number of bytes for the characters we've found and an
1726 // extra for the comma.
1727 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1731 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1732 /// it is a nested use tree.
1735 /// use foo::a::{b, c};
1736 /// ^^^^^^^^^^ // false
1738 /// use foo::{a, b, c};
1739 /// ^^^^^^^^^^ // true
1741 /// use foo::{a, b::{c, d}};
1742 /// ^^^^^^^^^^^^^^^ // true
1744 fn find_span_immediately_after_crate_name(
1746 module_name: Symbol,
1750 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1751 module_name, use_span
1753 let source_map = sess.source_map();
1755 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1756 let mut num_colons = 0;
1757 // Find second colon.. `use issue_59764:`
1758 let until_second_colon = source_map.span_take_while(use_span, |c| {
1762 !matches!(c, ':' if num_colons == 2)
1764 // Find everything after the second colon.. `foo::{baz, makro};`
1765 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1767 let mut found_a_non_whitespace_character = false;
1768 // Find the first non-whitespace character in `from_second_colon`.. `f`
1769 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1770 if found_a_non_whitespace_character {
1773 if !c.is_whitespace() {
1774 found_a_non_whitespace_character = true;
1779 // Find the first `{` in from_second_colon.. `foo::{`
1780 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1782 (next_left_bracket == after_second_colon, from_second_colon)
1785 /// When an entity with a given name is not available in scope, we search for
1786 /// entities with that name in all crates. This method allows outputting the
1787 /// results of this search in a programmer-friendly way
1788 crate fn show_candidates(
1789 definitions: &rustc_hir::definitions::Definitions,
1791 err: &mut DiagnosticBuilder<'_>,
1792 // This is `None` if all placement locations are inside expansions
1793 use_placement_span: Option<Span>,
1794 candidates: &[ImportSuggestion],
1798 if candidates.is_empty() {
1802 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1804 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1807 candidates.iter().for_each(|c| {
1808 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1809 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
1812 // we want consistent results across executions, but candidates are produced
1813 // by iterating through a hash map, so make sure they are ordered:
1814 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1815 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1816 let core_path_strings =
1817 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1818 path_strings.extend(core_path_strings);
1819 path_strings.dedup_by(|a, b| a.0 == b.0);
1822 if !accessible_path_strings.is_empty() {
1823 let (determiner, kind) = if accessible_path_strings.len() == 1 {
1824 ("this", accessible_path_strings[0].1)
1826 ("one of these", "items")
1829 let instead = if instead { " instead" } else { "" };
1830 let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1832 for note in accessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1836 if let Some(span) = use_placement_span {
1837 for candidate in &mut accessible_path_strings {
1838 // produce an additional newline to separate the new use statement
1839 // from the directly following item.
1840 let additional_newline = if found_use { "" } else { "\n" };
1841 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1844 err.span_suggestions(
1847 accessible_path_strings.into_iter().map(|a| a.0),
1848 Applicability::Unspecified,
1853 for candidate in accessible_path_strings {
1855 msg.push_str(&candidate.0);
1861 assert!(!inaccessible_path_strings.is_empty());
1863 if inaccessible_path_strings.len() == 1 {
1864 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
1865 let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1867 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1868 let span = definitions.def_span(local_def_id);
1869 let span = session.source_map().guess_head_span(span);
1870 let mut multi_span = MultiSpan::from_span(span);
1871 multi_span.push_span_label(span, "not accessible".to_string());
1872 err.span_note(multi_span, &msg);
1876 if let Some(note) = (*note).as_deref() {
1880 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
1881 let descr = if inaccessible_path_strings
1884 .all(|(_, descr, _, _)| descr == descr_first)
1886 descr_first.to_string()
1891 let mut msg = format!("these {}s exist but are inaccessible", descr);
1892 let mut has_colon = false;
1894 let mut spans = Vec::new();
1895 for (name, _, def_id, _) in &inaccessible_path_strings {
1896 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1897 let span = definitions.def_span(local_def_id);
1898 let span = session.source_map().guess_head_span(span);
1899 spans.push((name, span));
1910 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1911 for (name, span) in spans {
1912 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1915 for note in inaccessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1919 err.span_note(multi_span, &msg);