4 use rustc_ast::visit::{self, Visitor};
5 use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::struct_span_err;
9 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
10 use rustc_feature::BUILTIN_ATTRIBUTES;
11 use rustc_hir::def::Namespace::{self, *};
12 use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
13 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
14 use rustc_hir::PrimTy;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::bug;
17 use rustc_middle::ty::DefIdTree;
18 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
19 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
20 use rustc_session::lint::BuiltinLintDiagnostics;
21 use rustc_session::Session;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::MacroKind;
24 use rustc_span::lev_distance::find_best_match_for_name;
25 use rustc_span::source_map::SourceMap;
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
27 use rustc_span::{BytePos, Span};
30 use crate::imports::{Import, ImportKind, ImportResolver};
31 use crate::late::{PatternSource, Rib};
32 use crate::path_names_to_string;
33 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
34 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
35 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
36 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
37 use crate::{Segment, UseError};
42 type Res = def::Res<ast::NodeId>;
44 /// A vector of spans and replacements, a message and applicability.
45 pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability);
47 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
48 /// similarly named label and whether or not it is reachable.
49 pub(crate) type LabelSuggestion = (Ident, bool);
51 pub(crate) enum SuggestionTarget {
52 /// The target has a similar name as the name used by the programmer (probably a typo)
54 /// The target is the only valid item that can be used in the corresponding context
58 pub(crate) struct TypoSuggestion {
59 pub candidate: Symbol,
61 pub target: SuggestionTarget,
65 pub(crate) fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
66 Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
68 pub(crate) fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
69 Self { candidate, res, target: SuggestionTarget::SingleItem }
73 /// A free importable items suggested in case of resolution failure.
74 pub(crate) struct ImportSuggestion {
75 pub did: Option<DefId>,
76 pub descr: &'static str,
79 /// An extra note that should be issued if this item is suggested
80 pub note: Option<String>,
83 /// Adjust the impl span so that just the `impl` keyword is taken by removing
84 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
85 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
87 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
88 /// parser. If you need to use this function or something similar, please consider updating the
89 /// `source_map` functions and this function to something more robust.
90 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
91 let impl_span = sm.span_until_char(impl_span, '<');
92 sm.span_until_whitespace(impl_span)
95 impl<'a> Resolver<'a> {
96 pub(crate) fn report_errors(&mut self, krate: &Crate) {
97 self.report_with_use_injections(krate);
99 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
100 let msg = "macro-expanded `macro_export` macros from the current crate \
101 cannot be referred to by absolute paths";
102 self.lint_buffer.buffer_lint_with_diagnostic(
103 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
107 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
111 for ambiguity_error in &self.ambiguity_errors {
112 self.report_ambiguity_error(ambiguity_error);
115 let mut reported_spans = FxHashSet::default();
116 for error in &self.privacy_errors {
117 if reported_spans.insert(error.dedup_span) {
118 self.report_privacy_error(error);
123 fn report_with_use_injections(&mut self, krate: &Crate) {
124 for UseError { mut err, candidates, def_id, instead, suggestion, path } in
125 self.use_injections.drain(..)
127 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
128 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
132 if !candidates.is_empty() {
139 if instead { Instead::Yes } else { Instead::No },
144 } else if let Some((span, msg, sugg, appl)) = suggestion {
145 err.span_suggestion(span, msg, sugg, appl);
151 pub(crate) fn report_conflict<'b>(
156 new_binding: &NameBinding<'b>,
157 old_binding: &NameBinding<'b>,
159 // Error on the second of two conflicting names
160 if old_binding.span.lo() > new_binding.span.lo() {
161 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
164 let container = match parent.kind {
165 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
166 ModuleKind::Block => "block",
169 let old_noun = match old_binding.is_import() {
171 false => "definition",
174 let new_participle = match new_binding.is_import() {
180 (ident.name, self.session.source_map().guess_head_span(new_binding.span));
182 if let Some(s) = self.name_already_seen.get(&name) {
188 let old_kind = match (ns, old_binding.module()) {
189 (ValueNS, _) => "value",
190 (MacroNS, _) => "macro",
191 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
192 (TypeNS, Some(module)) if module.is_normal() => "module",
193 (TypeNS, Some(module)) if module.is_trait() => "trait",
194 (TypeNS, _) => "type",
197 let msg = format!("the name `{}` is defined multiple times", name);
199 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
200 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
201 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
202 true => struct_span_err!(self.session, span, E0254, "{}", msg),
203 false => struct_span_err!(self.session, span, E0260, "{}", msg),
205 _ => match (old_binding.is_import(), new_binding.is_import()) {
206 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
207 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
208 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
213 "`{}` must be defined only once in the {} namespace of this {}",
219 err.span_label(span, format!("`{}` re{} here", name, new_participle));
221 self.session.source_map().guess_head_span(old_binding.span),
222 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
225 // See https://github.com/rust-lang/rust/issues/32354
226 use NameBindingKind::Import;
227 let import = match (&new_binding.kind, &old_binding.kind) {
228 // If there are two imports where one or both have attributes then prefer removing the
229 // import without attributes.
230 (Import { import: new, .. }, Import { import: old, .. })
232 !new_binding.span.is_dummy()
233 && !old_binding.span.is_dummy()
234 && (new.has_attributes || old.has_attributes)
237 if old.has_attributes {
238 Some((new, new_binding.span, true))
240 Some((old, old_binding.span, true))
243 // Otherwise prioritize the new binding.
244 (Import { import, .. }, other) if !new_binding.span.is_dummy() => {
245 Some((import, new_binding.span, other.is_import()))
247 (other, Import { import, .. }) if !old_binding.span.is_dummy() => {
248 Some((import, old_binding.span, other.is_import()))
253 // Check if the target of the use for both bindings is the same.
254 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
255 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
257 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
258 // Only suggest removing an import if both bindings are to the same def, if both spans
259 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
260 // been introduced by an item.
261 let should_remove_import = duplicate
263 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
266 Some((import, span, true)) if should_remove_import && import.is_nested() => {
267 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
269 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
270 // Simple case - remove the entire import. Due to the above match arm, this can
271 // only be a single use so just remove it entirely.
272 err.tool_only_span_suggestion(
273 import.use_span_with_attributes,
274 "remove unnecessary import",
276 Applicability::MaybeIncorrect,
279 Some((import, span, _)) => {
280 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
286 self.name_already_seen.insert(name, span);
289 /// This function adds a suggestion to change the binding name of a new import that conflicts
290 /// with an existing import.
292 /// ```text,ignore (diagnostic)
293 /// help: you can use `as` to change the binding name of the import
295 /// LL | use foo::bar as other_bar;
296 /// | ^^^^^^^^^^^^^^^^^^^^^
298 fn add_suggestion_for_rename_of_use(
300 err: &mut Diagnostic,
305 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
306 format!("Other{}", name)
308 format!("other_{}", name)
311 let mut suggestion = None;
313 ImportKind::Single { type_ns_only: true, .. } => {
314 suggestion = Some(format!("self as {}", suggested_name))
316 ImportKind::Single { source, .. } => {
318 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
320 if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
321 if pos <= snippet.len() {
322 suggestion = Some(format!(
326 if snippet.ends_with(';') { ";" } else { "" }
332 ImportKind::ExternCrate { source, target } => {
333 suggestion = Some(format!(
334 "extern crate {} as {};",
335 source.unwrap_or(target.name),
342 let rename_msg = "you can use `as` to change the binding name of the import";
343 if let Some(suggestion) = suggestion {
348 Applicability::MaybeIncorrect,
351 err.span_label(binding_span, rename_msg);
355 /// This function adds a suggestion to remove an unnecessary binding from an import that is
356 /// nested. In the following example, this function will be invoked to remove the `a` binding
357 /// in the second use statement:
359 /// ```ignore (diagnostic)
360 /// use issue_52891::a;
361 /// use issue_52891::{d, a, e};
364 /// The following suggestion will be added:
366 /// ```ignore (diagnostic)
367 /// use issue_52891::{d, a, e};
368 /// ^-- help: remove unnecessary import
371 /// If the nested use contains only one import then the suggestion will remove the entire
374 /// It is expected that the provided import is nested - this isn't checked by the
375 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
376 /// as characters expected by span manipulations won't be present.
377 fn add_suggestion_for_duplicate_nested_use(
379 err: &mut Diagnostic,
383 assert!(import.is_nested());
384 let message = "remove unnecessary import";
386 // Two examples will be used to illustrate the span manipulations we're doing:
388 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
389 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
390 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
391 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
393 let (found_closing_brace, span) =
394 find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
396 // If there was a closing brace then identify the span to remove any trailing commas from
398 if found_closing_brace {
399 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
400 err.tool_only_span_suggestion(span, message, "", Applicability::MaybeIncorrect);
402 // Remove the entire line if we cannot extend the span back, this indicates an
403 // `issue_52891::{self}` case.
405 import.use_span_with_attributes,
408 Applicability::MaybeIncorrect,
415 err.span_suggestion(span, message, "", Applicability::MachineApplicable);
418 pub(crate) fn lint_if_path_starts_with_module(
420 finalize: Option<Finalize>,
422 second_binding: Option<&NameBinding<'_>>,
424 let Some(Finalize { node_id, root_span, .. }) = finalize else {
428 let first_name = match path.get(0) {
429 // In the 2018 edition this lint is a hard error, so nothing to do
430 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
434 // We're only interested in `use` paths which should start with
435 // `{{root}}` currently.
436 if first_name != kw::PathRoot {
441 // If this import looks like `crate::...` it's already good
442 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
443 // Otherwise go below to see if it's an extern crate
445 // If the path has length one (and it's `PathRoot` most likely)
446 // then we don't know whether we're gonna be importing a crate or an
447 // item in our crate. Defer this lint to elsewhere
451 // If the first element of our path was actually resolved to an
452 // `ExternCrate` (also used for `crate::...`) then no need to issue a
453 // warning, this looks all good!
454 if let Some(binding) = second_binding {
455 if let NameBindingKind::Import { import, .. } = binding.kind {
456 // Careful: we still want to rewrite paths from renamed extern crates.
457 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
463 let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
464 self.lint_buffer.buffer_lint_with_diagnostic(
465 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
468 "absolute paths must start with `self`, `super`, \
469 `crate`, or an external crate name in the 2018 edition",
474 pub(crate) fn add_module_candidates(
477 names: &mut Vec<TypoSuggestion>,
478 filter_fn: &impl Fn(Res) -> bool,
480 for (key, resolution) in self.resolutions(module).borrow().iter() {
481 if let Some(binding) = resolution.borrow().binding {
482 let res = binding.res();
484 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
490 /// Combines an error with provided span and emits it.
492 /// This takes the error provided, combines it with the span and any additional spans inside the
493 /// error and emits it.
494 pub(crate) fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
495 self.into_struct_error(span, resolution_error).emit();
498 pub(crate) fn into_struct_error(
501 resolution_error: ResolutionError<'a>,
502 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
503 match resolution_error {
504 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
505 let mut err = struct_span_err!(
509 "can't use generic parameters from outer function",
511 err.span_label(span, "use of generic parameter from outer function");
513 let sm = self.session.source_map();
515 Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => {
516 if let Some(impl_span) =
517 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
520 reduce_impl_span_to_impl_keyword(sm, impl_span),
521 "`Self` type implicitly declared here, by this `impl`",
524 match (maybe_trait_defid, maybe_impl_defid) {
526 err.span_label(span, "can't use `Self` here");
529 err.span_label(span, "use a type here instead");
531 (None, None) => bug!("`impl` without trait nor type?"),
535 Res::Def(DefKind::TyParam, def_id) => {
536 if let Some(span) = self.opt_span(def_id) {
537 err.span_label(span, "type parameter from outer function");
540 Res::Def(DefKind::ConstParam, def_id) => {
541 if let Some(span) = self.opt_span(def_id) {
542 err.span_label(span, "const parameter from outer function");
547 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
548 DefKind::TyParam or DefKind::ConstParam"
553 if has_generic_params == HasGenericParams::Yes {
554 // Try to retrieve the span of the function signature and generate a new
555 // message with a local type or const parameter.
556 let sugg_msg = "try using a local generic parameter instead";
557 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
558 // Suggest the modification to the user
563 Applicability::MachineApplicable,
565 } else if let Some(sp) = sm.generate_fn_name_span(span) {
568 "try adding a local generic parameter in this method instead",
571 err.help("try using a local generic parameter instead");
577 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
578 let mut err = struct_span_err!(
582 "the name `{}` is already used for a generic \
583 parameter in this item's generic parameters",
586 err.span_label(span, "already used");
587 err.span_label(first_use_span, format!("first use of `{}`", name));
590 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
591 let mut err = struct_span_err!(
595 "method `{}` is not a member of trait `{}`",
599 err.span_label(span, format!("not a member of trait `{}`", trait_));
600 if let Some(candidate) = candidate {
603 "there is an associated function with a similar name",
604 candidate.to_ident_string(),
605 Applicability::MaybeIncorrect,
610 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
611 let mut err = struct_span_err!(
615 "type `{}` is not a member of trait `{}`",
619 err.span_label(span, format!("not a member of trait `{}`", trait_));
620 if let Some(candidate) = candidate {
623 "there is an associated type with a similar name",
624 candidate.to_ident_string(),
625 Applicability::MaybeIncorrect,
630 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
631 let mut err = struct_span_err!(
635 "const `{}` is not a member of trait `{}`",
639 err.span_label(span, format!("not a member of trait `{}`", trait_));
640 if let Some(candidate) = candidate {
643 "there is an associated constant with a similar name",
644 candidate.to_ident_string(),
645 Applicability::MaybeIncorrect,
650 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
651 let BindingError { name, target, origin, could_be_path } = binding_error;
653 let target_sp = target.iter().copied().collect::<Vec<_>>();
654 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
656 let msp = MultiSpan::from_spans(target_sp.clone());
657 let mut err = struct_span_err!(
661 "variable `{}` is not bound in all patterns",
664 for sp in target_sp {
665 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
667 for sp in origin_sp {
668 err.span_label(sp, "variable not in all patterns");
671 let import_suggestions = self.lookup_import_candidates(
672 Ident::with_dummy_span(name),
675 &|res: Res| match res {
677 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
678 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
680 | DefKind::AssocConst,
687 if import_suggestions.is_empty() {
688 let help_msg = format!(
689 "if you meant to match on a variant or a `const` item, consider \
690 making the path in the pattern qualified: `path::to::ModOrType::{}`",
693 err.span_help(span, &help_msg);
709 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
710 let mut err = struct_span_err!(
714 "variable `{}` is bound inconsistently across alternatives separated by `|`",
717 err.span_label(span, "bound in different ways");
718 err.span_label(first_binding_span, "first binding");
721 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
722 let mut err = struct_span_err!(
726 "identifier `{}` is bound more than once in this parameter list",
729 err.span_label(span, "used as parameter more than once");
732 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
733 let mut err = struct_span_err!(
737 "identifier `{}` is bound more than once in the same pattern",
740 err.span_label(span, "used in a pattern more than once");
743 ResolutionError::UndeclaredLabel { name, suggestion } => {
744 let mut err = struct_span_err!(
748 "use of undeclared label `{}`",
752 err.span_label(span, format!("undeclared label `{}`", name));
755 // A reachable label with a similar name exists.
756 Some((ident, true)) => {
757 err.span_label(ident.span, "a label with a similar name is reachable");
760 "try using similarly named label",
762 Applicability::MaybeIncorrect,
765 // An unreachable label with a similar name exists.
766 Some((ident, false)) => {
769 "a label with a similar name exists but is unreachable",
772 // No similarly-named labels exist.
778 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
779 let mut err = struct_span_err!(
784 "`self` imports are only allowed within a { } list"
787 // None of the suggestions below would help with a case like `use self`.
789 // use foo::bar::self -> foo::bar
790 // use foo::bar::self as abc -> foo::bar as abc
793 "consider importing the module directly",
795 Applicability::MachineApplicable,
798 // use foo::bar::self -> foo::bar::{self}
799 // use foo::bar::self as abc -> foo::bar::{self as abc}
801 (span_with_rename.shrink_to_lo(), "{".to_string()),
802 (span_with_rename.shrink_to_hi(), "}".to_string()),
804 err.multipart_suggestion(
805 "alternatively, use the multi-path `use` syntax to import `self`",
807 Applicability::MachineApplicable,
812 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
813 let mut err = struct_span_err!(
817 "`self` import can only appear once in an import list"
819 err.span_label(span, "can only appear once in an import list");
822 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
823 let mut err = struct_span_err!(
827 "`self` import can only appear in an import list with \
830 err.span_label(span, "can only appear in an import list with a non-empty prefix");
833 ResolutionError::FailedToResolve { label, suggestion } => {
835 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
836 err.span_label(span, label);
838 if let Some((suggestions, msg, applicability)) = suggestion {
839 if suggestions.is_empty() {
843 err.multipart_suggestion(&msg, suggestions, applicability);
848 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
849 let mut err = struct_span_err!(
854 "can't capture dynamic environment in a fn item"
856 err.help("use the `|| { ... }` closure form instead");
859 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
860 let mut err = struct_span_err!(
864 "attempt to use a non-constant value in a constant"
867 // ^^^ given this Span
868 // ------- get this Span to have an applicable suggestion
871 // only do this if the const and usage of the non-constant value are on the same line
872 // the further the two are apart, the higher the chance of the suggestion being wrong
877 .span_extend_to_prev_str(ident.span, current, true, false);
880 Some(sp) if !self.session.source_map().is_multiline(sp) => {
881 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
884 &format!("consider using `{}` instead of `{}`", sugg, current),
885 format!("{} {}", sugg, ident),
886 Applicability::MaybeIncorrect,
888 err.span_label(span, "non-constant value");
891 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
897 ResolutionError::BindingShadowsSomethingUnacceptable {
903 shadowed_binding_span,
905 let shadowed_binding_descr = shadowed_binding.descr();
906 let mut err = struct_span_err!(
910 "{}s cannot shadow {}s",
911 shadowing_binding.descr(),
912 shadowed_binding_descr,
916 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
918 match (shadowing_binding, shadowed_binding) {
920 PatternSource::Match,
921 Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _),
925 "try specify the pattern arguments",
926 format!("{}(..)", name),
927 Applicability::Unspecified,
933 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
934 err.span_label(shadowed_binding_span, msg);
937 ResolutionError::ForwardDeclaredGenericParam => {
938 let mut err = struct_span_err!(
942 "generic parameters with a default cannot use \
943 forward declared identifiers"
945 err.span_label(span, "defaulted generic parameters cannot be forward declared");
948 ResolutionError::ParamInTyOfConstParam(name) => {
949 let mut err = struct_span_err!(
953 "the type of const parameters must not depend on other generic parameters"
957 format!("the type must not depend on the parameter `{}`", name),
961 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
962 let mut err = self.session.struct_span_err(
964 "generic parameters may not be used in const operations",
966 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
969 err.note("type parameters may not be used in const expressions");
972 "const parameters may only be used as standalone arguments, i.e. `{}`",
977 if self.session.is_nightly_build() {
979 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
985 ResolutionError::SelfInGenericParamDefault => {
986 let mut err = struct_span_err!(
990 "generic parameters cannot use `Self` in their defaults"
992 err.span_label(span, "`Self` in generic parameter default");
995 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
996 let mut err = struct_span_err!(
1000 "use of unreachable label `{}`",
1004 err.span_label(definition_span, "unreachable label defined here");
1005 err.span_label(span, format!("unreachable label `{}`", name));
1007 "labels are unreachable through functions, closures, async blocks and modules",
1011 // A reachable label with a similar name exists.
1012 Some((ident, true)) => {
1013 err.span_label(ident.span, "a label with a similar name is reachable");
1014 err.span_suggestion(
1016 "try using similarly named label",
1018 Applicability::MaybeIncorrect,
1021 // An unreachable label with a similar name exists.
1022 Some((ident, false)) => {
1025 "a label with a similar name exists but is also unreachable",
1028 // No similarly-named labels exist.
1034 ResolutionError::TraitImplMismatch {
1041 let mut err = self.session.struct_span_err_with_code(
1044 "item `{}` is an associated {}, which doesn't match its trait `{}`",
1045 name, kind, trait_path,
1049 err.span_label(span, "does not match trait");
1050 err.span_label(trait_item_span, "item in trait");
1053 ResolutionError::InvalidAsmSym => {
1054 let mut err = self.session.struct_span_err(span, "invalid `sym` operand");
1055 err.span_label(span, "is a local variable");
1056 err.help("`sym` operands must refer to either a function or a static");
1062 pub(crate) fn report_vis_error(
1064 vis_resolution_error: VisResolutionError<'_>,
1065 ) -> ErrorGuaranteed {
1066 match vis_resolution_error {
1067 VisResolutionError::Relative2018(span, path) => {
1068 let mut err = self.session.struct_span_err(
1070 "relative paths are not supported in visibilities in 2018 edition or later",
1072 err.span_suggestion(
1075 format!("crate::{}", pprust::path_to_string(&path)),
1076 Applicability::MaybeIncorrect,
1080 VisResolutionError::AncestorOnly(span) => struct_span_err!(
1084 "visibilities can only be restricted to ancestor modules"
1086 VisResolutionError::FailedToResolve(span, label, suggestion) => {
1087 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
1089 VisResolutionError::ExpectedFound(span, path_str, res) => {
1090 let mut err = struct_span_err!(
1094 "expected module, found {} `{}`",
1098 err.span_label(span, "not a module");
1101 VisResolutionError::Indeterminate(span) => struct_span_err!(
1105 "cannot determine resolution for the visibility"
1107 VisResolutionError::ModuleOnly(span) => {
1108 self.session.struct_span_err(span, "visibility must resolve to a module")
1114 /// Lookup typo candidate in scope for a macro or import.
1115 fn early_lookup_typo_candidate(
1117 scope_set: ScopeSet<'a>,
1118 parent_scope: &ParentScope<'a>,
1120 filter_fn: &impl Fn(Res) -> bool,
1121 ) -> Option<TypoSuggestion> {
1122 let mut suggestions = Vec::new();
1123 let ctxt = ident.span.ctxt();
1124 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1126 Scope::DeriveHelpers(expn_id) => {
1127 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1134 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1138 Scope::DeriveHelpersCompat => {
1139 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1141 for derive in parent_scope.derives {
1142 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1143 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1145 Some(MacroKind::Derive),
1153 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
1159 Scope::MacroRules(macro_rules_scope) => {
1160 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1161 let res = macro_rules_binding.binding.res();
1163 suggestions.push(TypoSuggestion::typo_from_res(
1164 macro_rules_binding.ident.name,
1170 Scope::CrateRoot => {
1171 let root_ident = Ident::new(kw::PathRoot, ident.span);
1172 let root_module = this.resolve_crate_root(root_ident);
1173 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
1175 Scope::Module(module, _) => {
1176 this.add_module_candidates(module, &mut suggestions, filter_fn);
1178 Scope::RegisteredAttrs => {
1179 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
1182 this.registered_attrs
1184 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1188 Scope::MacroUsePrelude => {
1189 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1191 let res = binding.res();
1192 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
1196 Scope::BuiltinAttrs => {
1197 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1202 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
1206 Scope::ExternPrelude => {
1207 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1208 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1209 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
1212 Scope::ToolPrelude => {
1213 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1215 this.registered_tools
1217 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1220 Scope::StdLibPrelude => {
1221 if let Some(prelude) = this.prelude {
1222 let mut tmp_suggestions = Vec::new();
1223 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
1227 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1231 Scope::BuiltinTypes => {
1232 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1233 let res = Res::PrimTy(*prim_ty);
1234 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
1242 // Make sure error reporting is deterministic.
1243 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1245 match find_best_match_for_name(
1246 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1250 Some(found) if found != ident.name => {
1251 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1257 fn lookup_import_candidates_from_module<FilterFn>(
1259 lookup_ident: Ident,
1260 namespace: Namespace,
1261 parent_scope: &ParentScope<'a>,
1262 start_module: Module<'a>,
1264 filter_fn: FilterFn,
1265 ) -> Vec<ImportSuggestion>
1267 FilterFn: Fn(Res) -> bool,
1269 let mut candidates = Vec::new();
1270 let mut seen_modules = FxHashSet::default();
1271 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
1272 let mut worklist_via_import = vec![];
1274 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1275 None => worklist_via_import.pop(),
1278 let in_module_is_extern = !in_module.def_id().is_local();
1279 // We have to visit module children in deterministic order to avoid
1280 // instabilities in reported imports (#43552).
1281 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1282 // avoid non-importable candidates
1283 if !name_binding.is_importable() {
1287 let child_accessible =
1288 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1290 // do not venture inside inaccessible items of other crates
1291 if in_module_is_extern && !child_accessible {
1295 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1297 // There is an assumption elsewhere that paths of variants are in the enum's
1298 // declaration and not imported. With this assumption, the variant component is
1299 // chopped and the rest of the path is assumed to be the enum's own path. For
1300 // errors where a variant is used as the type instead of the enum, this causes
1301 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1302 if via_import && name_binding.is_possibly_imported_variant() {
1306 // #90113: Do not count an inaccessible reexported item as a candidate.
1307 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1308 if this.is_accessible_from(binding.vis, parent_scope.module)
1309 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1315 // collect results based on the filter function
1316 // avoid suggesting anything from the same module in which we are resolving
1317 // avoid suggesting anything with a hygienic name
1318 if ident.name == lookup_ident.name
1320 && !ptr::eq(in_module, parent_scope.module)
1321 && !ident.span.normalize_to_macros_2_0().from_expansion()
1323 let res = name_binding.res();
1326 let mut segms = path_segments.clone();
1327 if lookup_ident.span.rust_2018() {
1328 // crate-local absolute paths start with `crate::` in edition 2018
1329 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1330 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1333 segms.push(ast::PathSegment::from_ident(ident));
1334 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1335 let did = match res {
1336 Res::Def(DefKind::Ctor(..), did) => this.opt_parent(did),
1337 _ => res.opt_def_id(),
1340 if child_accessible {
1341 // Remove invisible match if exists
1342 if let Some(idx) = candidates
1344 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1346 candidates.remove(idx);
1350 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1351 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1352 // a note about editions
1353 let note = if let Some(did) = did {
1354 let requires_note = !did.is_local()
1355 && this.cstore().item_attrs_untracked(did, this.session).any(
1357 if attr.has_name(sym::rustc_diagnostic_item) {
1358 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1360 .contains(&attr.value_str())
1367 requires_note.then(|| {
1369 "'{}' is included in the prelude starting in Edition 2021",
1370 path_names_to_string(&path)
1377 candidates.push(ImportSuggestion {
1381 accessible: child_accessible,
1388 // collect submodules to explore
1389 if let Some(module) = name_binding.module() {
1391 let mut path_segments = path_segments.clone();
1392 path_segments.push(ast::PathSegment::from_ident(ident));
1394 let is_extern_crate_that_also_appears_in_prelude =
1395 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1397 if !is_extern_crate_that_also_appears_in_prelude {
1398 // add the module to the lookup
1399 if seen_modules.insert(module.def_id()) {
1400 if via_import { &mut worklist_via_import } else { &mut worklist }
1401 .push((module, path_segments, child_accessible));
1408 // If only some candidates are accessible, take just them
1409 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1410 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
1416 /// When name resolution fails, this method can be used to look up candidate
1417 /// entities with the expected name. It allows filtering them using the
1418 /// supplied predicate (which should be used to only accept the types of
1419 /// definitions expected, e.g., traits). The lookup spans across all crates.
1421 /// N.B., the method does not look into imports, but this is not a problem,
1422 /// since we report the definitions (thus, the de-aliased imports).
1423 pub(crate) fn lookup_import_candidates<FilterFn>(
1425 lookup_ident: Ident,
1426 namespace: Namespace,
1427 parent_scope: &ParentScope<'a>,
1428 filter_fn: FilterFn,
1429 ) -> Vec<ImportSuggestion>
1431 FilterFn: Fn(Res) -> bool,
1433 let mut suggestions = self.lookup_import_candidates_from_module(
1438 Ident::with_dummy_span(kw::Crate),
1442 if lookup_ident.span.rust_2018() {
1443 let extern_prelude_names = self.extern_prelude.clone();
1444 for (ident, _) in extern_prelude_names.into_iter() {
1445 if ident.span.from_expansion() {
1446 // Idents are adjusted to the root context before being
1447 // resolved in the extern prelude, so reporting this to the
1448 // user is no help. This skips the injected
1449 // `extern crate std` in the 2018 edition, which would
1450 // otherwise cause duplicate suggestions.
1453 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1454 let crate_root = self.expect_module(crate_id.as_def_id());
1455 suggestions.extend(self.lookup_import_candidates_from_module(
1470 pub(crate) fn unresolved_macro_suggestions(
1472 err: &mut Diagnostic,
1473 macro_kind: MacroKind,
1474 parent_scope: &ParentScope<'a>,
1477 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1478 let suggestion = self.early_lookup_typo_candidate(
1479 ScopeSet::Macro(macro_kind),
1484 self.add_typo_suggestion(err, suggestion, ident.span);
1486 let import_suggestions =
1487 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1493 &import_suggestions,
1500 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1501 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1502 err.span_note(ident.span, &msg);
1505 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1506 err.help("have you added the `#[macro_use]` on the module/import?");
1509 if ident.name == kw::Default
1510 && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind
1511 && let Some(span) = self.opt_span(def_id)
1513 let source_map = self.session.source_map();
1514 let head_span = source_map.guess_head_span(span);
1515 if let Ok(head) = source_map.span_to_snippet(head_span) {
1516 err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect);
1520 "consider adding `#[derive(Default)]` to this enum",
1524 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1525 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1527 ScopeSet::All(ns, false),
1533 let desc = match binding.res() {
1534 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1535 "a function-like macro".to_string()
1537 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1538 format!("an attribute: `#[{}]`", ident)
1540 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1541 format!("a derive macro: `#[derive({})]`", ident)
1544 // Don't confuse the user with tool modules.
1547 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1548 "only a trait, without a derive macro".to_string()
1554 macro_kind.article(),
1555 macro_kind.descr_expected(),
1558 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1559 if !import.span.is_dummy() {
1562 &format!("`{}` is imported here, but it is {}", ident, desc),
1564 // Silence the 'unused import' warning we might get,
1565 // since this diagnostic already covers that import.
1566 self.record_use(ident, binding, false);
1570 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1576 pub(crate) fn add_typo_suggestion(
1578 err: &mut Diagnostic,
1579 suggestion: Option<TypoSuggestion>,
1582 let suggestion = match suggestion {
1583 None => return false,
1584 // We shouldn't suggest underscore.
1585 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1586 Some(suggestion) => suggestion,
1588 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1589 LOCAL_CRATE => self.opt_span(def_id),
1593 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1596 if let Some(def_span) = def_span {
1597 if span.overlaps(def_span) {
1598 // Don't suggest typo suggestion for itself like in the following:
1599 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1600 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1603 // | ----------- `X` defined here
1605 // LL | const Y: X = X("ö");
1606 // | -------------^^^^^^- similarly named constant `Y` defined here
1608 // help: use struct literal syntax instead
1610 // LL | const Y: X = X {};
1612 // help: a constant with a similar name exists
1614 // LL | const Y: X = Y("ö");
1618 let prefix = match suggestion.target {
1619 SuggestionTarget::SimilarlyNamed => "similarly named ",
1620 SuggestionTarget::SingleItem => "",
1624 self.session.source_map().guess_head_span(def_span),
1626 "{}{} `{}` defined here",
1628 suggestion.res.descr(),
1629 suggestion.candidate,
1633 let msg = match suggestion.target {
1634 SuggestionTarget::SimilarlyNamed => format!(
1635 "{} {} with a similar name exists",
1636 suggestion.res.article(),
1637 suggestion.res.descr()
1639 SuggestionTarget::SingleItem => {
1640 format!("maybe you meant this {}", suggestion.res.descr())
1643 err.span_suggestion(span, &msg, suggestion.candidate, Applicability::MaybeIncorrect);
1647 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1649 if b.span.is_dummy() || !self.session.source_map().is_span_accessible(b.span) {
1650 // These already contain the "built-in" prefix or look bad with it.
1652 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1653 let (built_in, from) = if from_prelude {
1654 ("", " from prelude")
1655 } else if b.is_extern_crate()
1657 && self.session.opts.externs.get(ident.as_str()).is_some()
1659 ("", " passed with `--extern`")
1660 } else if add_built_in {
1666 let a = if built_in.is_empty() { res.article() } else { "a" };
1667 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1669 let introduced = if b.is_import() { "imported" } else { "defined" };
1670 format!("the {thing} {introduced} here", thing = res.descr())
1674 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1675 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1676 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1677 // We have to print the span-less alternative first, otherwise formatting looks bad.
1678 (b2, b1, misc2, misc1, true)
1680 (b1, b2, misc1, misc2, false)
1683 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1684 err.span_label(ident.span, "ambiguous name");
1685 err.note(&format!("ambiguous because of {}", kind.descr()));
1687 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1688 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1689 let note_msg = format!("`{ident}` could{also} refer to {what}");
1691 let thing = b.res().descr();
1692 let mut help_msgs = Vec::new();
1693 if b.is_glob_import()
1694 && (kind == AmbiguityKind::GlobVsGlob
1695 || kind == AmbiguityKind::GlobVsExpanded
1696 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1698 help_msgs.push(format!(
1699 "consider adding an explicit import of `{ident}` to disambiguate"
1702 if b.is_extern_crate() && ident.span.rust_2018() {
1703 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1705 if misc == AmbiguityErrorMisc::SuggestCrate {
1707 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1708 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1710 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1713 err.span_note(b.span, ¬e_msg);
1714 for (i, help_msg) in help_msgs.iter().enumerate() {
1715 let or = if i == 0 { "" } else { "or " };
1716 err.help(&format!("{}{}", or, help_msg));
1720 could_refer_to(b1, misc1, "");
1721 could_refer_to(b2, misc2, " also");
1725 /// If the binding refers to a tuple struct constructor with fields,
1726 /// returns the span of its fields.
1727 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1728 if let NameBindingKind::Res(
1729 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1733 let def_id = self.parent(ctor_def_id);
1734 let fields = self.field_names.get(&def_id)?;
1735 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1740 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1741 let PrivacyError { ident, binding, .. } = *privacy_error;
1743 let res = binding.res();
1744 let ctor_fields_span = self.ctor_fields_span(binding);
1745 let plain_descr = res.descr().to_string();
1746 let nonimport_descr =
1747 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1748 let import_descr = nonimport_descr.clone() + " import";
1750 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1752 // Print the primary message.
1753 let descr = get_descr(binding);
1755 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1756 err.span_label(ident.span, &format!("private {}", descr));
1757 if let Some(span) = ctor_fields_span {
1758 err.span_label(span, "a constructor is private if any of the fields is private");
1761 // Print the whole import chain to make it easier to see what happens.
1762 let first_binding = binding;
1763 let mut next_binding = Some(binding);
1764 let mut next_ident = ident;
1765 while let Some(binding) = next_binding {
1766 let name = next_ident;
1767 next_binding = match binding.kind {
1768 _ if res == Res::Err => None,
1769 NameBindingKind::Import { binding, import, .. } => match import.kind {
1770 _ if binding.span.is_dummy() => None,
1771 ImportKind::Single { source, .. } => {
1772 next_ident = source;
1775 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1776 ImportKind::ExternCrate { .. } => None,
1781 let first = ptr::eq(binding, first_binding);
1783 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1784 and_refers_to = if first { "" } else { "...and refers to " },
1785 item = get_descr(binding),
1786 which = if first { "" } else { " which" },
1787 dots = if next_binding.is_some() { "..." } else { "" },
1789 let def_span = self.session.source_map().guess_head_span(binding.span);
1790 let mut note_span = MultiSpan::from_span(def_span);
1791 if !first && binding.vis.is_public() {
1792 note_span.push_span_label(def_span, "consider importing it directly");
1794 err.span_note(note_span, &msg);
1800 pub(crate) fn find_similarly_named_module_or_crate(
1803 current_module: &Module<'a>,
1804 ) -> Option<Symbol> {
1805 let mut candidates = self
1808 .map(|(ident, _)| ident.name)
1812 .filter(|(_, module)| {
1813 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1815 .flat_map(|(_, module)| module.kind.name()),
1817 .filter(|c| !c.to_string().is_empty())
1818 .collect::<Vec<_>>();
1821 match find_best_match_for_name(&candidates, ident, None) {
1822 Some(sugg) if sugg == ident => None,
1827 pub(crate) fn report_path_resolution_error(
1830 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1831 parent_scope: &ParentScope<'a>,
1832 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1833 ignore_binding: Option<&'a NameBinding<'a>>,
1834 module: Option<ModuleOrUniformRoot<'a>>,
1837 ) -> (String, Option<Suggestion>) {
1838 let is_last = i == path.len() - 1;
1839 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1840 let module_res = match module {
1841 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1844 if module_res == self.graph_root.res() {
1845 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1846 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1848 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1849 if let Some(candidate) = candidates.get(0) {
1851 String::from("unresolved import"),
1853 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1854 String::from("a similar path exists"),
1855 Applicability::MaybeIncorrect,
1858 } else if self.session.edition() == Edition::Edition2015 {
1860 format!("maybe a missing crate `{ident}`?"),
1864 "consider adding `extern crate {ident}` to use the `{ident}` crate"
1866 Applicability::MaybeIncorrect,
1870 (format!("could not find `{ident}` in the crate root"), None)
1873 let parent = path[i - 1].ident.name;
1874 let parent = match parent {
1875 // ::foo is mounted at the crate root for 2015, and is the extern
1876 // prelude for 2018+
1877 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1878 "the list of imported crates".to_owned()
1880 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1881 _ => format!("`{parent}`"),
1884 let mut msg = format!("could not find `{}` in {}", ident, parent);
1885 if ns == TypeNS || ns == ValueNS {
1886 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1887 let binding = if let Some(module) = module {
1888 self.resolve_ident_in_module(
1896 } else if let Some(ribs) = ribs
1897 && let Some(TypeNS | ValueNS) = opt_ns
1899 match self.resolve_ident_in_lexical_scope(
1907 // we found a locally-imported or available item/module
1908 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1912 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1913 self.early_resolve_ident_in_lexical_scope(
1922 if let Some(binding) = binding {
1923 let mut found = |what| {
1925 "expected {}, found {} `{}` in {}",
1932 if binding.module().is_some() {
1935 match binding.res() {
1936 Res::Def(kind, id) => found(kind.descr(id)),
1937 _ => found(ns_to_try.descr()),
1943 } else if ident.name == kw::SelfUpper {
1944 ("`Self` is only available in impls, traits, and type definitions".to_string(), None)
1945 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1946 // Check whether the name refers to an item in the value namespace.
1947 let binding = if let Some(ribs) = ribs {
1948 self.resolve_ident_in_lexical_scope(
1959 let match_span = match binding {
1960 // Name matches a local variable. For example:
1963 // let Foo: &str = "";
1964 // println!("{}", Foo::Bar); // Name refers to local
1965 // // variable `Foo`.
1968 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1969 Some(*self.pat_span_map.get(&id).unwrap())
1971 // Name matches item from a local name binding
1972 // created by `use` declaration. For example:
1974 // pub Foo: &str = "";
1978 // println!("{}", Foo::Bar); // Name refers to local
1979 // // binding `Foo`.
1982 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1985 let suggestion = if let Some(span) = match_span {
1987 vec![(span, String::from(""))],
1988 format!("`{}` is defined here, but is not a type", ident),
1989 Applicability::MaybeIncorrect,
1995 (format!("use of undeclared type `{}`", ident), suggestion)
1997 let suggestion = if ident.name == sym::alloc {
2000 String::from("add `extern crate alloc` to use the `alloc` crate"),
2001 Applicability::MaybeIncorrect,
2004 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
2007 vec![(ident.span, sugg.to_string())],
2008 String::from("there is a crate or module with a similar name"),
2009 Applicability::MaybeIncorrect,
2014 (format!("use of undeclared crate or module `{}`", ident), suggestion)
2019 impl<'a, 'b> ImportResolver<'a, 'b> {
2020 /// Adds suggestions for a path that cannot be resolved.
2021 pub(crate) fn make_path_suggestion(
2024 mut path: Vec<Segment>,
2025 parent_scope: &ParentScope<'b>,
2026 ) -> Option<(Vec<Segment>, Vec<String>)> {
2027 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
2029 match (path.get(0), path.get(1)) {
2030 // `{{root}}::ident::...` on both editions.
2031 // On 2015 `{{root}}` is usually added implicitly.
2032 (Some(fst), Some(snd))
2033 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
2034 // `ident::...` on 2018.
2036 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
2038 // Insert a placeholder that's later replaced by `self`/`super`/etc.
2039 path.insert(0, Segment::from_ident(Ident::empty()));
2044 self.make_missing_self_suggestion(path.clone(), parent_scope)
2045 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2046 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2047 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2050 /// Suggest a missing `self::` if that resolves to an correct module.
2054 /// LL | use foo::Bar;
2055 /// | ^^^ did you mean `self::foo`?
2057 fn make_missing_self_suggestion(
2059 mut path: Vec<Segment>,
2060 parent_scope: &ParentScope<'b>,
2061 ) -> Option<(Vec<Segment>, Vec<String>)> {
2062 // Replace first ident with `self` and check if that is valid.
2063 path[0].ident.name = kw::SelfLower;
2064 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2065 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
2066 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2069 /// Suggests a missing `crate::` if that resolves to an correct module.
2073 /// LL | use foo::Bar;
2074 /// | ^^^ did you mean `crate::foo`?
2076 fn make_missing_crate_suggestion(
2078 mut path: Vec<Segment>,
2079 parent_scope: &ParentScope<'b>,
2080 ) -> Option<(Vec<Segment>, Vec<String>)> {
2081 // Replace first ident with `crate` and check if that is valid.
2082 path[0].ident.name = kw::Crate;
2083 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2084 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
2085 if let PathResult::Module(..) = result {
2089 "`use` statements changed in Rust 2018; read more at \
2090 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2100 /// Suggests a missing `super::` if that resolves to an correct module.
2104 /// LL | use foo::Bar;
2105 /// | ^^^ did you mean `super::foo`?
2107 fn make_missing_super_suggestion(
2109 mut path: Vec<Segment>,
2110 parent_scope: &ParentScope<'b>,
2111 ) -> Option<(Vec<Segment>, Vec<String>)> {
2112 // Replace first ident with `crate` and check if that is valid.
2113 path[0].ident.name = kw::Super;
2114 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2115 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
2116 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2119 /// Suggests a missing external crate name if that resolves to an correct module.
2123 /// LL | use foobar::Baz;
2124 /// | ^^^^^^ did you mean `baz::foobar`?
2127 /// Used when importing a submodule of an external crate but missing that crate's
2128 /// name as the first part of path.
2129 fn make_external_crate_suggestion(
2131 mut path: Vec<Segment>,
2132 parent_scope: &ParentScope<'b>,
2133 ) -> Option<(Vec<Segment>, Vec<String>)> {
2134 if path[1].ident.span.rust_2015() {
2138 // Sort extern crate names in *reverse* order to get
2139 // 1) some consistent ordering for emitted diagnostics, and
2140 // 2) `std` suggestions before `core` suggestions.
2141 let mut extern_crate_names =
2142 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2143 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2145 for name in extern_crate_names.into_iter() {
2146 // Replace first ident with a crate name and check if that is valid.
2147 path[0].ident.name = name;
2148 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2150 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2153 if let PathResult::Module(..) = result {
2154 return Some((path, Vec::new()));
2161 /// Suggests importing a macro from the root of the crate rather than a module within
2165 /// help: a macro with this name exists at the root of the crate
2167 /// LL | use issue_59764::makro;
2168 /// | ^^^^^^^^^^^^^^^^^^
2170 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2171 /// at the root of the crate instead of the module where it is defined
2173 pub(crate) fn check_for_module_export_macro(
2175 import: &'b Import<'b>,
2176 module: ModuleOrUniformRoot<'b>,
2178 ) -> Option<(Option<Suggestion>, Vec<String>)> {
2179 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2183 while let Some(parent) = crate_module.parent {
2184 crate_module = parent;
2187 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2188 // Don't make a suggestion if the import was already from the root of the
2193 let resolutions = self.r.resolutions(crate_module).borrow();
2194 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2195 let binding = resolution.borrow().binding()?;
2196 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2197 let module_name = crate_module.kind.name().unwrap();
2198 let import_snippet = match import.kind {
2199 ImportKind::Single { source, target, .. } if source != target => {
2200 format!("{} as {}", source, target)
2202 _ => format!("{}", ident),
2205 let mut corrections: Vec<(Span, String)> = Vec::new();
2206 if !import.is_nested() {
2207 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2208 // intermediate segments.
2209 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2211 // Find the binding span (and any trailing commas and spaces).
2212 // ie. `use a::b::{c, d, e};`
2214 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2220 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2221 found_closing_brace, binding_span
2224 let mut removal_span = binding_span;
2225 if found_closing_brace {
2226 // If the binding span ended with a closing brace, as in the below example:
2227 // ie. `use a::b::{c, d};`
2229 // Then expand the span of characters to remove to include the previous
2230 // binding's trailing comma.
2231 // ie. `use a::b::{c, d};`
2233 if let Some(previous_span) =
2234 extend_span_to_previous_binding(self.r.session, binding_span)
2236 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2237 removal_span = removal_span.with_lo(previous_span.lo());
2240 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2242 // Remove the `removal_span`.
2243 corrections.push((removal_span, "".to_string()));
2245 // Find the span after the crate name and if it has nested imports immediately
2246 // after the crate name already.
2247 // ie. `use a::b::{c, d};`
2249 // or `use a::{b, c, d}};`
2251 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2257 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2258 has_nested, after_crate_name
2261 let source_map = self.r.session.source_map();
2263 // Add the import to the start, with a `{` if required.
2264 let start_point = source_map.start_point(after_crate_name);
2265 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2269 // In this case, `start_snippet` must equal '{'.
2270 format!("{}{}, ", start_snippet, import_snippet)
2272 // In this case, add a `{`, then the moved import, then whatever
2273 // was there before.
2274 format!("{{{}, {}", import_snippet, start_snippet)
2279 // Add a `};` to the end if nested, matching the `{` added at the start.
2281 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2285 let suggestion = Some((
2287 String::from("a macro with this name exists at the root of the crate"),
2288 Applicability::MaybeIncorrect,
2291 "this could be because a macro annotated with `#[macro_export]` will be exported \
2292 at the root of the crate instead of the module where it is defined"
2295 Some((suggestion, note))
2302 /// Given a `binding_span` of a binding within a use statement:
2304 /// ```ignore (illustrative)
2305 /// use foo::{a, b, c};
2309 /// then return the span until the next binding or the end of the statement:
2311 /// ```ignore (illustrative)
2312 /// use foo::{a, b, c};
2315 fn find_span_of_binding_until_next_binding(
2320 let source_map = sess.source_map();
2322 // Find the span of everything after the binding.
2323 // ie. `a, e};` or `a};`
2324 let binding_until_end = binding_span.with_hi(use_span.hi());
2326 // Find everything after the binding but not including the binding.
2327 // ie. `, e};` or `};`
2328 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2330 // Keep characters in the span until we encounter something that isn't a comma or
2334 // Also note whether a closing brace character was encountered. If there
2335 // was, then later go backwards to remove any trailing commas that are left.
2336 let mut found_closing_brace = false;
2337 let after_binding_until_next_binding =
2338 source_map.span_take_while(after_binding_until_end, |&ch| {
2340 found_closing_brace = true;
2342 ch == ' ' || ch == ','
2345 // Combine the two spans.
2346 // ie. `a, ` or `a`.
2348 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2349 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2351 (found_closing_brace, span)
2354 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2357 /// ```ignore (illustrative)
2358 /// use foo::a::{a, b, c};
2359 /// // ^^--- binding span
2361 /// // returned span
2363 /// use foo::{a, b, c};
2364 /// // --- binding span
2366 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2367 let source_map = sess.source_map();
2369 // `prev_source` will contain all of the source that came before the span.
2370 // Then split based on a command and take the first (ie. closest to our span)
2371 // snippet. In the example, this is a space.
2372 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2374 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2375 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2376 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2380 let prev_comma = prev_comma.first().unwrap();
2381 let prev_starting_brace = prev_starting_brace.first().unwrap();
2383 // If the amount of source code before the comma is greater than
2384 // the amount of source code before the starting brace then we've only
2385 // got one item in the nested item (eg. `issue_52891::{self}`).
2386 if prev_comma.len() > prev_starting_brace.len() {
2390 Some(binding_span.with_lo(BytePos(
2391 // Take away the number of bytes for the characters we've found and an
2392 // extra for the comma.
2393 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2397 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2398 /// it is a nested use tree.
2400 /// ```ignore (illustrative)
2401 /// use foo::a::{b, c};
2402 /// // ^^^^^^^^^^ -- false
2404 /// use foo::{a, b, c};
2405 /// // ^^^^^^^^^^ -- true
2407 /// use foo::{a, b::{c, d}};
2408 /// // ^^^^^^^^^^^^^^^ -- true
2410 fn find_span_immediately_after_crate_name(
2412 module_name: Symbol,
2416 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2417 module_name, use_span
2419 let source_map = sess.source_map();
2421 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2422 let mut num_colons = 0;
2423 // Find second colon.. `use issue_59764:`
2424 let until_second_colon = source_map.span_take_while(use_span, |c| {
2428 !matches!(c, ':' if num_colons == 2)
2430 // Find everything after the second colon.. `foo::{baz, makro};`
2431 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2433 let mut found_a_non_whitespace_character = false;
2434 // Find the first non-whitespace character in `from_second_colon`.. `f`
2435 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2436 if found_a_non_whitespace_character {
2439 if !c.is_whitespace() {
2440 found_a_non_whitespace_character = true;
2445 // Find the first `{` in from_second_colon.. `foo::{`
2446 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2448 (next_left_bracket == after_second_colon, from_second_colon)
2451 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2452 /// independent options.
2458 /// Whether an existing place with an `use` item was found.
2464 /// Whether a binding is part of a pattern or an expression. Used for diagnostics.
2466 /// The binding is part of a pattern
2468 /// The binding is part of an expression
2472 /// When an entity with a given name is not available in scope, we search for
2473 /// entities with that name in all crates. This method allows outputting the
2474 /// results of this search in a programmer-friendly way
2477 source_span: &IndexVec<LocalDefId, Span>,
2478 err: &mut Diagnostic,
2479 // This is `None` if all placement locations are inside expansions
2480 use_placement_span: Option<Span>,
2481 candidates: &[ImportSuggestion],
2483 found_use: FoundUse,
2484 is_pattern: IsPattern,
2487 if candidates.is_empty() {
2491 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2493 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2496 candidates.iter().for_each(|c| {
2497 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2498 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2501 // we want consistent results across executions, but candidates are produced
2502 // by iterating through a hash map, so make sure they are ordered:
2503 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2504 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2505 let core_path_strings =
2506 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2507 path_strings.extend(core_path_strings);
2508 path_strings.dedup_by(|a, b| a.0 == b.0);
2511 if !accessible_path_strings.is_empty() {
2512 let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2513 ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2515 ("one of these", "items", String::new())
2518 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2519 let mut msg = if let IsPattern::Yes = is_pattern {
2521 "if you meant to match on {}{}{}, use the full path in the pattern",
2525 format!("consider importing {} {}{}", determiner, kind, instead)
2528 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2532 if let (IsPattern::Yes, Some(span)) = (is_pattern, use_placement_span) {
2533 err.span_suggestions(
2536 accessible_path_strings.into_iter().map(|a| a.0),
2537 Applicability::MaybeIncorrect,
2539 } else if let Some(span) = use_placement_span {
2540 for candidate in &mut accessible_path_strings {
2541 // produce an additional newline to separate the new use statement
2542 // from the directly following item.
2543 let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" };
2544 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
2547 err.span_suggestions(
2550 accessible_path_strings.into_iter().map(|a| a.0),
2551 Applicability::MaybeIncorrect,
2553 if let [first, .., last] = &path[..] {
2554 err.span_suggestion_verbose(
2555 first.ident.span.until(last.ident.span),
2556 &format!("if you import `{}`, refer to it directly", last.ident),
2558 Applicability::Unspecified,
2564 for candidate in accessible_path_strings {
2566 msg.push_str(&candidate.0);
2572 assert!(!inaccessible_path_strings.is_empty());
2575 if let IsPattern::Yes = is_pattern { "you might have meant to match on " } else { "" };
2576 if inaccessible_path_strings.len() == 1 {
2577 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2579 "{}{} `{}`{} exists but is inaccessible",
2583 if let IsPattern::Yes = is_pattern { ", which" } else { "" }
2586 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2587 let span = source_span[local_def_id];
2588 let span = session.source_map().guess_head_span(span);
2589 let mut multi_span = MultiSpan::from_span(span);
2590 multi_span.push_span_label(span, "not accessible");
2591 err.span_note(multi_span, &msg);
2595 if let Some(note) = (*note).as_deref() {
2599 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2600 let descr = if inaccessible_path_strings
2603 .all(|(_, descr, _, _)| descr == descr_first)
2610 if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) };
2612 let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr);
2613 let mut has_colon = false;
2615 let mut spans = Vec::new();
2616 for (name, _, def_id, _) in &inaccessible_path_strings {
2617 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2618 let span = source_span[local_def_id];
2619 let span = session.source_map().guess_head_span(span);
2620 spans.push((name, span));
2631 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2632 for (name, span) in spans {
2633 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2636 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2640 err.span_note(multi_span, &msg);
2646 struct UsePlacementFinder {
2647 target_module: NodeId,
2648 first_legal_span: Option<Span>,
2649 first_use_span: Option<Span>,
2652 impl UsePlacementFinder {
2653 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2655 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2656 finder.visit_crate(krate);
2657 if let Some(use_span) = finder.first_use_span {
2658 (Some(use_span), FoundUse::Yes)
2660 (finder.first_legal_span, FoundUse::No)
2665 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2666 fn visit_crate(&mut self, c: &Crate) {
2667 if self.target_module == CRATE_NODE_ID {
2668 let inject = c.spans.inject_use_span;
2669 if is_span_suitable_for_use_injection(inject) {
2670 self.first_legal_span = Some(inject);
2672 self.first_use_span = search_for_any_use_in_items(&c.items);
2675 visit::walk_crate(self, c);
2679 fn visit_item(&mut self, item: &'tcx ast::Item) {
2680 if self.target_module == item.id {
2681 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2682 let inject = mod_spans.inject_use_span;
2683 if is_span_suitable_for_use_injection(inject) {
2684 self.first_legal_span = Some(inject);
2686 self.first_use_span = search_for_any_use_in_items(items);
2690 visit::walk_item(self, item);
2695 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2697 if let ItemKind::Use(..) = item.kind {
2698 if is_span_suitable_for_use_injection(item.span) {
2699 return Some(item.span.shrink_to_lo());
2706 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2707 // don't suggest placing a use before the prelude
2708 // import or other generated ones
2712 /// Convert the given number into the corresponding ordinal
2713 pub(crate) fn ordinalize(v: usize) -> String {
2714 let suffix = match ((11..=13).contains(&(v % 100)), v % 10) {
2720 format!("{v}{suffix}")