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;
9 pluralize, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
11 use rustc_errors::{struct_span_err, SuggestionStyle};
12 use rustc_feature::BUILTIN_ATTRIBUTES;
13 use rustc_hir::def::Namespace::{self, *};
14 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
15 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
16 use rustc_hir::PrimTy;
17 use rustc_index::vec::IndexVec;
18 use rustc_middle::bug;
19 use rustc_middle::ty::DefIdTree;
20 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
21 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
22 use rustc_session::lint::BuiltinLintDiagnostics;
23 use rustc_session::Session;
24 use rustc_span::edition::Edition;
25 use rustc_span::hygiene::MacroKind;
26 use rustc_span::lev_distance::find_best_match_for_name;
27 use rustc_span::source_map::SourceMap;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{BytePos, Span, SyntaxContext};
30 use thin_vec::ThinVec;
32 use crate::errors as errs;
33 use crate::imports::{Import, ImportKind, ImportResolver};
34 use crate::late::{PatternSource, Rib};
35 use crate::path_names_to_string;
36 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
37 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
38 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
39 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
40 use crate::{Segment, UseError};
45 type Res = def::Res<ast::NodeId>;
47 /// A vector of spans and replacements, a message and applicability.
48 pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
50 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
51 /// similarly named label and whether or not it is reachable.
52 pub(crate) type LabelSuggestion = (Ident, bool);
55 pub(crate) enum SuggestionTarget {
56 /// The target has a similar name as the name used by the programmer (probably a typo)
58 /// The target is the only valid item that can be used in the corresponding context
63 pub(crate) struct TypoSuggestion {
64 pub candidate: Symbol,
65 /// The source location where the name is defined; None if the name is not defined
66 /// in source e.g. primitives
67 pub span: Option<Span>,
69 pub target: SuggestionTarget,
73 pub(crate) fn typo_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
75 candidate: ident.name,
76 span: Some(ident.span),
78 target: SuggestionTarget::SimilarlyNamed,
81 pub(crate) fn typo_from_name(candidate: Symbol, res: Res) -> TypoSuggestion {
82 Self { candidate, span: None, res, target: SuggestionTarget::SimilarlyNamed }
84 pub(crate) fn single_item_from_ident(ident: Ident, res: Res) -> TypoSuggestion {
86 candidate: ident.name,
87 span: Some(ident.span),
89 target: SuggestionTarget::SingleItem,
94 /// A free importable items suggested in case of resolution failure.
95 #[derive(Debug, Clone)]
96 pub(crate) struct ImportSuggestion {
97 pub did: Option<DefId>,
98 pub descr: &'static str,
100 pub accessible: bool,
101 /// An extra note that should be issued if this item is suggested
102 pub note: Option<String>,
105 /// Adjust the impl span so that just the `impl` keyword is taken by removing
106 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
107 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
109 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
110 /// parser. If you need to use this function or something similar, please consider updating the
111 /// `source_map` functions and this function to something more robust.
112 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
113 let impl_span = sm.span_until_char(impl_span, '<');
114 sm.span_until_whitespace(impl_span)
117 impl<'a> Resolver<'a> {
118 pub(crate) fn report_errors(&mut self, krate: &Crate) {
119 self.report_with_use_injections(krate);
121 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
122 let msg = "macro-expanded `macro_export` macros from the current crate \
123 cannot be referred to by absolute paths";
124 self.lint_buffer.buffer_lint_with_diagnostic(
125 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
129 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
133 for ambiguity_error in &self.ambiguity_errors {
134 self.report_ambiguity_error(ambiguity_error);
137 let mut reported_spans = FxHashSet::default();
138 for error in &self.privacy_errors {
139 if reported_spans.insert(error.dedup_span) {
140 self.report_privacy_error(error);
145 fn report_with_use_injections(&mut self, krate: &Crate) {
146 for UseError { mut err, candidates, def_id, instead, suggestion, path, is_call } in
147 self.use_injections.drain(..)
149 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
150 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
155 if !candidates.is_empty() {
158 &self.untracked.source_span,
162 if instead { Instead::Yes } else { Instead::No },
164 DiagnosticMode::Normal,
169 } else if let Some((span, msg, sugg, appl)) = suggestion {
170 err.span_suggestion_verbose(span, msg, sugg, appl);
172 } else if let [segment] = path.as_slice() && is_call {
173 err.stash(segment.ident.span, rustc_errors::StashKey::CallIntoMethod);
180 pub(crate) fn report_conflict<'b>(
185 new_binding: &NameBinding<'b>,
186 old_binding: &NameBinding<'b>,
188 // Error on the second of two conflicting names
189 if old_binding.span.lo() > new_binding.span.lo() {
190 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
193 let container = match parent.kind {
194 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
195 ModuleKind::Block => "block",
198 let old_noun = match old_binding.is_import_user_facing() {
200 false => "definition",
203 let new_participle = match new_binding.is_import_user_facing() {
209 (ident.name, self.session.source_map().guess_head_span(new_binding.span));
211 if let Some(s) = self.name_already_seen.get(&name) {
217 let old_kind = match (ns, old_binding.module()) {
218 (ValueNS, _) => "value",
219 (MacroNS, _) => "macro",
220 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
221 (TypeNS, Some(module)) if module.is_normal() => "module",
222 (TypeNS, Some(module)) if module.is_trait() => "trait",
223 (TypeNS, _) => "type",
226 let msg = format!("the name `{}` is defined multiple times", name);
228 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
229 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
230 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
231 true => struct_span_err!(self.session, span, E0254, "{}", msg),
232 false => struct_span_err!(self.session, span, E0260, "{}", msg),
234 _ => match (old_binding.is_import_user_facing(), new_binding.is_import_user_facing()) {
235 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
236 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
237 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
242 "`{}` must be defined only once in the {} namespace of this {}",
248 err.span_label(span, format!("`{}` re{} here", name, new_participle));
249 if !old_binding.span.is_dummy() && old_binding.span != span {
251 self.session.source_map().guess_head_span(old_binding.span),
252 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
256 // See https://github.com/rust-lang/rust/issues/32354
257 use NameBindingKind::Import;
258 let can_suggest = |binding: &NameBinding<'_>, import: &self::Import<'_>| {
259 !binding.span.is_dummy()
260 && !matches!(import.kind, ImportKind::MacroUse | ImportKind::MacroExport)
262 let import = match (&new_binding.kind, &old_binding.kind) {
263 // If there are two imports where one or both have attributes then prefer removing the
264 // import without attributes.
265 (Import { import: new, .. }, Import { import: old, .. })
267 (new.has_attributes || old.has_attributes)
268 && can_suggest(old_binding, old)
269 && can_suggest(new_binding, new)
272 if old.has_attributes {
273 Some((new, new_binding.span, true))
275 Some((old, old_binding.span, true))
278 // Otherwise prioritize the new binding.
279 (Import { import, .. }, other) if can_suggest(new_binding, import) => {
280 Some((import, new_binding.span, other.is_import()))
282 (other, Import { import, .. }) if can_suggest(old_binding, import) => {
283 Some((import, old_binding.span, other.is_import()))
288 // Check if the target of the use for both bindings is the same.
289 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
290 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
292 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
293 // Only suggest removing an import if both bindings are to the same def, if both spans
294 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
295 // been introduced by an item.
296 let should_remove_import = duplicate
298 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
301 Some((import, span, true)) if should_remove_import && import.is_nested() => {
302 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
304 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
305 // Simple case - remove the entire import. Due to the above match arm, this can
306 // only be a single use so just remove it entirely.
307 err.tool_only_span_suggestion(
308 import.use_span_with_attributes,
309 "remove unnecessary import",
311 Applicability::MaybeIncorrect,
314 Some((import, span, _)) => {
315 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
321 self.name_already_seen.insert(name, span);
324 /// This function adds a suggestion to change the binding name of a new import that conflicts
325 /// with an existing import.
327 /// ```text,ignore (diagnostic)
328 /// help: you can use `as` to change the binding name of the import
330 /// LL | use foo::bar as other_bar;
331 /// | ^^^^^^^^^^^^^^^^^^^^^
333 fn add_suggestion_for_rename_of_use(
335 err: &mut Diagnostic,
340 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
341 format!("Other{}", name)
343 format!("other_{}", name)
346 let mut suggestion = None;
348 ImportKind::Single { type_ns_only: true, .. } => {
349 suggestion = Some(format!("self as {}", suggested_name))
351 ImportKind::Single { source, .. } => {
353 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
355 if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
356 if pos <= snippet.len() {
357 suggestion = Some(format!(
361 if snippet.ends_with(';') { ";" } else { "" }
367 ImportKind::ExternCrate { source, target, .. } => {
368 suggestion = Some(format!(
369 "extern crate {} as {};",
370 source.unwrap_or(target.name),
377 let rename_msg = "you can use `as` to change the binding name of the import";
378 if let Some(suggestion) = suggestion {
383 Applicability::MaybeIncorrect,
386 err.span_label(binding_span, rename_msg);
390 /// This function adds a suggestion to remove an unnecessary binding from an import that is
391 /// nested. In the following example, this function will be invoked to remove the `a` binding
392 /// in the second use statement:
394 /// ```ignore (diagnostic)
395 /// use issue_52891::a;
396 /// use issue_52891::{d, a, e};
399 /// The following suggestion will be added:
401 /// ```ignore (diagnostic)
402 /// use issue_52891::{d, a, e};
403 /// ^-- help: remove unnecessary import
406 /// If the nested use contains only one import then the suggestion will remove the entire
409 /// It is expected that the provided import is nested - this isn't checked by the
410 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
411 /// as characters expected by span manipulations won't be present.
412 fn add_suggestion_for_duplicate_nested_use(
414 err: &mut Diagnostic,
418 assert!(import.is_nested());
419 let message = "remove unnecessary import";
421 // Two examples will be used to illustrate the span manipulations we're doing:
423 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
424 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
425 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
426 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
428 let (found_closing_brace, span) =
429 find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
431 // If there was a closing brace then identify the span to remove any trailing commas from
433 if found_closing_brace {
434 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
435 err.tool_only_span_suggestion(span, message, "", Applicability::MaybeIncorrect);
437 // Remove the entire line if we cannot extend the span back, this indicates an
438 // `issue_52891::{self}` case.
440 import.use_span_with_attributes,
443 Applicability::MaybeIncorrect,
450 err.span_suggestion(span, message, "", Applicability::MachineApplicable);
453 pub(crate) fn lint_if_path_starts_with_module(
455 finalize: Option<Finalize>,
457 second_binding: Option<&NameBinding<'_>>,
459 let Some(Finalize { node_id, root_span, .. }) = finalize else {
463 let first_name = match path.get(0) {
464 // In the 2018 edition this lint is a hard error, so nothing to do
465 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
469 // We're only interested in `use` paths which should start with
470 // `{{root}}` currently.
471 if first_name != kw::PathRoot {
476 // If this import looks like `crate::...` it's already good
477 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
478 // Otherwise go below to see if it's an extern crate
480 // If the path has length one (and it's `PathRoot` most likely)
481 // then we don't know whether we're gonna be importing a crate or an
482 // item in our crate. Defer this lint to elsewhere
486 // If the first element of our path was actually resolved to an
487 // `ExternCrate` (also used for `crate::...`) then no need to issue a
488 // warning, this looks all good!
489 if let Some(binding) = second_binding {
490 if let NameBindingKind::Import { import, .. } = binding.kind {
491 // Careful: we still want to rewrite paths from renamed extern crates.
492 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
498 let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
499 self.lint_buffer.buffer_lint_with_diagnostic(
500 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
503 "absolute paths must start with `self`, `super`, \
504 `crate`, or an external crate name in the 2018 edition",
509 pub(crate) fn add_module_candidates(
512 names: &mut Vec<TypoSuggestion>,
513 filter_fn: &impl Fn(Res) -> bool,
514 ctxt: Option<SyntaxContext>,
516 for (key, resolution) in self.resolutions(module).borrow().iter() {
517 if let Some(binding) = resolution.borrow().binding {
518 let res = binding.res();
519 if filter_fn(res) && ctxt.map_or(true, |ctxt| ctxt == key.ident.span.ctxt()) {
520 names.push(TypoSuggestion::typo_from_ident(key.ident, res));
526 /// Combines an error with provided span and emits it.
528 /// This takes the error provided, combines it with the span and any additional spans inside the
529 /// error and emits it.
530 pub(crate) fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
531 self.into_struct_error(span, resolution_error).emit();
534 pub(crate) fn into_struct_error(
537 resolution_error: ResolutionError<'a>,
538 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
539 match resolution_error {
540 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
541 let mut err = struct_span_err!(
545 "can't use generic parameters from outer function",
547 err.span_label(span, "use of generic parameter from outer function");
549 let sm = self.session.source_map();
550 let def_id = match outer_res {
551 Res::SelfTyParam { .. } => {
552 err.span_label(span, "can't use `Self` here");
555 Res::SelfTyAlias { alias_to: def_id, .. } => {
556 if let Some(impl_span) = self.opt_span(def_id) {
558 reduce_impl_span_to_impl_keyword(sm, impl_span),
559 "`Self` type implicitly declared here, by this `impl`",
562 err.span_label(span, "use a type here instead");
565 Res::Def(DefKind::TyParam, def_id) => {
566 if let Some(span) = self.opt_span(def_id) {
567 err.span_label(span, "type parameter from outer function");
571 Res::Def(DefKind::ConstParam, def_id) => {
572 if let Some(span) = self.opt_span(def_id) {
573 err.span_label(span, "const parameter from outer function");
579 "GenericParamsFromOuterFunction should only be used with \
580 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
586 if let HasGenericParams::Yes(span) = has_generic_params {
587 // Try to retrieve the span of the function signature and generate a new
588 // message with a local type or const parameter.
589 let sugg_msg = "try using a local generic parameter instead";
590 let name = self.opt_name(def_id).unwrap_or(sym::T);
591 let (span, snippet) = if span.is_empty() {
592 let snippet = format!("<{}>", name);
595 let span = sm.span_through_char(span, '<').shrink_to_hi();
596 let snippet = format!("{}, ", name);
599 // Suggest the modification to the user
600 err.span_suggestion(span, sugg_msg, snippet, Applicability::MaybeIncorrect);
605 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
607 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
608 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
609 self.session.create_err(errs::MethodNotMemberOfTrait {
613 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
619 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
620 self.session.create_err(errs::TypeNotMemberOfTrait {
624 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
630 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
631 self.session.create_err(errs::ConstNotMemberOfTrait {
635 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
641 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
642 let BindingError { name, target, origin, could_be_path } = binding_error;
644 let target_sp = target.iter().copied().collect::<Vec<_>>();
645 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
647 let msp = MultiSpan::from_spans(target_sp.clone());
648 let mut err = struct_span_err!(
652 "variable `{}` is not bound in all patterns",
655 for sp in target_sp {
656 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
658 for sp in origin_sp {
659 err.span_label(sp, "variable not in all patterns");
662 let import_suggestions = self.lookup_import_candidates(
663 Ident::with_dummy_span(name),
666 &|res: Res| match res {
668 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
669 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
671 | DefKind::AssocConst,
678 if import_suggestions.is_empty() {
679 let help_msg = format!(
680 "if you meant to match on a variant or a `const` item, consider \
681 making the path in the pattern qualified: `path::to::ModOrType::{}`",
684 err.span_help(span, &help_msg);
688 &self.untracked.source_span,
694 DiagnosticMode::Pattern,
701 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
702 self.session.create_err(errs::VariableBoundWithDifferentMode {
708 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
710 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
711 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
713 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
714 ResolutionError::UndeclaredLabel { name, suggestion } => {
715 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
717 // A reachable label with a similar name exists.
718 Some((ident, true)) => (
720 Some(errs::LabelWithSimilarNameReachable(ident.span)),
721 Some(errs::TryUsingSimilarlyNamedLabel {
723 ident_name: ident.name,
728 // An unreachable label with a similar name exists.
729 Some((ident, false)) => (
731 Some(errs::UnreachableLabelWithSimilarNameExists {
732 ident_span: ident.span,
735 // No similarly-named labels exist.
736 None => ((None, None), None),
738 self.session.create_err(errs::UndeclaredLabel {
742 sub_reachable_suggestion,
746 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
747 // None of the suggestions below would help with a case like `use self`.
748 let (suggestion, mpart_suggestion) = if root {
751 // use foo::bar::self -> foo::bar
752 // use foo::bar::self as abc -> foo::bar as abc
753 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
755 // use foo::bar::self -> foo::bar::{self}
756 // use foo::bar::self as abc -> foo::bar::{self as abc}
757 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
758 multipart_start: span_with_rename.shrink_to_lo(),
759 multipart_end: span_with_rename.shrink_to_hi(),
761 (Some(suggestion), Some(mpart_suggestion))
763 self.session.create_err(errs::SelfImportsOnlyAllowedWithin {
769 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
770 self.session.create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
772 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
773 self.session.create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
775 ResolutionError::FailedToResolve { label, suggestion } => {
777 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
778 err.span_label(span, label);
780 if let Some((suggestions, msg, applicability)) = suggestion {
781 if suggestions.is_empty() {
785 err.multipart_suggestion(&msg, suggestions, applicability);
790 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
791 self.session.create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
793 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, suggestion, current) => {
795 // ^^^ given this Span
796 // ------- get this Span to have an applicable suggestion
799 // only do this if the const and usage of the non-constant value are on the same line
800 // the further the two are apart, the higher the chance of the suggestion being wrong
805 .span_extend_to_prev_str(ident.span, current, true, false);
807 let ((with, with_label), without) = match sp {
808 Some(sp) if !self.session.source_map().is_multiline(sp) => {
809 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
811 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
816 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
822 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
823 ident_span: ident.span,
829 self.session.create_err(errs::AttemptToUseNonConstantValueInConstant {
836 ResolutionError::BindingShadowsSomethingUnacceptable {
842 shadowed_binding_span,
843 } => self.session.create_err(errs::BindingShadowsSomethingUnacceptable {
848 sub_suggestion: match (shadowing_binding, shadowed_binding) {
850 PatternSource::Match,
851 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
852 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
855 shadowed_binding_span,
859 ResolutionError::ForwardDeclaredGenericParam => {
860 self.session.create_err(errs::ForwardDeclaredGenericParam { span })
862 ResolutionError::ParamInTyOfConstParam(name) => {
863 self.session.create_err(errs::ParamInTyOfConstParam { span, name })
865 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
866 self.session.create_err(errs::ParamInNonTrivialAnonConst {
869 sub_is_type: if is_type {
870 errs::ParamInNonTrivialAnonConstIsType::AType
872 errs::ParamInNonTrivialAnonConstIsType::NotAType { name }
877 .then_some(errs::ParamInNonTrivialAnonConstHelp),
880 ResolutionError::SelfInGenericParamDefault => {
881 self.session.create_err(errs::SelfInGenericParamDefault { span })
883 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
884 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
886 // A reachable label with a similar name exists.
887 Some((ident, true)) => (
889 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
890 Some(errs::UnreachableLabelSubSuggestion {
892 // intentionally taking 'ident.name' instead of 'ident' itself, as this
893 // could be used in suggestion context
894 ident_name: ident.name,
899 // An unreachable label with a similar name exists.
900 Some((ident, false)) => (
902 Some(errs::UnreachableLabelSubLabelUnreachable {
903 ident_span: ident.span,
906 // No similarly-named labels exist.
907 None => ((None, None), None),
909 self.session.create_err(errs::UnreachableLabel {
914 sub_suggestion_label,
915 sub_unreachable_label,
918 ResolutionError::TraitImplMismatch {
925 let mut err = self.session.struct_span_err_with_code(
928 "item `{}` is an associated {}, which doesn't match its trait `{}`",
929 name, kind, trait_path,
933 err.span_label(span, "does not match trait");
934 err.span_label(trait_item_span, "item in trait");
937 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
939 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
940 ResolutionError::InvalidAsmSym => self.session.create_err(errs::InvalidAsmSym { span }),
944 pub(crate) fn report_vis_error(
946 vis_resolution_error: VisResolutionError<'_>,
947 ) -> ErrorGuaranteed {
948 match vis_resolution_error {
949 VisResolutionError::Relative2018(span, path) => {
950 self.session.create_err(errs::Relative2018 {
952 path_span: path.span,
953 // intentionally converting to String, as the text would also be used as
954 // in suggestion context
955 path_str: pprust::path_to_string(&path),
958 VisResolutionError::AncestorOnly(span) => {
959 self.session.create_err(errs::AncestorOnly(span))
961 VisResolutionError::FailedToResolve(span, label, suggestion) => {
962 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
964 VisResolutionError::ExpectedFound(span, path_str, res) => {
965 self.session.create_err(errs::ExpectedFound { span, res, path_str })
967 VisResolutionError::Indeterminate(span) => {
968 self.session.create_err(errs::Indeterminate(span))
970 VisResolutionError::ModuleOnly(span) => self.session.create_err(errs::ModuleOnly(span)),
975 /// Lookup typo candidate in scope for a macro or import.
976 fn early_lookup_typo_candidate(
978 scope_set: ScopeSet<'a>,
979 parent_scope: &ParentScope<'a>,
981 filter_fn: &impl Fn(Res) -> bool,
982 ) -> Option<TypoSuggestion> {
983 let mut suggestions = Vec::new();
984 let ctxt = ident.span.ctxt();
985 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
987 Scope::DeriveHelpers(expn_id) => {
988 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
995 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
999 Scope::DeriveHelpersCompat => {
1000 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1002 for derive in parent_scope.derives {
1003 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1004 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1006 Some(MacroKind::Derive),
1014 .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1020 Scope::MacroRules(macro_rules_scope) => {
1021 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1022 let res = macro_rules_binding.binding.res();
1024 suggestions.push(TypoSuggestion::typo_from_ident(
1025 macro_rules_binding.ident,
1031 Scope::CrateRoot => {
1032 let root_ident = Ident::new(kw::PathRoot, ident.span);
1033 let root_module = this.resolve_crate_root(root_ident);
1034 this.add_module_candidates(root_module, &mut suggestions, filter_fn, None);
1036 Scope::Module(module) => {
1037 this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1039 Scope::MacroUsePrelude => {
1040 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1042 let res = binding.res();
1043 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1047 Scope::BuiltinAttrs => {
1048 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1053 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1057 Scope::ExternPrelude => {
1058 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1059 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1060 filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res))
1063 Scope::ToolPrelude => {
1064 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1066 this.registered_tools
1068 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1071 Scope::StdLibPrelude => {
1072 if let Some(prelude) = this.prelude {
1073 let mut tmp_suggestions = Vec::new();
1074 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1078 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1082 Scope::BuiltinTypes => {
1083 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1084 let res = Res::PrimTy(*prim_ty);
1086 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1094 // Make sure error reporting is deterministic.
1095 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1097 match find_best_match_for_name(
1098 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1102 Some(found) if found != ident.name => {
1103 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1109 fn lookup_import_candidates_from_module<FilterFn>(
1111 lookup_ident: Ident,
1112 namespace: Namespace,
1113 parent_scope: &ParentScope<'a>,
1114 start_module: Module<'a>,
1116 filter_fn: FilterFn,
1117 ) -> Vec<ImportSuggestion>
1119 FilterFn: Fn(Res) -> bool,
1121 let mut candidates = Vec::new();
1122 let mut seen_modules = FxHashSet::default();
1123 let mut worklist = vec![(start_module, ThinVec::<ast::PathSegment>::new(), true)];
1124 let mut worklist_via_import = vec![];
1126 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1127 None => worklist_via_import.pop(),
1130 let in_module_is_extern = !in_module.def_id().is_local();
1131 // We have to visit module children in deterministic order to avoid
1132 // instabilities in reported imports (#43552).
1133 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1134 // avoid non-importable candidates
1135 if !name_binding.is_importable() {
1139 let child_accessible =
1140 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1142 // do not venture inside inaccessible items of other crates
1143 if in_module_is_extern && !child_accessible {
1147 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1149 // There is an assumption elsewhere that paths of variants are in the enum's
1150 // declaration and not imported. With this assumption, the variant component is
1151 // chopped and the rest of the path is assumed to be the enum's own path. For
1152 // errors where a variant is used as the type instead of the enum, this causes
1153 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1154 if via_import && name_binding.is_possibly_imported_variant() {
1158 // #90113: Do not count an inaccessible reexported item as a candidate.
1159 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1160 if this.is_accessible_from(binding.vis, parent_scope.module)
1161 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1167 // collect results based on the filter function
1168 // avoid suggesting anything from the same module in which we are resolving
1169 // avoid suggesting anything with a hygienic name
1170 if ident.name == lookup_ident.name
1172 && !ptr::eq(in_module, parent_scope.module)
1173 && !ident.span.normalize_to_macros_2_0().from_expansion()
1175 let res = name_binding.res();
1178 let mut segms = path_segments.clone();
1179 if lookup_ident.span.rust_2018() {
1180 // crate-local absolute paths start with `crate::` in edition 2018
1181 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1182 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1185 segms.push(ast::PathSegment::from_ident(ident));
1186 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1187 let did = match res {
1188 Res::Def(DefKind::Ctor(..), did) => this.opt_parent(did),
1189 _ => res.opt_def_id(),
1192 if child_accessible {
1193 // Remove invisible match if exists
1194 if let Some(idx) = candidates
1196 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1198 candidates.remove(idx);
1202 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1203 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1204 // a note about editions
1205 let note = if let Some(did) = did {
1206 let requires_note = !did.is_local()
1207 && this.cstore().item_attrs_untracked(did, this.session).any(
1209 if attr.has_name(sym::rustc_diagnostic_item) {
1210 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1212 .contains(&attr.value_str())
1219 requires_note.then(|| {
1221 "'{}' is included in the prelude starting in Edition 2021",
1222 path_names_to_string(&path)
1229 candidates.push(ImportSuggestion {
1233 accessible: child_accessible,
1240 // collect submodules to explore
1241 if let Some(module) = name_binding.module() {
1243 let mut path_segments = path_segments.clone();
1244 path_segments.push(ast::PathSegment::from_ident(ident));
1246 let is_extern_crate_that_also_appears_in_prelude =
1247 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1249 if !is_extern_crate_that_also_appears_in_prelude {
1250 // add the module to the lookup
1251 if seen_modules.insert(module.def_id()) {
1252 if via_import { &mut worklist_via_import } else { &mut worklist }
1253 .push((module, path_segments, child_accessible));
1260 // If only some candidates are accessible, take just them
1261 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1262 candidates.retain(|x| x.accessible)
1268 /// When name resolution fails, this method can be used to look up candidate
1269 /// entities with the expected name. It allows filtering them using the
1270 /// supplied predicate (which should be used to only accept the types of
1271 /// definitions expected, e.g., traits). The lookup spans across all crates.
1273 /// N.B., the method does not look into imports, but this is not a problem,
1274 /// since we report the definitions (thus, the de-aliased imports).
1275 pub(crate) fn lookup_import_candidates<FilterFn>(
1277 lookup_ident: Ident,
1278 namespace: Namespace,
1279 parent_scope: &ParentScope<'a>,
1280 filter_fn: FilterFn,
1281 ) -> Vec<ImportSuggestion>
1283 FilterFn: Fn(Res) -> bool,
1285 let mut suggestions = self.lookup_import_candidates_from_module(
1290 Ident::with_dummy_span(kw::Crate),
1294 if lookup_ident.span.rust_2018() {
1295 let extern_prelude_names = self.extern_prelude.clone();
1296 for (ident, _) in extern_prelude_names.into_iter() {
1297 if ident.span.from_expansion() {
1298 // Idents are adjusted to the root context before being
1299 // resolved in the extern prelude, so reporting this to the
1300 // user is no help. This skips the injected
1301 // `extern crate std` in the 2018 edition, which would
1302 // otherwise cause duplicate suggestions.
1305 let crate_id = self.crate_loader().maybe_process_path_extern(ident.name);
1306 if let Some(crate_id) = crate_id {
1307 let crate_root = self.expect_module(crate_id.as_def_id());
1308 suggestions.extend(self.lookup_import_candidates_from_module(
1323 pub(crate) fn unresolved_macro_suggestions(
1325 err: &mut Diagnostic,
1326 macro_kind: MacroKind,
1327 parent_scope: &ParentScope<'a>,
1330 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1331 let suggestion = self.early_lookup_typo_candidate(
1332 ScopeSet::Macro(macro_kind),
1337 self.add_typo_suggestion(err, suggestion, ident.span);
1339 let import_suggestions =
1340 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1343 &self.untracked.source_span,
1346 &import_suggestions,
1349 DiagnosticMode::Normal,
1354 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1355 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1356 err.span_note(ident.span, &msg);
1359 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1360 err.help("have you added the `#[macro_use]` on the module/import?");
1363 if ident.name == kw::Default
1364 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1365 && let Some(span) = self.opt_span(def_id)
1367 let source_map = self.session.source_map();
1368 let head_span = source_map.guess_head_span(span);
1369 if let Ok(head) = source_map.span_to_snippet(head_span) {
1370 err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect);
1374 "consider adding `#[derive(Default)]` to this enum",
1378 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1379 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1381 ScopeSet::All(ns, false),
1387 let desc = match binding.res() {
1388 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1389 "a function-like macro".to_string()
1391 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1392 format!("an attribute: `#[{}]`", ident)
1394 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1395 format!("a derive macro: `#[derive({})]`", ident)
1398 // Don't confuse the user with tool modules.
1401 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1402 "only a trait, without a derive macro".to_string()
1408 macro_kind.article(),
1409 macro_kind.descr_expected(),
1412 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1413 if !import.span.is_dummy() {
1416 &format!("`{}` is imported here, but it is {}", ident, desc),
1418 // Silence the 'unused import' warning we might get,
1419 // since this diagnostic already covers that import.
1420 self.record_use(ident, binding, false);
1424 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1430 pub(crate) fn add_typo_suggestion(
1432 err: &mut Diagnostic,
1433 suggestion: Option<TypoSuggestion>,
1436 let suggestion = match suggestion {
1437 None => return false,
1438 // We shouldn't suggest underscore.
1439 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1440 Some(suggestion) => suggestion,
1442 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1443 LOCAL_CRATE => self.opt_span(def_id),
1444 _ => Some(self.cstore().get_span_untracked(def_id, self.session)),
1446 if let Some(def_span) = def_span {
1447 if span.overlaps(def_span) {
1448 // Don't suggest typo suggestion for itself like in the following:
1449 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1450 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1453 // | ----------- `X` defined here
1455 // LL | const Y: X = X("ö");
1456 // | -------------^^^^^^- similarly named constant `Y` defined here
1458 // help: use struct literal syntax instead
1460 // LL | const Y: X = X {};
1462 // help: a constant with a similar name exists
1464 // LL | const Y: X = Y("ö");
1468 let prefix = match suggestion.target {
1469 SuggestionTarget::SimilarlyNamed => "similarly named ",
1470 SuggestionTarget::SingleItem => "",
1474 self.session.source_map().guess_head_span(def_span),
1476 "{}{} `{}` defined here",
1478 suggestion.res.descr(),
1479 suggestion.candidate,
1483 let msg = match suggestion.target {
1484 SuggestionTarget::SimilarlyNamed => format!(
1485 "{} {} with a similar name exists",
1486 suggestion.res.article(),
1487 suggestion.res.descr()
1489 SuggestionTarget::SingleItem => {
1490 format!("maybe you meant this {}", suggestion.res.descr())
1493 err.span_suggestion(span, &msg, suggestion.candidate, Applicability::MaybeIncorrect);
1497 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1499 if b.span.is_dummy() || !self.session.source_map().is_span_accessible(b.span) {
1500 // These already contain the "built-in" prefix or look bad with it.
1502 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1503 let (built_in, from) = if from_prelude {
1504 ("", " from prelude")
1505 } else if b.is_extern_crate()
1507 && self.session.opts.externs.get(ident.as_str()).is_some()
1509 ("", " passed with `--extern`")
1510 } else if add_built_in {
1516 let a = if built_in.is_empty() { res.article() } else { "a" };
1517 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1519 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1520 format!("the {thing} {introduced} here", thing = res.descr())
1524 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1525 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1526 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1527 // We have to print the span-less alternative first, otherwise formatting looks bad.
1528 (b2, b1, misc2, misc1, true)
1530 (b1, b2, misc1, misc2, false)
1533 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1534 err.span_label(ident.span, "ambiguous name");
1535 err.note(&format!("ambiguous because of {}", kind.descr()));
1537 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1538 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1539 let note_msg = format!("`{ident}` could{also} refer to {what}");
1541 let thing = b.res().descr();
1542 let mut help_msgs = Vec::new();
1543 if b.is_glob_import()
1544 && (kind == AmbiguityKind::GlobVsGlob
1545 || kind == AmbiguityKind::GlobVsExpanded
1546 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1548 help_msgs.push(format!(
1549 "consider adding an explicit import of `{ident}` to disambiguate"
1552 if b.is_extern_crate() && ident.span.rust_2018() {
1553 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1555 if misc == AmbiguityErrorMisc::SuggestCrate {
1557 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1558 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1560 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1563 err.span_note(b.span, ¬e_msg);
1564 for (i, help_msg) in help_msgs.iter().enumerate() {
1565 let or = if i == 0 { "" } else { "or " };
1566 err.help(&format!("{}{}", or, help_msg));
1570 could_refer_to(b1, misc1, "");
1571 could_refer_to(b2, misc2, " also");
1575 /// If the binding refers to a tuple struct constructor with fields,
1576 /// returns the span of its fields.
1577 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1578 if let NameBindingKind::Res(Res::Def(
1579 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1583 let def_id = self.parent(ctor_def_id);
1584 let fields = self.field_names.get(&def_id)?;
1585 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1590 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1591 let PrivacyError { ident, binding, .. } = *privacy_error;
1593 let res = binding.res();
1594 let ctor_fields_span = self.ctor_fields_span(binding);
1595 let plain_descr = res.descr().to_string();
1596 let nonimport_descr =
1597 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1598 let import_descr = nonimport_descr.clone() + " import";
1600 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1602 // Print the primary message.
1603 let descr = get_descr(binding);
1605 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1606 err.span_label(ident.span, &format!("private {}", descr));
1607 if let Some(span) = ctor_fields_span {
1608 err.span_label(span, "a constructor is private if any of the fields is private");
1609 if let Res::Def(_, d) = res && let Some(fields) = self.field_visibility_spans.get(&d) {
1610 err.multipart_suggestion_verbose(
1612 "consider making the field{} publicly accessible",
1613 pluralize!(fields.len())
1615 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
1616 Applicability::MaybeIncorrect,
1621 // Print the whole import chain to make it easier to see what happens.
1622 let first_binding = binding;
1623 let mut next_binding = Some(binding);
1624 let mut next_ident = ident;
1625 while let Some(binding) = next_binding {
1626 let name = next_ident;
1627 next_binding = match binding.kind {
1628 _ if res == Res::Err => None,
1629 NameBindingKind::Import { binding, import, .. } => match import.kind {
1630 _ if binding.span.is_dummy() => None,
1631 ImportKind::Single { source, .. } => {
1632 next_ident = source;
1635 ImportKind::Glob { .. } | ImportKind::MacroUse | ImportKind::MacroExport => {
1638 ImportKind::ExternCrate { .. } => None,
1643 let first = ptr::eq(binding, first_binding);
1645 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1646 and_refers_to = if first { "" } else { "...and refers to " },
1647 item = get_descr(binding),
1648 which = if first { "" } else { " which" },
1649 dots = if next_binding.is_some() { "..." } else { "" },
1651 let def_span = self.session.source_map().guess_head_span(binding.span);
1652 let mut note_span = MultiSpan::from_span(def_span);
1653 if !first && binding.vis.is_public() {
1654 note_span.push_span_label(def_span, "consider importing it directly");
1656 err.span_note(note_span, &msg);
1662 pub(crate) fn find_similarly_named_module_or_crate(
1665 current_module: &Module<'a>,
1666 ) -> Option<Symbol> {
1667 let mut candidates = self
1670 .map(|(ident, _)| ident.name)
1674 .filter(|(_, module)| {
1675 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1677 .flat_map(|(_, module)| module.kind.name()),
1679 .filter(|c| !c.to_string().is_empty())
1680 .collect::<Vec<_>>();
1683 match find_best_match_for_name(&candidates, ident, None) {
1684 Some(sugg) if sugg == ident => None,
1689 pub(crate) fn report_path_resolution_error(
1692 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1693 parent_scope: &ParentScope<'a>,
1694 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1695 ignore_binding: Option<&'a NameBinding<'a>>,
1696 module: Option<ModuleOrUniformRoot<'a>>,
1699 ) -> (String, Option<Suggestion>) {
1700 let is_last = i == path.len() - 1;
1701 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1702 let module_res = match module {
1703 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1706 if module_res == self.graph_root.res() {
1707 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1708 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1710 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1711 if let Some(candidate) = candidates.get(0) {
1713 String::from("unresolved import"),
1715 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1716 String::from("a similar path exists"),
1717 Applicability::MaybeIncorrect,
1720 } else if self.session.edition() == Edition::Edition2015 {
1722 format!("maybe a missing crate `{ident}`?"),
1726 "consider adding `extern crate {ident}` to use the `{ident}` crate"
1728 Applicability::MaybeIncorrect,
1732 (format!("could not find `{ident}` in the crate root"), None)
1735 let parent = path[i - 1].ident.name;
1736 let parent = match parent {
1737 // ::foo is mounted at the crate root for 2015, and is the extern
1738 // prelude for 2018+
1739 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1740 "the list of imported crates".to_owned()
1742 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1743 _ => format!("`{parent}`"),
1746 let mut msg = format!("could not find `{}` in {}", ident, parent);
1747 if ns == TypeNS || ns == ValueNS {
1748 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1749 let binding = if let Some(module) = module {
1750 self.resolve_ident_in_module(
1758 } else if let Some(ribs) = ribs
1759 && let Some(TypeNS | ValueNS) = opt_ns
1761 match self.resolve_ident_in_lexical_scope(
1769 // we found a locally-imported or available item/module
1770 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1774 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1775 self.early_resolve_ident_in_lexical_scope(
1784 if let Some(binding) = binding {
1785 let mut found = |what| {
1787 "expected {}, found {} `{}` in {}",
1794 if binding.module().is_some() {
1797 match binding.res() {
1798 Res::Def(kind, id) => found(kind.descr(id)),
1799 _ => found(ns_to_try.descr()),
1805 } else if ident.name == kw::SelfUpper {
1806 ("`Self` is only available in impls, traits, and type definitions".to_string(), None)
1807 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1808 // Check whether the name refers to an item in the value namespace.
1809 let binding = if let Some(ribs) = ribs {
1810 self.resolve_ident_in_lexical_scope(
1821 let match_span = match binding {
1822 // Name matches a local variable. For example:
1825 // let Foo: &str = "";
1826 // println!("{}", Foo::Bar); // Name refers to local
1827 // // variable `Foo`.
1830 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1831 Some(*self.pat_span_map.get(&id).unwrap())
1833 // Name matches item from a local name binding
1834 // created by `use` declaration. For example:
1836 // pub Foo: &str = "";
1840 // println!("{}", Foo::Bar); // Name refers to local
1841 // // binding `Foo`.
1844 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1847 let suggestion = if let Some(span) = match_span {
1849 vec![(span, String::from(""))],
1850 format!("`{}` is defined here, but is not a type", ident),
1851 Applicability::MaybeIncorrect,
1857 (format!("use of undeclared type `{}`", ident), suggestion)
1859 let mut suggestion = None;
1860 if ident.name == sym::alloc {
1863 String::from("add `extern crate alloc` to use the `alloc` crate"),
1864 Applicability::MaybeIncorrect,
1868 suggestion = suggestion.or_else(|| {
1869 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1872 vec![(ident.span, sugg.to_string())],
1873 String::from("there is a crate or module with a similar name"),
1874 Applicability::MaybeIncorrect,
1879 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1884 impl<'a, 'b> ImportResolver<'a, 'b> {
1885 /// Adds suggestions for a path that cannot be resolved.
1886 pub(crate) fn make_path_suggestion(
1889 mut path: Vec<Segment>,
1890 parent_scope: &ParentScope<'b>,
1891 ) -> Option<(Vec<Segment>, Option<String>)> {
1892 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1894 match (path.get(0), path.get(1)) {
1895 // `{{root}}::ident::...` on both editions.
1896 // On 2015 `{{root}}` is usually added implicitly.
1897 (Some(fst), Some(snd))
1898 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1899 // `ident::...` on 2018.
1901 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1903 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1904 path.insert(0, Segment::from_ident(Ident::empty()));
1909 self.make_missing_self_suggestion(path.clone(), parent_scope)
1910 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
1911 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
1912 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
1915 /// Suggest a missing `self::` if that resolves to an correct module.
1919 /// LL | use foo::Bar;
1920 /// | ^^^ did you mean `self::foo`?
1922 fn make_missing_self_suggestion(
1924 mut path: Vec<Segment>,
1925 parent_scope: &ParentScope<'b>,
1926 ) -> Option<(Vec<Segment>, Option<String>)> {
1927 // Replace first ident with `self` and check if that is valid.
1928 path[0].ident.name = kw::SelfLower;
1929 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1930 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1931 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1934 /// Suggests a missing `crate::` if that resolves to an correct module.
1938 /// LL | use foo::Bar;
1939 /// | ^^^ did you mean `crate::foo`?
1941 fn make_missing_crate_suggestion(
1943 mut path: Vec<Segment>,
1944 parent_scope: &ParentScope<'b>,
1945 ) -> Option<(Vec<Segment>, Option<String>)> {
1946 // Replace first ident with `crate` and check if that is valid.
1947 path[0].ident.name = kw::Crate;
1948 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1949 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1950 if let PathResult::Module(..) = result {
1954 "`use` statements changed in Rust 2018; read more at \
1955 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1965 /// Suggests a missing `super::` if that resolves to an correct module.
1969 /// LL | use foo::Bar;
1970 /// | ^^^ did you mean `super::foo`?
1972 fn make_missing_super_suggestion(
1974 mut path: Vec<Segment>,
1975 parent_scope: &ParentScope<'b>,
1976 ) -> Option<(Vec<Segment>, Option<String>)> {
1977 // Replace first ident with `crate` and check if that is valid.
1978 path[0].ident.name = kw::Super;
1979 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1980 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1981 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1984 /// Suggests a missing external crate name if that resolves to an correct module.
1988 /// LL | use foobar::Baz;
1989 /// | ^^^^^^ did you mean `baz::foobar`?
1992 /// Used when importing a submodule of an external crate but missing that crate's
1993 /// name as the first part of path.
1994 fn make_external_crate_suggestion(
1996 mut path: Vec<Segment>,
1997 parent_scope: &ParentScope<'b>,
1998 ) -> Option<(Vec<Segment>, Option<String>)> {
1999 if path[1].ident.span.rust_2015() {
2003 // Sort extern crate names in *reverse* order to get
2004 // 1) some consistent ordering for emitted diagnostics, and
2005 // 2) `std` suggestions before `core` suggestions.
2006 let mut extern_crate_names =
2007 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2008 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2010 for name in extern_crate_names.into_iter() {
2011 // Replace first ident with a crate name and check if that is valid.
2012 path[0].ident.name = name;
2013 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2015 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2018 if let PathResult::Module(..) = result {
2019 return Some((path, None));
2026 /// Suggests importing a macro from the root of the crate rather than a module within
2030 /// help: a macro with this name exists at the root of the crate
2032 /// LL | use issue_59764::makro;
2033 /// | ^^^^^^^^^^^^^^^^^^
2035 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2036 /// at the root of the crate instead of the module where it is defined
2038 pub(crate) fn check_for_module_export_macro(
2040 import: &'b Import<'b>,
2041 module: ModuleOrUniformRoot<'b>,
2043 ) -> Option<(Option<Suggestion>, Option<String>)> {
2044 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2048 while let Some(parent) = crate_module.parent {
2049 crate_module = parent;
2052 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2053 // Don't make a suggestion if the import was already from the root of the
2058 let resolutions = self.r.resolutions(crate_module).borrow();
2059 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2060 let binding = resolution.borrow().binding()?;
2061 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2062 let module_name = crate_module.kind.name().unwrap();
2063 let import_snippet = match import.kind {
2064 ImportKind::Single { source, target, .. } if source != target => {
2065 format!("{} as {}", source, target)
2067 _ => format!("{}", ident),
2070 let mut corrections: Vec<(Span, String)> = Vec::new();
2071 if !import.is_nested() {
2072 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2073 // intermediate segments.
2074 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2076 // Find the binding span (and any trailing commas and spaces).
2077 // ie. `use a::b::{c, d, e};`
2079 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2085 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2086 found_closing_brace, binding_span
2089 let mut removal_span = binding_span;
2090 if found_closing_brace {
2091 // If the binding span ended with a closing brace, as in the below example:
2092 // ie. `use a::b::{c, d};`
2094 // Then expand the span of characters to remove to include the previous
2095 // binding's trailing comma.
2096 // ie. `use a::b::{c, d};`
2098 if let Some(previous_span) =
2099 extend_span_to_previous_binding(self.r.session, binding_span)
2101 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2102 removal_span = removal_span.with_lo(previous_span.lo());
2105 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2107 // Remove the `removal_span`.
2108 corrections.push((removal_span, "".to_string()));
2110 // Find the span after the crate name and if it has nested imports immediately
2111 // after the crate name already.
2112 // ie. `use a::b::{c, d};`
2114 // or `use a::{b, c, d}};`
2116 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2122 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2123 has_nested, after_crate_name
2126 let source_map = self.r.session.source_map();
2128 // Add the import to the start, with a `{` if required.
2129 let start_point = source_map.start_point(after_crate_name);
2130 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2134 // In this case, `start_snippet` must equal '{'.
2135 format!("{}{}, ", start_snippet, import_snippet)
2137 // In this case, add a `{`, then the moved import, then whatever
2138 // was there before.
2139 format!("{{{}, {}", import_snippet, start_snippet)
2144 // Add a `};` to the end if nested, matching the `{` added at the start.
2146 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2150 let suggestion = Some((
2152 String::from("a macro with this name exists at the root of the crate"),
2153 Applicability::MaybeIncorrect,
2155 Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \
2156 at the root of the crate instead of the module where it is defined"
2164 /// Given a `binding_span` of a binding within a use statement:
2166 /// ```ignore (illustrative)
2167 /// use foo::{a, b, c};
2171 /// then return the span until the next binding or the end of the statement:
2173 /// ```ignore (illustrative)
2174 /// use foo::{a, b, c};
2177 fn find_span_of_binding_until_next_binding(
2182 let source_map = sess.source_map();
2184 // Find the span of everything after the binding.
2185 // ie. `a, e};` or `a};`
2186 let binding_until_end = binding_span.with_hi(use_span.hi());
2188 // Find everything after the binding but not including the binding.
2189 // ie. `, e};` or `};`
2190 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2192 // Keep characters in the span until we encounter something that isn't a comma or
2196 // Also note whether a closing brace character was encountered. If there
2197 // was, then later go backwards to remove any trailing commas that are left.
2198 let mut found_closing_brace = false;
2199 let after_binding_until_next_binding =
2200 source_map.span_take_while(after_binding_until_end, |&ch| {
2202 found_closing_brace = true;
2204 ch == ' ' || ch == ','
2207 // Combine the two spans.
2208 // ie. `a, ` or `a`.
2210 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2211 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2213 (found_closing_brace, span)
2216 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2219 /// ```ignore (illustrative)
2220 /// use foo::a::{a, b, c};
2221 /// // ^^--- binding span
2223 /// // returned span
2225 /// use foo::{a, b, c};
2226 /// // --- binding span
2228 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2229 let source_map = sess.source_map();
2231 // `prev_source` will contain all of the source that came before the span.
2232 // Then split based on a command and take the first (ie. closest to our span)
2233 // snippet. In the example, this is a space.
2234 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2236 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2237 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2238 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2242 let prev_comma = prev_comma.first().unwrap();
2243 let prev_starting_brace = prev_starting_brace.first().unwrap();
2245 // If the amount of source code before the comma is greater than
2246 // the amount of source code before the starting brace then we've only
2247 // got one item in the nested item (eg. `issue_52891::{self}`).
2248 if prev_comma.len() > prev_starting_brace.len() {
2252 Some(binding_span.with_lo(BytePos(
2253 // Take away the number of bytes for the characters we've found and an
2254 // extra for the comma.
2255 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2259 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2260 /// it is a nested use tree.
2262 /// ```ignore (illustrative)
2263 /// use foo::a::{b, c};
2264 /// // ^^^^^^^^^^ -- false
2266 /// use foo::{a, b, c};
2267 /// // ^^^^^^^^^^ -- true
2269 /// use foo::{a, b::{c, d}};
2270 /// // ^^^^^^^^^^^^^^^ -- true
2272 fn find_span_immediately_after_crate_name(
2274 module_name: Symbol,
2278 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2279 module_name, use_span
2281 let source_map = sess.source_map();
2283 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2284 let mut num_colons = 0;
2285 // Find second colon.. `use issue_59764:`
2286 let until_second_colon = source_map.span_take_while(use_span, |c| {
2290 !matches!(c, ':' if num_colons == 2)
2292 // Find everything after the second colon.. `foo::{baz, makro};`
2293 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2295 let mut found_a_non_whitespace_character = false;
2296 // Find the first non-whitespace character in `from_second_colon`.. `f`
2297 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2298 if found_a_non_whitespace_character {
2301 if !c.is_whitespace() {
2302 found_a_non_whitespace_character = true;
2307 // Find the first `{` in from_second_colon.. `foo::{`
2308 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2310 (next_left_bracket == after_second_colon, from_second_colon)
2313 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2314 /// independent options.
2320 /// Whether an existing place with an `use` item was found.
2326 /// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
2327 pub(crate) enum DiagnosticMode {
2329 /// The binding is part of a pattern
2331 /// The binding is part of a use statement
2335 pub(crate) fn import_candidates(
2337 source_span: &IndexVec<LocalDefId, Span>,
2338 err: &mut Diagnostic,
2339 // This is `None` if all placement locations are inside expansions
2340 use_placement_span: Option<Span>,
2341 candidates: &[ImportSuggestion],
2342 mode: DiagnosticMode,
2359 /// When an entity with a given name is not available in scope, we search for
2360 /// entities with that name in all crates. This method allows outputting the
2361 /// results of this search in a programmer-friendly way
2364 source_span: &IndexVec<LocalDefId, Span>,
2365 err: &mut Diagnostic,
2366 // This is `None` if all placement locations are inside expansions
2367 use_placement_span: Option<Span>,
2368 candidates: &[ImportSuggestion],
2370 found_use: FoundUse,
2371 mode: DiagnosticMode,
2375 if candidates.is_empty() {
2379 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2381 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2384 candidates.iter().for_each(|c| {
2385 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2386 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2389 // we want consistent results across executions, but candidates are produced
2390 // by iterating through a hash map, so make sure they are ordered:
2391 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2392 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2393 let core_path_strings =
2394 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2395 path_strings.extend(core_path_strings);
2396 path_strings.dedup_by(|a, b| a.0 == b.0);
2399 if !accessible_path_strings.is_empty() {
2400 let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2401 ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2403 ("one of these", "items", String::new())
2406 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2407 let mut msg = if let DiagnosticMode::Pattern = mode {
2409 "if you meant to match on {}{}{}, use the full path in the pattern",
2413 format!("consider importing {} {}{}", determiner, kind, instead)
2416 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2420 if let Some(span) = use_placement_span {
2421 let (add_use, trailing) = match mode {
2422 DiagnosticMode::Pattern => {
2423 err.span_suggestions(
2426 accessible_path_strings.into_iter().map(|a| a.0),
2427 Applicability::MaybeIncorrect,
2431 DiagnosticMode::Import => ("", ""),
2432 DiagnosticMode::Normal => ("use ", ";\n"),
2434 for candidate in &mut accessible_path_strings {
2435 // produce an additional newline to separate the new use statement
2436 // from the directly following item.
2437 let additional_newline = if let FoundUse::No = found_use && let DiagnosticMode::Normal = mode { "\n" } else { "" };
2439 format!("{add_use}{}{append}{trailing}{additional_newline}", &candidate.0);
2442 err.span_suggestions_with_style(
2445 accessible_path_strings.into_iter().map(|a| a.0),
2446 Applicability::MaybeIncorrect,
2447 SuggestionStyle::ShowAlways,
2449 if let [first, .., last] = &path[..] {
2450 let sp = first.ident.span.until(last.ident.span);
2451 if sp.can_be_used_for_suggestions() {
2452 err.span_suggestion_verbose(
2454 &format!("if you import `{}`, refer to it directly", last.ident),
2456 Applicability::Unspecified,
2463 for candidate in accessible_path_strings {
2465 msg.push_str(&candidate.0);
2470 } else if !matches!(mode, DiagnosticMode::Import) {
2471 assert!(!inaccessible_path_strings.is_empty());
2473 let prefix = if let DiagnosticMode::Pattern = mode {
2474 "you might have meant to match on "
2478 if inaccessible_path_strings.len() == 1 {
2479 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2481 "{}{} `{}`{} exists but is inaccessible",
2485 if let DiagnosticMode::Pattern = mode { ", which" } else { "" }
2488 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2489 let span = source_span[local_def_id];
2490 let span = session.source_map().guess_head_span(span);
2491 let mut multi_span = MultiSpan::from_span(span);
2492 multi_span.push_span_label(span, "not accessible");
2493 err.span_note(multi_span, &msg);
2497 if let Some(note) = (*note).as_deref() {
2501 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2502 let descr = if inaccessible_path_strings
2505 .all(|(_, descr, _, _)| descr == descr_first)
2512 if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) };
2514 let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr);
2515 let mut has_colon = false;
2517 let mut spans = Vec::new();
2518 for (name, _, def_id, _) in &inaccessible_path_strings {
2519 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2520 let span = source_span[local_def_id];
2521 let span = session.source_map().guess_head_span(span);
2522 spans.push((name, span));
2533 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2534 for (name, span) in spans {
2535 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2538 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2542 err.span_note(multi_span, &msg);
2548 struct UsePlacementFinder {
2549 target_module: NodeId,
2550 first_legal_span: Option<Span>,
2551 first_use_span: Option<Span>,
2554 impl UsePlacementFinder {
2555 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2557 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2558 finder.visit_crate(krate);
2559 if let Some(use_span) = finder.first_use_span {
2560 (Some(use_span), FoundUse::Yes)
2562 (finder.first_legal_span, FoundUse::No)
2567 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2568 fn visit_crate(&mut self, c: &Crate) {
2569 if self.target_module == CRATE_NODE_ID {
2570 let inject = c.spans.inject_use_span;
2571 if is_span_suitable_for_use_injection(inject) {
2572 self.first_legal_span = Some(inject);
2574 self.first_use_span = search_for_any_use_in_items(&c.items);
2577 visit::walk_crate(self, c);
2581 fn visit_item(&mut self, item: &'tcx ast::Item) {
2582 if self.target_module == item.id {
2583 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2584 let inject = mod_spans.inject_use_span;
2585 if is_span_suitable_for_use_injection(inject) {
2586 self.first_legal_span = Some(inject);
2588 self.first_use_span = search_for_any_use_in_items(items);
2592 visit::walk_item(self, item);
2597 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2599 if let ItemKind::Use(..) = item.kind {
2600 if is_span_suitable_for_use_injection(item.span) {
2601 return Some(item.span.shrink_to_lo());
2608 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2609 // don't suggest placing a use before the prelude
2610 // import or other generated ones
2614 /// Convert the given number into the corresponding ordinal
2615 pub(crate) fn ordinalize(v: usize) -> String {
2616 let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2622 format!("{v}{suffix}")