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.is_rust_2015() && self.session.is_rust_2015() => {
471 // We're only interested in `use` paths which should start with
472 // `{{root}}` currently.
473 if first_name != kw::PathRoot {
478 // If this import looks like `crate::...` it's already good
479 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
480 // Otherwise go below to see if it's an extern crate
482 // If the path has length one (and it's `PathRoot` most likely)
483 // then we don't know whether we're gonna be importing a crate or an
484 // item in our crate. Defer this lint to elsewhere
488 // If the first element of our path was actually resolved to an
489 // `ExternCrate` (also used for `crate::...`) then no need to issue a
490 // warning, this looks all good!
491 if let Some(binding) = second_binding {
492 if let NameBindingKind::Import { import, .. } = binding.kind {
493 // Careful: we still want to rewrite paths from renamed extern crates.
494 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
500 let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
501 self.lint_buffer.buffer_lint_with_diagnostic(
502 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
505 "absolute paths must start with `self`, `super`, \
506 `crate`, or an external crate name in the 2018 edition",
511 pub(crate) fn add_module_candidates(
514 names: &mut Vec<TypoSuggestion>,
515 filter_fn: &impl Fn(Res) -> bool,
516 ctxt: Option<SyntaxContext>,
518 for (key, resolution) in self.resolutions(module).borrow().iter() {
519 if let Some(binding) = resolution.borrow().binding {
520 let res = binding.res();
521 if filter_fn(res) && ctxt.map_or(true, |ctxt| ctxt == key.ident.span.ctxt()) {
522 names.push(TypoSuggestion::typo_from_ident(key.ident, res));
528 /// Combines an error with provided span and emits it.
530 /// This takes the error provided, combines it with the span and any additional spans inside the
531 /// error and emits it.
532 pub(crate) fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
533 self.into_struct_error(span, resolution_error).emit();
536 pub(crate) fn into_struct_error(
539 resolution_error: ResolutionError<'a>,
540 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
541 match resolution_error {
542 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
543 let mut err = struct_span_err!(
547 "can't use generic parameters from outer function",
549 err.span_label(span, "use of generic parameter from outer function");
551 let sm = self.session.source_map();
552 let def_id = match outer_res {
553 Res::SelfTyParam { .. } => {
554 err.span_label(span, "can't use `Self` here");
557 Res::SelfTyAlias { alias_to: def_id, .. } => {
558 if let Some(impl_span) = self.opt_span(def_id) {
560 reduce_impl_span_to_impl_keyword(sm, impl_span),
561 "`Self` type implicitly declared here, by this `impl`",
564 err.span_label(span, "use a type here instead");
567 Res::Def(DefKind::TyParam, def_id) => {
568 if let Some(span) = self.opt_span(def_id) {
569 err.span_label(span, "type parameter from outer function");
573 Res::Def(DefKind::ConstParam, def_id) => {
574 if let Some(span) = self.opt_span(def_id) {
575 err.span_label(span, "const parameter from outer function");
581 "GenericParamsFromOuterFunction should only be used with \
582 Res::SelfTyParam, Res::SelfTyAlias, DefKind::TyParam or \
588 if let HasGenericParams::Yes(span) = has_generic_params {
589 // Try to retrieve the span of the function signature and generate a new
590 // message with a local type or const parameter.
591 let sugg_msg = "try using a local generic parameter instead";
592 let name = self.opt_name(def_id).unwrap_or(sym::T);
593 let (span, snippet) = if span.is_empty() {
594 let snippet = format!("<{}>", name);
597 let span = sm.span_through_char(span, '<').shrink_to_hi();
598 let snippet = format!("{}, ", name);
601 // Suggest the modification to the user
602 err.span_suggestion(span, sugg_msg, snippet, Applicability::MaybeIncorrect);
607 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => self
609 .create_err(errs::NameAlreadyUsedInParameterList { span, first_use_span, name }),
610 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
611 self.session.create_err(errs::MethodNotMemberOfTrait {
615 sub: candidate.map(|c| errs::AssociatedFnWithSimilarNameExists {
621 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
622 self.session.create_err(errs::TypeNotMemberOfTrait {
626 sub: candidate.map(|c| errs::AssociatedTypeWithSimilarNameExists {
632 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
633 self.session.create_err(errs::ConstNotMemberOfTrait {
637 sub: candidate.map(|c| errs::AssociatedConstWithSimilarNameExists {
643 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
644 let BindingError { name, target, origin, could_be_path } = binding_error;
646 let target_sp = target.iter().copied().collect::<Vec<_>>();
647 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
649 let msp = MultiSpan::from_spans(target_sp.clone());
650 let mut err = struct_span_err!(
654 "variable `{}` is not bound in all patterns",
657 for sp in target_sp {
658 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
660 for sp in origin_sp {
661 err.span_label(sp, "variable not in all patterns");
664 let import_suggestions = self.lookup_import_candidates(
665 Ident::with_dummy_span(name),
668 &|res: Res| match res {
670 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
671 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
673 | DefKind::AssocConst,
680 if import_suggestions.is_empty() {
681 let help_msg = format!(
682 "if you meant to match on a variant or a `const` item, consider \
683 making the path in the pattern qualified: `path::to::ModOrType::{}`",
686 err.span_help(span, &help_msg);
690 &self.untracked.source_span,
696 DiagnosticMode::Pattern,
703 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
704 self.session.create_err(errs::VariableBoundWithDifferentMode {
710 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => self
712 .create_err(errs::IdentifierBoundMoreThanOnceInParameterList { span, identifier }),
713 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => self
715 .create_err(errs::IdentifierBoundMoreThanOnceInSamePattern { span, identifier }),
716 ResolutionError::UndeclaredLabel { name, suggestion } => {
717 let ((sub_reachable, sub_reachable_suggestion), sub_unreachable) = match suggestion
719 // A reachable label with a similar name exists.
720 Some((ident, true)) => (
722 Some(errs::LabelWithSimilarNameReachable(ident.span)),
723 Some(errs::TryUsingSimilarlyNamedLabel {
725 ident_name: ident.name,
730 // An unreachable label with a similar name exists.
731 Some((ident, false)) => (
733 Some(errs::UnreachableLabelWithSimilarNameExists {
734 ident_span: ident.span,
737 // No similarly-named labels exist.
738 None => ((None, None), None),
740 self.session.create_err(errs::UndeclaredLabel {
744 sub_reachable_suggestion,
748 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
749 // None of the suggestions below would help with a case like `use self`.
750 let (suggestion, mpart_suggestion) = if root {
753 // use foo::bar::self -> foo::bar
754 // use foo::bar::self as abc -> foo::bar as abc
755 let suggestion = errs::SelfImportsOnlyAllowedWithinSuggestion { span };
757 // use foo::bar::self -> foo::bar::{self}
758 // use foo::bar::self as abc -> foo::bar::{self as abc}
759 let mpart_suggestion = errs::SelfImportsOnlyAllowedWithinMultipartSuggestion {
760 multipart_start: span_with_rename.shrink_to_lo(),
761 multipart_end: span_with_rename.shrink_to_hi(),
763 (Some(suggestion), Some(mpart_suggestion))
765 self.session.create_err(errs::SelfImportsOnlyAllowedWithin {
771 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
772 self.session.create_err(errs::SelfImportCanOnlyAppearOnceInTheList { span })
774 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
775 self.session.create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
777 ResolutionError::FailedToResolve { label, suggestion } => {
779 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
780 err.span_label(span, label);
782 if let Some((suggestions, msg, applicability)) = suggestion {
783 if suggestions.is_empty() {
787 err.multipart_suggestion(&msg, suggestions, applicability);
792 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
793 self.session.create_err(errs::CannotCaptureDynamicEnvironmentInFnItem { span })
795 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, suggestion, current) => {
797 // ^^^ given this Span
798 // ------- get this Span to have an applicable suggestion
801 // only do this if the const and usage of the non-constant value are on the same line
802 // the further the two are apart, the higher the chance of the suggestion being wrong
807 .span_extend_to_prev_str(ident.span, current, true, false);
809 let ((with, with_label), without) = match sp {
810 Some(sp) if !self.session.source_map().is_multiline(sp) => {
811 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
813 (Some(errs::AttemptToUseNonConstantValueInConstantWithSuggestion {
818 }), Some(errs::AttemptToUseNonConstantValueInConstantLabelWithSuggestion {span})),
824 Some(errs::AttemptToUseNonConstantValueInConstantWithoutSuggestion {
825 ident_span: ident.span,
831 self.session.create_err(errs::AttemptToUseNonConstantValueInConstant {
838 ResolutionError::BindingShadowsSomethingUnacceptable {
844 shadowed_binding_span,
845 } => self.session.create_err(errs::BindingShadowsSomethingUnacceptable {
850 sub_suggestion: match (shadowing_binding, shadowed_binding) {
852 PatternSource::Match,
853 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
854 ) => Some(errs::BindingShadowsSomethingUnacceptableSuggestion { span, name }),
857 shadowed_binding_span,
861 ResolutionError::ForwardDeclaredGenericParam => {
862 self.session.create_err(errs::ForwardDeclaredGenericParam { span })
864 ResolutionError::ParamInTyOfConstParam(name) => {
865 self.session.create_err(errs::ParamInTyOfConstParam { span, name })
867 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
868 self.session.create_err(errs::ParamInNonTrivialAnonConst {
871 sub_is_type: if is_type {
872 errs::ParamInNonTrivialAnonConstIsType::AType
874 errs::ParamInNonTrivialAnonConstIsType::NotAType { name }
879 .then_some(errs::ParamInNonTrivialAnonConstHelp),
882 ResolutionError::SelfInGenericParamDefault => {
883 self.session.create_err(errs::SelfInGenericParamDefault { span })
885 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
886 let ((sub_suggestion_label, sub_suggestion), sub_unreachable_label) =
888 // A reachable label with a similar name exists.
889 Some((ident, true)) => (
891 Some(errs::UnreachableLabelSubLabel { ident_span: ident.span }),
892 Some(errs::UnreachableLabelSubSuggestion {
894 // intentionally taking 'ident.name' instead of 'ident' itself, as this
895 // could be used in suggestion context
896 ident_name: ident.name,
901 // An unreachable label with a similar name exists.
902 Some((ident, false)) => (
904 Some(errs::UnreachableLabelSubLabelUnreachable {
905 ident_span: ident.span,
908 // No similarly-named labels exist.
909 None => ((None, None), None),
911 self.session.create_err(errs::UnreachableLabel {
916 sub_suggestion_label,
917 sub_unreachable_label,
920 ResolutionError::TraitImplMismatch {
927 let mut err = self.session.struct_span_err_with_code(
930 "item `{}` is an associated {}, which doesn't match its trait `{}`",
931 name, kind, trait_path,
935 err.span_label(span, "does not match trait");
936 err.span_label(trait_item_span, "item in trait");
939 ResolutionError::TraitImplDuplicate { name, trait_item_span, old_span } => self
941 .create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
942 ResolutionError::InvalidAsmSym => self.session.create_err(errs::InvalidAsmSym { span }),
946 pub(crate) fn report_vis_error(
948 vis_resolution_error: VisResolutionError<'_>,
949 ) -> ErrorGuaranteed {
950 match vis_resolution_error {
951 VisResolutionError::Relative2018(span, path) => {
952 self.session.create_err(errs::Relative2018 {
954 path_span: path.span,
955 // intentionally converting to String, as the text would also be used as
956 // in suggestion context
957 path_str: pprust::path_to_string(&path),
960 VisResolutionError::AncestorOnly(span) => {
961 self.session.create_err(errs::AncestorOnly(span))
963 VisResolutionError::FailedToResolve(span, label, suggestion) => {
964 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
966 VisResolutionError::ExpectedFound(span, path_str, res) => {
967 self.session.create_err(errs::ExpectedFound { span, res, path_str })
969 VisResolutionError::Indeterminate(span) => {
970 self.session.create_err(errs::Indeterminate(span))
972 VisResolutionError::ModuleOnly(span) => self.session.create_err(errs::ModuleOnly(span)),
977 /// Lookup typo candidate in scope for a macro or import.
978 fn early_lookup_typo_candidate(
980 scope_set: ScopeSet<'a>,
981 parent_scope: &ParentScope<'a>,
983 filter_fn: &impl Fn(Res) -> bool,
984 ) -> Option<TypoSuggestion> {
985 let mut suggestions = Vec::new();
986 let ctxt = ident.span.ctxt();
987 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
989 Scope::DeriveHelpers(expn_id) => {
990 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
997 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1001 Scope::DeriveHelpersCompat => {
1002 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1004 for derive in parent_scope.derives {
1005 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1006 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1008 Some(MacroKind::Derive),
1016 .map(|name| TypoSuggestion::typo_from_name(*name, res)),
1022 Scope::MacroRules(macro_rules_scope) => {
1023 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1024 let res = macro_rules_binding.binding.res();
1026 suggestions.push(TypoSuggestion::typo_from_ident(
1027 macro_rules_binding.ident,
1033 Scope::CrateRoot => {
1034 let root_ident = Ident::new(kw::PathRoot, ident.span);
1035 let root_module = this.resolve_crate_root(root_ident);
1036 this.add_module_candidates(root_module, &mut suggestions, filter_fn, None);
1038 Scope::Module(module, _) => {
1039 this.add_module_candidates(module, &mut suggestions, filter_fn, None);
1041 Scope::MacroUsePrelude => {
1042 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1044 let res = binding.res();
1045 filter_fn(res).then_some(TypoSuggestion::typo_from_name(*name, res))
1049 Scope::BuiltinAttrs => {
1050 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1055 .map(|attr| TypoSuggestion::typo_from_name(attr.name, res)),
1059 Scope::ExternPrelude => {
1060 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1061 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1062 filter_fn(res).then_some(TypoSuggestion::typo_from_ident(*ident, res))
1065 Scope::ToolPrelude => {
1066 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1068 this.registered_tools
1070 .map(|ident| TypoSuggestion::typo_from_ident(*ident, res)),
1073 Scope::StdLibPrelude => {
1074 if let Some(prelude) = this.prelude {
1075 let mut tmp_suggestions = Vec::new();
1076 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn, None);
1080 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1084 Scope::BuiltinTypes => {
1085 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1086 let res = Res::PrimTy(*prim_ty);
1088 .then_some(TypoSuggestion::typo_from_name(prim_ty.name(), res))
1096 // Make sure error reporting is deterministic.
1097 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1099 match find_best_match_for_name(
1100 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1104 Some(found) if found != ident.name => {
1105 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1111 fn lookup_import_candidates_from_module<FilterFn>(
1113 lookup_ident: Ident,
1114 namespace: Namespace,
1115 parent_scope: &ParentScope<'a>,
1116 start_module: Module<'a>,
1118 filter_fn: FilterFn,
1119 ) -> Vec<ImportSuggestion>
1121 FilterFn: Fn(Res) -> bool,
1123 let mut candidates = Vec::new();
1124 let mut seen_modules = FxHashSet::default();
1125 let mut worklist = vec![(start_module, ThinVec::<ast::PathSegment>::new(), true)];
1126 let mut worklist_via_import = vec![];
1128 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1129 None => worklist_via_import.pop(),
1132 let in_module_is_extern = !in_module.def_id().is_local();
1133 // We have to visit module children in deterministic order to avoid
1134 // instabilities in reported imports (#43552).
1135 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1136 // avoid non-importable candidates
1137 if !name_binding.is_importable() {
1141 let child_accessible =
1142 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1144 // do not venture inside inaccessible items of other crates
1145 if in_module_is_extern && !child_accessible {
1149 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1151 // There is an assumption elsewhere that paths of variants are in the enum's
1152 // declaration and not imported. With this assumption, the variant component is
1153 // chopped and the rest of the path is assumed to be the enum's own path. For
1154 // errors where a variant is used as the type instead of the enum, this causes
1155 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1156 if via_import && name_binding.is_possibly_imported_variant() {
1160 // #90113: Do not count an inaccessible reexported item as a candidate.
1161 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1162 if this.is_accessible_from(binding.vis, parent_scope.module)
1163 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1169 // collect results based on the filter function
1170 // avoid suggesting anything from the same module in which we are resolving
1171 // avoid suggesting anything with a hygienic name
1172 if ident.name == lookup_ident.name
1174 && !ptr::eq(in_module, parent_scope.module)
1175 && !ident.span.normalize_to_macros_2_0().from_expansion()
1177 let res = name_binding.res();
1180 let mut segms = path_segments.clone();
1181 if lookup_ident.span.rust_2018() {
1182 // crate-local absolute paths start with `crate::` in edition 2018
1183 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1184 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1187 segms.push(ast::PathSegment::from_ident(ident));
1188 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1189 let did = match res {
1190 Res::Def(DefKind::Ctor(..), did) => this.opt_parent(did),
1191 _ => res.opt_def_id(),
1194 if child_accessible {
1195 // Remove invisible match if exists
1196 if let Some(idx) = candidates
1198 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1200 candidates.remove(idx);
1204 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1205 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1206 // a note about editions
1207 let note = if let Some(did) = did {
1208 let requires_note = !did.is_local()
1209 && this.cstore().item_attrs_untracked(did, this.session).any(
1211 if attr.has_name(sym::rustc_diagnostic_item) {
1212 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1214 .contains(&attr.value_str())
1221 requires_note.then(|| {
1223 "'{}' is included in the prelude starting in Edition 2021",
1224 path_names_to_string(&path)
1231 candidates.push(ImportSuggestion {
1235 accessible: child_accessible,
1242 // collect submodules to explore
1243 if let Some(module) = name_binding.module() {
1245 let mut path_segments = path_segments.clone();
1246 path_segments.push(ast::PathSegment::from_ident(ident));
1248 let is_extern_crate_that_also_appears_in_prelude =
1249 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1251 if !is_extern_crate_that_also_appears_in_prelude {
1252 // add the module to the lookup
1253 if seen_modules.insert(module.def_id()) {
1254 if via_import { &mut worklist_via_import } else { &mut worklist }
1255 .push((module, path_segments, child_accessible));
1262 // If only some candidates are accessible, take just them
1263 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1264 candidates.retain(|x| x.accessible)
1270 /// When name resolution fails, this method can be used to look up candidate
1271 /// entities with the expected name. It allows filtering them using the
1272 /// supplied predicate (which should be used to only accept the types of
1273 /// definitions expected, e.g., traits). The lookup spans across all crates.
1275 /// N.B., the method does not look into imports, but this is not a problem,
1276 /// since we report the definitions (thus, the de-aliased imports).
1277 pub(crate) fn lookup_import_candidates<FilterFn>(
1279 lookup_ident: Ident,
1280 namespace: Namespace,
1281 parent_scope: &ParentScope<'a>,
1282 filter_fn: FilterFn,
1283 ) -> Vec<ImportSuggestion>
1285 FilterFn: Fn(Res) -> bool,
1287 let mut suggestions = self.lookup_import_candidates_from_module(
1292 Ident::with_dummy_span(kw::Crate),
1296 if lookup_ident.span.rust_2018() {
1297 let extern_prelude_names = self.extern_prelude.clone();
1298 for (ident, _) in extern_prelude_names.into_iter() {
1299 if ident.span.from_expansion() {
1300 // Idents are adjusted to the root context before being
1301 // resolved in the extern prelude, so reporting this to the
1302 // user is no help. This skips the injected
1303 // `extern crate std` in the 2018 edition, which would
1304 // otherwise cause duplicate suggestions.
1307 let crate_id = self.crate_loader().maybe_process_path_extern(ident.name);
1308 if let Some(crate_id) = crate_id {
1309 let crate_root = self.expect_module(crate_id.as_def_id());
1310 suggestions.extend(self.lookup_import_candidates_from_module(
1325 pub(crate) fn unresolved_macro_suggestions(
1327 err: &mut Diagnostic,
1328 macro_kind: MacroKind,
1329 parent_scope: &ParentScope<'a>,
1332 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1333 let suggestion = self.early_lookup_typo_candidate(
1334 ScopeSet::Macro(macro_kind),
1339 self.add_typo_suggestion(err, suggestion, ident.span);
1341 let import_suggestions =
1342 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1345 &self.untracked.source_span,
1348 &import_suggestions,
1351 DiagnosticMode::Normal,
1356 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1357 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1358 err.span_note(ident.span, &msg);
1361 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1362 err.help("have you added the `#[macro_use]` on the module/import?");
1365 if ident.name == kw::Default
1366 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1367 && let Some(span) = self.opt_span(def_id)
1369 let source_map = self.session.source_map();
1370 let head_span = source_map.guess_head_span(span);
1371 if let Ok(head) = source_map.span_to_snippet(head_span) {
1372 err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect);
1376 "consider adding `#[derive(Default)]` to this enum",
1380 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1381 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1383 ScopeSet::All(ns, false),
1389 let desc = match binding.res() {
1390 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1391 "a function-like macro".to_string()
1393 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1394 format!("an attribute: `#[{}]`", ident)
1396 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1397 format!("a derive macro: `#[derive({})]`", ident)
1400 // Don't confuse the user with tool modules.
1403 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1404 "only a trait, without a derive macro".to_string()
1410 macro_kind.article(),
1411 macro_kind.descr_expected(),
1414 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1415 if !import.span.is_dummy() {
1418 &format!("`{}` is imported here, but it is {}", ident, desc),
1420 // Silence the 'unused import' warning we might get,
1421 // since this diagnostic already covers that import.
1422 self.record_use(ident, binding, false);
1426 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1432 pub(crate) fn add_typo_suggestion(
1434 err: &mut Diagnostic,
1435 suggestion: Option<TypoSuggestion>,
1438 let suggestion = match suggestion {
1439 None => return false,
1440 // We shouldn't suggest underscore.
1441 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1442 Some(suggestion) => suggestion,
1444 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1445 LOCAL_CRATE => self.opt_span(def_id),
1446 _ => Some(self.cstore().get_span_untracked(def_id, self.session)),
1448 if let Some(def_span) = def_span {
1449 if span.overlaps(def_span) {
1450 // Don't suggest typo suggestion for itself like in the following:
1451 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1452 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1455 // | ----------- `X` defined here
1457 // LL | const Y: X = X("ö");
1458 // | -------------^^^^^^- similarly named constant `Y` defined here
1460 // help: use struct literal syntax instead
1462 // LL | const Y: X = X {};
1464 // help: a constant with a similar name exists
1466 // LL | const Y: X = Y("ö");
1470 let prefix = match suggestion.target {
1471 SuggestionTarget::SimilarlyNamed => "similarly named ",
1472 SuggestionTarget::SingleItem => "",
1476 self.session.source_map().guess_head_span(def_span),
1478 "{}{} `{}` defined here",
1480 suggestion.res.descr(),
1481 suggestion.candidate,
1485 let msg = match suggestion.target {
1486 SuggestionTarget::SimilarlyNamed => format!(
1487 "{} {} with a similar name exists",
1488 suggestion.res.article(),
1489 suggestion.res.descr()
1491 SuggestionTarget::SingleItem => {
1492 format!("maybe you meant this {}", suggestion.res.descr())
1495 err.span_suggestion(span, &msg, suggestion.candidate, Applicability::MaybeIncorrect);
1499 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1501 if b.span.is_dummy() || !self.session.source_map().is_span_accessible(b.span) {
1502 // These already contain the "built-in" prefix or look bad with it.
1504 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1505 let (built_in, from) = if from_prelude {
1506 ("", " from prelude")
1507 } else if b.is_extern_crate()
1509 && self.session.opts.externs.get(ident.as_str()).is_some()
1511 ("", " passed with `--extern`")
1512 } else if add_built_in {
1518 let a = if built_in.is_empty() { res.article() } else { "a" };
1519 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1521 let introduced = if b.is_import_user_facing() { "imported" } else { "defined" };
1522 format!("the {thing} {introduced} here", thing = res.descr())
1526 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1527 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1528 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1529 // We have to print the span-less alternative first, otherwise formatting looks bad.
1530 (b2, b1, misc2, misc1, true)
1532 (b1, b2, misc1, misc2, false)
1535 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1536 err.span_label(ident.span, "ambiguous name");
1537 err.note(&format!("ambiguous because of {}", kind.descr()));
1539 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1540 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1541 let note_msg = format!("`{ident}` could{also} refer to {what}");
1543 let thing = b.res().descr();
1544 let mut help_msgs = Vec::new();
1545 if b.is_glob_import()
1546 && (kind == AmbiguityKind::GlobVsGlob
1547 || kind == AmbiguityKind::GlobVsExpanded
1548 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1550 help_msgs.push(format!(
1551 "consider adding an explicit import of `{ident}` to disambiguate"
1554 if b.is_extern_crate() && ident.span.rust_2018() {
1555 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1558 AmbiguityErrorMisc::SuggestCrate => help_msgs
1559 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")),
1560 AmbiguityErrorMisc::SuggestSelf => help_msgs
1561 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")),
1562 AmbiguityErrorMisc::FromPrelude | AmbiguityErrorMisc::None => {}
1565 err.span_note(b.span, ¬e_msg);
1566 for (i, help_msg) in help_msgs.iter().enumerate() {
1567 let or = if i == 0 { "" } else { "or " };
1568 err.help(&format!("{}{}", or, help_msg));
1572 could_refer_to(b1, misc1, "");
1573 could_refer_to(b2, misc2, " also");
1577 /// If the binding refers to a tuple struct constructor with fields,
1578 /// returns the span of its fields.
1579 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1580 if let NameBindingKind::Res(Res::Def(
1581 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
1585 let def_id = self.parent(ctor_def_id);
1586 let fields = self.field_names.get(&def_id)?;
1587 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1592 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1593 let PrivacyError { ident, binding, .. } = *privacy_error;
1595 let res = binding.res();
1596 let ctor_fields_span = self.ctor_fields_span(binding);
1597 let plain_descr = res.descr().to_string();
1598 let nonimport_descr =
1599 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1600 let import_descr = nonimport_descr.clone() + " import";
1602 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1604 // Print the primary message.
1605 let descr = get_descr(binding);
1607 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1608 err.span_label(ident.span, &format!("private {}", descr));
1609 if let Some(span) = ctor_fields_span {
1610 err.span_label(span, "a constructor is private if any of the fields is private");
1611 if let Res::Def(_, d) = res && let Some(fields) = self.field_visibility_spans.get(&d) {
1612 err.multipart_suggestion_verbose(
1614 "consider making the field{} publicly accessible",
1615 pluralize!(fields.len())
1617 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
1618 Applicability::MaybeIncorrect,
1623 // Print the whole import chain to make it easier to see what happens.
1624 let first_binding = binding;
1625 let mut next_binding = Some(binding);
1626 let mut next_ident = ident;
1627 while let Some(binding) = next_binding {
1628 let name = next_ident;
1629 next_binding = match binding.kind {
1630 _ if res == Res::Err => None,
1631 NameBindingKind::Import { binding, import, .. } => match import.kind {
1632 _ if binding.span.is_dummy() => None,
1633 ImportKind::Single { source, .. } => {
1634 next_ident = source;
1637 ImportKind::Glob { .. } | ImportKind::MacroUse | ImportKind::MacroExport => {
1640 ImportKind::ExternCrate { .. } => None,
1645 let first = ptr::eq(binding, first_binding);
1647 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1648 and_refers_to = if first { "" } else { "...and refers to " },
1649 item = get_descr(binding),
1650 which = if first { "" } else { " which" },
1651 dots = if next_binding.is_some() { "..." } else { "" },
1653 let def_span = self.session.source_map().guess_head_span(binding.span);
1654 let mut note_span = MultiSpan::from_span(def_span);
1655 if !first && binding.vis.is_public() {
1656 note_span.push_span_label(def_span, "consider importing it directly");
1658 err.span_note(note_span, &msg);
1664 pub(crate) fn find_similarly_named_module_or_crate(
1667 current_module: &Module<'a>,
1668 ) -> Option<Symbol> {
1669 let mut candidates = self
1672 .map(|(ident, _)| ident.name)
1676 .filter(|(_, module)| {
1677 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1679 .flat_map(|(_, module)| module.kind.name()),
1681 .filter(|c| !c.to_string().is_empty())
1682 .collect::<Vec<_>>();
1685 match find_best_match_for_name(&candidates, ident, None) {
1686 Some(sugg) if sugg == ident => None,
1691 pub(crate) fn report_path_resolution_error(
1694 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1695 parent_scope: &ParentScope<'a>,
1696 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1697 ignore_binding: Option<&'a NameBinding<'a>>,
1698 module: Option<ModuleOrUniformRoot<'a>>,
1701 ) -> (String, Option<Suggestion>) {
1702 let is_last = i == path.len() - 1;
1703 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1704 let module_res = match module {
1705 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1708 if module_res == self.graph_root.res() {
1709 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1710 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1712 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1713 if let Some(candidate) = candidates.get(0) {
1715 String::from("unresolved import"),
1717 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1718 String::from("a similar path exists"),
1719 Applicability::MaybeIncorrect,
1722 } else if self.session.is_rust_2015() {
1724 format!("maybe a missing crate `{ident}`?"),
1728 "consider adding `extern crate {ident}` to use the `{ident}` crate"
1730 Applicability::MaybeIncorrect,
1734 (format!("could not find `{ident}` in the crate root"), None)
1737 let parent = path[i - 1].ident.name;
1738 let parent = match parent {
1739 // ::foo is mounted at the crate root for 2015, and is the extern
1740 // prelude for 2018+
1741 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1742 "the list of imported crates".to_owned()
1744 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1745 _ => format!("`{parent}`"),
1748 let mut msg = format!("could not find `{}` in {}", ident, parent);
1749 if ns == TypeNS || ns == ValueNS {
1750 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1751 let binding = if let Some(module) = module {
1752 self.resolve_ident_in_module(
1760 } else if let Some(ribs) = ribs
1761 && let Some(TypeNS | ValueNS) = opt_ns
1763 match self.resolve_ident_in_lexical_scope(
1771 // we found a locally-imported or available item/module
1772 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1776 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1777 self.early_resolve_ident_in_lexical_scope(
1786 if let Some(binding) = binding {
1787 let mut found = |what| {
1789 "expected {}, found {} `{}` in {}",
1796 if binding.module().is_some() {
1799 match binding.res() {
1800 Res::Def(kind, id) => found(kind.descr(id)),
1801 _ => found(ns_to_try.descr()),
1807 } else if ident.name == kw::SelfUpper {
1808 ("`Self` is only available in impls, traits, and type definitions".to_string(), None)
1809 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1810 // Check whether the name refers to an item in the value namespace.
1811 let binding = if let Some(ribs) = ribs {
1812 self.resolve_ident_in_lexical_scope(
1823 let match_span = match binding {
1824 // Name matches a local variable. For example:
1827 // let Foo: &str = "";
1828 // println!("{}", Foo::Bar); // Name refers to local
1829 // // variable `Foo`.
1832 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1833 Some(*self.pat_span_map.get(&id).unwrap())
1835 // Name matches item from a local name binding
1836 // created by `use` declaration. For example:
1838 // pub Foo: &str = "";
1842 // println!("{}", Foo::Bar); // Name refers to local
1843 // // binding `Foo`.
1846 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1849 let suggestion = if let Some(span) = match_span {
1851 vec![(span, String::from(""))],
1852 format!("`{}` is defined here, but is not a type", ident),
1853 Applicability::MaybeIncorrect,
1859 (format!("use of undeclared type `{}`", ident), suggestion)
1861 let mut suggestion = None;
1862 if ident.name == sym::alloc {
1865 String::from("add `extern crate alloc` to use the `alloc` crate"),
1866 Applicability::MaybeIncorrect,
1870 suggestion = suggestion.or_else(|| {
1871 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1874 vec![(ident.span, sugg.to_string())],
1875 String::from("there is a crate or module with a similar name"),
1876 Applicability::MaybeIncorrect,
1881 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1886 impl<'a, 'b> ImportResolver<'a, 'b> {
1887 /// Adds suggestions for a path that cannot be resolved.
1888 pub(crate) fn make_path_suggestion(
1891 mut path: Vec<Segment>,
1892 parent_scope: &ParentScope<'b>,
1893 ) -> Option<(Vec<Segment>, Option<String>)> {
1894 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1896 match (path.get(0), path.get(1)) {
1897 // `{{root}}::ident::...` on both editions.
1898 // On 2015 `{{root}}` is usually added implicitly.
1899 (Some(fst), Some(snd))
1900 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
1901 // `ident::...` on 2018.
1903 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
1905 // Insert a placeholder that's later replaced by `self`/`super`/etc.
1906 path.insert(0, Segment::from_ident(Ident::empty()));
1911 self.make_missing_self_suggestion(path.clone(), parent_scope)
1912 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
1913 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
1914 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
1917 /// Suggest a missing `self::` if that resolves to an correct module.
1921 /// LL | use foo::Bar;
1922 /// | ^^^ did you mean `self::foo`?
1924 fn make_missing_self_suggestion(
1926 mut path: Vec<Segment>,
1927 parent_scope: &ParentScope<'b>,
1928 ) -> Option<(Vec<Segment>, Option<String>)> {
1929 // Replace first ident with `self` and check if that is valid.
1930 path[0].ident.name = kw::SelfLower;
1931 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1932 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
1933 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1936 /// Suggests a missing `crate::` if that resolves to an correct module.
1940 /// LL | use foo::Bar;
1941 /// | ^^^ did you mean `crate::foo`?
1943 fn make_missing_crate_suggestion(
1945 mut path: Vec<Segment>,
1946 parent_scope: &ParentScope<'b>,
1947 ) -> Option<(Vec<Segment>, Option<String>)> {
1948 // Replace first ident with `crate` and check if that is valid.
1949 path[0].ident.name = kw::Crate;
1950 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1951 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
1952 if let PathResult::Module(..) = result {
1956 "`use` statements changed in Rust 2018; read more at \
1957 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
1967 /// Suggests a missing `super::` if that resolves to an correct module.
1971 /// LL | use foo::Bar;
1972 /// | ^^^ did you mean `super::foo`?
1974 fn make_missing_super_suggestion(
1976 mut path: Vec<Segment>,
1977 parent_scope: &ParentScope<'b>,
1978 ) -> Option<(Vec<Segment>, Option<String>)> {
1979 // Replace first ident with `crate` and check if that is valid.
1980 path[0].ident.name = kw::Super;
1981 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
1982 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
1983 if let PathResult::Module(..) = result { Some((path, None)) } else { None }
1986 /// Suggests a missing external crate name if that resolves to an correct module.
1990 /// LL | use foobar::Baz;
1991 /// | ^^^^^^ did you mean `baz::foobar`?
1994 /// Used when importing a submodule of an external crate but missing that crate's
1995 /// name as the first part of path.
1996 fn make_external_crate_suggestion(
1998 mut path: Vec<Segment>,
1999 parent_scope: &ParentScope<'b>,
2000 ) -> Option<(Vec<Segment>, Option<String>)> {
2001 if path[1].ident.span.is_rust_2015() {
2005 // Sort extern crate names in *reverse* order to get
2006 // 1) some consistent ordering for emitted diagnostics, and
2007 // 2) `std` suggestions before `core` suggestions.
2008 let mut extern_crate_names =
2009 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2010 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2012 for name in extern_crate_names.into_iter() {
2013 // Replace first ident with a crate name and check if that is valid.
2014 path[0].ident.name = name;
2015 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2017 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2020 if let PathResult::Module(..) = result {
2021 return Some((path, None));
2028 /// Suggests importing a macro from the root of the crate rather than a module within
2032 /// help: a macro with this name exists at the root of the crate
2034 /// LL | use issue_59764::makro;
2035 /// | ^^^^^^^^^^^^^^^^^^
2037 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2038 /// at the root of the crate instead of the module where it is defined
2040 pub(crate) fn check_for_module_export_macro(
2042 import: &'b Import<'b>,
2043 module: ModuleOrUniformRoot<'b>,
2045 ) -> Option<(Option<Suggestion>, Option<String>)> {
2046 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2050 while let Some(parent) = crate_module.parent {
2051 crate_module = parent;
2054 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2055 // Don't make a suggestion if the import was already from the root of the
2060 let resolutions = self.r.resolutions(crate_module).borrow();
2061 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2062 let binding = resolution.borrow().binding()?;
2063 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2064 let module_name = crate_module.kind.name().unwrap();
2065 let import_snippet = match import.kind {
2066 ImportKind::Single { source, target, .. } if source != target => {
2067 format!("{} as {}", source, target)
2069 _ => format!("{}", ident),
2072 let mut corrections: Vec<(Span, String)> = Vec::new();
2073 if !import.is_nested() {
2074 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2075 // intermediate segments.
2076 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2078 // Find the binding span (and any trailing commas and spaces).
2079 // ie. `use a::b::{c, d, e};`
2081 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2087 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2088 found_closing_brace, binding_span
2091 let mut removal_span = binding_span;
2092 if found_closing_brace {
2093 // If the binding span ended with a closing brace, as in the below example:
2094 // ie. `use a::b::{c, d};`
2096 // Then expand the span of characters to remove to include the previous
2097 // binding's trailing comma.
2098 // ie. `use a::b::{c, d};`
2100 if let Some(previous_span) =
2101 extend_span_to_previous_binding(self.r.session, binding_span)
2103 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2104 removal_span = removal_span.with_lo(previous_span.lo());
2107 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2109 // Remove the `removal_span`.
2110 corrections.push((removal_span, "".to_string()));
2112 // Find the span after the crate name and if it has nested imports immediately
2113 // after the crate name already.
2114 // ie. `use a::b::{c, d};`
2116 // or `use a::{b, c, d}};`
2118 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2124 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2125 has_nested, after_crate_name
2128 let source_map = self.r.session.source_map();
2130 // Make sure this is actually crate-relative.
2131 let is_definitely_crate = import
2134 .map_or(false, |f| f.ident.name != kw::SelfLower && f.ident.name != kw::Super);
2136 // Add the import to the start, with a `{` if required.
2137 let start_point = source_map.start_point(after_crate_name);
2138 if is_definitely_crate && let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2142 // In this case, `start_snippet` must equal '{'.
2143 format!("{}{}, ", start_snippet, import_snippet)
2145 // In this case, add a `{`, then the moved import, then whatever
2146 // was there before.
2147 format!("{{{}, {}", import_snippet, start_snippet)
2151 // Add a `};` to the end if nested, matching the `{` added at the start.
2153 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2156 // If the root import is module-relative, add the import separately
2158 import.use_span.shrink_to_lo(),
2159 format!("use {module_name}::{import_snippet};\n"),
2164 let suggestion = Some((
2166 String::from("a macro with this name exists at the root of the crate"),
2167 Applicability::MaybeIncorrect,
2169 Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \
2170 at the root of the crate instead of the module where it is defined"
2178 /// Given a `binding_span` of a binding within a use statement:
2180 /// ```ignore (illustrative)
2181 /// use foo::{a, b, c};
2185 /// then return the span until the next binding or the end of the statement:
2187 /// ```ignore (illustrative)
2188 /// use foo::{a, b, c};
2191 fn find_span_of_binding_until_next_binding(
2196 let source_map = sess.source_map();
2198 // Find the span of everything after the binding.
2199 // ie. `a, e};` or `a};`
2200 let binding_until_end = binding_span.with_hi(use_span.hi());
2202 // Find everything after the binding but not including the binding.
2203 // ie. `, e};` or `};`
2204 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2206 // Keep characters in the span until we encounter something that isn't a comma or
2210 // Also note whether a closing brace character was encountered. If there
2211 // was, then later go backwards to remove any trailing commas that are left.
2212 let mut found_closing_brace = false;
2213 let after_binding_until_next_binding =
2214 source_map.span_take_while(after_binding_until_end, |&ch| {
2216 found_closing_brace = true;
2218 ch == ' ' || ch == ','
2221 // Combine the two spans.
2222 // ie. `a, ` or `a`.
2224 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2225 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2227 (found_closing_brace, span)
2230 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2233 /// ```ignore (illustrative)
2234 /// use foo::a::{a, b, c};
2235 /// // ^^--- binding span
2237 /// // returned span
2239 /// use foo::{a, b, c};
2240 /// // --- binding span
2242 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2243 let source_map = sess.source_map();
2245 // `prev_source` will contain all of the source that came before the span.
2246 // Then split based on a command and take the first (ie. closest to our span)
2247 // snippet. In the example, this is a space.
2248 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2250 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2251 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2252 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2256 let prev_comma = prev_comma.first().unwrap();
2257 let prev_starting_brace = prev_starting_brace.first().unwrap();
2259 // If the amount of source code before the comma is greater than
2260 // the amount of source code before the starting brace then we've only
2261 // got one item in the nested item (eg. `issue_52891::{self}`).
2262 if prev_comma.len() > prev_starting_brace.len() {
2266 Some(binding_span.with_lo(BytePos(
2267 // Take away the number of bytes for the characters we've found and an
2268 // extra for the comma.
2269 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2273 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2274 /// it is a nested use tree.
2276 /// ```ignore (illustrative)
2277 /// use foo::a::{b, c};
2278 /// // ^^^^^^^^^^ -- false
2280 /// use foo::{a, b, c};
2281 /// // ^^^^^^^^^^ -- true
2283 /// use foo::{a, b::{c, d}};
2284 /// // ^^^^^^^^^^^^^^^ -- true
2286 fn find_span_immediately_after_crate_name(
2288 module_name: Symbol,
2292 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2293 module_name, use_span
2295 let source_map = sess.source_map();
2297 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2298 let mut num_colons = 0;
2299 // Find second colon.. `use issue_59764:`
2300 let until_second_colon = source_map.span_take_while(use_span, |c| {
2304 !matches!(c, ':' if num_colons == 2)
2306 // Find everything after the second colon.. `foo::{baz, makro};`
2307 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2309 let mut found_a_non_whitespace_character = false;
2310 // Find the first non-whitespace character in `from_second_colon`.. `f`
2311 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2312 if found_a_non_whitespace_character {
2315 if !c.is_whitespace() {
2316 found_a_non_whitespace_character = true;
2321 // Find the first `{` in from_second_colon.. `foo::{`
2322 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2324 (next_left_bracket == after_second_colon, from_second_colon)
2327 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2328 /// independent options.
2334 /// Whether an existing place with an `use` item was found.
2340 /// Whether a binding is part of a pattern or a use statement. Used for diagnostics.
2341 pub(crate) enum DiagnosticMode {
2343 /// The binding is part of a pattern
2345 /// The binding is part of a use statement
2349 pub(crate) fn import_candidates(
2351 source_span: &IndexVec<LocalDefId, Span>,
2352 err: &mut Diagnostic,
2353 // This is `None` if all placement locations are inside expansions
2354 use_placement_span: Option<Span>,
2355 candidates: &[ImportSuggestion],
2356 mode: DiagnosticMode,
2373 /// When an entity with a given name is not available in scope, we search for
2374 /// entities with that name in all crates. This method allows outputting the
2375 /// results of this search in a programmer-friendly way
2378 source_span: &IndexVec<LocalDefId, Span>,
2379 err: &mut Diagnostic,
2380 // This is `None` if all placement locations are inside expansions
2381 use_placement_span: Option<Span>,
2382 candidates: &[ImportSuggestion],
2384 found_use: FoundUse,
2385 mode: DiagnosticMode,
2389 if candidates.is_empty() {
2393 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2395 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2398 candidates.iter().for_each(|c| {
2399 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2400 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2403 // we want consistent results across executions, but candidates are produced
2404 // by iterating through a hash map, so make sure they are ordered:
2405 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2406 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2407 let core_path_strings =
2408 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2409 path_strings.extend(core_path_strings);
2410 path_strings.dedup_by(|a, b| a.0 == b.0);
2413 if !accessible_path_strings.is_empty() {
2414 let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2415 ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2417 ("one of these", "items", String::new())
2420 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2421 let mut msg = if let DiagnosticMode::Pattern = mode {
2423 "if you meant to match on {}{}{}, use the full path in the pattern",
2427 format!("consider importing {} {}{}", determiner, kind, instead)
2430 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2434 if let Some(span) = use_placement_span {
2435 let (add_use, trailing) = match mode {
2436 DiagnosticMode::Pattern => {
2437 err.span_suggestions(
2440 accessible_path_strings.into_iter().map(|a| a.0),
2441 Applicability::MaybeIncorrect,
2445 DiagnosticMode::Import => ("", ""),
2446 DiagnosticMode::Normal => ("use ", ";\n"),
2448 for candidate in &mut accessible_path_strings {
2449 // produce an additional newline to separate the new use statement
2450 // from the directly following item.
2451 let additional_newline = if let FoundUse::No = found_use && let DiagnosticMode::Normal = mode { "\n" } else { "" };
2453 format!("{add_use}{}{append}{trailing}{additional_newline}", &candidate.0);
2456 err.span_suggestions_with_style(
2459 accessible_path_strings.into_iter().map(|a| a.0),
2460 Applicability::MaybeIncorrect,
2461 SuggestionStyle::ShowAlways,
2463 if let [first, .., last] = &path[..] {
2464 let sp = first.ident.span.until(last.ident.span);
2465 if sp.can_be_used_for_suggestions() {
2466 err.span_suggestion_verbose(
2468 &format!("if you import `{}`, refer to it directly", last.ident),
2470 Applicability::Unspecified,
2477 for candidate in accessible_path_strings {
2479 msg.push_str(&candidate.0);
2484 } else if !matches!(mode, DiagnosticMode::Import) {
2485 assert!(!inaccessible_path_strings.is_empty());
2487 let prefix = if let DiagnosticMode::Pattern = mode {
2488 "you might have meant to match on "
2492 if inaccessible_path_strings.len() == 1 {
2493 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2495 "{}{} `{}`{} exists but is inaccessible",
2499 if let DiagnosticMode::Pattern = mode { ", which" } else { "" }
2502 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2503 let span = source_span[local_def_id];
2504 let span = session.source_map().guess_head_span(span);
2505 let mut multi_span = MultiSpan::from_span(span);
2506 multi_span.push_span_label(span, "not accessible");
2507 err.span_note(multi_span, &msg);
2511 if let Some(note) = (*note).as_deref() {
2515 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2516 let descr = if inaccessible_path_strings
2519 .all(|(_, descr, _, _)| descr == descr_first)
2526 if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) };
2528 let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr);
2529 let mut has_colon = false;
2531 let mut spans = Vec::new();
2532 for (name, _, def_id, _) in &inaccessible_path_strings {
2533 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2534 let span = source_span[local_def_id];
2535 let span = session.source_map().guess_head_span(span);
2536 spans.push((name, span));
2547 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2548 for (name, span) in spans {
2549 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2552 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2556 err.span_note(multi_span, &msg);
2562 struct UsePlacementFinder {
2563 target_module: NodeId,
2564 first_legal_span: Option<Span>,
2565 first_use_span: Option<Span>,
2568 impl UsePlacementFinder {
2569 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2571 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2572 finder.visit_crate(krate);
2573 if let Some(use_span) = finder.first_use_span {
2574 (Some(use_span), FoundUse::Yes)
2576 (finder.first_legal_span, FoundUse::No)
2581 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2582 fn visit_crate(&mut self, c: &Crate) {
2583 if self.target_module == CRATE_NODE_ID {
2584 let inject = c.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(&c.items);
2591 visit::walk_crate(self, c);
2595 fn visit_item(&mut self, item: &'tcx ast::Item) {
2596 if self.target_module == item.id {
2597 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2598 let inject = mod_spans.inject_use_span;
2599 if is_span_suitable_for_use_injection(inject) {
2600 self.first_legal_span = Some(inject);
2602 self.first_use_span = search_for_any_use_in_items(items);
2606 visit::walk_item(self, item);
2611 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2613 if let ItemKind::Use(..) = item.kind {
2614 if is_span_suitable_for_use_injection(item.span) {
2615 return Some(item.span.shrink_to_lo());
2622 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2623 // don't suggest placing a use before the prelude
2624 // import or other generated ones
2628 /// Convert the given number into the corresponding ordinal
2629 pub(crate) fn ordinalize(v: usize) -> String {
2630 let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2636 format!("{v}{suffix}")