3 use rustc_ast::{self as ast, Path};
4 use rustc_ast_pretty::pprust;
5 use rustc_data_structures::fx::FxHashSet;
7 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
9 use rustc_feature::BUILTIN_ATTRIBUTES;
10 use rustc_hir::def::Namespace::{self, *};
11 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind};
12 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_hir::PrimTy;
14 use rustc_middle::bug;
15 use rustc_middle::ty::DefIdTree;
16 use rustc_session::Session;
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::lev_distance::find_best_match_for_name;
19 use rustc_span::source_map::SourceMap;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::{BytePos, MultiSpan, Span};
24 use crate::imports::{Import, ImportKind, ImportResolver};
25 use crate::path_names_to_string;
26 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
28 BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
30 use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
31 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
33 type Res = def::Res<ast::NodeId>;
35 /// A vector of spans and replacements, a message and applicability.
36 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
38 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
39 /// similarly named label and whether or not it is reachable.
40 crate type LabelSuggestion = (Ident, bool);
42 crate enum SuggestionTarget {
43 /// The target has a similar name as the name used by the programmer (probably a typo)
45 /// The target is the only valid item that can be used in the corresponding context
49 crate struct TypoSuggestion {
50 pub candidate: Symbol,
52 pub target: SuggestionTarget,
56 crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
57 Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
59 crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
60 Self { candidate, res, target: SuggestionTarget::SingleItem }
64 /// A free importable items suggested in case of resolution failure.
65 crate struct ImportSuggestion {
66 pub did: Option<DefId>,
67 pub descr: &'static str,
70 /// An extra note that should be issued if this item is suggested
71 pub note: Option<String>,
74 /// Adjust the impl span so that just the `impl` keyword is taken by removing
75 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
76 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
78 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
79 /// parser. If you need to use this function or something similar, please consider updating the
80 /// `source_map` functions and this function to something more robust.
81 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
82 let impl_span = sm.span_until_char(impl_span, '<');
83 sm.span_until_whitespace(impl_span)
86 impl<'a> Resolver<'a> {
87 crate fn add_module_candidates(
90 names: &mut Vec<TypoSuggestion>,
91 filter_fn: &impl Fn(Res) -> bool,
93 for (key, resolution) in self.resolutions(module).borrow().iter() {
94 if let Some(binding) = resolution.borrow().binding {
95 let res = binding.res();
97 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
103 /// Combines an error with provided span and emits it.
105 /// This takes the error provided, combines it with the span and any additional spans inside the
106 /// error and emits it.
107 crate fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) {
108 self.into_struct_error(span, resolution_error).emit();
111 crate fn into_struct_error(
114 resolution_error: ResolutionError<'_>,
115 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
116 match resolution_error {
117 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
118 let mut err = struct_span_err!(
122 "can't use generic parameters from outer function",
124 err.span_label(span, "use of generic parameter from outer function".to_string());
126 let sm = self.session.source_map();
128 Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => {
129 if let Some(impl_span) =
130 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
133 reduce_impl_span_to_impl_keyword(sm, impl_span),
134 "`Self` type implicitly declared here, by this `impl`",
137 match (maybe_trait_defid, maybe_impl_defid) {
139 err.span_label(span, "can't use `Self` here");
142 err.span_label(span, "use a type here instead");
144 (None, None) => bug!("`impl` without trait nor type?"),
148 Res::Def(DefKind::TyParam, def_id) => {
149 if let Some(span) = self.opt_span(def_id) {
150 err.span_label(span, "type parameter from outer function");
153 Res::Def(DefKind::ConstParam, def_id) => {
154 if let Some(span) = self.opt_span(def_id) {
155 err.span_label(span, "const parameter from outer function");
160 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
161 DefKind::TyParam or DefKind::ConstParam"
166 if has_generic_params == HasGenericParams::Yes {
167 // Try to retrieve the span of the function signature and generate a new
168 // message with a local type or const parameter.
169 let sugg_msg = "try using a local generic parameter instead";
170 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
171 // Suggest the modification to the user
176 Applicability::MachineApplicable,
178 } else if let Some(sp) = sm.generate_fn_name_span(span) {
181 "try adding a local generic parameter in this method instead"
185 err.help("try using a local generic parameter instead");
191 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
192 let mut err = struct_span_err!(
196 "the name `{}` is already used for a generic \
197 parameter in this item's generic parameters",
200 err.span_label(span, "already used");
201 err.span_label(first_use_span, format!("first use of `{}`", name));
204 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
205 let mut err = struct_span_err!(
209 "method `{}` is not a member of trait `{}`",
213 err.span_label(span, format!("not a member of trait `{}`", trait_));
214 if let Some(candidate) = candidate {
217 "there is an associated function with a similar name",
218 candidate.to_ident_string(),
219 Applicability::MaybeIncorrect,
224 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
225 let mut err = struct_span_err!(
229 "type `{}` is not a member of trait `{}`",
233 err.span_label(span, format!("not a member of trait `{}`", trait_));
234 if let Some(candidate) = candidate {
237 "there is an associated type with a similar name",
238 candidate.to_ident_string(),
239 Applicability::MaybeIncorrect,
244 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
245 let mut err = struct_span_err!(
249 "const `{}` is not a member of trait `{}`",
253 err.span_label(span, format!("not a member of trait `{}`", trait_));
254 if let Some(candidate) = candidate {
257 "there is an associated constant with a similar name",
258 candidate.to_ident_string(),
259 Applicability::MaybeIncorrect,
264 ResolutionError::VariableNotBoundInPattern(binding_error) => {
265 let BindingError { name, target, origin, could_be_path } = binding_error;
267 let target_sp = target.iter().copied().collect::<Vec<_>>();
268 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
270 let msp = MultiSpan::from_spans(target_sp.clone());
271 let mut err = struct_span_err!(
275 "variable `{}` is not bound in all patterns",
278 for sp in target_sp {
279 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
281 for sp in origin_sp {
282 err.span_label(sp, "variable not in all patterns");
285 let help_msg = format!(
286 "if you meant to match on a variant or a `const` item, consider \
287 making the path in the pattern qualified: `?::{}`",
290 err.span_help(span, &help_msg);
294 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
295 let mut err = struct_span_err!(
299 "variable `{}` is bound inconsistently across alternatives separated by `|`",
302 err.span_label(span, "bound in different ways");
303 err.span_label(first_binding_span, "first binding");
306 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
307 let mut err = struct_span_err!(
311 "identifier `{}` is bound more than once in this parameter list",
314 err.span_label(span, "used as parameter more than once");
317 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
318 let mut err = struct_span_err!(
322 "identifier `{}` is bound more than once in the same pattern",
325 err.span_label(span, "used in a pattern more than once");
328 ResolutionError::UndeclaredLabel { name, suggestion } => {
329 let mut err = struct_span_err!(
333 "use of undeclared label `{}`",
337 err.span_label(span, format!("undeclared label `{}`", name));
340 // A reachable label with a similar name exists.
341 Some((ident, true)) => {
342 err.span_label(ident.span, "a label with a similar name is reachable");
345 "try using similarly named label",
346 ident.name.to_string(),
347 Applicability::MaybeIncorrect,
350 // An unreachable label with a similar name exists.
351 Some((ident, false)) => {
354 "a label with a similar name exists but is unreachable",
357 // No similarly-named labels exist.
363 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
364 let mut err = struct_span_err!(
369 "`self` imports are only allowed within a { } list"
372 // None of the suggestions below would help with a case like `use self`.
374 // use foo::bar::self -> foo::bar
375 // use foo::bar::self as abc -> foo::bar as abc
378 "consider importing the module directly",
380 Applicability::MachineApplicable,
383 // use foo::bar::self -> foo::bar::{self}
384 // use foo::bar::self as abc -> foo::bar::{self as abc}
386 (span_with_rename.shrink_to_lo(), "{".to_string()),
387 (span_with_rename.shrink_to_hi(), "}".to_string()),
389 err.multipart_suggestion(
390 "alternatively, use the multi-path `use` syntax to import `self`",
392 Applicability::MachineApplicable,
397 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
398 let mut err = struct_span_err!(
402 "`self` import can only appear once in an import list"
404 err.span_label(span, "can only appear once in an import list");
407 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
408 let mut err = struct_span_err!(
412 "`self` import can only appear in an import list with \
415 err.span_label(span, "can only appear in an import list with a non-empty prefix");
418 ResolutionError::FailedToResolve { label, suggestion } => {
420 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
421 err.span_label(span, label);
423 if let Some((suggestions, msg, applicability)) = suggestion {
424 if suggestions.is_empty() {
428 err.multipart_suggestion(&msg, suggestions, applicability);
433 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
434 let mut err = struct_span_err!(
439 "can't capture dynamic environment in a fn item"
441 err.help("use the `|| { ... }` closure form instead");
444 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
445 let mut err = struct_span_err!(
449 "attempt to use a non-constant value in a constant"
452 // ^^^ given this Span
453 // ------- get this Span to have an applicable suggestion
456 // only do this if the const and usage of the non-constant value are on the same line
457 // the further the two are apart, the higher the chance of the suggestion being wrong
462 .span_extend_to_prev_str(ident.span, current, true, false);
465 Some(sp) if !self.session.source_map().is_multiline(sp) => {
466 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
469 &format!("consider using `{}` instead of `{}`", sugg, current),
470 format!("{} {}", sugg, ident),
471 Applicability::MaybeIncorrect,
473 err.span_label(span, "non-constant value");
476 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
482 ResolutionError::BindingShadowsSomethingUnacceptable {
483 shadowing_binding_descr,
487 shadowed_binding_descr,
488 shadowed_binding_span,
490 let mut err = struct_span_err!(
494 "{}s cannot shadow {}s",
495 shadowing_binding_descr,
496 shadowed_binding_descr,
500 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
503 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
504 err.span_label(shadowed_binding_span, msg);
507 ResolutionError::ForwardDeclaredGenericParam => {
508 let mut err = struct_span_err!(
512 "generic parameters with a default cannot use \
513 forward declared identifiers"
517 "defaulted generic parameters cannot be forward declared".to_string(),
521 ResolutionError::ParamInTyOfConstParam(name) => {
522 let mut err = struct_span_err!(
526 "the type of const parameters must not depend on other generic parameters"
530 format!("the type must not depend on the parameter `{}`", name),
534 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
535 let mut err = self.session.struct_span_err(
537 "generic parameters may not be used in const operations",
539 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
542 err.note("type parameters may not be used in const expressions");
545 "const parameters may only be used as standalone arguments, i.e. `{}`",
550 if self.session.is_nightly_build() {
552 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
558 ResolutionError::SelfInGenericParamDefault => {
559 let mut err = struct_span_err!(
563 "generic parameters cannot use `Self` in their defaults"
565 err.span_label(span, "`Self` in generic parameter default".to_string());
568 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
569 let mut err = struct_span_err!(
573 "use of unreachable label `{}`",
577 err.span_label(definition_span, "unreachable label defined here");
578 err.span_label(span, format!("unreachable label `{}`", name));
580 "labels are unreachable through functions, closures, async blocks and modules",
584 // A reachable label with a similar name exists.
585 Some((ident, true)) => {
586 err.span_label(ident.span, "a label with a similar name is reachable");
589 "try using similarly named label",
590 ident.name.to_string(),
591 Applicability::MaybeIncorrect,
594 // An unreachable label with a similar name exists.
595 Some((ident, false)) => {
598 "a label with a similar name exists but is also unreachable",
601 // No similarly-named labels exist.
607 ResolutionError::TraitImplMismatch {
614 let mut err = self.session.struct_span_err_with_code(
617 "item `{}` is an associated {}, which doesn't match its trait `{}`",
618 name, kind, trait_path,
622 err.span_label(span, "does not match trait");
623 err.span_label(trait_item_span, "item in trait");
629 crate fn report_vis_error(
631 vis_resolution_error: VisResolutionError<'_>,
632 ) -> ErrorGuaranteed {
633 match vis_resolution_error {
634 VisResolutionError::Relative2018(span, path) => {
635 let mut err = self.session.struct_span_err(
637 "relative paths are not supported in visibilities on 2018 edition",
642 format!("crate::{}", pprust::path_to_string(&path)),
643 Applicability::MaybeIncorrect,
647 VisResolutionError::AncestorOnly(span) => struct_span_err!(
651 "visibilities can only be restricted to ancestor modules"
653 VisResolutionError::FailedToResolve(span, label, suggestion) => {
654 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
656 VisResolutionError::ExpectedFound(span, path_str, res) => {
657 let mut err = struct_span_err!(
661 "expected module, found {} `{}`",
665 err.span_label(span, "not a module");
668 VisResolutionError::Indeterminate(span) => struct_span_err!(
672 "cannot determine resolution for the visibility"
674 VisResolutionError::ModuleOnly(span) => {
675 self.session.struct_span_err(span, "visibility must resolve to a module")
681 /// Lookup typo candidate in scope for a macro or import.
682 fn early_lookup_typo_candidate(
684 scope_set: ScopeSet<'a>,
685 parent_scope: &ParentScope<'a>,
687 filter_fn: &impl Fn(Res) -> bool,
688 ) -> Option<TypoSuggestion> {
689 let mut suggestions = Vec::new();
690 let ctxt = ident.span.ctxt();
691 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
693 Scope::DeriveHelpers(expn_id) => {
694 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
701 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
705 Scope::DeriveHelpersCompat => {
706 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
708 for derive in parent_scope.derives {
709 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
710 if let Ok((Some(ext), _)) = this.resolve_macro_path(
712 Some(MacroKind::Derive),
720 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
726 Scope::MacroRules(macro_rules_scope) => {
727 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
728 let res = macro_rules_binding.binding.res();
730 suggestions.push(TypoSuggestion::typo_from_res(
731 macro_rules_binding.ident.name,
737 Scope::CrateRoot => {
738 let root_ident = Ident::new(kw::PathRoot, ident.span);
739 let root_module = this.resolve_crate_root(root_ident);
740 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
742 Scope::Module(module, _) => {
743 this.add_module_candidates(module, &mut suggestions, filter_fn);
745 Scope::RegisteredAttrs => {
746 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
749 this.registered_attrs
751 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
755 Scope::MacroUsePrelude => {
756 suggestions.extend(this.macro_use_prelude.iter().filter_map(
758 let res = binding.res();
759 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
763 Scope::BuiltinAttrs => {
764 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
769 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
773 Scope::ExternPrelude => {
774 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
775 let res = Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX));
776 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
779 Scope::ToolPrelude => {
780 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
782 this.registered_tools
784 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
787 Scope::StdLibPrelude => {
788 if let Some(prelude) = this.prelude {
789 let mut tmp_suggestions = Vec::new();
790 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
794 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
798 Scope::BuiltinTypes => {
799 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
800 let res = Res::PrimTy(*prim_ty);
801 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
809 // Make sure error reporting is deterministic.
810 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
812 match find_best_match_for_name(
813 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
817 Some(found) if found != ident.name => {
818 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
824 fn lookup_import_candidates_from_module<FilterFn>(
827 namespace: Namespace,
828 parent_scope: &ParentScope<'a>,
829 start_module: Module<'a>,
832 ) -> Vec<ImportSuggestion>
834 FilterFn: Fn(Res) -> bool,
836 let mut candidates = Vec::new();
837 let mut seen_modules = FxHashSet::default();
838 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
839 let mut worklist_via_import = vec![];
841 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
842 None => worklist_via_import.pop(),
845 let in_module_is_extern = !in_module.def_id().is_local();
846 // We have to visit module children in deterministic order to avoid
847 // instabilities in reported imports (#43552).
848 in_module.for_each_child(self, |this, ident, ns, name_binding| {
849 // avoid non-importable candidates
850 if !name_binding.is_importable() {
854 let child_accessible =
855 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
857 // do not venture inside inaccessible items of other crates
858 if in_module_is_extern && !child_accessible {
862 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
864 // There is an assumption elsewhere that paths of variants are in the enum's
865 // declaration and not imported. With this assumption, the variant component is
866 // chopped and the rest of the path is assumed to be the enum's own path. For
867 // errors where a variant is used as the type instead of the enum, this causes
868 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
869 if via_import && name_binding.is_possibly_imported_variant() {
873 // #90113: Do not count an inaccessible reexported item as a candidate.
874 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
875 if this.is_accessible_from(binding.vis, parent_scope.module)
876 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
882 // collect results based on the filter function
883 // avoid suggesting anything from the same module in which we are resolving
884 // avoid suggesting anything with a hygienic name
885 if ident.name == lookup_ident.name
887 && !ptr::eq(in_module, parent_scope.module)
888 && !ident.span.normalize_to_macros_2_0().from_expansion()
890 let res = name_binding.res();
893 let mut segms = path_segments.clone();
894 if lookup_ident.span.rust_2018() {
895 // crate-local absolute paths start with `crate::` in edition 2018
896 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
897 segms.insert(0, ast::PathSegment::from_ident(crate_name));
900 segms.push(ast::PathSegment::from_ident(ident));
901 let path = Path { span: name_binding.span, segments: segms, tokens: None };
902 let did = match res {
903 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
904 _ => res.opt_def_id(),
907 if child_accessible {
908 // Remove invisible match if exists
909 if let Some(idx) = candidates
911 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
913 candidates.remove(idx);
917 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
918 // See if we're recommending TryFrom, TryInto, or FromIterator and add
919 // a note about editions
920 let note = if let Some(did) = did {
921 let requires_note = !did.is_local()
922 && this.cstore().item_attrs_untracked(did, this.session).any(
924 if attr.has_name(sym::rustc_diagnostic_item) {
925 [sym::TryInto, sym::TryFrom, sym::FromIterator]
927 .contains(&attr.value_str())
934 requires_note.then(|| {
936 "'{}' is included in the prelude starting in Edition 2021",
937 path_names_to_string(&path)
944 candidates.push(ImportSuggestion {
948 accessible: child_accessible,
955 // collect submodules to explore
956 if let Some(module) = name_binding.module() {
958 let mut path_segments = path_segments.clone();
959 path_segments.push(ast::PathSegment::from_ident(ident));
961 let is_extern_crate_that_also_appears_in_prelude =
962 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
964 if !is_extern_crate_that_also_appears_in_prelude {
965 // add the module to the lookup
966 if seen_modules.insert(module.def_id()) {
967 if via_import { &mut worklist_via_import } else { &mut worklist }
968 .push((module, path_segments, child_accessible));
975 // If only some candidates are accessible, take just them
976 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
977 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
983 /// When name resolution fails, this method can be used to look up candidate
984 /// entities with the expected name. It allows filtering them using the
985 /// supplied predicate (which should be used to only accept the types of
986 /// definitions expected, e.g., traits). The lookup spans across all crates.
988 /// N.B., the method does not look into imports, but this is not a problem,
989 /// since we report the definitions (thus, the de-aliased imports).
990 crate fn lookup_import_candidates<FilterFn>(
993 namespace: Namespace,
994 parent_scope: &ParentScope<'a>,
996 ) -> Vec<ImportSuggestion>
998 FilterFn: Fn(Res) -> bool,
1000 let mut suggestions = self.lookup_import_candidates_from_module(
1005 Ident::with_dummy_span(kw::Crate),
1009 if lookup_ident.span.rust_2018() {
1010 let extern_prelude_names = self.extern_prelude.clone();
1011 for (ident, _) in extern_prelude_names.into_iter() {
1012 if ident.span.from_expansion() {
1013 // Idents are adjusted to the root context before being
1014 // resolved in the extern prelude, so reporting this to the
1015 // user is no help. This skips the injected
1016 // `extern crate std` in the 2018 edition, which would
1017 // otherwise cause duplicate suggestions.
1020 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1021 let crate_root = self.expect_module(crate_id.as_def_id());
1022 suggestions.extend(self.lookup_import_candidates_from_module(
1037 crate fn unresolved_macro_suggestions(
1039 err: &mut Diagnostic,
1040 macro_kind: MacroKind,
1041 parent_scope: &ParentScope<'a>,
1044 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1045 let suggestion = self.early_lookup_typo_candidate(
1046 ScopeSet::Macro(macro_kind),
1051 self.add_typo_suggestion(err, suggestion, ident.span);
1053 let import_suggestions =
1054 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1060 &import_suggestions,
1065 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1066 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1067 err.span_note(ident.span, &msg);
1070 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1071 err.help("have you added the `#[macro_use]` on the module/import?");
1074 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1075 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1077 ScopeSet::All(ns, false),
1083 let desc = match binding.res() {
1084 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1085 "a function-like macro".to_string()
1087 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1088 format!("an attribute: `#[{}]`", ident)
1090 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1091 format!("a derive macro: `#[derive({})]`", ident)
1094 // Don't confuse the user with tool modules.
1097 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1098 "only a trait, without a derive macro".to_string()
1104 macro_kind.article(),
1105 macro_kind.descr_expected(),
1108 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1109 if !import.span.is_dummy() {
1112 &format!("`{}` is imported here, but it is {}", ident, desc),
1114 // Silence the 'unused import' warning we might get,
1115 // since this diagnostic already covers that import.
1116 self.record_use(ident, binding, false);
1120 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1126 crate fn add_typo_suggestion(
1128 err: &mut Diagnostic,
1129 suggestion: Option<TypoSuggestion>,
1132 let suggestion = match suggestion {
1133 None => return false,
1134 // We shouldn't suggest underscore.
1135 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1136 Some(suggestion) => suggestion,
1138 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1139 LOCAL_CRATE => self.opt_span(def_id),
1143 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1146 if let Some(def_span) = def_span {
1147 if span.overlaps(def_span) {
1148 // Don't suggest typo suggestion for itself like in the following:
1149 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1150 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1153 // | ----------- `X` defined here
1155 // LL | const Y: X = X("ö");
1156 // | -------------^^^^^^- similarly named constant `Y` defined here
1158 // help: use struct literal syntax instead
1160 // LL | const Y: X = X {};
1162 // help: a constant with a similar name exists
1164 // LL | const Y: X = Y("ö");
1168 let prefix = match suggestion.target {
1169 SuggestionTarget::SimilarlyNamed => "similarly named ",
1170 SuggestionTarget::SingleItem => "",
1174 self.session.source_map().guess_head_span(def_span),
1176 "{}{} `{}` defined here",
1178 suggestion.res.descr(),
1179 suggestion.candidate.as_str(),
1183 let msg = match suggestion.target {
1184 SuggestionTarget::SimilarlyNamed => format!(
1185 "{} {} with a similar name exists",
1186 suggestion.res.article(),
1187 suggestion.res.descr()
1189 SuggestionTarget::SingleItem => {
1190 format!("maybe you meant this {}", suggestion.res.descr())
1193 err.span_suggestion(
1196 suggestion.candidate.to_string(),
1197 Applicability::MaybeIncorrect,
1202 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1204 if b.span.is_dummy() || self.session.source_map().span_to_snippet(b.span).is_err() {
1205 // These already contain the "built-in" prefix or look bad with it.
1207 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1208 let (built_in, from) = if from_prelude {
1209 ("", " from prelude")
1210 } else if b.is_extern_crate()
1212 && self.session.opts.externs.get(ident.as_str()).is_some()
1214 ("", " passed with `--extern`")
1215 } else if add_built_in {
1221 let a = if built_in.is_empty() { res.article() } else { "a" };
1222 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1224 let introduced = if b.is_import() { "imported" } else { "defined" };
1225 format!("the {thing} {introduced} here", thing = res.descr())
1229 crate fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1230 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1231 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1232 // We have to print the span-less alternative first, otherwise formatting looks bad.
1233 (b2, b1, misc2, misc1, true)
1235 (b1, b2, misc1, misc2, false)
1238 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1239 err.span_label(ident.span, "ambiguous name");
1240 err.note(&format!("ambiguous because of {}", kind.descr()));
1242 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1243 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1244 let note_msg = format!("`{ident}` could{also} refer to {what}");
1246 let thing = b.res().descr();
1247 let mut help_msgs = Vec::new();
1248 if b.is_glob_import()
1249 && (kind == AmbiguityKind::GlobVsGlob
1250 || kind == AmbiguityKind::GlobVsExpanded
1251 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1253 help_msgs.push(format!(
1254 "consider adding an explicit import of `{ident}` to disambiguate"
1257 if b.is_extern_crate() && ident.span.rust_2018() {
1258 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1260 if misc == AmbiguityErrorMisc::SuggestCrate {
1262 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1263 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1265 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1268 err.span_note(b.span, ¬e_msg);
1269 for (i, help_msg) in help_msgs.iter().enumerate() {
1270 let or = if i == 0 { "" } else { "or " };
1271 err.help(&format!("{}{}", or, help_msg));
1275 could_refer_to(b1, misc1, "");
1276 could_refer_to(b2, misc2, " also");
1280 /// If the binding refers to a tuple struct constructor with fields,
1281 /// returns the span of its fields.
1282 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1283 if let NameBindingKind::Res(
1284 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1288 let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1289 let fields = self.field_names.get(&def_id)?;
1290 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1295 crate fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1296 let PrivacyError { ident, binding, .. } = *privacy_error;
1298 let res = binding.res();
1299 let ctor_fields_span = self.ctor_fields_span(binding);
1300 let plain_descr = res.descr().to_string();
1301 let nonimport_descr =
1302 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1303 let import_descr = nonimport_descr.clone() + " import";
1305 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1307 // Print the primary message.
1308 let descr = get_descr(binding);
1310 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1311 err.span_label(ident.span, &format!("private {}", descr));
1312 if let Some(span) = ctor_fields_span {
1313 err.span_label(span, "a constructor is private if any of the fields is private");
1316 // Print the whole import chain to make it easier to see what happens.
1317 let first_binding = binding;
1318 let mut next_binding = Some(binding);
1319 let mut next_ident = ident;
1320 while let Some(binding) = next_binding {
1321 let name = next_ident;
1322 next_binding = match binding.kind {
1323 _ if res == Res::Err => None,
1324 NameBindingKind::Import { binding, import, .. } => match import.kind {
1325 _ if binding.span.is_dummy() => None,
1326 ImportKind::Single { source, .. } => {
1327 next_ident = source;
1330 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1331 ImportKind::ExternCrate { .. } => None,
1336 let first = ptr::eq(binding, first_binding);
1338 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1339 and_refers_to = if first { "" } else { "...and refers to " },
1340 item = get_descr(binding),
1341 which = if first { "" } else { " which" },
1342 dots = if next_binding.is_some() { "..." } else { "" },
1344 let def_span = self.session.source_map().guess_head_span(binding.span);
1345 let mut note_span = MultiSpan::from_span(def_span);
1346 if !first && binding.vis.is_public() {
1347 note_span.push_span_label(def_span, "consider importing it directly".into());
1349 err.span_note(note_span, &msg);
1355 crate fn find_similarly_named_module_or_crate(
1358 current_module: &Module<'a>,
1359 ) -> Option<Symbol> {
1360 let mut candidates = self
1363 .map(|(ident, _)| ident.name)
1367 .filter(|(_, module)| {
1368 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1370 .flat_map(|(_, module)| module.kind.name()),
1372 .filter(|c| !c.to_string().is_empty())
1373 .collect::<Vec<_>>();
1376 match find_best_match_for_name(&candidates, ident, None) {
1377 Some(sugg) if sugg == ident => None,
1383 impl<'a, 'b> ImportResolver<'a, 'b> {
1384 /// Adds suggestions for a path that cannot be resolved.
1385 pub(crate) fn make_path_suggestion(
1388 mut path: Vec<Segment>,
1389 parent_scope: &ParentScope<'b>,
1390 ) -> Option<(Vec<Segment>, Vec<String>)> {
1391 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1393 match (path.get(0), path.get(1)) {
1394 // `{{root}}::ident::...` on both editions.
1395 // On 2015 `{{root}}` is usually added implicitly.
1396 (Some(fst), Some(snd))
1397 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1398 // `ident::...` on 2018.
1400 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1402 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1403 path.insert(0, Segment::from_ident(Ident::empty()));
1408 self.make_missing_self_suggestion(span, path.clone(), parent_scope)
1409 .or_else(|| self.make_missing_crate_suggestion(span, path.clone(), parent_scope))
1410 .or_else(|| self.make_missing_super_suggestion(span, path.clone(), parent_scope))
1411 .or_else(|| self.make_external_crate_suggestion(span, path, parent_scope))
1414 /// Suggest a missing `self::` if that resolves to an correct module.
1418 /// LL | use foo::Bar;
1419 /// | ^^^ did you mean `self::foo`?
1421 fn make_missing_self_suggestion(
1424 mut path: Vec<Segment>,
1425 parent_scope: &ParentScope<'b>,
1426 ) -> Option<(Vec<Segment>, Vec<String>)> {
1427 // Replace first ident with `self` and check if that is valid.
1428 path[0].ident.name = kw::SelfLower;
1429 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1430 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1431 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1434 /// Suggests a missing `crate::` if that resolves to an correct module.
1438 /// LL | use foo::Bar;
1439 /// | ^^^ did you mean `crate::foo`?
1441 fn make_missing_crate_suggestion(
1444 mut path: Vec<Segment>,
1445 parent_scope: &ParentScope<'b>,
1446 ) -> Option<(Vec<Segment>, Vec<String>)> {
1447 // Replace first ident with `crate` and check if that is valid.
1448 path[0].ident.name = kw::Crate;
1449 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1450 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1451 if let PathResult::Module(..) = result {
1455 "`use` statements changed in Rust 2018; read more at \
1456 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1466 /// Suggests a missing `super::` if that resolves to an correct module.
1470 /// LL | use foo::Bar;
1471 /// | ^^^ did you mean `super::foo`?
1473 fn make_missing_super_suggestion(
1476 mut path: Vec<Segment>,
1477 parent_scope: &ParentScope<'b>,
1478 ) -> Option<(Vec<Segment>, Vec<String>)> {
1479 // Replace first ident with `crate` and check if that is valid.
1480 path[0].ident.name = kw::Super;
1481 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1482 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1483 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
1486 /// Suggests a missing external crate name if that resolves to an correct module.
1490 /// LL | use foobar::Baz;
1491 /// | ^^^^^^ did you mean `baz::foobar`?
1494 /// Used when importing a submodule of an external crate but missing that crate's
1495 /// name as the first part of path.
1496 fn make_external_crate_suggestion(
1499 mut path: Vec<Segment>,
1500 parent_scope: &ParentScope<'b>,
1501 ) -> Option<(Vec<Segment>, Vec<String>)> {
1502 if path[1].ident.span.rust_2015() {
1506 // Sort extern crate names in *reverse* order to get
1507 // 1) some consistent ordering for emitted diagnostics, and
1508 // 2) `std` suggestions before `core` suggestions.
1509 let mut extern_crate_names =
1510 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1511 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
1513 for name in extern_crate_names.into_iter() {
1514 // Replace first ident with a crate name and check if that is valid.
1515 path[0].ident.name = name;
1516 let result = self.r.resolve_path(&path, None, parent_scope, false, span, CrateLint::No);
1518 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
1521 if let PathResult::Module(..) = result {
1522 return Some((path, Vec::new()));
1529 /// Suggests importing a macro from the root of the crate rather than a module within
1533 /// help: a macro with this name exists at the root of the crate
1535 /// LL | use issue_59764::makro;
1536 /// | ^^^^^^^^^^^^^^^^^^
1538 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
1539 /// at the root of the crate instead of the module where it is defined
1541 pub(crate) fn check_for_module_export_macro(
1543 import: &'b Import<'b>,
1544 module: ModuleOrUniformRoot<'b>,
1546 ) -> Option<(Option<Suggestion>, Vec<String>)> {
1547 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
1551 while let Some(parent) = crate_module.parent {
1552 crate_module = parent;
1555 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
1556 // Don't make a suggestion if the import was already from the root of the
1561 let resolutions = self.r.resolutions(crate_module).borrow();
1562 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
1563 let binding = resolution.borrow().binding()?;
1564 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
1565 let module_name = crate_module.kind.name().unwrap();
1566 let import_snippet = match import.kind {
1567 ImportKind::Single { source, target, .. } if source != target => {
1568 format!("{} as {}", source, target)
1570 _ => format!("{}", ident),
1573 let mut corrections: Vec<(Span, String)> = Vec::new();
1574 if !import.is_nested() {
1575 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
1576 // intermediate segments.
1577 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
1579 // Find the binding span (and any trailing commas and spaces).
1580 // ie. `use a::b::{c, d, e};`
1582 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
1588 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
1589 found_closing_brace, binding_span
1592 let mut removal_span = binding_span;
1593 if found_closing_brace {
1594 // If the binding span ended with a closing brace, as in the below example:
1595 // ie. `use a::b::{c, d};`
1597 // Then expand the span of characters to remove to include the previous
1598 // binding's trailing comma.
1599 // ie. `use a::b::{c, d};`
1601 if let Some(previous_span) =
1602 extend_span_to_previous_binding(self.r.session, binding_span)
1604 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
1605 removal_span = removal_span.with_lo(previous_span.lo());
1608 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
1610 // Remove the `removal_span`.
1611 corrections.push((removal_span, "".to_string()));
1613 // Find the span after the crate name and if it has nested imports immediatately
1614 // after the crate name already.
1615 // ie. `use a::b::{c, d};`
1617 // or `use a::{b, c, d}};`
1619 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
1625 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
1626 has_nested, after_crate_name
1629 let source_map = self.r.session.source_map();
1631 // Add the import to the start, with a `{` if required.
1632 let start_point = source_map.start_point(after_crate_name);
1633 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
1637 // In this case, `start_snippet` must equal '{'.
1638 format!("{}{}, ", start_snippet, import_snippet)
1640 // In this case, add a `{`, then the moved import, then whatever
1641 // was there before.
1642 format!("{{{}, {}", import_snippet, start_snippet)
1647 // Add a `};` to the end if nested, matching the `{` added at the start.
1649 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
1653 let suggestion = Some((
1655 String::from("a macro with this name exists at the root of the crate"),
1656 Applicability::MaybeIncorrect,
1659 "this could be because a macro annotated with `#[macro_export]` will be exported \
1660 at the root of the crate instead of the module where it is defined"
1663 Some((suggestion, note))
1670 /// Given a `binding_span` of a binding within a use statement:
1673 /// use foo::{a, b, c};
1677 /// then return the span until the next binding or the end of the statement:
1680 /// use foo::{a, b, c};
1683 pub(crate) fn find_span_of_binding_until_next_binding(
1688 let source_map = sess.source_map();
1690 // Find the span of everything after the binding.
1691 // ie. `a, e};` or `a};`
1692 let binding_until_end = binding_span.with_hi(use_span.hi());
1694 // Find everything after the binding but not including the binding.
1695 // ie. `, e};` or `};`
1696 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
1698 // Keep characters in the span until we encounter something that isn't a comma or
1702 // Also note whether a closing brace character was encountered. If there
1703 // was, then later go backwards to remove any trailing commas that are left.
1704 let mut found_closing_brace = false;
1705 let after_binding_until_next_binding =
1706 source_map.span_take_while(after_binding_until_end, |&ch| {
1708 found_closing_brace = true;
1710 ch == ' ' || ch == ','
1713 // Combine the two spans.
1714 // ie. `a, ` or `a`.
1716 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
1717 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
1719 (found_closing_brace, span)
1722 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
1726 /// use foo::a::{a, b, c};
1727 /// ^^--- binding span
1731 /// use foo::{a, b, c};
1732 /// --- binding span
1734 pub(crate) fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
1735 let source_map = sess.source_map();
1737 // `prev_source` will contain all of the source that came before the span.
1738 // Then split based on a command and take the first (ie. closest to our span)
1739 // snippet. In the example, this is a space.
1740 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
1742 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
1743 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
1744 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
1748 let prev_comma = prev_comma.first().unwrap();
1749 let prev_starting_brace = prev_starting_brace.first().unwrap();
1751 // If the amount of source code before the comma is greater than
1752 // the amount of source code before the starting brace then we've only
1753 // got one item in the nested item (eg. `issue_52891::{self}`).
1754 if prev_comma.len() > prev_starting_brace.len() {
1758 Some(binding_span.with_lo(BytePos(
1759 // Take away the number of bytes for the characters we've found and an
1760 // extra for the comma.
1761 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
1765 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
1766 /// it is a nested use tree.
1769 /// use foo::a::{b, c};
1770 /// ^^^^^^^^^^ // false
1772 /// use foo::{a, b, c};
1773 /// ^^^^^^^^^^ // true
1775 /// use foo::{a, b::{c, d}};
1776 /// ^^^^^^^^^^^^^^^ // true
1778 fn find_span_immediately_after_crate_name(
1780 module_name: Symbol,
1784 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
1785 module_name, use_span
1787 let source_map = sess.source_map();
1789 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
1790 let mut num_colons = 0;
1791 // Find second colon.. `use issue_59764:`
1792 let until_second_colon = source_map.span_take_while(use_span, |c| {
1796 !matches!(c, ':' if num_colons == 2)
1798 // Find everything after the second colon.. `foo::{baz, makro};`
1799 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
1801 let mut found_a_non_whitespace_character = false;
1802 // Find the first non-whitespace character in `from_second_colon`.. `f`
1803 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
1804 if found_a_non_whitespace_character {
1807 if !c.is_whitespace() {
1808 found_a_non_whitespace_character = true;
1813 // Find the first `{` in from_second_colon.. `foo::{`
1814 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
1816 (next_left_bracket == after_second_colon, from_second_colon)
1819 /// When an entity with a given name is not available in scope, we search for
1820 /// entities with that name in all crates. This method allows outputting the
1821 /// results of this search in a programmer-friendly way
1822 crate fn show_candidates(
1823 definitions: &rustc_hir::definitions::Definitions,
1825 err: &mut Diagnostic,
1826 // This is `None` if all placement locations are inside expansions
1827 use_placement_span: Option<Span>,
1828 candidates: &[ImportSuggestion],
1832 if candidates.is_empty() {
1836 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1838 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
1841 candidates.iter().for_each(|c| {
1842 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
1843 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
1846 // we want consistent results across executions, but candidates are produced
1847 // by iterating through a hash map, so make sure they are ordered:
1848 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
1849 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
1850 let core_path_strings =
1851 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
1852 path_strings.extend(core_path_strings);
1853 path_strings.dedup_by(|a, b| a.0 == b.0);
1856 if !accessible_path_strings.is_empty() {
1857 let (determiner, kind) = if accessible_path_strings.len() == 1 {
1858 ("this", accessible_path_strings[0].1)
1860 ("one of these", "items")
1863 let instead = if instead { " instead" } else { "" };
1864 let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
1866 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
1870 if let Some(span) = use_placement_span {
1871 for candidate in &mut accessible_path_strings {
1872 // produce an additional newline to separate the new use statement
1873 // from the directly following item.
1874 let additional_newline = if found_use { "" } else { "\n" };
1875 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
1878 err.span_suggestions(
1881 accessible_path_strings.into_iter().map(|a| a.0),
1882 Applicability::Unspecified,
1887 for candidate in accessible_path_strings {
1889 msg.push_str(&candidate.0);
1895 assert!(!inaccessible_path_strings.is_empty());
1897 if inaccessible_path_strings.len() == 1 {
1898 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
1899 let msg = format!("{} `{}` exists but is inaccessible", descr, name);
1901 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1902 let span = definitions.def_span(local_def_id);
1903 let span = session.source_map().guess_head_span(span);
1904 let mut multi_span = MultiSpan::from_span(span);
1905 multi_span.push_span_label(span, "not accessible".to_string());
1906 err.span_note(multi_span, &msg);
1910 if let Some(note) = (*note).as_deref() {
1914 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
1915 let descr = if inaccessible_path_strings
1918 .all(|(_, descr, _, _)| descr == descr_first)
1920 descr_first.to_string()
1925 let mut msg = format!("these {}s exist but are inaccessible", descr);
1926 let mut has_colon = false;
1928 let mut spans = Vec::new();
1929 for (name, _, def_id, _) in &inaccessible_path_strings {
1930 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
1931 let span = definitions.def_span(local_def_id);
1932 let span = session.source_map().guess_head_span(span);
1933 spans.push((name, span));
1944 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
1945 for (name, span) in spans {
1946 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
1949 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
1953 err.span_note(multi_span, &msg);