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 err.multipart_suggestion(&msg, suggestions, applicability);
428 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
429 let mut err = struct_span_err!(
434 "can't capture dynamic environment in a fn item"
436 err.help("use the `|| { ... }` closure form instead");
439 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
440 let mut err = struct_span_err!(
444 "attempt to use a non-constant value in a constant"
447 // ^^^ given this Span
448 // ------- get this Span to have an applicable suggestion
450 self.session.source_map().span_extend_to_prev_str(ident.span, current, true);
452 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
454 let sp = sp.with_lo(BytePos(sp.lo().0 - current.len() as u32));
457 &format!("consider using `{}` instead of `{}`", sugg, current),
458 format!("{} {}", sugg, ident),
459 Applicability::MaybeIncorrect,
461 err.span_label(span, "non-constant value");
465 ResolutionError::BindingShadowsSomethingUnacceptable {
466 shadowing_binding_descr,
470 shadowed_binding_descr,
471 shadowed_binding_span,
473 let mut err = struct_span_err!(
477 "{}s cannot shadow {}s",
478 shadowing_binding_descr,
479 shadowed_binding_descr,
483 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
486 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
487 err.span_label(shadowed_binding_span, msg);
490 ResolutionError::ForwardDeclaredGenericParam => {
491 let mut err = struct_span_err!(
495 "generic parameters with a default cannot use \
496 forward declared identifiers"
500 "defaulted generic parameters cannot be forward declared".to_string(),
504 ResolutionError::ParamInTyOfConstParam(name) => {
505 let mut err = struct_span_err!(
509 "the type of const parameters must not depend on other generic parameters"
513 format!("the type must not depend on the parameter `{}`", name),
517 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
518 let mut err = self.session.struct_span_err(
520 "generic parameters may not be used in const operations",
522 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
525 err.note("type parameters may not be used in const expressions");
528 "const parameters may only be used as standalone arguments, i.e. `{}`",
533 if self.session.is_nightly_build() {
535 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
541 ResolutionError::SelfInGenericParamDefault => {
542 let mut err = struct_span_err!(
546 "generic parameters cannot use `Self` in their defaults"
548 err.span_label(span, "`Self` in generic parameter default".to_string());
551 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
552 let mut err = struct_span_err!(
556 "use of unreachable label `{}`",
560 err.span_label(definition_span, "unreachable label defined here");
561 err.span_label(span, format!("unreachable label `{}`", name));
563 "labels are unreachable through functions, closures, async blocks and modules",
567 // A reachable label with a similar name exists.
568 Some((ident, true)) => {
569 err.span_label(ident.span, "a label with a similar name is reachable");
572 "try using similarly named label",
573 ident.name.to_string(),
574 Applicability::MaybeIncorrect,
577 // An unreachable label with a similar name exists.
578 Some((ident, false)) => {
581 "a label with a similar name exists but is also unreachable",
584 // No similarly-named labels exist.
593 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
594 match vis_resolution_error {
595 VisResolutionError::Relative2018(span, path) => {
596 let mut err = self.session.struct_span_err(
598 "relative paths are not supported in visibilities on 2018 edition",
603 format!("crate::{}", pprust::path_to_string(&path)),
604 Applicability::MaybeIncorrect,
608 VisResolutionError::AncestorOnly(span) => struct_span_err!(
612 "visibilities can only be restricted to ancestor modules"
614 VisResolutionError::FailedToResolve(span, label, suggestion) => {
615 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
617 VisResolutionError::ExpectedFound(span, path_str, res) => {
618 let mut err = struct_span_err!(
622 "expected module, found {} `{}`",
626 err.span_label(span, "not a module");
629 VisResolutionError::Indeterminate(span) => struct_span_err!(
633 "cannot determine resolution for the visibility"
635 VisResolutionError::ModuleOnly(span) => {
636 self.session.struct_span_err(span, "visibility must resolve to a module")
642 /// Lookup typo candidate in scope for a macro or import.
643 fn early_lookup_typo_candidate(
645 scope_set: ScopeSet<'a>,
646 parent_scope: &ParentScope<'a>,
648 filter_fn: &impl Fn(Res) -> bool,
649 ) -> Option<TypoSuggestion> {
650 let mut suggestions = Vec::new();
651 let ctxt = ident.span.ctxt();
652 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
654 Scope::DeriveHelpers(expn_id) => {
655 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
662 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
666 Scope::DeriveHelpersCompat => {
667 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
669 for derive in parent_scope.derives {
670 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
671 if let Ok((Some(ext), _)) = this.resolve_macro_path(
673 Some(MacroKind::Derive),
681 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
687 Scope::MacroRules(macro_rules_scope) => {
688 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
689 let res = macro_rules_binding.binding.res();
691 suggestions.push(TypoSuggestion::typo_from_res(
692 macro_rules_binding.ident.name,
698 Scope::CrateRoot => {
699 let root_ident = Ident::new(kw::PathRoot, ident.span);
700 let root_module = this.resolve_crate_root(root_ident);
701 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
703 Scope::Module(module, _) => {
704 this.add_module_candidates(module, &mut suggestions, filter_fn);
706 Scope::RegisteredAttrs => {
707 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
710 this.registered_attrs
712 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
716 Scope::MacroUsePrelude => {
717 suggestions.extend(this.macro_use_prelude.iter().filter_map(
719 let res = binding.res();
720 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
724 Scope::BuiltinAttrs => {
725 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
730 .map(|(name, ..)| TypoSuggestion::typo_from_res(*name, res)),
734 Scope::ExternPrelude => {
735 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
736 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
737 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
740 Scope::ToolPrelude => {
741 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
743 this.registered_tools
745 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
748 Scope::StdLibPrelude => {
749 if let Some(prelude) = this.prelude {
750 let mut tmp_suggestions = Vec::new();
751 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
755 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
759 Scope::BuiltinTypes => {
760 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
761 let res = Res::PrimTy(*prim_ty);
762 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
770 // Make sure error reporting is deterministic.
771 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
773 match find_best_match_for_name(
774 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
778 Some(found) if found != ident.name => {
779 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
785 fn lookup_import_candidates_from_module<FilterFn>(
788 namespace: Namespace,
789 parent_scope: &ParentScope<'a>,
790 start_module: Module<'a>,
793 ) -> Vec<ImportSuggestion>
795 FilterFn: Fn(Res) -> bool,
797 let mut candidates = Vec::new();
798 let mut seen_modules = FxHashSet::default();
799 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
800 let mut worklist_via_import = vec![];
802 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
803 None => worklist_via_import.pop(),
806 let in_module_is_extern = !in_module.def_id().is_local();
807 // We have to visit module children in deterministic order to avoid
808 // instabilities in reported imports (#43552).
809 in_module.for_each_child(self, |this, ident, ns, name_binding| {
810 // avoid non-importable candidates
811 if !name_binding.is_importable() {
815 let child_accessible =
816 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
818 // do not venture inside inaccessible items of other crates
819 if in_module_is_extern && !child_accessible {
823 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
825 // There is an assumption elsewhere that paths of variants are in the enum's
826 // declaration and not imported. With this assumption, the variant component is
827 // chopped and the rest of the path is assumed to be the enum's own path. For
828 // errors where a variant is used as the type instead of the enum, this causes
829 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
830 if via_import && name_binding.is_possibly_imported_variant() {
834 // #90113: Do not count an inaccessible reexported item as a candidate.
835 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
836 if this.is_accessible_from(binding.vis, parent_scope.module)
837 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
843 // collect results based on the filter function
844 // avoid suggesting anything from the same module in which we are resolving
845 if ident.name == lookup_ident.name
847 && !ptr::eq(in_module, parent_scope.module)
849 let res = name_binding.res();
852 let mut segms = path_segments.clone();
853 if lookup_ident.span.rust_2018() {
854 // crate-local absolute paths start with `crate::` in edition 2018
855 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
856 segms.insert(0, ast::PathSegment::from_ident(crate_name));
859 segms.push(ast::PathSegment::from_ident(ident));
860 let path = Path { span: name_binding.span, segments: segms, tokens: None };
861 let did = match res {
862 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
863 _ => res.opt_def_id(),
866 if child_accessible {
867 // Remove invisible match if exists
868 if let Some(idx) = candidates
870 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
872 candidates.remove(idx);
876 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
877 // See if we're recommending TryFrom, TryInto, or FromIterator and add
878 // a note about editions
879 let note = if let Some(did) = did {
880 let requires_note = !did.is_local()
881 && this.cstore().item_attrs(did, this.session).iter().any(
883 if attr.has_name(sym::rustc_diagnostic_item) {
884 [sym::TryInto, sym::TryFrom, sym::FromIterator]
886 .contains(&attr.value_str())
893 requires_note.then(|| {
895 "'{}' is included in the prelude starting in Edition 2021",
896 path_names_to_string(&path)
903 candidates.push(ImportSuggestion {
907 accessible: child_accessible,
914 // collect submodules to explore
915 if let Some(module) = name_binding.module() {
917 let mut path_segments = path_segments.clone();
918 path_segments.push(ast::PathSegment::from_ident(ident));
920 let is_extern_crate_that_also_appears_in_prelude =
921 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
923 if !is_extern_crate_that_also_appears_in_prelude {
924 // add the module to the lookup
925 if seen_modules.insert(module.def_id()) {
926 if via_import { &mut worklist_via_import } else { &mut worklist }
927 .push((module, path_segments, child_accessible));
934 // If only some candidates are accessible, take just them
935 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
936 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
942 /// When name resolution fails, this method can be used to look up candidate
943 /// entities with the expected name. It allows filtering them using the
944 /// supplied predicate (which should be used to only accept the types of
945 /// definitions expected, e.g., traits). The lookup spans across all crates.
947 /// N.B., the method does not look into imports, but this is not a problem,
948 /// since we report the definitions (thus, the de-aliased imports).
949 crate fn lookup_import_candidates<FilterFn>(
952 namespace: Namespace,
953 parent_scope: &ParentScope<'a>,
955 ) -> Vec<ImportSuggestion>
957 FilterFn: Fn(Res) -> bool,
959 let mut suggestions = self.lookup_import_candidates_from_module(
964 Ident::with_dummy_span(kw::Crate),
968 if lookup_ident.span.rust_2018() {
969 let extern_prelude_names = self.extern_prelude.clone();
970 for (ident, _) in extern_prelude_names.into_iter() {
971 if ident.span.from_expansion() {
972 // Idents are adjusted to the root context before being
973 // resolved in the extern prelude, so reporting this to the
974 // user is no help. This skips the injected
975 // `extern crate std` in the 2018 edition, which would
976 // otherwise cause duplicate suggestions.
979 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
980 let crate_root = self.expect_module(crate_id.as_def_id());
981 suggestions.extend(self.lookup_import_candidates_from_module(
996 crate fn unresolved_macro_suggestions(
998 err: &mut DiagnosticBuilder<'a>,
999 macro_kind: MacroKind,
1000 parent_scope: &ParentScope<'a>,
1003 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1004 let suggestion = self.early_lookup_typo_candidate(
1005 ScopeSet::Macro(macro_kind),
1010 self.add_typo_suggestion(err, suggestion, ident.span);
1012 let import_suggestions =
1013 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1019 &import_suggestions,
1024 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1025 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1026 err.span_note(ident.span, &msg);
1029 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1030 err.help("have you added the `#[macro_use]` on the module/import?");
1033 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1034 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1036 ScopeSet::All(ns, false),
1042 let desc = match binding.res() {
1043 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1044 "a function-like macro".to_string()
1046 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1047 format!("an attribute: `#[{}]`", ident)
1049 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1050 format!("a derive macro: `#[derive({})]`", ident)
1053 // Don't confuse the user with tool modules.
1056 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1057 "only a trait, without a derive macro".to_string()
1063 macro_kind.article(),
1064 macro_kind.descr_expected(),
1067 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1068 if !import.span.is_dummy() {
1071 &format!("`{}` is imported here, but it is {}", ident, desc),
1073 // Silence the 'unused import' warning we might get,
1074 // since this diagnostic already covers that import.
1075 self.record_use(ident, binding, false);
1079 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1085 crate fn add_typo_suggestion(
1087 err: &mut DiagnosticBuilder<'_>,
1088 suggestion: Option<TypoSuggestion>,
1091 let suggestion = match suggestion {
1092 None => return false,
1093 // We shouldn't suggest underscore.
1094 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1095 Some(suggestion) => suggestion,
1097 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1098 LOCAL_CRATE => self.opt_span(def_id),
1102 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1105 if let Some(def_span) = def_span {
1106 if span.overlaps(def_span) {
1107 // Don't suggest typo suggestion for itself like in the following:
1108 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1109 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1112 // | ----------- `X` defined here
1114 // LL | const Y: X = X("ö");
1115 // | -------------^^^^^^- similarly named constant `Y` defined here
1117 // help: use struct literal syntax instead
1119 // LL | const Y: X = X {};
1121 // help: a constant with a similar name exists
1123 // LL | const Y: X = Y("ö");
1127 let prefix = match suggestion.target {
1128 SuggestionTarget::SimilarlyNamed => "similarly named ",
1129 SuggestionTarget::SingleItem => "",
1133 self.session.source_map().guess_head_span(def_span),
1135 "{}{} `{}` defined here",
1137 suggestion.res.descr(),
1138 suggestion.candidate.as_str(),
1142 let msg = match suggestion.target {
1143 SuggestionTarget::SimilarlyNamed => format!(
1144 "{} {} with a similar name exists",
1145 suggestion.res.article(),
1146 suggestion.res.descr()
1148 SuggestionTarget::SingleItem => {
1149 format!("maybe you meant this {}", suggestion.res.descr())
1152 err.span_suggestion(
1155 suggestion.candidate.to_string(),
1156 Applicability::MaybeIncorrect,
1161 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1163 if b.span.is_dummy() {
1164 // These already contain the "built-in" prefix or look bad with it.
1166 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1167 let (built_in, from) = if from_prelude {
1168 ("", " from prelude")
1169 } else if b.is_extern_crate()
1171 && self.session.opts.externs.get(&ident.as_str()).is_some()
1173 ("", " passed with `--extern`")
1174 } else if add_built_in {
1180 let a = if built_in.is_empty() { res.article() } else { "a" };
1181 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1183 let introduced = if b.is_import() { "imported" } else { "defined" };
1184 format!("the {thing} {introduced} here", thing = res.descr())
1188 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1189 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1190 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1191 // We have to print the span-less alternative first, otherwise formatting looks bad.
1192 (b2, b1, misc2, misc1, true)
1194 (b1, b2, misc1, misc2, false)
1197 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1198 err.span_label(ident.span, "ambiguous name");
1199 err.note(&format!("ambiguous because of {}", kind.descr()));
1201 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1202 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1203 let note_msg = format!("`{ident}` could{also} refer to {what}");
1205 let thing = b.res().descr();
1206 let mut help_msgs = Vec::new();
1207 if b.is_glob_import()
1208 && (kind == AmbiguityKind::GlobVsGlob
1209 || kind == AmbiguityKind::GlobVsExpanded
1210 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1212 help_msgs.push(format!(
1213 "consider adding an explicit import of `{ident}` to disambiguate"
1216 if b.is_extern_crate() && ident.span.rust_2018() {
1217 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1219 if misc == AmbiguityErrorMisc::SuggestCrate {
1221 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1222 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1224 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1227 err.span_note(b.span, ¬e_msg);
1228 for (i, help_msg) in help_msgs.iter().enumerate() {
1229 let or = if i == 0 { "" } else { "or " };
1230 err.help(&format!("{}{}", or, help_msg));
1234 could_refer_to(b1, misc1, "");
1235 could_refer_to(b2, misc2, " also");
1239 /// If the binding refers to a tuple struct constructor with fields,
1240 /// returns the span of its fields.
1241 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1242 if let NameBindingKind::Res(
1243 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1247 let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1248 let fields = self.field_names.get(&def_id)?;
1249 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1254 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1255 let PrivacyError { ident, binding, .. } = *privacy_error;
1257 let res = binding.res();
1258 let ctor_fields_span = self.ctor_fields_span(binding);
1259 let plain_descr = res.descr().to_string();
1260 let nonimport_descr =
1261 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1262 let import_descr = nonimport_descr.clone() + " import";
1264 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1266 // Print the primary message.
1267 let descr = get_descr(binding);
1269 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1270 err.span_label(ident.span, &format!("private {}", descr));
1271 if let Some(span) = ctor_fields_span {
1272 err.span_label(span, "a constructor is private if any of the fields is private");
1275 // Print the whole import chain to make it easier to see what happens.
1276 let first_binding = binding;
1277 let mut next_binding = Some(binding);
1278 let mut next_ident = ident;
1279 while let Some(binding) = next_binding {
1280 let name = next_ident;
1281 next_binding = match binding.kind {
1282 _ if res == Res::Err => None,
1283 NameBindingKind::Import { binding, import, .. } => match import.kind {
1284 _ if binding.span.is_dummy() => None,
1285 ImportKind::Single { source, .. } => {
1286 next_ident = source;
1289 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1290 ImportKind::ExternCrate { .. } => None,
1295 let first = ptr::eq(binding, first_binding);
1297 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1298 and_refers_to = if first { "" } else { "...and refers to " },
1299 item = get_descr(binding),
1300 which = if first { "" } else { " which" },
1301 dots = if next_binding.is_some() { "..." } else { "" },
1303 let def_span = self.session.source_map().guess_head_span(binding.span);
1304 let mut note_span = MultiSpan::from_span(def_span);
1305 if !first && binding.vis == ty::Visibility::Public {
1306 note_span.push_span_label(def_span, "consider importing it directly".into());
1308 err.span_note(note_span, &msg);
1314 crate fn find_similarly_named_module_or_crate(
1317 current_module: &Module<'a>,
1318 ) -> Option<Symbol> {
1319 let mut candidates = self
1322 .map(|(ident, _)| ident.name)
1326 .filter(|(_, module)| {
1327 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1329 .map(|(_, module)| module.kind.name())
1332 .filter(|c| !c.to_string().is_empty())
1333 .collect::<Vec<_>>();
1336 match find_best_match_for_name(&candidates, ident, None) {
1337 Some(sugg) if sugg == ident => None,
1343 impl<'a, 'b> ImportResolver<'a, 'b> {
1344 /// Adds suggestions for a path that cannot be resolved.
1345 pub(crate) fn make_path_suggestion(
1348 mut path: Vec<Segment>,
1349 parent_scope: &ParentScope<'b>,
1350 ) -> Option<(Vec<Segment>, Vec<String>)> {
1351 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1353 match (path.get(0), path.get(1)) {
1354 // `{{root}}::ident::...` on both editions.
1355 // On 2015 `{{root}}` is usually added implicitly.
1356 (Some(fst), Some(snd))
1357 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1358 // `ident::...` on 2018.
1360 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1362 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1363 path.insert(0, Segment::from_ident(Ident::empty()));
1368 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1369 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1370 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1371 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1374 /// Suggest a missing `self::` if that resolves to an correct module.
1378 /// LL | use foo::Bar;
1379 /// | ^^^ did you mean `self::foo`?
1381 fn make_missing_self_suggestion(
1384 mut path: Vec<Segment>,
1385 parent_scope: &ParentScope<'b>,
1386 ) -> Option<(Vec<Segment>, Vec<String>)> {
1387 // Replace first ident with `self` and check if that is valid.
1388 path[0].ident.name = kw::SelfLower;
1389 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1390 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1391 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1394 /// Suggests a missing `crate::` if that resolves to an correct module.
1398 /// LL | use foo::Bar;
1399 /// | ^^^ did you mean `crate::foo`?
1401 fn make_missing_crate_suggestion(
1404 mut path: Vec<Segment>,
1405 parent_scope: &ParentScope<'b>,
1406 ) -> Option<(Vec<Segment>, Vec<String>)> {
1407 // Replace first ident with `crate` and check if that is valid.
1408 path[0].ident.name = kw::Crate;
1409 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1410 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1411 if let PathResult::Module(..) = result {
1415 "`use` statements changed in Rust 2018; read more at \
1416 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1426 /// Suggests a missing `super::` if that resolves to an correct module.
1430 /// LL | use foo::Bar;
1431 /// | ^^^ did you mean `super::foo`?
1433 fn make_missing_super_suggestion(
1436 mut path: Vec<Segment>,
1437 parent_scope: &ParentScope<'b>,
1438 ) -> Option<(Vec<Segment>, Vec<String>)> {
1439 // Replace first ident with `crate` and check if that is valid.
1440 path[0].ident.name = kw::Super;
1441 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1442 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1443 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1446 /// Suggests a missing external crate name if that resolves to an correct module.
1450 /// LL | use foobar::Baz;
1451 /// | ^^^^^^ did you mean `baz::foobar`?
1454 /// Used when importing a submodule of an external crate but missing that crate's
1455 /// name as the first part of path.
1456 fn make_external_crate_suggestion(
1459 mut path: Vec<Segment>,
1460 parent_scope: &ParentScope<'b>,
1461 ) -> Option<(Vec<Segment>, Vec<String>)> {
1462 if path[1].ident.span.rust_2015() {
1466 // Sort extern crate names in reverse order to get
1467 // 1) some consistent ordering for emitted diagnostics, and
1468 // 2) `std` suggestions before `core` suggestions.
1469 let mut extern_crate_names =
1470 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1471 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1473 for name in extern_crate_names.into_iter() {
1474 // Replace first ident with a crate name and check if that is valid.
1475 path[0].ident.name = name;
1476 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1478 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1481 if let PathResult::Module(..) = result {
1482 return Some((path, Vec::new()));
1489 /// Suggests importing a macro from the root of the crate rather than a module within
1493 /// help: a macro with this name exists at the root of the crate
1495 /// LL | use issue_59764::makro;
1496 /// | ^^^^^^^^^^^^^^^^^^
1498 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1499 /// at the root of the crate instead of the module where it is defined
1501 pub(crate) fn check_for_module_export_macro(
1503 import: &'b Import<'b>,
1504 module: ModuleOrUniformRoot<'b>,
1506 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1507 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
1511 while let Some(parent) = crate_module.parent {
1512 crate_module = parent;
1515 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1516 // Don't make a suggestion if the import was already from the root of the
1521 let resolutions = self.r.resolutions(crate_module).borrow();
1522 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1523 let binding = resolution.borrow().binding()?;
1524 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1525 let module_name = crate_module.kind.name().unwrap();
1526 let import_snippet = match import.kind {
1527 ImportKind::Single { source, target, .. } if source != target => {
1528 format!("{} as {}", source, target)
1530 _ => format!("{}", ident),
1533 let mut corrections: Vec<(Span, String)> = Vec::new();
1534 if !import.is_nested() {
1535 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1536 // intermediate segments.
1537 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1539 // Find the binding span (and any trailing commas and spaces).
1540 // ie. `use a::b::{c, d, e};`
1542 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1548 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1549 found_closing_brace, binding_span
1552 let mut removal_span = binding_span;
1553 if found_closing_brace {
1554 // If the binding span ended with a closing brace, as in the below example:
1555 // ie. `use a::b::{c, d};`
1557 // Then expand the span of characters to remove to include the previous
1558 // binding's trailing comma.
1559 // ie. `use a::b::{c, d};`
1561 if let Some(previous_span) =
1562 extend_span_to_previous_binding(self.r.session, binding_span)
1564 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1565 removal_span = removal_span.with_lo(previous_span.lo());
1568 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1570 // Remove the `removal_span`.
1571 corrections.push((removal_span, "".to_string()));
1573 // Find the span after the crate name and if it has nested imports immediatately
1574 // after the crate name already.
1575 // ie. `use a::b::{c, d};`
1577 // or `use a::{b, c, d}};`
1579 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1585 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1586 has_nested, after_crate_name
1589 let source_map = self.r.session.source_map();
1591 // Add the import to the start, with a `{` if required.
1592 let start_point = source_map.start_point(after_crate_name);
1593 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1597 // In this case, `start_snippet` must equal '{'.
1598 format!("{}{}, ", start_snippet, import_snippet)
1600 // In this case, add a `{`, then the moved import, then whatever
1601 // was there before.
1602 format!("{{{}, {}", import_snippet, start_snippet)
1607 // Add a `};` to the end if nested, matching the `{` added at the start.
1609 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1613 let suggestion = Some((
1615 String::from("a macro with this name exists at the root of the crate"),
1616 Applicability::MaybeIncorrect,
1619 "this could be because a macro annotated with `#[macro_export]` will be exported \
1620 at the root of the crate instead of the module where it is defined"
1623 Some((suggestion, note))
1630 /// Given a `binding_span` of a binding within a use statement:
1633 /// use foo::{a, b, c};
1637 /// then return the span until the next binding or the end of the statement:
1640 /// use foo::{a, b, c};
1643 pub(crate) fn find_span_of_binding_until_next_binding(
1648 let source_map = sess.source_map();
1650 // Find the span of everything after the binding.
1651 // ie. `a, e};` or `a};`
1652 let binding_until_end = binding_span.with_hi(use_span.hi());
1654 // Find everything after the binding but not including the binding.
1655 // ie. `, e};` or `};`
1656 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1658 // Keep characters in the span until we encounter something that isn't a comma or
1662 // Also note whether a closing brace character was encountered. If there
1663 // was, then later go backwards to remove any trailing commas that are left.
1664 let mut found_closing_brace = false;
1665 let after_binding_until_next_binding =
1666 source_map.span_take_while(after_binding_until_end, |&ch| {
1668 found_closing_brace = true;
1670 ch == ' ' || ch == ','
1673 // Combine the two spans.
1674 // ie. `a, ` or `a`.
1676 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1677 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1679 (found_closing_brace, span)
1682 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1686 /// use foo::a::{a, b, c};
1687 /// ^^--- binding span
1691 /// use foo::{a, b, c};
1692 /// --- binding span
1694 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1695 let source_map = sess.source_map();
1697 // `prev_source` will contain all of the source that came before the span.
1698 // Then split based on a command and take the first (ie. closest to our span)
1699 // snippet. In the example, this is a space.
1700 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1702 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1703 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1704 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1708 let prev_comma = prev_comma.first().unwrap();
1709 let prev_starting_brace = prev_starting_brace.first().unwrap();
1711 // If the amount of source code before the comma is greater than
1712 // the amount of source code before the starting brace then we've only
1713 // got one item in the nested item (eg. `issue_52891::{self}`).
1714 if prev_comma.len() > prev_starting_brace.len() {
1718 Some(binding_span.with_lo(BytePos(
1719 // Take away the number of bytes for the characters we've found and an
1720 // extra for the comma.
1721 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1725 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1726 /// it is a nested use tree.
1729 /// use foo::a::{b, c};
1730 /// ^^^^^^^^^^ // false
1732 /// use foo::{a, b, c};
1733 /// ^^^^^^^^^^ // true
1735 /// use foo::{a, b::{c, d}};
1736 /// ^^^^^^^^^^^^^^^ // true
1738 fn find_span_immediately_after_crate_name(
1740 module_name: Symbol,
1744 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1745 module_name, use_span
1747 let source_map = sess.source_map();
1749 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1750 let mut num_colons = 0;
1751 // Find second colon.. `use issue_59764:`
1752 let until_second_colon = source_map.span_take_while(use_span, |c| {
1756 !matches!(c, ':' if num_colons == 2)
1758 // Find everything after the second colon.. `foo::{baz, makro};`
1759 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1761 let mut found_a_non_whitespace_character = false;
1762 // Find the first non-whitespace character in `from_second_colon`.. `f`
1763 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1764 if found_a_non_whitespace_character {
1767 if !c.is_whitespace() {
1768 found_a_non_whitespace_character = true;
1773 // Find the first `{` in from_second_colon.. `foo::{`
1774 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1776 (next_left_bracket == after_second_colon, from_second_colon)
1779 /// When an entity with a given name is not available in scope, we search for
1780 /// entities with that name in all crates. This method allows outputting the
1781 /// results of this search in a programmer-friendly way
1782 crate fn show_candidates(
1783 definitions: &rustc_hir::definitions::Definitions,
1785 err: &mut DiagnosticBuilder<'_>,
1786 // This is `None` if all placement locations are inside expansions
1787 use_placement_span: Option<Span>,
1788 candidates: &[ImportSuggestion],
1792 if candidates.is_empty() {
1796 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1798 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1801 candidates.iter().for_each(|c| {
1802 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1803 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
1806 // we want consistent results across executions, but candidates are produced
1807 // by iterating through a hash map, so make sure they are ordered:
1808 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1809 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1810 let core_path_strings =
1811 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1812 path_strings.extend(core_path_strings);
1813 path_strings.dedup_by(|a, b| a.0 == b.0);
1816 if !accessible_path_strings.is_empty() {
1817 let (determiner, kind) = if accessible_path_strings.len() == 1 {
1818 ("this", accessible_path_strings[0].1)
1820 ("one of these", "items")
1823 let instead = if instead { " instead" } else { "" };
1824 let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1827 for note in accessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1831 if let Some(span) = use_placement_span {
1832 for candidate in &mut accessible_path_strings {
1833 // produce an additional newline to separate the new use statement
1834 // from the directly following item.
1835 let additional_newline = if found_use { "" } else { "\n" };
1836 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1839 err.span_suggestions(
1842 accessible_path_strings.into_iter().map(|a| a.0),
1843 Applicability::Unspecified,
1848 for candidate in accessible_path_strings {
1850 msg.push_str(&candidate.0);
1856 assert!(!inaccessible_path_strings.is_empty());
1858 if inaccessible_path_strings.len() == 1 {
1859 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
1860 let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1862 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1863 let span = definitions.def_span(local_def_id);
1864 let span = session.source_map().guess_head_span(span);
1865 let mut multi_span = MultiSpan::from_span(span);
1866 multi_span.push_span_label(span, "not accessible".to_string());
1867 err.span_note(multi_span, &msg);
1871 if let Some(note) = (*note).as_deref() {
1875 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
1876 let descr = if inaccessible_path_strings
1879 .all(|(_, descr, _, _)| descr == descr_first)
1881 descr_first.to_string()
1886 let mut msg = format!("these {}s exist but are inaccessible", descr);
1887 let mut has_colon = false;
1889 let mut spans = Vec::new();
1890 for (name, _, def_id, _) in &inaccessible_path_strings {
1891 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1892 let span = definitions.def_span(local_def_id);
1893 let span = session.source_map().guess_head_span(span);
1894 spans.push((name, span));
1905 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1906 for (name, span) in spans {
1907 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1910 for note in inaccessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() {
1914 err.span_note(multi_span, &msg);