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,
71 /// Adjust the impl span so that just the `impl` keyword is taken by removing
72 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
73 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
75 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
76 /// parser. If you need to use this function or something similar, please consider updating the
77 /// `source_map` functions and this function to something more robust.
78 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
79 let impl_span = sm.span_until_char(impl_span, '<');
80 sm.span_until_whitespace(impl_span)
83 impl<'a> Resolver<'a> {
84 crate fn add_module_candidates(
87 names: &mut Vec<TypoSuggestion>,
88 filter_fn: &impl Fn(Res) -> bool,
90 for (key, resolution) in self.resolutions(module).borrow().iter() {
91 if let Some(binding) = resolution.borrow().binding {
92 let res = binding.res();
94 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
100 /// Combines an error with provided span and emits it.
102 /// This takes the error provided, combines it with the span and any additional spans inside the
103 /// error and emits it.
104 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
105 self.into_struct_error(span, resolution_error).emit();
108 crate fn into_struct_error(
111 resolution_error: ResolutionError<'_>,
112 ) -> DiagnosticBuilder<'_> {
113 match resolution_error {
114 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
115 let mut err = struct_span_err!(
119 "can't use generic parameters from outer function",
121 err.span_label(span, "use of generic parameter from outer function".to_string());
123 let sm = self.session.source_map();
125 Res::SelfTy(maybe_trait_defid, maybe_impl_defid) => {
126 if let Some(impl_span) =
127 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
130 reduce_impl_span_to_impl_keyword(sm, impl_span),
131 "`Self` type implicitly declared here, by this `impl`",
134 match (maybe_trait_defid, maybe_impl_defid) {
136 err.span_label(span, "can't use `Self` here");
139 err.span_label(span, "use a type here instead");
141 (None, None) => bug!("`impl` without trait nor type?"),
145 Res::Def(DefKind::TyParam, def_id) => {
146 if let Some(span) = self.opt_span(def_id) {
147 err.span_label(span, "type parameter from outer function");
150 Res::Def(DefKind::ConstParam, def_id) => {
151 if let Some(span) = self.opt_span(def_id) {
152 err.span_label(span, "const parameter from outer function");
157 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
158 DefKind::TyParam or DefKind::ConstParam"
163 if has_generic_params == HasGenericParams::Yes {
164 // Try to retrieve the span of the function signature and generate a new
165 // message with a local type or const parameter.
166 let sugg_msg = "try using a local generic parameter instead";
167 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
168 // Suggest the modification to the user
173 Applicability::MachineApplicable,
175 } else if let Some(sp) = sm.generate_fn_name_span(span) {
178 "try adding a local generic parameter in this method instead"
182 err.help("try using a local generic parameter instead");
188 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
189 let mut err = struct_span_err!(
193 "the name `{}` is already used for a generic \
194 parameter in this item's generic parameters",
197 err.span_label(span, "already used");
198 err.span_label(first_use_span, format!("first use of `{}`", name));
201 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
202 let mut err = struct_span_err!(
206 "method `{}` is not a member of trait `{}`",
210 err.span_label(span, format!("not a member of trait `{}`", trait_));
211 if let Some(candidate) = candidate {
214 "there is an associated function with a similar name",
215 candidate.to_ident_string(),
216 Applicability::MaybeIncorrect,
221 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
222 let mut err = struct_span_err!(
226 "type `{}` is not a member of trait `{}`",
230 err.span_label(span, format!("not a member of trait `{}`", trait_));
231 if let Some(candidate) = candidate {
234 "there is an associated type with a similar name",
235 candidate.to_ident_string(),
236 Applicability::MaybeIncorrect,
241 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
242 let mut err = struct_span_err!(
246 "const `{}` is not a member of trait `{}`",
250 err.span_label(span, format!("not a member of trait `{}`", trait_));
251 if let Some(candidate) = candidate {
254 "there is an associated constant with a similar name",
255 candidate.to_ident_string(),
256 Applicability::MaybeIncorrect,
261 ResolutionError::VariableNotBoundInPattern(binding_error) => {
262 let BindingError { name, target, origin, could_be_path } = binding_error;
264 let target_sp = target.iter().copied().collect::<Vec<_>>();
265 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
267 let msp = MultiSpan::from_spans(target_sp.clone());
268 let mut err = struct_span_err!(
272 "variable `{}` is not bound in all patterns",
275 for sp in target_sp {
276 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
278 for sp in origin_sp {
279 err.span_label(sp, "variable not in all patterns");
282 let help_msg = format!(
283 "if you meant to match on a variant or a `const` item, consider \
284 making the path in the pattern qualified: `?::{}`",
287 err.span_help(span, &help_msg);
291 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
292 let mut err = struct_span_err!(
296 "variable `{}` is bound inconsistently across alternatives separated by `|`",
299 err.span_label(span, "bound in different ways");
300 err.span_label(first_binding_span, "first binding");
303 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
304 let mut err = struct_span_err!(
308 "identifier `{}` is bound more than once in this parameter list",
311 err.span_label(span, "used as parameter more than once");
314 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
315 let mut err = struct_span_err!(
319 "identifier `{}` is bound more than once in the same pattern",
322 err.span_label(span, "used in a pattern more than once");
325 ResolutionError::UndeclaredLabel { name, suggestion } => {
326 let mut err = struct_span_err!(
330 "use of undeclared label `{}`",
334 err.span_label(span, format!("undeclared label `{}`", name));
337 // A reachable label with a similar name exists.
338 Some((ident, true)) => {
339 err.span_label(ident.span, "a label with a similar name is reachable");
342 "try using similarly named label",
343 ident.name.to_string(),
344 Applicability::MaybeIncorrect,
347 // An unreachable label with a similar name exists.
348 Some((ident, false)) => {
351 "a label with a similar name exists but is unreachable",
354 // No similarly-named labels exist.
360 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
361 let mut err = struct_span_err!(
366 "`self` imports are only allowed within a { } list"
369 // None of the suggestions below would help with a case like `use self`.
371 // use foo::bar::self -> foo::bar
372 // use foo::bar::self as abc -> foo::bar as abc
375 "consider importing the module directly",
377 Applicability::MachineApplicable,
380 // use foo::bar::self -> foo::bar::{self}
381 // use foo::bar::self as abc -> foo::bar::{self as abc}
383 (span_with_rename.shrink_to_lo(), "{".to_string()),
384 (span_with_rename.shrink_to_hi(), "}".to_string()),
386 err.multipart_suggestion(
387 "alternatively, use the multi-path `use` syntax to import `self`",
389 Applicability::MachineApplicable,
394 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
395 let mut err = struct_span_err!(
399 "`self` import can only appear once in an import list"
401 err.span_label(span, "can only appear once in an import list");
404 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
405 let mut err = struct_span_err!(
409 "`self` import can only appear in an import list with \
412 err.span_label(span, "can only appear in an import list with a non-empty prefix");
415 ResolutionError::FailedToResolve { label, suggestion } => {
417 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
418 err.span_label(span, label);
420 if let Some((suggestions, msg, applicability)) = suggestion {
421 err.multipart_suggestion(&msg, suggestions, applicability);
426 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
427 let mut err = struct_span_err!(
432 "can't capture dynamic environment in a fn item"
434 err.help("use the `|| { ... }` closure form instead");
437 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
438 let mut err = struct_span_err!(
442 "attempt to use a non-constant value in a constant"
445 // ^^^ given this Span
446 // ------- get this Span to have an applicable suggestion
448 self.session.source_map().span_extend_to_prev_str(ident.span, current, true);
450 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
452 let sp = sp.with_lo(BytePos(sp.lo().0 - current.len() as u32));
455 &format!("consider using `{}` instead of `{}`", sugg, current),
456 format!("{} {}", sugg, ident),
457 Applicability::MaybeIncorrect,
459 err.span_label(span, "non-constant value");
463 ResolutionError::BindingShadowsSomethingUnacceptable {
464 shadowing_binding_descr,
468 shadowed_binding_descr,
469 shadowed_binding_span,
471 let mut err = struct_span_err!(
475 "{}s cannot shadow {}s",
476 shadowing_binding_descr,
477 shadowed_binding_descr,
481 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
484 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
485 err.span_label(shadowed_binding_span, msg);
488 ResolutionError::ForwardDeclaredGenericParam => {
489 let mut err = struct_span_err!(
493 "generic parameters with a default cannot use \
494 forward declared identifiers"
498 "defaulted generic parameters cannot be forward declared".to_string(),
502 ResolutionError::ParamInTyOfConstParam(name) => {
503 let mut err = struct_span_err!(
507 "the type of const parameters must not depend on other generic parameters"
511 format!("the type must not depend on the parameter `{}`", name),
515 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
516 let mut err = self.session.struct_span_err(
518 "generic parameters may not be used in const operations",
520 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
523 err.note("type parameters may not be used in const expressions");
526 "const parameters may only be used as standalone arguments, i.e. `{}`",
531 if self.session.is_nightly_build() {
533 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
539 ResolutionError::SelfInGenericParamDefault => {
540 let mut err = struct_span_err!(
544 "generic parameters cannot use `Self` in their defaults"
546 err.span_label(span, "`Self` in generic parameter default".to_string());
549 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
550 let mut err = struct_span_err!(
554 "use of unreachable label `{}`",
558 err.span_label(definition_span, "unreachable label defined here");
559 err.span_label(span, format!("unreachable label `{}`", name));
561 "labels are unreachable through functions, closures, async blocks and modules",
565 // A reachable label with a similar name exists.
566 Some((ident, true)) => {
567 err.span_label(ident.span, "a label with a similar name is reachable");
570 "try using similarly named label",
571 ident.name.to_string(),
572 Applicability::MaybeIncorrect,
575 // An unreachable label with a similar name exists.
576 Some((ident, false)) => {
579 "a label with a similar name exists but is also unreachable",
582 // No similarly-named labels exist.
591 crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
592 match vis_resolution_error {
593 VisResolutionError::Relative2018(span, path) => {
594 let mut err = self.session.struct_span_err(
596 "relative paths are not supported in visibilities on 2018 edition",
601 format!("crate::{}", pprust::path_to_string(&path)),
602 Applicability::MaybeIncorrect,
606 VisResolutionError::AncestorOnly(span) => struct_span_err!(
610 "visibilities can only be restricted to ancestor modules"
612 VisResolutionError::FailedToResolve(span, label, suggestion) => {
613 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
615 VisResolutionError::ExpectedFound(span, path_str, res) => {
616 let mut err = struct_span_err!(
620 "expected module, found {} `{}`",
624 err.span_label(span, "not a module");
627 VisResolutionError::Indeterminate(span) => struct_span_err!(
631 "cannot determine resolution for the visibility"
633 VisResolutionError::ModuleOnly(span) => {
634 self.session.struct_span_err(span, "visibility must resolve to a module")
640 /// Lookup typo candidate in scope for a macro or import.
641 fn early_lookup_typo_candidate(
643 scope_set: ScopeSet<'a>,
644 parent_scope: &ParentScope<'a>,
646 filter_fn: &impl Fn(Res) -> bool,
647 ) -> Option<TypoSuggestion> {
648 let mut suggestions = Vec::new();
649 let ctxt = ident.span.ctxt();
650 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
652 Scope::DeriveHelpers(expn_id) => {
653 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
660 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
664 Scope::DeriveHelpersCompat => {
665 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
667 for derive in parent_scope.derives {
668 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
669 if let Ok((Some(ext), _)) = this.resolve_macro_path(
671 Some(MacroKind::Derive),
679 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
685 Scope::MacroRules(macro_rules_scope) => {
686 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
687 let res = macro_rules_binding.binding.res();
689 suggestions.push(TypoSuggestion::typo_from_res(
690 macro_rules_binding.ident.name,
696 Scope::CrateRoot => {
697 let root_ident = Ident::new(kw::PathRoot, ident.span);
698 let root_module = this.resolve_crate_root(root_ident);
699 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
701 Scope::Module(module, _) => {
702 this.add_module_candidates(module, &mut suggestions, filter_fn);
704 Scope::RegisteredAttrs => {
705 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
708 this.registered_attrs
710 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
714 Scope::MacroUsePrelude => {
715 suggestions.extend(this.macro_use_prelude.iter().filter_map(
717 let res = binding.res();
718 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
722 Scope::BuiltinAttrs => {
723 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
728 .map(|(name, ..)| TypoSuggestion::typo_from_res(*name, res)),
732 Scope::ExternPrelude => {
733 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
734 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
735 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
738 Scope::ToolPrelude => {
739 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
741 this.registered_tools
743 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
746 Scope::StdLibPrelude => {
747 if let Some(prelude) = this.prelude {
748 let mut tmp_suggestions = Vec::new();
749 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
753 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
757 Scope::BuiltinTypes => {
758 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
759 let res = Res::PrimTy(*prim_ty);
760 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
768 // Make sure error reporting is deterministic.
769 suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
771 match find_best_match_for_name(
772 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
776 Some(found) if found != ident.name => {
777 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
783 fn lookup_import_candidates_from_module<FilterFn>(
786 namespace: Namespace,
787 parent_scope: &ParentScope<'a>,
788 start_module: Module<'a>,
791 ) -> Vec<ImportSuggestion>
793 FilterFn: Fn(Res) -> bool,
795 let mut candidates = Vec::new();
796 let mut seen_modules = FxHashSet::default();
797 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
798 let mut worklist_via_import = vec![];
800 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
801 None => worklist_via_import.pop(),
804 let in_module_is_extern = !in_module.def_id().is_local();
805 // We have to visit module children in deterministic order to avoid
806 // instabilities in reported imports (#43552).
807 in_module.for_each_child(self, |this, ident, ns, name_binding| {
808 // avoid non-importable candidates
809 if !name_binding.is_importable() {
813 let child_accessible =
814 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
816 // do not venture inside inaccessible items of other crates
817 if in_module_is_extern && !child_accessible {
821 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
823 // There is an assumption elsewhere that paths of variants are in the enum's
824 // declaration and not imported. With this assumption, the variant component is
825 // chopped and the rest of the path is assumed to be the enum's own path. For
826 // errors where a variant is used as the type instead of the enum, this causes
827 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
828 if via_import && name_binding.is_possibly_imported_variant() {
832 // collect results based on the filter function
833 // avoid suggesting anything from the same module in which we are resolving
834 if ident.name == lookup_ident.name
836 && !ptr::eq(in_module, parent_scope.module)
838 let res = name_binding.res();
841 let mut segms = path_segments.clone();
842 if lookup_ident.span.rust_2018() {
843 // crate-local absolute paths start with `crate::` in edition 2018
844 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
845 segms.insert(0, ast::PathSegment::from_ident(crate_name));
848 segms.push(ast::PathSegment::from_ident(ident));
849 let path = Path { span: name_binding.span, segments: segms, tokens: None };
850 let did = match res {
851 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
852 _ => res.opt_def_id(),
855 if child_accessible {
856 // Remove invisible match if exists
857 if let Some(idx) = candidates
859 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
861 candidates.remove(idx);
865 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
866 candidates.push(ImportSuggestion {
870 accessible: child_accessible,
876 // collect submodules to explore
877 if let Some(module) = name_binding.module() {
879 let mut path_segments = path_segments.clone();
880 path_segments.push(ast::PathSegment::from_ident(ident));
882 let is_extern_crate_that_also_appears_in_prelude =
883 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
885 if !is_extern_crate_that_also_appears_in_prelude {
886 // add the module to the lookup
887 if seen_modules.insert(module.def_id()) {
888 if via_import { &mut worklist_via_import } else { &mut worklist }
889 .push((module, path_segments, child_accessible));
896 // If only some candidates are accessible, take just them
897 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
898 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
904 /// When name resolution fails, this method can be used to look up candidate
905 /// entities with the expected name. It allows filtering them using the
906 /// supplied predicate (which should be used to only accept the types of
907 /// definitions expected, e.g., traits). The lookup spans across all crates.
909 /// N.B., the method does not look into imports, but this is not a problem,
910 /// since we report the definitions (thus, the de-aliased imports).
911 crate fn lookup_import_candidates<FilterFn>(
914 namespace: Namespace,
915 parent_scope: &ParentScope<'a>,
917 ) -> Vec<ImportSuggestion>
919 FilterFn: Fn(Res) -> bool,
921 let mut suggestions = self.lookup_import_candidates_from_module(
926 Ident::with_dummy_span(kw::Crate),
930 if lookup_ident.span.rust_2018() {
931 let extern_prelude_names = self.extern_prelude.clone();
932 for (ident, _) in extern_prelude_names.into_iter() {
933 if ident.span.from_expansion() {
934 // Idents are adjusted to the root context before being
935 // resolved in the extern prelude, so reporting this to the
936 // user is no help. This skips the injected
937 // `extern crate std` in the 2018 edition, which would
938 // otherwise cause duplicate suggestions.
941 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
942 let crate_root = self.expect_module(crate_id.as_def_id());
943 suggestions.extend(self.lookup_import_candidates_from_module(
958 crate fn unresolved_macro_suggestions(
960 err: &mut DiagnosticBuilder<'a>,
961 macro_kind: MacroKind,
962 parent_scope: &ParentScope<'a>,
965 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
966 let suggestion = self.early_lookup_typo_candidate(
967 ScopeSet::Macro(macro_kind),
972 self.add_typo_suggestion(err, suggestion, ident.span);
974 let import_suggestions =
975 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
986 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
987 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
988 err.span_note(ident.span, &msg);
991 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
992 err.help("have you added the `#[macro_use]` on the module/import?");
995 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
996 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
998 ScopeSet::All(ns, false),
1004 let desc = match binding.res() {
1005 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1006 "a function-like macro".to_string()
1008 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1009 format!("an attribute: `#[{}]`", ident)
1011 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1012 format!("a derive macro: `#[derive({})]`", ident)
1015 // Don't confuse the user with tool modules.
1018 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1019 "only a trait, without a derive macro".to_string()
1025 macro_kind.article(),
1026 macro_kind.descr_expected(),
1029 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1030 if !import.span.is_dummy() {
1033 &format!("`{}` is imported here, but it is {}", ident, desc),
1035 // Silence the 'unused import' warning we might get,
1036 // since this diagnostic already covers that import.
1037 self.record_use(ident, binding, false);
1041 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1047 crate fn add_typo_suggestion(
1049 err: &mut DiagnosticBuilder<'_>,
1050 suggestion: Option<TypoSuggestion>,
1053 let suggestion = match suggestion {
1054 None => return false,
1055 // We shouldn't suggest underscore.
1056 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1057 Some(suggestion) => suggestion,
1059 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1060 LOCAL_CRATE => self.opt_span(def_id),
1064 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1067 if let Some(def_span) = def_span {
1068 if span.overlaps(def_span) {
1069 // Don't suggest typo suggestion for itself like in the following:
1070 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1071 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1074 // | ----------- `X` defined here
1076 // LL | const Y: X = X("ö");
1077 // | -------------^^^^^^- similarly named constant `Y` defined here
1079 // help: use struct literal syntax instead
1081 // LL | const Y: X = X {};
1083 // help: a constant with a similar name exists
1085 // LL | const Y: X = Y("ö");
1089 let prefix = match suggestion.target {
1090 SuggestionTarget::SimilarlyNamed => "similarly named ",
1091 SuggestionTarget::SingleItem => "",
1095 self.session.source_map().guess_head_span(def_span),
1097 "{}{} `{}` defined here",
1099 suggestion.res.descr(),
1100 suggestion.candidate.as_str(),
1104 let msg = match suggestion.target {
1105 SuggestionTarget::SimilarlyNamed => format!(
1106 "{} {} with a similar name exists",
1107 suggestion.res.article(),
1108 suggestion.res.descr()
1110 SuggestionTarget::SingleItem => {
1111 format!("maybe you meant this {}", suggestion.res.descr())
1114 err.span_suggestion(
1117 suggestion.candidate.to_string(),
1118 Applicability::MaybeIncorrect,
1123 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1125 if b.span.is_dummy() {
1126 // These already contain the "built-in" prefix or look bad with it.
1128 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1129 let (built_in, from) = if from_prelude {
1130 ("", " from prelude")
1131 } else if b.is_extern_crate()
1133 && self.session.opts.externs.get(&ident.as_str()).is_some()
1135 ("", " passed with `--extern`")
1136 } else if add_built_in {
1142 let a = if built_in.is_empty() { res.article() } else { "a" };
1143 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1145 let introduced = if b.is_import() { "imported" } else { "defined" };
1146 format!("the {thing} {introduced} here", thing = res.descr())
1150 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1151 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1152 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1153 // We have to print the span-less alternative first, otherwise formatting looks bad.
1154 (b2, b1, misc2, misc1, true)
1156 (b1, b2, misc1, misc2, false)
1159 let mut err = struct_span_err!(
1163 "`{ident}` is ambiguous ({why})",
1166 err.span_label(ident.span, "ambiguous name");
1168 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1169 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1170 let note_msg = format!("`{ident}` could{also} refer to {what}");
1172 let thing = b.res().descr();
1173 let mut help_msgs = Vec::new();
1174 if b.is_glob_import()
1175 && (kind == AmbiguityKind::GlobVsGlob
1176 || kind == AmbiguityKind::GlobVsExpanded
1177 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1179 help_msgs.push(format!(
1180 "consider adding an explicit import of `{ident}` to disambiguate"
1183 if b.is_extern_crate() && ident.span.rust_2018() {
1184 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1186 if misc == AmbiguityErrorMisc::SuggestCrate {
1188 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1189 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1191 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1194 err.span_note(b.span, ¬e_msg);
1195 for (i, help_msg) in help_msgs.iter().enumerate() {
1196 let or = if i == 0 { "" } else { "or " };
1197 err.help(&format!("{}{}", or, help_msg));
1201 could_refer_to(b1, misc1, "");
1202 could_refer_to(b2, misc2, " also");
1206 /// If the binding refers to a tuple struct constructor with fields,
1207 /// returns the span of its fields.
1208 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1209 if let NameBindingKind::Res(
1210 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1214 let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1215 let fields = self.field_names.get(&def_id)?;
1216 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1221 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1222 let PrivacyError { ident, binding, .. } = *privacy_error;
1224 let res = binding.res();
1225 let ctor_fields_span = self.ctor_fields_span(binding);
1226 let plain_descr = res.descr().to_string();
1227 let nonimport_descr =
1228 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1229 let import_descr = nonimport_descr.clone() + " import";
1231 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1233 // Print the primary message.
1234 let descr = get_descr(binding);
1236 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1237 err.span_label(ident.span, &format!("private {}", descr));
1238 if let Some(span) = ctor_fields_span {
1239 err.span_label(span, "a constructor is private if any of the fields is private");
1242 // Print the whole import chain to make it easier to see what happens.
1243 let first_binding = binding;
1244 let mut next_binding = Some(binding);
1245 let mut next_ident = ident;
1246 while let Some(binding) = next_binding {
1247 let name = next_ident;
1248 next_binding = match binding.kind {
1249 _ if res == Res::Err => None,
1250 NameBindingKind::Import { binding, import, .. } => match import.kind {
1251 _ if binding.span.is_dummy() => None,
1252 ImportKind::Single { source, .. } => {
1253 next_ident = source;
1256 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1257 ImportKind::ExternCrate { .. } => None,
1262 let first = ptr::eq(binding, first_binding);
1264 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1265 and_refers_to = if first { "" } else { "...and refers to " },
1266 item = get_descr(binding),
1267 which = if first { "" } else { " which" },
1268 dots = if next_binding.is_some() { "..." } else { "" },
1270 let def_span = self.session.source_map().guess_head_span(binding.span);
1271 let mut note_span = MultiSpan::from_span(def_span);
1272 if !first && binding.vis == ty::Visibility::Public {
1273 note_span.push_span_label(def_span, "consider importing it directly".into());
1275 err.span_note(note_span, &msg);
1281 crate fn find_similarly_named_module_or_crate(
1284 current_module: &Module<'a>,
1285 ) -> Option<Symbol> {
1286 let mut candidates = self
1289 .map(|(ident, _)| ident.name)
1293 .filter(|(_, module)| {
1294 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1296 .map(|(_, module)| module.kind.name())
1299 .filter(|c| !c.to_string().is_empty())
1300 .collect::<Vec<_>>();
1303 match find_best_match_for_name(&candidates, ident, None) {
1304 Some(sugg) if sugg == ident => None,
1310 impl<'a, 'b> ImportResolver<'a, 'b> {
1311 /// Adds suggestions for a path that cannot be resolved.
1312 pub(crate) fn make_path_suggestion(
1315 mut path: Vec<Segment>,
1316 parent_scope: &ParentScope<'b>,
1317 ) -> Option<(Vec<Segment>, Vec<String>)> {
1318 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1320 match (path.get(0), path.get(1)) {
1321 // `{{root}}::ident::...` on both editions.
1322 // On 2015 `{{root}}` is usually added implicitly.
1323 (Some(fst), Some(snd))
1324 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1325 // `ident::...` on 2018.
1327 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1329 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1330 path.insert(0, Segment::from_ident(Ident::empty()));
1335 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1336 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1337 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1338 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1341 /// Suggest a missing `self::` if that resolves to an correct module.
1345 /// LL | use foo::Bar;
1346 /// | ^^^ did you mean `self::foo`?
1348 fn make_missing_self_suggestion(
1351 mut path: Vec<Segment>,
1352 parent_scope: &ParentScope<'b>,
1353 ) -> Option<(Vec<Segment>, Vec<String>)> {
1354 // Replace first ident with `self` and check if that is valid.
1355 path[0].ident.name = kw::SelfLower;
1356 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1357 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1358 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1361 /// Suggests a missing `crate::` if that resolves to an correct module.
1365 /// LL | use foo::Bar;
1366 /// | ^^^ did you mean `crate::foo`?
1368 fn make_missing_crate_suggestion(
1371 mut path: Vec<Segment>,
1372 parent_scope: &ParentScope<'b>,
1373 ) -> Option<(Vec<Segment>, Vec<String>)> {
1374 // Replace first ident with `crate` and check if that is valid.
1375 path[0].ident.name = kw::Crate;
1376 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1377 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1378 if let PathResult::Module(..) = result {
1382 "`use` statements changed in Rust 2018; read more at \
1383 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1393 /// Suggests a missing `super::` if that resolves to an correct module.
1397 /// LL | use foo::Bar;
1398 /// | ^^^ did you mean `super::foo`?
1400 fn make_missing_super_suggestion(
1403 mut path: Vec<Segment>,
1404 parent_scope: &ParentScope<'b>,
1405 ) -> Option<(Vec<Segment>, Vec<String>)> {
1406 // Replace first ident with `crate` and check if that is valid.
1407 path[0].ident.name = kw::Super;
1408 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1409 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1410 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1413 /// Suggests a missing external crate name if that resolves to an correct module.
1417 /// LL | use foobar::Baz;
1418 /// | ^^^^^^ did you mean `baz::foobar`?
1421 /// Used when importing a submodule of an external crate but missing that crate's
1422 /// name as the first part of path.
1423 fn make_external_crate_suggestion(
1426 mut path: Vec<Segment>,
1427 parent_scope: &ParentScope<'b>,
1428 ) -> Option<(Vec<Segment>, Vec<String>)> {
1429 if path[1].ident.span.rust_2015() {
1433 // Sort extern crate names in reverse order to get
1434 // 1) some consistent ordering for emitted diagnostics, and
1435 // 2) `std` suggestions before `core` suggestions.
1436 let mut extern_crate_names =
1437 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1438 extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
1440 for name in extern_crate_names.into_iter() {
1441 // Replace first ident with a crate name and check if that is valid.
1442 path[0].ident.name = name;
1443 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1445 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1448 if let PathResult::Module(..) = result {
1449 return Some((path, Vec::new()));
1456 /// Suggests importing a macro from the root of the crate rather than a module within
1460 /// help: a macro with this name exists at the root of the crate
1462 /// LL | use issue_59764::makro;
1463 /// | ^^^^^^^^^^^^^^^^^^
1465 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1466 /// at the root of the crate instead of the module where it is defined
1468 pub(crate) fn check_for_module_export_macro(
1470 import: &'b Import<'b>,
1471 module: ModuleOrUniformRoot<'b>,
1473 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1474 let mut crate_module = if let ModuleOrUniformRoot::Module(module) = module {
1480 while let Some(parent) = crate_module.parent {
1481 crate_module = parent;
1484 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1485 // Don't make a suggestion if the import was already from the root of the
1490 let resolutions = self.r.resolutions(crate_module).borrow();
1491 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1492 let binding = resolution.borrow().binding()?;
1493 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1494 let module_name = crate_module.kind.name().unwrap();
1495 let import_snippet = match import.kind {
1496 ImportKind::Single { source, target, .. } if source != target => {
1497 format!("{} as {}", source, target)
1499 _ => format!("{}", ident),
1502 let mut corrections: Vec<(Span, String)> = Vec::new();
1503 if !import.is_nested() {
1504 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1505 // intermediate segments.
1506 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1508 // Find the binding span (and any trailing commas and spaces).
1509 // ie. `use a::b::{c, d, e};`
1511 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1517 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1518 found_closing_brace, binding_span
1521 let mut removal_span = binding_span;
1522 if found_closing_brace {
1523 // If the binding span ended with a closing brace, as in the below example:
1524 // ie. `use a::b::{c, d};`
1526 // Then expand the span of characters to remove to include the previous
1527 // binding's trailing comma.
1528 // ie. `use a::b::{c, d};`
1530 if let Some(previous_span) =
1531 extend_span_to_previous_binding(self.r.session, binding_span)
1533 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1534 removal_span = removal_span.with_lo(previous_span.lo());
1537 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1539 // Remove the `removal_span`.
1540 corrections.push((removal_span, "".to_string()));
1542 // Find the span after the crate name and if it has nested imports immediatately
1543 // after the crate name already.
1544 // ie. `use a::b::{c, d};`
1546 // or `use a::{b, c, d}};`
1548 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1554 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1555 has_nested, after_crate_name
1558 let source_map = self.r.session.source_map();
1560 // Add the import to the start, with a `{` if required.
1561 let start_point = source_map.start_point(after_crate_name);
1562 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1566 // In this case, `start_snippet` must equal '{'.
1567 format!("{}{}, ", start_snippet, import_snippet)
1569 // In this case, add a `{`, then the moved import, then whatever
1570 // was there before.
1571 format!("{{{}, {}", import_snippet, start_snippet)
1576 // Add a `};` to the end if nested, matching the `{` added at the start.
1578 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1582 let suggestion = Some((
1584 String::from("a macro with this name exists at the root of the crate"),
1585 Applicability::MaybeIncorrect,
1588 "this could be because a macro annotated with `#[macro_export]` will be exported \
1589 at the root of the crate instead of the module where it is defined"
1592 Some((suggestion, note))
1599 /// Given a `binding_span` of a binding within a use statement:
1602 /// use foo::{a, b, c};
1606 /// then return the span until the next binding or the end of the statement:
1609 /// use foo::{a, b, c};
1612 pub(crate) fn find_span_of_binding_until_next_binding(
1617 let source_map = sess.source_map();
1619 // Find the span of everything after the binding.
1620 // ie. `a, e};` or `a};`
1621 let binding_until_end = binding_span.with_hi(use_span.hi());
1623 // Find everything after the binding but not including the binding.
1624 // ie. `, e};` or `};`
1625 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1627 // Keep characters in the span until we encounter something that isn't a comma or
1631 // Also note whether a closing brace character was encountered. If there
1632 // was, then later go backwards to remove any trailing commas that are left.
1633 let mut found_closing_brace = false;
1634 let after_binding_until_next_binding =
1635 source_map.span_take_while(after_binding_until_end, |&ch| {
1637 found_closing_brace = true;
1639 ch == ' ' || ch == ','
1642 // Combine the two spans.
1643 // ie. `a, ` or `a`.
1645 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1646 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1648 (found_closing_brace, span)
1651 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1655 /// use foo::a::{a, b, c};
1656 /// ^^--- binding span
1660 /// use foo::{a, b, c};
1661 /// --- binding span
1663 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1664 let source_map = sess.source_map();
1666 // `prev_source` will contain all of the source that came before the span.
1667 // Then split based on a command and take the first (ie. closest to our span)
1668 // snippet. In the example, this is a space.
1669 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1671 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1672 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1673 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1677 let prev_comma = prev_comma.first().unwrap();
1678 let prev_starting_brace = prev_starting_brace.first().unwrap();
1680 // If the amount of source code before the comma is greater than
1681 // the amount of source code before the starting brace then we've only
1682 // got one item in the nested item (eg. `issue_52891::{self}`).
1683 if prev_comma.len() > prev_starting_brace.len() {
1687 Some(binding_span.with_lo(BytePos(
1688 // Take away the number of bytes for the characters we've found and an
1689 // extra for the comma.
1690 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1694 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1695 /// it is a nested use tree.
1698 /// use foo::a::{b, c};
1699 /// ^^^^^^^^^^ // false
1701 /// use foo::{a, b, c};
1702 /// ^^^^^^^^^^ // true
1704 /// use foo::{a, b::{c, d}};
1705 /// ^^^^^^^^^^^^^^^ // true
1707 fn find_span_immediately_after_crate_name(
1709 module_name: Symbol,
1713 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1714 module_name, use_span
1716 let source_map = sess.source_map();
1718 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1719 let mut num_colons = 0;
1720 // Find second colon.. `use issue_59764:`
1721 let until_second_colon = source_map.span_take_while(use_span, |c| {
1725 !matches!(c, ':' if num_colons == 2)
1727 // Find everything after the second colon.. `foo::{baz, makro};`
1728 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1730 let mut found_a_non_whitespace_character = false;
1731 // Find the first non-whitespace character in `from_second_colon`.. `f`
1732 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1733 if found_a_non_whitespace_character {
1736 if !c.is_whitespace() {
1737 found_a_non_whitespace_character = true;
1742 // Find the first `{` in from_second_colon.. `foo::{`
1743 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1745 (next_left_bracket == after_second_colon, from_second_colon)
1748 /// When an entity with a given name is not available in scope, we search for
1749 /// entities with that name in all crates. This method allows outputting the
1750 /// results of this search in a programmer-friendly way
1751 crate fn show_candidates(
1752 definitions: &rustc_hir::definitions::Definitions,
1754 err: &mut DiagnosticBuilder<'_>,
1755 // This is `None` if all placement locations are inside expansions
1756 use_placement_span: Option<Span>,
1757 candidates: &[ImportSuggestion],
1761 if candidates.is_empty() {
1765 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>)> = Vec::new();
1766 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>)> = Vec::new();
1768 candidates.iter().for_each(|c| {
1769 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1770 .push((path_names_to_string(&c.path), c.descr, c.did))
1773 // we want consistent results across executions, but candidates are produced
1774 // by iterating through a hash map, so make sure they are ordered:
1775 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1776 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1777 let core_path_strings =
1778 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1779 path_strings.extend(core_path_strings);
1780 path_strings.dedup_by(|a, b| a.0 == b.0);
1783 if !accessible_path_strings.is_empty() {
1784 let (determiner, kind) = if accessible_path_strings.len() == 1 {
1785 ("this", accessible_path_strings[0].1)
1787 ("one of these", "items")
1790 let instead = if instead { " instead" } else { "" };
1791 let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1793 if let Some(span) = use_placement_span {
1794 for candidate in &mut accessible_path_strings {
1795 // produce an additional newline to separate the new use statement
1796 // from the directly following item.
1797 let additional_newline = if found_use { "" } else { "\n" };
1798 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1801 err.span_suggestions(
1804 accessible_path_strings.into_iter().map(|a| a.0),
1805 Applicability::Unspecified,
1810 for candidate in accessible_path_strings {
1812 msg.push_str(&candidate.0);
1818 assert!(!inaccessible_path_strings.is_empty());
1820 if inaccessible_path_strings.len() == 1 {
1821 let (name, descr, def_id) = &inaccessible_path_strings[0];
1822 let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1824 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1825 let span = definitions.def_span(local_def_id);
1826 let span = session.source_map().guess_head_span(span);
1827 let mut multi_span = MultiSpan::from_span(span);
1828 multi_span.push_span_label(span, "not accessible".to_string());
1829 err.span_note(multi_span, &msg);
1834 let (_, descr_first, _) = &inaccessible_path_strings[0];
1835 let descr = if inaccessible_path_strings
1838 .all(|(_, descr, _)| descr == descr_first)
1840 descr_first.to_string()
1845 let mut msg = format!("these {}s exist but are inaccessible", descr);
1846 let mut has_colon = false;
1848 let mut spans = Vec::new();
1849 for (name, _, def_id) in &inaccessible_path_strings {
1850 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1851 let span = definitions.def_span(local_def_id);
1852 let span = session.source_map().guess_head_span(span);
1853 spans.push((name, span));
1864 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1865 for (name, span) in spans {
1866 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1869 err.span_note(multi_span, &msg);