4 use rustc_ast::visit::{self, Visitor};
5 use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::struct_span_err;
9 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
10 use rustc_feature::BUILTIN_ATTRIBUTES;
11 use rustc_hir::def::Namespace::{self, *};
12 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
13 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
14 use rustc_hir::PrimTy;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::bug;
17 use rustc_middle::ty::DefIdTree;
18 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
19 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
20 use rustc_session::lint::BuiltinLintDiagnostics;
21 use rustc_session::Session;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::MacroKind;
24 use rustc_span::lev_distance::find_best_match_for_name;
25 use rustc_span::source_map::SourceMap;
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
27 use rustc_span::{BytePos, Span, SyntaxContext};
28 use thin_vec::ThinVec;
30 use crate::errors as errs;
31 use crate::imports::{Import, ImportKind, ImportResolver};
32 use crate::late::{PatternSource, Rib};
33 use crate::path_names_to_string;
34 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
35 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
36 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
37 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
38 use crate::{Segment, UseError};
43 type Res = def::Res<ast::NodeId>;
45 /// A vector of spans and replacements, a message and applicability.
46 pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
48 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
49 /// similarly named label and whether or not it is reachable.
50 pub(crate) type LabelSuggestion = (Ident, bool);
53 pub(crate) enum SuggestionTarget {
54 /// The target has a similar name as the name used by the programmer (probably a typo)
56 /// The target is the only valid item that can be used in the corresponding context
61 pub(crate) struct TypoSuggestion {
62 pub candidate: Symbol,
63 /// The source location where the name is defined; None if the name is not defined
64 /// in source e.g. primitives
65 pub span: Option<Span>,
67 pub target: SuggestionTarget,
71 pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
73 candidate: ident.name,
74 span: Some(ident.span),
76 target: SuggestionTarget::SimilarlyNamed,
79 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
80 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
82 pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
84 candidate: ident.name,
85 span: Some(ident.span),
87 target: SuggestionTarget::SingleItem,
92 /// A free importable items suggested in case of resolution failure.
93 #[derive(Debug, Clone)]
94 pub(crate) struct ImportSuggestion {
95 pub did: Option<DefId>,
96 pub descr: &'static str,
99 /// An extra note that should be issued if this item is suggested
100 pub note: Option<String>,
103 /// Adjust the impl span so that just the `impl` keyword is taken by removing
104 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
105 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
107 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
108 /// parser. If you need to use this function or something similar, please consider updating the
109 /// `source_map` functions and this function to something more robust.
110 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
111 let impl_span = sm.span_until_char(impl_span, '<');
112 sm.span_until_whitespace(impl_span)
115 impl<'a> Resolver<'a> {
116 pub(crate) fn report_errors(&mut self, krate: &Crate) {
117 self.report_with_use_injections(krate);
119 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
120 let msg = "macro-expanded `macro_export` macros from the current crate \
121 cannot be referred to by absolute paths";
122 self.lint_buffer.buffer_lint_with_diagnostic(
123 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
127 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
131 for ambiguity_error in &self.ambiguity_errors {
132 self.report_ambiguity_error(ambiguity_error);
135 let mut reported_spans = FxHashSet::default();
136 for error in &self.privacy_errors {
137 if reported_spans.insert(error.dedup_span) {
138 self.report_privacy_error(error);
143 fn report_with_use_injections(&mut self, krate: &Crate) {
144 for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
145 self.use_injections.drain(..)
147 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
148 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
153 if !candidates.is_empty() {
156 &self.untracked.source_span,
160 if instead { Instead::Yes } else { Instead::No },
162 DiagnosticMode::Normal,
166 } else if let Some((span, msg, sugg, appl)) = suggestion {
167 err.span_suggestion(span, msg, sugg, appl);
169 } else if let [segment] = path.as_slice() && is_call {
170 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
177 pub(crate) fn report_conflict<'b>(
182 new_binding: &NameBinding<'b>,
183 old_binding: &NameBinding<'b>,
185 // Error on the second of two conflicting names
186 if old_binding.span.lo() > new_binding.span.lo() {
187 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
190 let container = match parent.kind {
191 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
192 ModuleKind::Block => "block",
195 let old_noun = match old_binding.is_import_user_facing() {
197 false => "definition",
200 let new_participle = match new_binding.is_import_user_facing() {
206 (ident.name, self.session.source_map().guess_head_span(new_binding.span));
208 if let Some(s) = self.name_already_seen.get(&name) {
214 let old_kind = match (ns, old_binding.module()) {
215 (ValueNS, _) => "value",
216 (MacroNS, _) => "macro",
217 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
218 (TypeNS, Some(module)) if module.is_normal() => "module",
219 (TypeNS, Some(module)) if module.is_trait() => "trait",
220 (TypeNS, _) => "type",
223 let msg = format!("the name `{}` is defined multiple times", name);
225 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
226 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
227 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
228 true => struct_span_err!(self.session, span, E0254, "{}", msg),
229 false => struct_span_err!(self.session, span, E0260, "{}", msg),
231 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
232 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
233 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
234 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
239 "`{}` must be defined only once in the {} namespace of this {}",
245 err.span_label(span, format!("`{}` re{} here", name, new_participle));
246 if !old_binding.span.is_dummy() && old_binding.span != span {
248 self.session.source_map().guess_head_span(old_binding.span),
249 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
253 // See https://github.com/rust-lang/rust/issues/32354
254 use NameBindingKind::Import;
255 let can_suggest = |binding: &NameBinding<'_>, import: &self::Import<'_>| {
256 !binding.span.is_dummy()
257 && !matches!(import.kind, ImportKind::MacroUse | ImportKind::MacroExport)
259 let import = match (&new_binding.kind, &old_binding.kind) {
260 // If there are two imports where one or both have attributes then prefer removing the
261 // import without attributes.
262 (Import { import: new, .. }, Import { import: old, .. })
264 (new.has_attributes || old.has_attributes)
265 && can_suggest(old_binding, old)
266 && can_suggest(new_binding, new)
269 if old.has_attributes {
270 Some((new, new_binding.span, true))
272 Some((old, old_binding.span, true))
275 // Otherwise prioritize the new binding.
276 (Import { import, .. }, other) if can_suggest(new_binding, import) => {
277 Some((import, new_binding.span, other.is_import()))
279 (other, Import { import, .. }) if can_suggest(old_binding, import) => {
280 Some((import, old_binding.span, other.is_import()))
285 // Check if the target of the use for both bindings is the same.
286 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
287 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
289 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
290 // Only suggest removing an import if both bindings are to the same def, if both spans
291 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
292 // been introduced by an item.
293 let should_remove_import = duplicate
295 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
298 Some((import, span, true)) if should_remove_import && import.is_nested() => {
299 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
301 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
302 // Simple case - remove the entire import. Due to the above match arm, this can
303 // only be a single use so just remove it entirely.
304 err.tool_only_span_suggestion(
305 import.use_span_with_attributes,
306 "remove unnecessary import",
308 Applicability::MaybeIncorrect,
311 Some((import, span, _)) => {
312 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
318 self.name_already_seen.insert(name, span);
321 /// This function adds a suggestion to change the binding name of a new import that conflicts
322 /// with an existing import.
324 /// ```text,ignore (diagnostic)
325 /// help: you can use `as` to change the binding name of the import
327 /// LL | use foo::bar as other_bar;
328 /// | ^^^^^^^^^^^^^^^^^^^^^
330 fn add_suggestion_for_rename_of_use(
332 err: &mut Diagnostic,
337 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
338 format!("Other{}", name)
340 format!("other_{}", name)
343 let mut suggestion = None;
345 ImportKind::Single { type_ns_only: true, .. } => {
346 suggestion = Some(format!("self as {}", suggested_name))
348 ImportKind::Single { source, .. } => {
350 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
352 if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
353 if pos <= snippet.len() {
354 suggestion = Some(format!(
358 if snippet.ends_with(';') { ";" } else { "" }
364 ImportKind::ExternCrate { source, target, .. } => {
365 suggestion = Some(format!(
366 "extern crate {} as {};",
367 source.unwrap_or(target.name),
374 let rename_msg = "you can use `as` to change the binding name of the import";
375 if let Some(suggestion) = suggestion {
380 Applicability::MaybeIncorrect,
383 err.span_label(binding_span, rename_msg);
387 /// This function adds a suggestion to remove an unnecessary binding from an import that is
388 /// nested. In the following example, this function will be invoked to remove the `a` binding
389 /// in the second use statement:
391 /// ```ignore (diagnostic)
392 /// use issue_52891::a;
393 /// use issue_52891::{d, a, e};
396 /// The following suggestion will be added:
398 /// ```ignore (diagnostic)
399 /// use issue_52891::{d, a, e};
400 /// ^-- help: remove unnecessary import
403 /// If the nested use contains only one import then the suggestion will remove the entire
406 /// It is expected that the provided import is nested - this isn't checked by the
407 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
408 /// as characters expected by span manipulations won't be present.
409 fn add_suggestion_for_duplicate_nested_use(
411 err: &mut Diagnostic,
415 assert!(import.is_nested());
416 let message = "remove unnecessary import";
418 // Two examples will be used to illustrate the span manipulations we're doing:
420 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
421 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
422 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
423 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
425 let (found_closing_brace, span) =
426 find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
428 // If there was a closing brace then identify the span to remove any trailing commas from
430 if found_closing_brace {
431 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
432 err.tool_only_span_suggestion(span, message, "", Applicability::MaybeIncorrect);
434 // Remove the entire line if we cannot extend the span back, this indicates an
435 // `issue_52891::{self}` case.
437 import.use_span_with_attributes,
440 Applicability::MaybeIncorrect,
447 err.span_suggestion(span, message, "", Applicability::MachineApplicable);
450 pub(crate) fn lint_if_path_starts_with_module(
452 finalize: Option<Finalize>,
454 second_binding: Option<&NameBinding<'_>>,
456 let Some(Finalize { node_id, root_span, .. }) = finalize else {
460 let first_name = match path.get(0) {
461 // In the 2018 edition this lint is a hard error, so nothing to do
462 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
466 // We're only interested in `use` paths which should start with
467 // `{{root}}` currently.
468 if first_name != kw::PathRoot {
473 // If this import looks like `crate::...` it's already good
474 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
475 // Otherwise go below to see if it's an extern crate
477 // If the path has length one (and it's `PathRoot` most likely)
478 // then we don't know whether we're gonna be importing a crate or an
479 // item in our crate. Defer this lint to elsewhere
483 // If the first element of our path was actually resolved to an
484 // `ExternCrate` (also used for `crate::...`) then no need to issue a
485 // warning, this looks all good!
486 if let Some(binding) = second_binding {
487 if let NameBindingKind::Import { import, .. } = binding.kind {
488 // Careful: we still want to rewrite paths from renamed extern crates.
489 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
495 let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
496 self.lint_buffer.buffer_lint_with_diagnostic(
497 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
500 "absolute paths must start with `self`, `super`, \
501 `crate`, or an external crate name in the 2018 edition",
506 pub(crate) fn add_module_candidates(
509 names: &mut Vec<TypoSuggestion>,
510 filter_fn: &impl Fn(Res) -> bool,
511 ctxt: Option<SyntaxContext>,
513 for (key, resolution) in self.resolutions(module).borrow().iter() {
514 if let Some(binding) = resolution.borrow().binding {
515 let res = binding.res();
516 if filter_fn(res) && ctxt.map_or(true, |ctxt| ctxt == key.ident.span.ctxt()) {
517 names.push(TypoSuggestion::typo_from_ident(key.ident, res));
523 /// Combines an error with provided span and emits it.
525 /// This takes the error provided, combines it with the span and any additional spans inside the
526 /// error and emits it.
527 pub(crate) fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
528 self.into_struct_error(span, resolution_error).emit();
531 pub(crate) fn into_struct_error(
534 resolution_error: ResolutionError<'a>,
535 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
536 match resolution_error {
537 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
538 let mut err = struct_span_err!(
542 "can't use generic parameters from outer function",
544 err.span_label(span, "use of generic parameter from outer function");
546 let sm = self.session.source_map();
547 let def_id = match outer_res {
548 Res::SelfTyParam { .. } => {
549 err.span_label(span, "can't use `Self` here");
552 Res::SelfTyAlias { alias_to: def_id, .. } => {
553 if let Some(impl_span) = self.opt_span(def_id) {
555 reduce_impl_span_to_impl_keyword(sm, impl_span),
556 "`Self` type implicitly declared here, by this `impl`",
559 err.span_label(span, "use a type here instead");
562 Res::Def(DefKind::TyParam, def_id) => {
563 if let Some(span) = self.opt_span(def_id) {
564 err.span_label(span, "type parameter from outer function");
568 Res::Def(DefKind::ConstParam, def_id) => {
569 if let Some(span) = self.opt_span(def_id) {
570 err.span_label(span, "const parameter from outer function");
576 "GenericParamsFromOuterFunction should only be used with \
577 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
583 if let HasGenericParams::Yes(span) = has_generic_params {
584 // Try to retrieve the span of the function signature and generate a new
585 // message with a local type or const parameter.
586 let sugg_msg = "try using a local generic parameter instead";
587 let name = self.opt_name(def_id).unwrap_or(sym::T);
588 let (span, snippet) = if span.is_empty() {
589 let snippet = format!("<{}>", name);
592 let span = sm.span_through_char(span, '<').shrink_to_hi();
593 let snippet = format!("{}, ", name);
596 // Suggest the modification to the user
597 err.span_suggestion(span, sugg_msg, snippet, Applicability::MaybeIncorrect);
602 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
604 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
605 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
606 self.session.create_err(errs::MethodNotMemberOfTrait {
610 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
616 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
617 self.session.create_err(errs::TypeNotMemberOfTrait {
621 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
627 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
628 self.session.create_err(errs::ConstNotMemberOfTrait {
632 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
638 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
639 let BindingError { name, target, origin, could_be_path } = binding_error;
641 let target_sp = target.iter().copied().collect::<Vec<_>>();
642 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
644 let msp = MultiSpan::from_spans(target_sp.clone());
645 let mut err = struct_span_err!(
649 "variable `{}` is not bound in all patterns",
652 for sp in target_sp {
653 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
655 for sp in origin_sp {
656 err.span_label(sp, "variable not in all patterns");
659 let import_suggestions = self.lookup_import_candidates(
660 Ident::with_dummy_span(name),
663 &|res: Res| match res {
665 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
666 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
668 | DefKind::AssocConst,
675 if import_suggestions.is_empty() {
676 let help_msg = format!(
677 "if you meant to match on a variant or a `const` item, consider \
678 making the path in the pattern qualified: `path::to::ModOrType::{}`",
681 err.span_help(span, &help_msg);
685 &self.untracked.source_span,
691 DiagnosticMode::Pattern,
697 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
698 self.session.create_err(errs::VariableBoundWithDifferentMode {
704 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
706 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
707 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
709 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
710 ResolutionError::UndeclaredLabel { name, suggestion } => {
711 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
713 // A reachable label with a similar name exists.
714 Some((ident, true)) => (
716 Some(errs::LabelWithSimilarNameReachable(ident.span)),
717 Some(errs::TryUsingSimilarlyNamedLabel {
719 ident_name: ident.name,
724 // An unreachable label with a similar name exists.
725 Some((ident, false)) => (
727 Some(errs::UnreachableLabelWithSimilarNameExists {
728 ident_span: ident.span,
731 // No similarly-named labels exist.
732 None => ((None, None), None),
734 self.session.create_err(errs::UndeclaredLabel {
738 sub_reachable_suggestion,
742 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
743 // None of the suggestions below would help with a case like `use self`.
744 let (suggestion, mpart_suggestion) = if root {
747 // use foo::bar::self -> foo::bar
748 // use foo::bar::self as abc -> foo::bar as abc
749 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
751 // use foo::bar::self -> foo::bar::{self}
752 // use foo::bar::self as abc -> foo::bar::{self as abc}
753 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
754 multipart_start: span_with_rename.shrink_to_lo(),
755 multipart_end: span_with_rename.shrink_to_hi(),
757 (Some(suggestion), Some(mpart_suggestion))
759 self.session.create_err(errs::SelfImportsOnlyAllowedWithin {
765 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
766 self.session.create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
768 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
769 self.session.create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
771 ResolutionError::FailedToResolve { label, suggestion } => {
773 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
774 err.span_label(span, label);
776 if let Some((suggestions, msg, applicability)) = suggestion {
777 if suggestions.is_empty() {
781 err.multipart_suggestion(&msg, suggestions, applicability);
786 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
787 self.session.create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
789 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, suggestion, current) => {
791 // ^^^ given this Span
792 // ------- get this Span to have an applicable suggestion
795 // only do this if the const and usage of the non-constant value are on the same line
796 // the further the two are apart, the higher the chance of the suggestion being wrong
801 .span_extend_to_prev_str(ident.span, current, true, false);
803 let ((with, with_label), without) = match sp {
804 Some(sp) if !self.session.source_map().is_multiline(sp) => {
805 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
807 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
812 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
818 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
819 ident_span: ident.span,
825 self.session.create_err(errs::AttemptToUseNonConstantValueInConstant {
832 ResolutionError::BindingShadowsSomethingUnacceptable {
838 shadowed_binding_span,
839 } => self.session.create_err(errs::BindingShadowsSomethingUnacceptable {
844 sub_suggestion: match (shadowing_binding, shadowed_binding) {
846 PatternSource::Match,
847 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
848 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
851 shadowed_binding_span,
855 ResolutionError::ForwardDeclaredGenericParam => {
856 self.session.create_err(errs::ForwardDeclaredGenericParam { span })
858 ResolutionError::ParamInTyOfConstParam(name) => {
859 self.session.create_err(errs::ParamInTyOfConstParam { span, name })
861 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
862 self.session.create_err(errs::ParamInNonTrivialAnonConst {
865 sub_is_type: if is_type {
866 errs::ParamInNonTrivialAnonConstIsType::AType
868 errs::ParamInNonTrivialAnonConstIsType::NotAType { name }
873 .then_some(errs::ParamInNonTrivialAnonConstHelp),
876 ResolutionError::SelfInGenericParamDefault => {
877 self.session.create_err(errs::SelfInGenericParamDefault { span })
879 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
880 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
882 // A reachable label with a similar name exists.
883 Some((ident, true)) => (
885 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
886 Some(errs::UnreachableLabelSubSuggestion {
888 // intentionally taking 'ident.name' instead of 'ident' itself, as this
889 // could be used in suggestion context
890 ident_name: ident.name,
895 // An unreachable label with a similar name exists.
896 Some((ident, false)) => (
898 Some(errs::UnreachableLabelSubLabelUnreachable {
899 ident_span: ident.span,
902 // No similarly-named labels exist.
903 None => ((None, None), None),
905 self.session.create_err(errs::UnreachableLabel {
910 sub_suggestion_label,
911 sub_unreachable_label,
914 ResolutionError::TraitImplMismatch {
921 let mut err = self.session.struct_span_err_with_code(
924 "item `{}` is an associated {}, which doesn't match its trait `{}`",
925 name, kind, trait_path,
929 err.span_label(span, "does not match trait");
930 err.span_label(trait_item_span, "item in trait");
933 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
935 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
936 ResolutionError::InvalidAsmSym => self.session.create_err(errs::InvalidAsmSym { span }),
940 pub(crate) fn report_vis_error(
942 vis_resolution_error: VisResolutionError<'_>,
943 ) -> ErrorGuaranteed {
944 match vis_resolution_error {
945 VisResolutionError::Relative2018(span, path) => {
946 self.session.create_err(errs::Relative2018 {
948 path_span: path.span,
949 // intentionally converting to String, as the text would also be used as
950 // in suggestion context
951 path_str: pprust::path_to_string(&path),
954 VisResolutionError::AncestorOnly(span) => {
955 self.session.create_err(errs::AncestorOnly(span))
957 VisResolutionError::FailedToResolve(span, label, suggestion) => {
958 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
960 VisResolutionError::ExpectedFound(span, path_str, res) => {
961 self.session.create_err(errs::ExpectedFound { span, res, path_str })
963 VisResolutionError::Indeterminate(span) => {
964 self.session.create_err(errs::Indeterminate(span))
966 VisResolutionError::ModuleOnly(span) => self.session.create_err(errs::ModuleOnly(span)),
971 /// Lookup typo candidate in scope for a macro or import.
972 fn early_lookup_typo_candidate(
974 scope_set: ScopeSet<'a>,
975 parent_scope: &ParentScope<'a>,
977 filter_fn: &impl Fn(Res) -> bool,
978 ) -> Option<TypoSuggestion> {
979 let mut suggestions = Vec::new();
980 let ctxt = ident.span.ctxt();
981 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
983 Scope::DeriveHelpers(expn_id) => {
984 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
991 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
995 Scope::DeriveHelpersCompat => {
996 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
998 for derive in parent_scope.derives {
999 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1000 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1002 Some(MacroKind::Derive),
1010 .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1016 Scope::MacroRules(macro_rules_scope) => {
1017 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1018 let res = macro_rules_binding.binding.res();
1020 suggestions.push(TypoSuggestion::typo_from_ident(
1021 macro_rules_binding.ident,
1027 Scope::CrateRoot => {
1028 let root_ident = Ident::new(kw::PathRoot, ident.span);
1029 let root_module = this.resolve_crate_root(root_ident);
1030 this.add_module_candidates(root_module, &mut suggestions, filter_fn, None);
1032 Scope::Module(module) => {
1033 this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1035 Scope::MacroUsePrelude => {
1036 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1038 let res = binding.res();
1039 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1043 Scope::BuiltinAttrs => {
1044 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1049 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1053 Scope::ExternPrelude => {
1054 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1055 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1056 filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res))
1059 Scope::ToolPrelude => {
1060 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1062 this.registered_tools
1064 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1067 Scope::StdLibPrelude => {
1068 if let Some(prelude) = this.prelude {
1069 let mut tmp_suggestions = Vec::new();
1070 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1074 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1078 Scope::BuiltinTypes => {
1079 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1080 let res = Res::PrimTy(*prim_ty);
1082 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1090 // Make sure error reporting is deterministic.
1091 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1093 match find_best_match_for_name(
1094 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1098 Some(found) if found != ident.name => {
1099 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1105 fn lookup_import_candidates_from_module<FilterFn>(
1107 lookup_ident: Ident,
1108 namespace: Namespace,
1109 parent_scope: &ParentScope<'a>,
1110 start_module: Module<'a>,
1112 filter_fn: FilterFn,
1113 ) -> Vec<ImportSuggestion>
1115 FilterFn: Fn(Res) -> bool,
1117 let mut candidates = Vec::new();
1118 let mut seen_modules = FxHashSet::default();
1119 let mut worklist = vec![(start_module, ThinVec::<ast::PathSegment>::new(), true)];
1120 let mut worklist_via_import = vec![];
1122 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1123 None => worklist_via_import.pop(),
1126 let in_module_is_extern = !in_module.def_id().is_local();
1127 // We have to visit module children in deterministic order to avoid
1128 // instabilities in reported imports (#43552).
1129 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1130 // avoid non-importable candidates
1131 if !name_binding.is_importable() {
1135 let child_accessible =
1136 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1138 // do not venture inside inaccessible items of other crates
1139 if in_module_is_extern && !child_accessible {
1143 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1145 // There is an assumption elsewhere that paths of variants are in the enum's
1146 // declaration and not imported. With this assumption, the variant component is
1147 // chopped and the rest of the path is assumed to be the enum's own path. For
1148 // errors where a variant is used as the type instead of the enum, this causes
1149 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1150 if via_import && name_binding.is_possibly_imported_variant() {
1154 // #90113: Do not count an inaccessible reexported item as a candidate.
1155 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1156 if this.is_accessible_from(binding.vis, parent_scope.module)
1157 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1163 // collect results based on the filter function
1164 // avoid suggesting anything from the same module in which we are resolving
1165 // avoid suggesting anything with a hygienic name
1166 if ident.name == lookup_ident.name
1168 && !ptr::eq(in_module, parent_scope.module)
1169 && !ident.span.normalize_to_macros_2_0().from_expansion()
1171 let res = name_binding.res();
1174 let mut segms = path_segments.clone();
1175 if lookup_ident.span.rust_2018() {
1176 // crate-local absolute paths start with `crate::` in edition 2018
1177 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1178 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1181 segms.push(ast::PathSegment::from_ident(ident));
1182 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1183 let did = match res {
1184 Res::Def(DefKind::Ctor(..), did) => this.opt_parent(did),
1185 _ => res.opt_def_id(),
1188 if child_accessible {
1189 // Remove invisible match if exists
1190 if let Some(idx) = candidates
1192 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1194 candidates.remove(idx);
1198 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1199 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1200 // a note about editions
1201 let note = if let Some(did) = did {
1202 let requires_note = !did.is_local()
1203 && this.cstore().item_attrs_untracked(did, this.session).any(
1205 if attr.has_name(sym::rustc_diagnostic_item) {
1206 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1208 .contains(&attr.value_str())
1215 requires_note.then(|| {
1217 "'{}' is included in the prelude starting in Edition 2021",
1218 path_names_to_string(&path)
1225 candidates.push(ImportSuggestion {
1229 accessible: child_accessible,
1236 // collect submodules to explore
1237 if let Some(module) = name_binding.module() {
1239 let mut path_segments = path_segments.clone();
1240 path_segments.push(ast::PathSegment::from_ident(ident));
1242 let is_extern_crate_that_also_appears_in_prelude =
1243 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1245 if !is_extern_crate_that_also_appears_in_prelude {
1246 // add the module to the lookup
1247 if seen_modules.insert(module.def_id()) {
1248 if via_import { &mut worklist_via_import } else { &mut worklist }
1249 .push((module, path_segments, child_accessible));
1256 // If only some candidates are accessible, take just them
1257 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1258 candidates.retain(|x| x.accessible)
1264 /// When name resolution fails, this method can be used to look up candidate
1265 /// entities with the expected name. It allows filtering them using the
1266 /// supplied predicate (which should be used to only accept the types of
1267 /// definitions expected, e.g., traits). The lookup spans across all crates.
1269 /// N.B., the method does not look into imports, but this is not a problem,
1270 /// since we report the definitions (thus, the de-aliased imports).
1271 pub(crate) fn lookup_import_candidates<FilterFn>(
1273 lookup_ident: Ident,
1274 namespace: Namespace,
1275 parent_scope: &ParentScope<'a>,
1276 filter_fn: FilterFn,
1277 ) -> Vec<ImportSuggestion>
1279 FilterFn: Fn(Res) -> bool,
1281 let mut suggestions = self.lookup_import_candidates_from_module(
1286 Ident::with_dummy_span(kw::Crate),
1290 if lookup_ident.span.rust_2018() {
1291 let extern_prelude_names = self.extern_prelude.clone();
1292 for (ident, _) in extern_prelude_names.into_iter() {
1293 if ident.span.from_expansion() {
1294 // Idents are adjusted to the root context before being
1295 // resolved in the extern prelude, so reporting this to the
1296 // user is no help. This skips the injected
1297 // `extern crate std` in the 2018 edition, which would
1298 // otherwise cause duplicate suggestions.
1301 let crate_id = self.crate_loader().maybe_process_path_extern(ident.name);
1302 if let Some(crate_id) = crate_id {
1303 let crate_root = self.expect_module(crate_id.as_def_id());
1304 suggestions.extend(self.lookup_import_candidates_from_module(
1319 pub(crate) fn unresolved_macro_suggestions(
1321 err: &mut Diagnostic,
1322 macro_kind: MacroKind,
1323 parent_scope: &ParentScope<'a>,
1326 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1327 let suggestion = self.early_lookup_typo_candidate(
1328 ScopeSet::Macro(macro_kind),
1333 self.add_typo_suggestion(err, suggestion, ident.span);
1335 let import_suggestions =
1336 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1339 &self.untracked.source_span,
1342 &import_suggestions,
1345 DiagnosticMode::Normal,
1349 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1350 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1351 err.span_note(ident.span, &msg);
1354 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1355 err.help("have you added the `#[macro_use]` on the module/import?");
1358 if ident.name == kw::Default
1359 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1360 && let Some(span) = self.opt_span(def_id)
1362 let source_map = self.session.source_map();
1363 let head_span = source_map.guess_head_span(span);
1364 if let Ok(head) = source_map.span_to_snippet(head_span) {
1365 err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect);
1369 "consider adding `#[derive(Default)]` to this enum",
1373 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1374 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1376 ScopeSet::All(ns, false),
1382 let desc = match binding.res() {
1383 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1384 "a function-like macro".to_string()
1386 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1387 format!("an attribute: `#[{}]`", ident)
1389 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1390 format!("a derive macro: `#[derive({})]`", ident)
1393 // Don't confuse the user with tool modules.
1396 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1397 "only a trait, without a derive macro".to_string()
1403 macro_kind.article(),
1404 macro_kind.descr_expected(),
1407 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1408 if !import.span.is_dummy() {
1411 &format!("`{}` is imported here, but it is {}", ident, desc),
1413 // Silence the 'unused import' warning we might get,
1414 // since this diagnostic already covers that import.
1415 self.record_use(ident, binding, false);
1419 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1425 pub(crate) fn add_typo_suggestion(
1427 err: &mut Diagnostic,
1428 suggestion: Option<TypoSuggestion>,
1431 let suggestion = match suggestion {
1432 None => return false,
1433 // We shouldn't suggest underscore.
1434 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1435 Some(suggestion) => suggestion,
1437 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1438 LOCAL_CRATE => self.opt_span(def_id),
1439 _ => Some(self.cstore().get_span_untracked(def_id, self.session)),
1441 if let Some(def_span) = def_span {
1442 if span.overlaps(def_span) {
1443 // Don't suggest typo suggestion for itself like in the following:
1444 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1445 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1448 // | ----------- `X` defined here
1450 // LL | const Y: X = X("ö");
1451 // | -------------^^^^^^- similarly named constant `Y` defined here
1453 // help: use struct literal syntax instead
1455 // LL | const Y: X = X {};
1457 // help: a constant with a similar name exists
1459 // LL | const Y: X = Y("ö");
1463 let prefix = match suggestion.target {
1464 SuggestionTarget::SimilarlyNamed => "similarly named ",
1465 SuggestionTarget::SingleItem => "",
1469 self.session.source_map().guess_head_span(def_span),
1471 "{}{} `{}` defined here",
1473 suggestion.res.descr(),
1474 suggestion.candidate,
1478 let msg = match suggestion.target {
1479 SuggestionTarget::SimilarlyNamed => format!(
1480 "{} {} with a similar name exists",
1481 suggestion.res.article(),
1482 suggestion.res.descr()
1484 SuggestionTarget::SingleItem => {
1485 format!("maybe you meant this {}", suggestion.res.descr())
1488 err.span_suggestion(span, &msg, suggestion.candidate, Applicability::MaybeIncorrect);
1492 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1494 if b.span.is_dummy() || !self.session.source_map().is_span_accessible(b.span) {
1495 // These already contain the "built-in" prefix or look bad with it.
1497 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1498 let (built_in, from) = if from_prelude {
1499 ("", " from prelude")
1500 } else if b.is_extern_crate()
1502 && self.session.opts.externs.get(ident.as_str()).is_some()
1504 ("", " passed with `--extern`")
1505 } else if add_built_in {
1511 let a = if built_in.is_empty() { res.article() } else { "a" };
1512 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1514 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1515 format!("the {thing} {introduced} here", thing = res.descr())
1519 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1520 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1521 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1522 // We have to print the span-less alternative first, otherwise formatting looks bad.
1523 (b2, b1, misc2, misc1, true)
1525 (b1, b2, misc1, misc2, false)
1528 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1529 err.span_label(ident.span, "ambiguous name");
1530 err.note(&format!("ambiguous because of {}", kind.descr()));
1532 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1533 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1534 let note_msg = format!("`{ident}` could{also} refer to {what}");
1536 let thing = b.res().descr();
1537 let mut help_msgs = Vec::new();
1538 if b.is_glob_import()
1539 && (kind == AmbiguityKind::GlobVsGlob
1540 || kind == AmbiguityKind::GlobVsExpanded
1541 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1543 help_msgs.push(format!(
1544 "consider adding an explicit import of `{ident}` to disambiguate"
1547 if b.is_extern_crate() && ident.span.rust_2018() {
1548 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1550 if misc == AmbiguityErrorMisc::SuggestCrate {
1552 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1553 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1555 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1558 err.span_note(b.span, ¬e_msg);
1559 for (i, help_msg) in help_msgs.iter().enumerate() {
1560 let or = if i == 0 { "" } else { "or " };
1561 err.help(&format!("{}{}", or, help_msg));
1565 could_refer_to(b1, misc1, "");
1566 could_refer_to(b2, misc2, " also");
1570 /// If the binding refers to a tuple struct constructor with fields,
1571 /// returns the span of its fields.
1572 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1573 if let NameBindingKind::Res(Res::Def(
1574 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1578 let def_id = self.parent(ctor_def_id);
1579 let fields = self.field_names.get(&def_id)?;
1580 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1585 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1586 let PrivacyError { ident, binding, .. } = *privacy_error;
1588 let res = binding.res();
1589 let ctor_fields_span = self.ctor_fields_span(binding);
1590 let plain_descr = res.descr().to_string();
1591 let nonimport_descr =
1592 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1593 let import_descr = nonimport_descr.clone() + " import";
1595 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1597 // Print the primary message.
1598 let descr = get_descr(binding);
1600 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1601 err.span_label(ident.span, &format!("private {}", descr));
1602 if let Some(span) = ctor_fields_span {
1603 err.span_label(span, "a constructor is private if any of the fields is private");
1606 // Print the whole import chain to make it easier to see what happens.
1607 let first_binding = binding;
1608 let mut next_binding = Some(binding);
1609 let mut next_ident = ident;
1610 while let Some(binding) = next_binding {
1611 let name = next_ident;
1612 next_binding = match binding.kind {
1613 _ if res == Res::Err => None,
1614 NameBindingKind::Import { binding, import, .. } => match import.kind {
1615 _ if binding.span.is_dummy() => None,
1616 ImportKind::Single { source, .. } => {
1617 next_ident = source;
1620 ImportKind::Glob { .. } | ImportKind::MacroUse | ImportKind::MacroExport => {
1623 ImportKind::ExternCrate { .. } => None,
1628 let first = ptr::eq(binding, first_binding);
1630 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1631 and_refers_to = if first { "" } else { "...and refers to " },
1632 item = get_descr(binding),
1633 which = if first { "" } else { " which" },
1634 dots = if next_binding.is_some() { "..." } else { "" },
1636 let def_span = self.session.source_map().guess_head_span(binding.span);
1637 let mut note_span = MultiSpan::from_span(def_span);
1638 if !first && binding.vis.is_public() {
1639 note_span.push_span_label(def_span, "consider importing it directly");
1641 err.span_note(note_span, &msg);
1647 pub(crate) fn find_similarly_named_module_or_crate(
1650 current_module: &Module<'a>,
1651 ) -> Option<Symbol> {
1652 let mut candidates = self
1655 .map(|(ident, _)| ident.name)
1659 .filter(|(_, module)| {
1660 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1662 .flat_map(|(_, module)| module.kind.name()),
1664 .filter(|c| !c.to_string().is_empty())
1665 .collect::<Vec<_>>();
1668 match find_best_match_for_name(&candidates, ident, None) {
1669 Some(sugg) if sugg == ident => None,
1674 pub(crate) fn report_path_resolution_error(
1677 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1678 parent_scope: &ParentScope<'a>,
1679 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1680 ignore_binding: Option<&'a NameBinding<'a>>,
1681 module: Option<ModuleOrUniformRoot<'a>>,
1684 ) -> (String, Option<Suggestion>) {
1685 let is_last = i == path.len() - 1;
1686 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1687 let module_res = match module {
1688 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1691 if module_res == self.graph_root.res() {
1692 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1693 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1695 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1696 if let Some(candidate) = candidates.get(0) {
1698 String::from("unresolved import"),
1700 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1701 String::from("a similar path exists"),
1702 Applicability::MaybeIncorrect,
1705 } else if self.session.edition() == Edition::Edition2015 {
1707 format!("maybe a missing crate `{ident}`?"),
1711 "consider adding `extern crate {ident}` to use the `{ident}` crate"
1713 Applicability::MaybeIncorrect,
1717 (format!("could not find `{ident}` in the crate root"), None)
1720 let parent = path[i - 1].ident.name;
1721 let parent = match parent {
1722 // ::foo is mounted at the crate root for 2015, and is the extern
1723 // prelude for 2018+
1724 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1725 "the list of imported crates".to_owned()
1727 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1728 _ => format!("`{parent}`"),
1731 let mut msg = format!("could not find `{}` in {}", ident, parent);
1732 if ns == TypeNS || ns == ValueNS {
1733 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1734 let binding = if let Some(module) = module {
1735 self.resolve_ident_in_module(
1743 } else if let Some(ribs) = ribs
1744 && let Some(TypeNS | ValueNS) = opt_ns
1746 match self.resolve_ident_in_lexical_scope(
1754 // we found a locally-imported or available item/module
1755 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1759 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1760 self.early_resolve_ident_in_lexical_scope(
1769 if let Some(binding) = binding {
1770 let mut found = |what| {
1772 "expected {}, found {} `{}` in {}",
1779 if binding.module().is_some() {
1782 match binding.res() {
1783 Res::Def(kind, id) => found(kind.descr(id)),
1784 _ => found(ns_to_try.descr()),
1790 } else if ident.name == kw::SelfUpper {
1791 ("`Self` is only available in impls, traits, and type definitions".to_string(), None)
1792 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1793 // Check whether the name refers to an item in the value namespace.
1794 let binding = if let Some(ribs) = ribs {
1795 self.resolve_ident_in_lexical_scope(
1806 let match_span = match binding {
1807 // Name matches a local variable. For example:
1810 // let Foo: &str = "";
1811 // println!("{}", Foo::Bar); // Name refers to local
1812 // // variable `Foo`.
1815 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1816 Some(*self.pat_span_map.get(&id).unwrap())
1818 // Name matches item from a local name binding
1819 // created by `use` declaration. For example:
1821 // pub Foo: &str = "";
1825 // println!("{}", Foo::Bar); // Name refers to local
1826 // // binding `Foo`.
1829 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1832 let suggestion = if let Some(span) = match_span {
1834 vec![(span, String::from(""))],
1835 format!("`{}` is defined here, but is not a type", ident),
1836 Applicability::MaybeIncorrect,
1842 (format!("use of undeclared type `{}`", ident), suggestion)
1844 let mut suggestion = None;
1845 if ident.name == sym::alloc {
1848 String::from("add `extern crate alloc` to use the `alloc` crate"),
1849 Applicability::MaybeIncorrect,
1853 suggestion = suggestion.or_else(|| {
1854 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1857 vec![(ident.span, sugg.to_string())],
1858 String::from("there is a crate or module with a similar name"),
1859 Applicability::MaybeIncorrect,
1864 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1869 impl<'a, 'b> ImportResolver<'a, 'b> {
1870 /// Adds suggestions for a path that cannot be resolved.
1871 pub(crate) fn make_path_suggestion(
1874 mut path: Vec<Segment>,
1875 parent_scope: &ParentScope<'b>,
1876 ) -> Option<(Vec<Segment>, Option<String>)> {
1877 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1879 match (path.get(0), path.get(1)) {
1880 // `{{root}}::ident::...` on both editions.
1881 // On 2015 `{{root}}` is usually added implicitly.
1882 (Some(fst), Some(snd))
1883 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1884 // `ident::...` on 2018.
1886 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1888 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1889 path.insert(0, Segment::from_ident(Ident::empty()));
1894 self.make_missing_self_suggestion(path.clone(), parent_scope)
1895 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
1896 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
1897 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
1900 /// Suggest a missing `self::` if that resolves to an correct module.
1904 /// LL | use foo::Bar;
1905 /// | ^^^ did you mean `self::foo`?
1907 fn make_missing_self_suggestion(
1909 mut path: Vec<Segment>,
1910 parent_scope: &ParentScope<'b>,
1911 ) -> Option<(Vec<Segment>, Option<String>)> {
1912 // Replace first ident with `self` and check if that is valid.
1913 path[0].ident.name = kw::SelfLower;
1914 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1915 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1916 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1919 /// Suggests a missing `crate::` if that resolves to an correct module.
1923 /// LL | use foo::Bar;
1924 /// | ^^^ did you mean `crate::foo`?
1926 fn make_missing_crate_suggestion(
1928 mut path: Vec<Segment>,
1929 parent_scope: &ParentScope<'b>,
1930 ) -> Option<(Vec<Segment>, Option<String>)> {
1931 // Replace first ident with `crate` and check if that is valid.
1932 path[0].ident.name = kw::Crate;
1933 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1934 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1935 if let PathResult::Module(..) = result {
1939 "`use` statements changed in Rust 2018; read more at \
1940 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1950 /// Suggests a missing `super::` if that resolves to an correct module.
1954 /// LL | use foo::Bar;
1955 /// | ^^^ did you mean `super::foo`?
1957 fn make_missing_super_suggestion(
1959 mut path: Vec<Segment>,
1960 parent_scope: &ParentScope<'b>,
1961 ) -> Option<(Vec<Segment>, Option<String>)> {
1962 // Replace first ident with `crate` and check if that is valid.
1963 path[0].ident.name = kw::Super;
1964 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1965 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1966 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1969 /// Suggests a missing external crate name if that resolves to an correct module.
1973 /// LL | use foobar::Baz;
1974 /// | ^^^^^^ did you mean `baz::foobar`?
1977 /// Used when importing a submodule of an external crate but missing that crate's
1978 /// name as the first part of path.
1979 fn make_external_crate_suggestion(
1981 mut path: Vec<Segment>,
1982 parent_scope: &ParentScope<'b>,
1983 ) -> Option<(Vec<Segment>, Option<String>)> {
1984 if path[1].ident.span.rust_2015() {
1988 // Sort extern crate names in *reverse* order to get
1989 // 1) some consistent ordering for emitted diagnostics, and
1990 // 2) `std` suggestions before `core` suggestions.
1991 let mut extern_crate_names =
1992 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
1993 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
1995 for name in extern_crate_names.into_iter() {
1996 // Replace first ident with a crate name and check if that is valid.
1997 path[0].ident.name = name;
1998 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2000 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2003 if let PathResult::Module(..) = result {
2004 return Some((path, None));
2011 /// Suggests importing a macro from the root of the crate rather than a module within
2015 /// help: a macro with this name exists at the root of the crate
2017 /// LL | use issue_59764::makro;
2018 /// | ^^^^^^^^^^^^^^^^^^
2020 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2021 /// at the root of the crate instead of the module where it is defined
2023 pub(crate) fn check_for_module_export_macro(
2025 import: &'b Import<'b>,
2026 module: ModuleOrUniformRoot<'b>,
2028 ) -> Option<(Option<Suggestion>, Option<String>)> {
2029 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2033 while let Some(parent) = crate_module.parent {
2034 crate_module = parent;
2037 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2038 // Don't make a suggestion if the import was already from the root of the
2043 let resolutions = self.r.resolutions(crate_module).borrow();
2044 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2045 let binding = resolution.borrow().binding()?;
2046 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2047 let module_name = crate_module.kind.name().unwrap();
2048 let import_snippet = match import.kind {
2049 ImportKind::Single { source, target, .. } if source != target => {
2050 format!("{} as {}", source, target)
2052 _ => format!("{}", ident),
2055 let mut corrections: Vec<(Span, String)> = Vec::new();
2056 if !import.is_nested() {
2057 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2058 // intermediate segments.
2059 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2061 // Find the binding span (and any trailing commas and spaces).
2062 // ie. `use a::b::{c, d, e};`
2064 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2070 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2071 found_closing_brace, binding_span
2074 let mut removal_span = binding_span;
2075 if found_closing_brace {
2076 // If the binding span ended with a closing brace, as in the below example:
2077 // ie. `use a::b::{c, d};`
2079 // Then expand the span of characters to remove to include the previous
2080 // binding's trailing comma.
2081 // ie. `use a::b::{c, d};`
2083 if let Some(previous_span) =
2084 extend_span_to_previous_binding(self.r.session, binding_span)
2086 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2087 removal_span = removal_span.with_lo(previous_span.lo());
2090 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2092 // Remove the `removal_span`.
2093 corrections.push((removal_span, "".to_string()));
2095 // Find the span after the crate name and if it has nested imports immediately
2096 // after the crate name already.
2097 // ie. `use a::b::{c, d};`
2099 // or `use a::{b, c, d}};`
2101 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2107 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2108 has_nested, after_crate_name
2111 let source_map = self.r.session.source_map();
2113 // Add the import to the start, with a `{` if required.
2114 let start_point = source_map.start_point(after_crate_name);
2115 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2119 // In this case, `start_snippet` must equal '{'.
2120 format!("{}{}, ", start_snippet, import_snippet)
2122 // In this case, add a `{`, then the moved import, then whatever
2123 // was there before.
2124 format!("{{{}, {}", import_snippet, start_snippet)
2129 // Add a `};` to the end if nested, matching the `{` added at the start.
2131 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2135 let suggestion = Some((
2137 String::from("a macro with this name exists at the root of the crate"),
2138 Applicability::MaybeIncorrect,
2140 Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \
2141 at the root of the crate instead of the module where it is defined"
2149 /// Given a `binding_span` of a binding within a use statement:
2151 /// ```ignore (illustrative)
2152 /// use foo::{a, b, c};
2156 /// then return the span until the next binding or the end of the statement:
2158 /// ```ignore (illustrative)
2159 /// use foo::{a, b, c};
2162 fn find_span_of_binding_until_next_binding(
2167 let source_map = sess.source_map();
2169 // Find the span of everything after the binding.
2170 // ie. `a, e};` or `a};`
2171 let binding_until_end = binding_span.with_hi(use_span.hi());
2173 // Find everything after the binding but not including the binding.
2174 // ie. `, e};` or `};`
2175 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2177 // Keep characters in the span until we encounter something that isn't a comma or
2181 // Also note whether a closing brace character was encountered. If there
2182 // was, then later go backwards to remove any trailing commas that are left.
2183 let mut found_closing_brace = false;
2184 let after_binding_until_next_binding =
2185 source_map.span_take_while(after_binding_until_end, |&ch| {
2187 found_closing_brace = true;
2189 ch == ' ' || ch == ','
2192 // Combine the two spans.
2193 // ie. `a, ` or `a`.
2195 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2196 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2198 (found_closing_brace, span)
2201 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2204 /// ```ignore (illustrative)
2205 /// use foo::a::{a, b, c};
2206 /// // ^^--- binding span
2208 /// // returned span
2210 /// use foo::{a, b, c};
2211 /// // --- binding span
2213 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2214 let source_map = sess.source_map();
2216 // `prev_source` will contain all of the source that came before the span.
2217 // Then split based on a command and take the first (ie. closest to our span)
2218 // snippet. In the example, this is a space.
2219 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2221 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2222 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2223 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2227 let prev_comma = prev_comma.first().unwrap();
2228 let prev_starting_brace = prev_starting_brace.first().unwrap();
2230 // If the amount of source code before the comma is greater than
2231 // the amount of source code before the starting brace then we've only
2232 // got one item in the nested item (eg. `issue_52891::{self}`).
2233 if prev_comma.len() > prev_starting_brace.len() {
2237 Some(binding_span.with_lo(BytePos(
2238 // Take away the number of bytes for the characters we've found and an
2239 // extra for the comma.
2240 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2244 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2245 /// it is a nested use tree.
2247 /// ```ignore (illustrative)
2248 /// use foo::a::{b, c};
2249 /// // ^^^^^^^^^^ -- false
2251 /// use foo::{a, b, c};
2252 /// // ^^^^^^^^^^ -- true
2254 /// use foo::{a, b::{c, d}};
2255 /// // ^^^^^^^^^^^^^^^ -- true
2257 fn find_span_immediately_after_crate_name(
2259 module_name: Symbol,
2263 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2264 module_name, use_span
2266 let source_map = sess.source_map();
2268 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2269 let mut num_colons = 0;
2270 // Find second colon.. `use issue_59764:`
2271 let until_second_colon = source_map.span_take_while(use_span, |c| {
2275 !matches!(c, ':' if num_colons == 2)
2277 // Find everything after the second colon.. `foo::{baz, makro};`
2278 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2280 let mut found_a_non_whitespace_character = false;
2281 // Find the first non-whitespace character in `from_second_colon`.. `f`
2282 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2283 if found_a_non_whitespace_character {
2286 if !c.is_whitespace() {
2287 found_a_non_whitespace_character = true;
2292 // Find the first `{` in from_second_colon.. `foo::{`
2293 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2295 (next_left_bracket == after_second_colon, from_second_colon)
2298 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2299 /// independent options.
2305 /// Whether an existing place with an `use` item was found.
2311 /// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
2312 enum DiagnosticMode {
2314 /// The binding is part of a pattern
2316 /// The binding is part of a use statement
2320 pub(crate) fn import_candidates(
2322 source_span: &IndexVec<LocalDefId, Span>,
2323 err: &mut Diagnostic,
2324 // This is `None` if all placement locations are inside expansions
2325 use_placement_span: Option<Span>,
2326 candidates: &[ImportSuggestion],
2336 DiagnosticMode::Import,
2341 /// When an entity with a given name is not available in scope, we search for
2342 /// entities with that name in all crates. This method allows outputting the
2343 /// results of this search in a programmer-friendly way
2346 source_span: &IndexVec<LocalDefId, Span>,
2347 err: &mut Diagnostic,
2348 // This is `None` if all placement locations are inside expansions
2349 use_placement_span: Option<Span>,
2350 candidates: &[ImportSuggestion],
2352 found_use: FoundUse,
2353 mode: DiagnosticMode,
2356 if candidates.is_empty() {
2360 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2362 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2365 candidates.iter().for_each(|c| {
2366 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2367 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2370 // we want consistent results across executions, but candidates are produced
2371 // by iterating through a hash map, so make sure they are ordered:
2372 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2373 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2374 let core_path_strings =
2375 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2376 path_strings.extend(core_path_strings);
2377 path_strings.dedup_by(|a, b| a.0 == b.0);
2380 if !accessible_path_strings.is_empty() {
2381 let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2382 ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2384 ("one of these", "items", String::new())
2387 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2388 let mut msg = if let DiagnosticMode::Pattern = mode {
2390 "if you meant to match on {}{}{}, use the full path in the pattern",
2394 format!("consider importing {} {}{}", determiner, kind, instead)
2397 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2401 if let Some(span) = use_placement_span {
2402 let add_use = match mode {
2403 DiagnosticMode::Pattern => {
2404 err.span_suggestions(
2407 accessible_path_strings.into_iter().map(|a| a.0),
2408 Applicability::MaybeIncorrect,
2412 DiagnosticMode::Import => "",
2413 DiagnosticMode::Normal => "use ",
2415 for candidate in &mut accessible_path_strings {
2416 // produce an additional newline to separate the new use statement
2417 // from the directly following item.
2418 let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" };
2419 candidate.0 = format!("{}{};\n{}", add_use, &candidate.0, additional_newline);
2422 err.span_suggestions(
2425 accessible_path_strings.into_iter().map(|a| a.0),
2426 Applicability::MaybeIncorrect,
2428 if let [first, .., last] = &path[..] {
2429 let sp = first.ident.span.until(last.ident.span);
2430 if sp.can_be_used_for_suggestions() {
2431 err.span_suggestion_verbose(
2433 &format!("if you import `{}`, refer to it directly", last.ident),
2435 Applicability::Unspecified,
2442 for candidate in accessible_path_strings {
2444 msg.push_str(&candidate.0);
2449 } else if !matches!(mode, DiagnosticMode::Import) {
2450 assert!(!inaccessible_path_strings.is_empty());
2452 let prefix = if let DiagnosticMode::Pattern = mode {
2453 "you might have meant to match on "
2457 if inaccessible_path_strings.len() == 1 {
2458 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2460 "{}{} `{}`{} exists but is inaccessible",
2464 if let DiagnosticMode::Pattern = mode { ", which" } else { "" }
2467 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2468 let span = source_span[local_def_id];
2469 let span = session.source_map().guess_head_span(span);
2470 let mut multi_span = MultiSpan::from_span(span);
2471 multi_span.push_span_label(span, "not accessible");
2472 err.span_note(multi_span, &msg);
2476 if let Some(note) = (*note).as_deref() {
2480 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2481 let descr = if inaccessible_path_strings
2484 .all(|(_, descr, _, _)| descr == descr_first)
2491 if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) };
2493 let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr);
2494 let mut has_colon = false;
2496 let mut spans = Vec::new();
2497 for (name, _, def_id, _) in &inaccessible_path_strings {
2498 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2499 let span = source_span[local_def_id];
2500 let span = session.source_map().guess_head_span(span);
2501 spans.push((name, span));
2512 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2513 for (name, span) in spans {
2514 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2517 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2521 err.span_note(multi_span, &msg);
2527 struct UsePlacementFinder {
2528 target_module: NodeId,
2529 first_legal_span: Option<Span>,
2530 first_use_span: Option<Span>,
2533 impl UsePlacementFinder {
2534 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2536 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2537 finder.visit_crate(krate);
2538 if let Some(use_span) = finder.first_use_span {
2539 (Some(use_span), FoundUse::Yes)
2541 (finder.first_legal_span, FoundUse::No)
2546 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2547 fn visit_crate(&mut self, c: &Crate) {
2548 if self.target_module == CRATE_NODE_ID {
2549 let inject = c.spans.inject_use_span;
2550 if is_span_suitable_for_use_injection(inject) {
2551 self.first_legal_span = Some(inject);
2553 self.first_use_span = search_for_any_use_in_items(&c.items);
2556 visit::walk_crate(self, c);
2560 fn visit_item(&mut self, item: &'tcx ast::Item) {
2561 if self.target_module == item.id {
2562 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2563 let inject = mod_spans.inject_use_span;
2564 if is_span_suitable_for_use_injection(inject) {
2565 self.first_legal_span = Some(inject);
2567 self.first_use_span = search_for_any_use_in_items(items);
2571 visit::walk_item(self, item);
2576 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2578 if let ItemKind::Use(..) = item.kind {
2579 if is_span_suitable_for_use_injection(item.span) {
2580 return Some(item.span.shrink_to_lo());
2587 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2588 // don't suggest placing a use before the prelude
2589 // import or other generated ones
2593 /// Convert the given number into the corresponding ordinal
2594 pub(crate) fn ordinalize(v: usize) -> String {
2595 let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2601 format!("{v}{suffix}")