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, CRATE_DEF_ID, LOCAL_CRATE};
14 use rustc_hir::PrimTy;
15 use rustc_middle::bug;
16 use rustc_middle::ty::DefIdTree;
17 use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE;
18 use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS;
19 use rustc_session::lint::BuiltinLintDiagnostics;
20 use rustc_session::Session;
21 use rustc_span::edition::Edition;
22 use rustc_span::hygiene::MacroKind;
23 use rustc_span::lev_distance::find_best_match_for_name;
24 use rustc_span::source_map::SourceMap;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, Span};
29 use crate::imports::{Import, ImportKind, ImportResolver};
31 use crate::path_names_to_string;
32 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
33 use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
34 use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
35 use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet};
36 use crate::{Segment, UseError};
38 type Res = def::Res<ast::NodeId>;
40 /// A vector of spans and replacements, a message and applicability.
41 crate type Suggestion = (Vec<(Span, String)>, String, Applicability);
43 /// Potential candidate for an undeclared or out-of-scope label - contains the ident of a
44 /// similarly named label and whether or not it is reachable.
45 crate type LabelSuggestion = (Ident, bool);
47 crate enum SuggestionTarget {
48 /// The target has a similar name as the name used by the programmer (probably a typo)
50 /// The target is the only valid item that can be used in the corresponding context
54 crate struct TypoSuggestion {
55 pub candidate: Symbol,
57 pub target: SuggestionTarget,
61 crate fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
62 Self { candidate, res, target: SuggestionTarget::SimilarlyNamed }
64 crate fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion {
65 Self { candidate, res, target: SuggestionTarget::SingleItem }
69 /// A free importable items suggested in case of resolution failure.
70 crate struct ImportSuggestion {
71 pub did: Option<DefId>,
72 pub descr: &'static str,
75 /// An extra note that should be issued if this item is suggested
76 pub note: Option<String>,
79 /// Adjust the impl span so that just the `impl` keyword is taken by removing
80 /// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and
81 /// everything after the first whitespace (`"impl Iterator for A" -> "impl"`).
83 /// *Attention*: the method used is very fragile since it essentially duplicates the work of the
84 /// parser. If you need to use this function or something similar, please consider updating the
85 /// `source_map` functions and this function to something more robust.
86 fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
87 let impl_span = sm.span_until_char(impl_span, '<');
88 sm.span_until_whitespace(impl_span)
91 impl<'a> Resolver<'a> {
92 crate fn report_errors(&mut self, krate: &Crate) {
93 self.report_with_use_injections(krate);
95 for &(span_use, span_def) in &self.macro_expanded_macro_export_errors {
96 let msg = "macro-expanded `macro_export` macros from the current crate \
97 cannot be referred to by absolute paths";
98 self.lint_buffer.buffer_lint_with_diagnostic(
99 MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
103 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def),
107 for ambiguity_error in &self.ambiguity_errors {
108 self.report_ambiguity_error(ambiguity_error);
111 let mut reported_spans = FxHashSet::default();
112 for error in &self.privacy_errors {
113 if reported_spans.insert(error.dedup_span) {
114 self.report_privacy_error(error);
119 fn report_with_use_injections(&mut self, krate: &Crate) {
120 for UseError { mut err, candidates, def_id, instead, suggestion, path } in
121 self.use_injections.drain(..)
123 let (span, found_use) = if let Some(def_id) = def_id.as_local() {
124 UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id])
128 if !candidates.is_empty() {
135 if instead { Instead::Yes } else { Instead::No },
140 } else if let Some((span, msg, sugg, appl)) = suggestion {
141 err.span_suggestion(span, msg, sugg, appl);
147 crate fn report_conflict<'b>(
152 new_binding: &NameBinding<'b>,
153 old_binding: &NameBinding<'b>,
155 // Error on the second of two conflicting names
156 if old_binding.span.lo() > new_binding.span.lo() {
157 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
160 let container = match parent.kind {
161 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
162 ModuleKind::Block(..) => "block",
165 let old_noun = match old_binding.is_import() {
167 false => "definition",
170 let new_participle = match new_binding.is_import() {
176 (ident.name, self.session.source_map().guess_head_span(new_binding.span));
178 if let Some(s) = self.name_already_seen.get(&name) {
184 let old_kind = match (ns, old_binding.module()) {
185 (ValueNS, _) => "value",
186 (MacroNS, _) => "macro",
187 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
188 (TypeNS, Some(module)) if module.is_normal() => "module",
189 (TypeNS, Some(module)) if module.is_trait() => "trait",
190 (TypeNS, _) => "type",
193 let msg = format!("the name `{}` is defined multiple times", name);
195 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
196 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
197 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
198 true => struct_span_err!(self.session, span, E0254, "{}", msg),
199 false => struct_span_err!(self.session, span, E0260, "{}", msg),
201 _ => match (old_binding.is_import(), new_binding.is_import()) {
202 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
203 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
204 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
209 "`{}` must be defined only once in the {} namespace of this {}",
215 err.span_label(span, format!("`{}` re{} here", name, new_participle));
217 self.session.source_map().guess_head_span(old_binding.span),
218 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
221 // See https://github.com/rust-lang/rust/issues/32354
222 use NameBindingKind::Import;
223 let import = match (&new_binding.kind, &old_binding.kind) {
224 // If there are two imports where one or both have attributes then prefer removing the
225 // import without attributes.
226 (Import { import: new, .. }, Import { import: old, .. })
228 !new_binding.span.is_dummy()
229 && !old_binding.span.is_dummy()
230 && (new.has_attributes || old.has_attributes)
233 if old.has_attributes {
234 Some((new, new_binding.span, true))
236 Some((old, old_binding.span, true))
239 // Otherwise prioritize the new binding.
240 (Import { import, .. }, other) if !new_binding.span.is_dummy() => {
241 Some((import, new_binding.span, other.is_import()))
243 (other, Import { import, .. }) if !old_binding.span.is_dummy() => {
244 Some((import, old_binding.span, other.is_import()))
249 // Check if the target of the use for both bindings is the same.
250 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
251 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
253 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
254 // Only suggest removing an import if both bindings are to the same def, if both spans
255 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
256 // been introduced by an item.
257 let should_remove_import = duplicate
259 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
262 Some((import, span, true)) if should_remove_import && import.is_nested() => {
263 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
265 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
266 // Simple case - remove the entire import. Due to the above match arm, this can
267 // only be a single use so just remove it entirely.
268 err.tool_only_span_suggestion(
269 import.use_span_with_attributes,
270 "remove unnecessary import",
272 Applicability::MaybeIncorrect,
275 Some((import, span, _)) => {
276 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
282 self.name_already_seen.insert(name, span);
285 /// This function adds a suggestion to change the binding name of a new import that conflicts
286 /// with an existing import.
288 /// ```text,ignore (diagnostic)
289 /// help: you can use `as` to change the binding name of the import
291 /// LL | use foo::bar as other_bar;
292 /// | ^^^^^^^^^^^^^^^^^^^^^
294 fn add_suggestion_for_rename_of_use(
296 err: &mut Diagnostic,
301 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
302 format!("Other{}", name)
304 format!("other_{}", name)
307 let mut suggestion = None;
309 ImportKind::Single { type_ns_only: true, .. } => {
310 suggestion = Some(format!("self as {}", suggested_name))
312 ImportKind::Single { source, .. } => {
314 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
316 if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
317 if pos <= snippet.len() {
318 suggestion = Some(format!(
322 if snippet.ends_with(';') { ";" } else { "" }
328 ImportKind::ExternCrate { source, target } => {
329 suggestion = Some(format!(
330 "extern crate {} as {};",
331 source.unwrap_or(target.name),
338 let rename_msg = "you can use `as` to change the binding name of the import";
339 if let Some(suggestion) = suggestion {
344 Applicability::MaybeIncorrect,
347 err.span_label(binding_span, rename_msg);
351 /// This function adds a suggestion to remove an unnecessary binding from an import that is
352 /// nested. In the following example, this function will be invoked to remove the `a` binding
353 /// in the second use statement:
355 /// ```ignore (diagnostic)
356 /// use issue_52891::a;
357 /// use issue_52891::{d, a, e};
360 /// The following suggestion will be added:
362 /// ```ignore (diagnostic)
363 /// use issue_52891::{d, a, e};
364 /// ^-- help: remove unnecessary import
367 /// If the nested use contains only one import then the suggestion will remove the entire
370 /// It is expected that the provided import is nested - this isn't checked by the
371 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
372 /// as characters expected by span manipulations won't be present.
373 fn add_suggestion_for_duplicate_nested_use(
375 err: &mut Diagnostic,
379 assert!(import.is_nested());
380 let message = "remove unnecessary import";
382 // Two examples will be used to illustrate the span manipulations we're doing:
384 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
385 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
386 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
387 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
389 let (found_closing_brace, span) =
390 find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
392 // If there was a closing brace then identify the span to remove any trailing commas from
394 if found_closing_brace {
395 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
396 err.tool_only_span_suggestion(
400 Applicability::MaybeIncorrect,
403 // Remove the entire line if we cannot extend the span back, this indicates an
404 // `issue_52891::{self}` case.
406 import.use_span_with_attributes,
409 Applicability::MaybeIncorrect,
416 err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable);
419 crate fn lint_if_path_starts_with_module(
421 finalize: Option<Finalize>,
423 second_binding: Option<&NameBinding<'_>>,
425 let Some(Finalize { node_id, root_span, .. }) = finalize else {
429 let first_name = match path.get(0) {
430 // In the 2018 edition this lint is a hard error, so nothing to do
431 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
435 // We're only interested in `use` paths which should start with
436 // `{{root}}` currently.
437 if first_name != kw::PathRoot {
442 // If this import looks like `crate::...` it's already good
443 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
444 // Otherwise go below to see if it's an extern crate
446 // If the path has length one (and it's `PathRoot` most likely)
447 // then we don't know whether we're gonna be importing a crate or an
448 // item in our crate. Defer this lint to elsewhere
452 // If the first element of our path was actually resolved to an
453 // `ExternCrate` (also used for `crate::...`) then no need to issue a
454 // warning, this looks all good!
455 if let Some(binding) = second_binding {
456 if let NameBindingKind::Import { import, .. } = binding.kind {
457 // Careful: we still want to rewrite paths from renamed extern crates.
458 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
464 let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span);
465 self.lint_buffer.buffer_lint_with_diagnostic(
466 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
469 "absolute paths must start with `self`, `super`, \
470 `crate`, or an external crate name in the 2018 edition",
475 crate fn add_module_candidates(
478 names: &mut Vec<TypoSuggestion>,
479 filter_fn: &impl Fn(Res) -> bool,
481 for (key, resolution) in self.resolutions(module).borrow().iter() {
482 if let Some(binding) = resolution.borrow().binding {
483 let res = binding.res();
485 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
491 /// Combines an error with provided span and emits it.
493 /// This takes the error provided, combines it with the span and any additional spans inside the
494 /// error and emits it.
495 crate fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
496 self.into_struct_error(span, resolution_error).emit();
499 crate fn into_struct_error(
502 resolution_error: ResolutionError<'a>,
503 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
504 match resolution_error {
505 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
506 let mut err = struct_span_err!(
510 "can't use generic parameters from outer function",
512 err.span_label(span, "use of generic parameter from outer function".to_string());
514 let sm = self.session.source_map();
516 Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => {
517 if let Some(impl_span) =
518 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
521 reduce_impl_span_to_impl_keyword(sm, impl_span),
522 "`Self` type implicitly declared here, by this `impl`",
525 match (maybe_trait_defid, maybe_impl_defid) {
527 err.span_label(span, "can't use `Self` here");
530 err.span_label(span, "use a type here instead");
532 (None, None) => bug!("`impl` without trait nor type?"),
536 Res::Def(DefKind::TyParam, def_id) => {
537 if let Some(span) = self.opt_span(def_id) {
538 err.span_label(span, "type parameter from outer function");
541 Res::Def(DefKind::ConstParam, def_id) => {
542 if let Some(span) = self.opt_span(def_id) {
543 err.span_label(span, "const parameter from outer function");
548 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
549 DefKind::TyParam or DefKind::ConstParam"
554 if has_generic_params == HasGenericParams::Yes {
555 // Try to retrieve the span of the function signature and generate a new
556 // message with a local type or const parameter.
557 let sugg_msg = "try using a local generic parameter instead";
558 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
559 // Suggest the modification to the user
564 Applicability::MachineApplicable,
566 } else if let Some(sp) = sm.generate_fn_name_span(span) {
569 "try adding a local generic parameter in this method instead"
573 err.help("try using a local generic parameter instead");
579 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
580 let mut err = struct_span_err!(
584 "the name `{}` is already used for a generic \
585 parameter in this item's generic parameters",
588 err.span_label(span, "already used");
589 err.span_label(first_use_span, format!("first use of `{}`", name));
592 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
593 let mut err = struct_span_err!(
597 "method `{}` is not a member of trait `{}`",
601 err.span_label(span, format!("not a member of trait `{}`", trait_));
602 if let Some(candidate) = candidate {
605 "there is an associated function with a similar name",
606 candidate.to_ident_string(),
607 Applicability::MaybeIncorrect,
612 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
613 let mut err = struct_span_err!(
617 "type `{}` is not a member of trait `{}`",
621 err.span_label(span, format!("not a member of trait `{}`", trait_));
622 if let Some(candidate) = candidate {
625 "there is an associated type with a similar name",
626 candidate.to_ident_string(),
627 Applicability::MaybeIncorrect,
632 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
633 let mut err = struct_span_err!(
637 "const `{}` is not a member of trait `{}`",
641 err.span_label(span, format!("not a member of trait `{}`", trait_));
642 if let Some(candidate) = candidate {
645 "there is an associated constant with a similar name",
646 candidate.to_ident_string(),
647 Applicability::MaybeIncorrect,
652 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
653 let BindingError { name, target, origin, could_be_path } = binding_error;
655 let target_sp = target.iter().copied().collect::<Vec<_>>();
656 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
658 let msp = MultiSpan::from_spans(target_sp.clone());
659 let mut err = struct_span_err!(
663 "variable `{}` is not bound in all patterns",
666 for sp in target_sp {
667 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
669 for sp in origin_sp {
670 err.span_label(sp, "variable not in all patterns");
673 let import_suggestions = self.lookup_import_candidates(
674 Ident::with_dummy_span(name),
677 &|res: Res| match res {
679 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
680 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
682 | DefKind::AssocConst,
689 if import_suggestions.is_empty() {
690 let help_msg = format!(
691 "if you meant to match on a variant or a `const` item, consider \
692 making the path in the pattern qualified: `path::to::ModOrType::{}`",
695 err.span_help(span, &help_msg);
711 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
712 let mut err = struct_span_err!(
716 "variable `{}` is bound inconsistently across alternatives separated by `|`",
719 err.span_label(span, "bound in different ways");
720 err.span_label(first_binding_span, "first binding");
723 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
724 let mut err = struct_span_err!(
728 "identifier `{}` is bound more than once in this parameter list",
731 err.span_label(span, "used as parameter more than once");
734 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
735 let mut err = struct_span_err!(
739 "identifier `{}` is bound more than once in the same pattern",
742 err.span_label(span, "used in a pattern more than once");
745 ResolutionError::UndeclaredLabel { name, suggestion } => {
746 let mut err = struct_span_err!(
750 "use of undeclared label `{}`",
754 err.span_label(span, format!("undeclared label `{}`", name));
757 // A reachable label with a similar name exists.
758 Some((ident, true)) => {
759 err.span_label(ident.span, "a label with a similar name is reachable");
762 "try using similarly named label",
763 ident.name.to_string(),
764 Applicability::MaybeIncorrect,
767 // An unreachable label with a similar name exists.
768 Some((ident, false)) => {
771 "a label with a similar name exists but is unreachable",
774 // No similarly-named labels exist.
780 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
781 let mut err = struct_span_err!(
786 "`self` imports are only allowed within a { } list"
789 // None of the suggestions below would help with a case like `use self`.
791 // use foo::bar::self -> foo::bar
792 // use foo::bar::self as abc -> foo::bar as abc
795 "consider importing the module directly",
797 Applicability::MachineApplicable,
800 // use foo::bar::self -> foo::bar::{self}
801 // use foo::bar::self as abc -> foo::bar::{self as abc}
803 (span_with_rename.shrink_to_lo(), "{".to_string()),
804 (span_with_rename.shrink_to_hi(), "}".to_string()),
806 err.multipart_suggestion(
807 "alternatively, use the multi-path `use` syntax to import `self`",
809 Applicability::MachineApplicable,
814 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
815 let mut err = struct_span_err!(
819 "`self` import can only appear once in an import list"
821 err.span_label(span, "can only appear once in an import list");
824 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
825 let mut err = struct_span_err!(
829 "`self` import can only appear in an import list with \
832 err.span_label(span, "can only appear in an import list with a non-empty prefix");
835 ResolutionError::FailedToResolve { label, suggestion } => {
837 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
838 err.span_label(span, label);
840 if let Some((suggestions, msg, applicability)) = suggestion {
841 if suggestions.is_empty() {
845 err.multipart_suggestion(&msg, suggestions, applicability);
850 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
851 let mut err = struct_span_err!(
856 "can't capture dynamic environment in a fn item"
858 err.help("use the `|| { ... }` closure form instead");
861 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
862 let mut err = struct_span_err!(
866 "attempt to use a non-constant value in a constant"
869 // ^^^ given this Span
870 // ------- get this Span to have an applicable suggestion
873 // only do this if the const and usage of the non-constant value are on the same line
874 // the further the two are apart, the higher the chance of the suggestion being wrong
879 .span_extend_to_prev_str(ident.span, current, true, false);
882 Some(sp) if !self.session.source_map().is_multiline(sp) => {
883 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
886 &format!("consider using `{}` instead of `{}`", sugg, current),
887 format!("{} {}", sugg, ident),
888 Applicability::MaybeIncorrect,
890 err.span_label(span, "non-constant value");
893 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
899 ResolutionError::BindingShadowsSomethingUnacceptable {
900 shadowing_binding_descr,
904 shadowed_binding_descr,
905 shadowed_binding_span,
907 let mut err = struct_span_err!(
911 "{}s cannot shadow {}s",
912 shadowing_binding_descr,
913 shadowed_binding_descr,
917 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
920 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
921 err.span_label(shadowed_binding_span, msg);
924 ResolutionError::ForwardDeclaredGenericParam => {
925 let mut err = struct_span_err!(
929 "generic parameters with a default cannot use \
930 forward declared identifiers"
934 "defaulted generic parameters cannot be forward declared".to_string(),
938 ResolutionError::ParamInTyOfConstParam(name) => {
939 let mut err = struct_span_err!(
943 "the type of const parameters must not depend on other generic parameters"
947 format!("the type must not depend on the parameter `{}`", name),
951 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
952 let mut err = self.session.struct_span_err(
954 "generic parameters may not be used in const operations",
956 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
959 err.note("type parameters may not be used in const expressions");
962 "const parameters may only be used as standalone arguments, i.e. `{}`",
967 if self.session.is_nightly_build() {
969 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
975 ResolutionError::SelfInGenericParamDefault => {
976 let mut err = struct_span_err!(
980 "generic parameters cannot use `Self` in their defaults"
982 err.span_label(span, "`Self` in generic parameter default".to_string());
985 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
986 let mut err = struct_span_err!(
990 "use of unreachable label `{}`",
994 err.span_label(definition_span, "unreachable label defined here");
995 err.span_label(span, format!("unreachable label `{}`", name));
997 "labels are unreachable through functions, closures, async blocks and modules",
1001 // A reachable label with a similar name exists.
1002 Some((ident, true)) => {
1003 err.span_label(ident.span, "a label with a similar name is reachable");
1004 err.span_suggestion(
1006 "try using similarly named label",
1007 ident.name.to_string(),
1008 Applicability::MaybeIncorrect,
1011 // An unreachable label with a similar name exists.
1012 Some((ident, false)) => {
1015 "a label with a similar name exists but is also unreachable",
1018 // No similarly-named labels exist.
1024 ResolutionError::TraitImplMismatch {
1031 let mut err = self.session.struct_span_err_with_code(
1034 "item `{}` is an associated {}, which doesn't match its trait `{}`",
1035 name, kind, trait_path,
1039 err.span_label(span, "does not match trait");
1040 err.span_label(trait_item_span, "item in trait");
1043 ResolutionError::InvalidAsmSym => {
1044 let mut err = self.session.struct_span_err(span, "invalid `sym` operand");
1045 err.span_label(span, "is a local variable");
1046 err.help("`sym` operands must refer to either a function or a static");
1052 crate fn report_vis_error(
1054 vis_resolution_error: VisResolutionError<'_>,
1055 ) -> ErrorGuaranteed {
1056 match vis_resolution_error {
1057 VisResolutionError::Relative2018(span, path) => {
1058 let mut err = self.session.struct_span_err(
1060 "relative paths are not supported in visibilities in 2018 edition or later",
1062 err.span_suggestion(
1065 format!("crate::{}", pprust::path_to_string(&path)),
1066 Applicability::MaybeIncorrect,
1070 VisResolutionError::AncestorOnly(span) => struct_span_err!(
1074 "visibilities can only be restricted to ancestor modules"
1076 VisResolutionError::FailedToResolve(span, label, suggestion) => {
1077 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
1079 VisResolutionError::ExpectedFound(span, path_str, res) => {
1080 let mut err = struct_span_err!(
1084 "expected module, found {} `{}`",
1088 err.span_label(span, "not a module");
1091 VisResolutionError::Indeterminate(span) => struct_span_err!(
1095 "cannot determine resolution for the visibility"
1097 VisResolutionError::ModuleOnly(span) => {
1098 self.session.struct_span_err(span, "visibility must resolve to a module")
1104 /// Lookup typo candidate in scope for a macro or import.
1105 fn early_lookup_typo_candidate(
1107 scope_set: ScopeSet<'a>,
1108 parent_scope: &ParentScope<'a>,
1110 filter_fn: &impl Fn(Res) -> bool,
1111 ) -> Option<TypoSuggestion> {
1112 let mut suggestions = Vec::new();
1113 let ctxt = ident.span.ctxt();
1114 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1116 Scope::DeriveHelpers(expn_id) => {
1117 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1124 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1128 Scope::DeriveHelpersCompat => {
1129 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1131 for derive in parent_scope.derives {
1132 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1133 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1135 Some(MacroKind::Derive),
1143 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
1149 Scope::MacroRules(macro_rules_scope) => {
1150 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1151 let res = macro_rules_binding.binding.res();
1153 suggestions.push(TypoSuggestion::typo_from_res(
1154 macro_rules_binding.ident.name,
1160 Scope::CrateRoot => {
1161 let root_ident = Ident::new(kw::PathRoot, ident.span);
1162 let root_module = this.resolve_crate_root(root_ident);
1163 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
1165 Scope::Module(module, _) => {
1166 this.add_module_candidates(module, &mut suggestions, filter_fn);
1168 Scope::RegisteredAttrs => {
1169 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
1172 this.registered_attrs
1174 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1178 Scope::MacroUsePrelude => {
1179 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1181 let res = binding.res();
1182 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
1186 Scope::BuiltinAttrs => {
1187 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1192 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
1196 Scope::ExternPrelude => {
1197 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1198 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1199 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
1202 Scope::ToolPrelude => {
1203 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1205 this.registered_tools
1207 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1210 Scope::StdLibPrelude => {
1211 if let Some(prelude) = this.prelude {
1212 let mut tmp_suggestions = Vec::new();
1213 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
1217 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1221 Scope::BuiltinTypes => {
1222 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1223 let res = Res::PrimTy(*prim_ty);
1224 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
1232 // Make sure error reporting is deterministic.
1233 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1235 match find_best_match_for_name(
1236 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1240 Some(found) if found != ident.name => {
1241 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1247 fn lookup_import_candidates_from_module<FilterFn>(
1249 lookup_ident: Ident,
1250 namespace: Namespace,
1251 parent_scope: &ParentScope<'a>,
1252 start_module: Module<'a>,
1254 filter_fn: FilterFn,
1255 ) -> Vec<ImportSuggestion>
1257 FilterFn: Fn(Res) -> bool,
1259 let mut candidates = Vec::new();
1260 let mut seen_modules = FxHashSet::default();
1261 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
1262 let mut worklist_via_import = vec![];
1264 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1265 None => worklist_via_import.pop(),
1268 let in_module_is_extern = !in_module.def_id().is_local();
1269 // We have to visit module children in deterministic order to avoid
1270 // instabilities in reported imports (#43552).
1271 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1272 // avoid non-importable candidates
1273 if !name_binding.is_importable() {
1277 let child_accessible =
1278 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1280 // do not venture inside inaccessible items of other crates
1281 if in_module_is_extern && !child_accessible {
1285 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1287 // There is an assumption elsewhere that paths of variants are in the enum's
1288 // declaration and not imported. With this assumption, the variant component is
1289 // chopped and the rest of the path is assumed to be the enum's own path. For
1290 // errors where a variant is used as the type instead of the enum, this causes
1291 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1292 if via_import && name_binding.is_possibly_imported_variant() {
1296 // #90113: Do not count an inaccessible reexported item as a candidate.
1297 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1298 if this.is_accessible_from(binding.vis, parent_scope.module)
1299 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1305 // collect results based on the filter function
1306 // avoid suggesting anything from the same module in which we are resolving
1307 // avoid suggesting anything with a hygienic name
1308 if ident.name == lookup_ident.name
1310 && !ptr::eq(in_module, parent_scope.module)
1311 && !ident.span.normalize_to_macros_2_0().from_expansion()
1313 let res = name_binding.res();
1316 let mut segms = path_segments.clone();
1317 if lookup_ident.span.rust_2018() {
1318 // crate-local absolute paths start with `crate::` in edition 2018
1319 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1320 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1323 segms.push(ast::PathSegment::from_ident(ident));
1324 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1325 let did = match res {
1326 Res::Def(DefKind::Ctor(..), did) => this.opt_parent(did),
1327 _ => res.opt_def_id(),
1330 if child_accessible {
1331 // Remove invisible match if exists
1332 if let Some(idx) = candidates
1334 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1336 candidates.remove(idx);
1340 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1341 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1342 // a note about editions
1343 let note = if let Some(did) = did {
1344 let requires_note = !did.is_local()
1345 && this.cstore().item_attrs_untracked(did, this.session).any(
1347 if attr.has_name(sym::rustc_diagnostic_item) {
1348 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1350 .contains(&attr.value_str())
1357 requires_note.then(|| {
1359 "'{}' is included in the prelude starting in Edition 2021",
1360 path_names_to_string(&path)
1367 candidates.push(ImportSuggestion {
1371 accessible: child_accessible,
1378 // collect submodules to explore
1379 if let Some(module) = name_binding.module() {
1381 let mut path_segments = path_segments.clone();
1382 path_segments.push(ast::PathSegment::from_ident(ident));
1384 let is_extern_crate_that_also_appears_in_prelude =
1385 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1387 if !is_extern_crate_that_also_appears_in_prelude {
1388 // add the module to the lookup
1389 if seen_modules.insert(module.def_id()) {
1390 if via_import { &mut worklist_via_import } else { &mut worklist }
1391 .push((module, path_segments, child_accessible));
1398 // If only some candidates are accessible, take just them
1399 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1400 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
1406 /// When name resolution fails, this method can be used to look up candidate
1407 /// entities with the expected name. It allows filtering them using the
1408 /// supplied predicate (which should be used to only accept the types of
1409 /// definitions expected, e.g., traits). The lookup spans across all crates.
1411 /// N.B., the method does not look into imports, but this is not a problem,
1412 /// since we report the definitions (thus, the de-aliased imports).
1413 crate fn lookup_import_candidates<FilterFn>(
1415 lookup_ident: Ident,
1416 namespace: Namespace,
1417 parent_scope: &ParentScope<'a>,
1418 filter_fn: FilterFn,
1419 ) -> Vec<ImportSuggestion>
1421 FilterFn: Fn(Res) -> bool,
1423 let mut suggestions = self.lookup_import_candidates_from_module(
1428 Ident::with_dummy_span(kw::Crate),
1432 if lookup_ident.span.rust_2018() {
1433 let extern_prelude_names = self.extern_prelude.clone();
1434 for (ident, _) in extern_prelude_names.into_iter() {
1435 if ident.span.from_expansion() {
1436 // Idents are adjusted to the root context before being
1437 // resolved in the extern prelude, so reporting this to the
1438 // user is no help. This skips the injected
1439 // `extern crate std` in the 2018 edition, which would
1440 // otherwise cause duplicate suggestions.
1443 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1444 let crate_root = self.expect_module(crate_id.as_def_id());
1445 suggestions.extend(self.lookup_import_candidates_from_module(
1460 crate fn unresolved_macro_suggestions(
1462 err: &mut Diagnostic,
1463 macro_kind: MacroKind,
1464 parent_scope: &ParentScope<'a>,
1467 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1468 let suggestion = self.early_lookup_typo_candidate(
1469 ScopeSet::Macro(macro_kind),
1474 self.add_typo_suggestion(err, suggestion, ident.span);
1476 let import_suggestions =
1477 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1483 &import_suggestions,
1490 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1491 let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
1492 err.span_note(ident.span, &msg);
1495 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1496 err.help("have you added the `#[macro_use]` on the module/import?");
1499 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
1500 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
1502 ScopeSet::All(ns, false),
1508 let desc = match binding.res() {
1509 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1510 "a function-like macro".to_string()
1512 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1513 format!("an attribute: `#[{}]`", ident)
1515 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1516 format!("a derive macro: `#[derive({})]`", ident)
1519 // Don't confuse the user with tool modules.
1522 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1523 "only a trait, without a derive macro".to_string()
1529 macro_kind.article(),
1530 macro_kind.descr_expected(),
1533 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1534 if !import.span.is_dummy() {
1537 &format!("`{}` is imported here, but it is {}", ident, desc),
1539 // Silence the 'unused import' warning we might get,
1540 // since this diagnostic already covers that import.
1541 self.record_use(ident, binding, false);
1545 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1551 crate fn add_typo_suggestion(
1553 err: &mut Diagnostic,
1554 suggestion: Option<TypoSuggestion>,
1557 let suggestion = match suggestion {
1558 None => return false,
1559 // We shouldn't suggest underscore.
1560 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1561 Some(suggestion) => suggestion,
1563 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1564 LOCAL_CRATE => self.opt_span(def_id),
1568 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1571 if let Some(def_span) = def_span {
1572 if span.overlaps(def_span) {
1573 // Don't suggest typo suggestion for itself like in the following:
1574 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1575 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1578 // | ----------- `X` defined here
1580 // LL | const Y: X = X("ö");
1581 // | -------------^^^^^^- similarly named constant `Y` defined here
1583 // help: use struct literal syntax instead
1585 // LL | const Y: X = X {};
1587 // help: a constant with a similar name exists
1589 // LL | const Y: X = Y("ö");
1593 let prefix = match suggestion.target {
1594 SuggestionTarget::SimilarlyNamed => "similarly named ",
1595 SuggestionTarget::SingleItem => "",
1599 self.session.source_map().guess_head_span(def_span),
1601 "{}{} `{}` defined here",
1603 suggestion.res.descr(),
1604 suggestion.candidate.as_str(),
1608 let msg = match suggestion.target {
1609 SuggestionTarget::SimilarlyNamed => format!(
1610 "{} {} with a similar name exists",
1611 suggestion.res.article(),
1612 suggestion.res.descr()
1614 SuggestionTarget::SingleItem => {
1615 format!("maybe you meant this {}", suggestion.res.descr())
1618 err.span_suggestion(
1621 suggestion.candidate.to_string(),
1622 Applicability::MaybeIncorrect,
1627 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1629 if b.span.is_dummy() || self.session.source_map().span_to_snippet(b.span).is_err() {
1630 // These already contain the "built-in" prefix or look bad with it.
1632 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1633 let (built_in, from) = if from_prelude {
1634 ("", " from prelude")
1635 } else if b.is_extern_crate()
1637 && self.session.opts.externs.get(ident.as_str()).is_some()
1639 ("", " passed with `--extern`")
1640 } else if add_built_in {
1646 let a = if built_in.is_empty() { res.article() } else { "a" };
1647 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1649 let introduced = if b.is_import() { "imported" } else { "defined" };
1650 format!("the {thing} {introduced} here", thing = res.descr())
1654 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1655 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1656 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1657 // We have to print the span-less alternative first, otherwise formatting looks bad.
1658 (b2, b1, misc2, misc1, true)
1660 (b1, b2, misc1, misc2, false)
1663 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1664 err.span_label(ident.span, "ambiguous name");
1665 err.note(&format!("ambiguous because of {}", kind.descr()));
1667 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1668 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1669 let note_msg = format!("`{ident}` could{also} refer to {what}");
1671 let thing = b.res().descr();
1672 let mut help_msgs = Vec::new();
1673 if b.is_glob_import()
1674 && (kind == AmbiguityKind::GlobVsGlob
1675 || kind == AmbiguityKind::GlobVsExpanded
1676 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1678 help_msgs.push(format!(
1679 "consider adding an explicit import of `{ident}` to disambiguate"
1682 if b.is_extern_crate() && ident.span.rust_2018() {
1683 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1685 if misc == AmbiguityErrorMisc::SuggestCrate {
1687 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1688 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1690 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1693 err.span_note(b.span, ¬e_msg);
1694 for (i, help_msg) in help_msgs.iter().enumerate() {
1695 let or = if i == 0 { "" } else { "or " };
1696 err.help(&format!("{}{}", or, help_msg));
1700 could_refer_to(b1, misc1, "");
1701 could_refer_to(b2, misc2, " also");
1705 /// If the binding refers to a tuple struct constructor with fields,
1706 /// returns the span of its fields.
1707 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1708 if let NameBindingKind::Res(
1709 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1713 let def_id = self.parent(ctor_def_id);
1714 let fields = self.field_names.get(&def_id)?;
1715 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1720 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1721 let PrivacyError { ident, binding, .. } = *privacy_error;
1723 let res = binding.res();
1724 let ctor_fields_span = self.ctor_fields_span(binding);
1725 let plain_descr = res.descr().to_string();
1726 let nonimport_descr =
1727 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1728 let import_descr = nonimport_descr.clone() + " import";
1730 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1732 // Print the primary message.
1733 let descr = get_descr(binding);
1735 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1736 err.span_label(ident.span, &format!("private {}", descr));
1737 if let Some(span) = ctor_fields_span {
1738 err.span_label(span, "a constructor is private if any of the fields is private");
1741 // Print the whole import chain to make it easier to see what happens.
1742 let first_binding = binding;
1743 let mut next_binding = Some(binding);
1744 let mut next_ident = ident;
1745 while let Some(binding) = next_binding {
1746 let name = next_ident;
1747 next_binding = match binding.kind {
1748 _ if res == Res::Err => None,
1749 NameBindingKind::Import { binding, import, .. } => match import.kind {
1750 _ if binding.span.is_dummy() => None,
1751 ImportKind::Single { source, .. } => {
1752 next_ident = source;
1755 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1756 ImportKind::ExternCrate { .. } => None,
1761 let first = ptr::eq(binding, first_binding);
1763 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1764 and_refers_to = if first { "" } else { "...and refers to " },
1765 item = get_descr(binding),
1766 which = if first { "" } else { " which" },
1767 dots = if next_binding.is_some() { "..." } else { "" },
1769 let def_span = self.session.source_map().guess_head_span(binding.span);
1770 let mut note_span = MultiSpan::from_span(def_span);
1771 if !first && binding.vis.is_public() {
1772 note_span.push_span_label(def_span, "consider importing it directly");
1774 err.span_note(note_span, &msg);
1780 crate fn find_similarly_named_module_or_crate(
1783 current_module: &Module<'a>,
1784 ) -> Option<Symbol> {
1785 let mut candidates = self
1788 .map(|(ident, _)| ident.name)
1792 .filter(|(_, module)| {
1793 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1795 .flat_map(|(_, module)| module.kind.name()),
1797 .filter(|c| !c.to_string().is_empty())
1798 .collect::<Vec<_>>();
1801 match find_best_match_for_name(&candidates, ident, None) {
1802 Some(sugg) if sugg == ident => None,
1807 crate fn report_path_resolution_error(
1810 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1811 parent_scope: &ParentScope<'a>,
1812 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1813 ignore_binding: Option<&'a NameBinding<'a>>,
1814 module: Option<ModuleOrUniformRoot<'a>>,
1817 ) -> (String, Option<Suggestion>) {
1818 let is_last = i == path.len() - 1;
1819 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1820 let module_res = match module {
1821 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1824 if module_res == self.graph_root.res() {
1825 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1826 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1828 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1829 if let Some(candidate) = candidates.get(0) {
1831 String::from("unresolved import"),
1833 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1834 String::from("a similar path exists"),
1835 Applicability::MaybeIncorrect,
1838 } else if self.session.edition() == Edition::Edition2015 {
1839 (format!("maybe a missing crate `{}`?", ident), None)
1841 (format!("could not find `{}` in the crate root", ident), None)
1844 let parent = path[i - 1].ident.name;
1845 let parent = match parent {
1846 // ::foo is mounted at the crate root for 2015, and is the extern
1847 // prelude for 2018+
1848 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1849 "the list of imported crates".to_owned()
1851 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1852 _ => format!("`{}`", parent),
1855 let mut msg = format!("could not find `{}` in {}", ident, parent);
1856 if ns == TypeNS || ns == ValueNS {
1857 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1858 let binding = if let Some(module) = module {
1859 self.resolve_ident_in_module(
1867 } else if let Some(ribs) = ribs
1868 && let Some(TypeNS | ValueNS) = opt_ns
1870 match self.resolve_ident_in_lexical_scope(
1878 // we found a locally-imported or available item/module
1879 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1883 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1884 self.early_resolve_ident_in_lexical_scope(
1893 if let Some(binding) = binding {
1894 let mut found = |what| {
1896 "expected {}, found {} `{}` in {}",
1903 if binding.module().is_some() {
1906 match binding.res() {
1907 Res::Def(kind, id) => found(kind.descr(id)),
1908 _ => found(ns_to_try.descr()),
1914 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1915 // Check whether the name refers to an item in the value namespace.
1916 let binding = if let Some(ribs) = ribs {
1917 self.resolve_ident_in_lexical_scope(
1928 let match_span = match binding {
1929 // Name matches a local variable. For example:
1932 // let Foo: &str = "";
1933 // println!("{}", Foo::Bar); // Name refers to local
1934 // // variable `Foo`.
1937 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1938 Some(*self.pat_span_map.get(&id).unwrap())
1940 // Name matches item from a local name binding
1941 // created by `use` declaration. For example:
1943 // pub Foo: &str = "";
1947 // println!("{}", Foo::Bar); // Name refers to local
1948 // // binding `Foo`.
1951 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1954 let suggestion = if let Some(span) = match_span {
1956 vec![(span, String::from(""))],
1957 format!("`{}` is defined here, but is not a type", ident),
1958 Applicability::MaybeIncorrect,
1964 (format!("use of undeclared type `{}`", ident), suggestion)
1966 let suggestion = if ident.name == sym::alloc {
1969 String::from("add `extern crate alloc` to use the `alloc` crate"),
1970 Applicability::MaybeIncorrect,
1973 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1976 vec![(ident.span, sugg.to_string())],
1977 String::from("there is a crate or module with a similar name"),
1978 Applicability::MaybeIncorrect,
1983 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1988 impl<'a, 'b> ImportResolver<'a, 'b> {
1989 /// Adds suggestions for a path that cannot be resolved.
1990 pub(crate) fn make_path_suggestion(
1993 mut path: Vec<Segment>,
1994 parent_scope: &ParentScope<'b>,
1995 ) -> Option<(Vec<Segment>, Vec<String>)> {
1996 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
1998 match (path.get(0), path.get(1)) {
1999 // `{{root}}::ident::...` on both editions.
2000 // On 2015 `{{root}}` is usually added implicitly.
2001 (Some(fst), Some(snd))
2002 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
2003 // `ident::...` on 2018.
2005 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
2007 // Insert a placeholder that's later replaced by `self`/`super`/etc.
2008 path.insert(0, Segment::from_ident(Ident::empty()));
2013 self.make_missing_self_suggestion(path.clone(), parent_scope)
2014 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2015 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2016 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2019 /// Suggest a missing `self::` if that resolves to an correct module.
2023 /// LL | use foo::Bar;
2024 /// | ^^^ did you mean `self::foo`?
2026 fn make_missing_self_suggestion(
2028 mut path: Vec<Segment>,
2029 parent_scope: &ParentScope<'b>,
2030 ) -> Option<(Vec<Segment>, Vec<String>)> {
2031 // Replace first ident with `self` and check if that is valid.
2032 path[0].ident.name = kw::SelfLower;
2033 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2034 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
2035 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2038 /// Suggests a missing `crate::` if that resolves to an correct module.
2042 /// LL | use foo::Bar;
2043 /// | ^^^ did you mean `crate::foo`?
2045 fn make_missing_crate_suggestion(
2047 mut path: Vec<Segment>,
2048 parent_scope: &ParentScope<'b>,
2049 ) -> Option<(Vec<Segment>, Vec<String>)> {
2050 // Replace first ident with `crate` and check if that is valid.
2051 path[0].ident.name = kw::Crate;
2052 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2053 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
2054 if let PathResult::Module(..) = result {
2058 "`use` statements changed in Rust 2018; read more at \
2059 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2069 /// Suggests a missing `super::` if that resolves to an correct module.
2073 /// LL | use foo::Bar;
2074 /// | ^^^ did you mean `super::foo`?
2076 fn make_missing_super_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::Super;
2083 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2084 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
2085 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2088 /// Suggests a missing external crate name if that resolves to an correct module.
2092 /// LL | use foobar::Baz;
2093 /// | ^^^^^^ did you mean `baz::foobar`?
2096 /// Used when importing a submodule of an external crate but missing that crate's
2097 /// name as the first part of path.
2098 fn make_external_crate_suggestion(
2100 mut path: Vec<Segment>,
2101 parent_scope: &ParentScope<'b>,
2102 ) -> Option<(Vec<Segment>, Vec<String>)> {
2103 if path[1].ident.span.rust_2015() {
2107 // Sort extern crate names in *reverse* order to get
2108 // 1) some consistent ordering for emitted diagnostics, and
2109 // 2) `std` suggestions before `core` suggestions.
2110 let mut extern_crate_names =
2111 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2112 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2114 for name in extern_crate_names.into_iter() {
2115 // Replace first ident with a crate name and check if that is valid.
2116 path[0].ident.name = name;
2117 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2119 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2122 if let PathResult::Module(..) = result {
2123 return Some((path, Vec::new()));
2130 /// Suggests importing a macro from the root of the crate rather than a module within
2134 /// help: a macro with this name exists at the root of the crate
2136 /// LL | use issue_59764::makro;
2137 /// | ^^^^^^^^^^^^^^^^^^
2139 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2140 /// at the root of the crate instead of the module where it is defined
2142 pub(crate) fn check_for_module_export_macro(
2144 import: &'b Import<'b>,
2145 module: ModuleOrUniformRoot<'b>,
2147 ) -> Option<(Option<Suggestion>, Vec<String>)> {
2148 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2152 while let Some(parent) = crate_module.parent {
2153 crate_module = parent;
2156 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2157 // Don't make a suggestion if the import was already from the root of the
2162 let resolutions = self.r.resolutions(crate_module).borrow();
2163 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2164 let binding = resolution.borrow().binding()?;
2165 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2166 let module_name = crate_module.kind.name().unwrap();
2167 let import_snippet = match import.kind {
2168 ImportKind::Single { source, target, .. } if source != target => {
2169 format!("{} as {}", source, target)
2171 _ => format!("{}", ident),
2174 let mut corrections: Vec<(Span, String)> = Vec::new();
2175 if !import.is_nested() {
2176 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2177 // intermediate segments.
2178 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2180 // Find the binding span (and any trailing commas and spaces).
2181 // ie. `use a::b::{c, d, e};`
2183 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2189 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2190 found_closing_brace, binding_span
2193 let mut removal_span = binding_span;
2194 if found_closing_brace {
2195 // If the binding span ended with a closing brace, as in the below example:
2196 // ie. `use a::b::{c, d};`
2198 // Then expand the span of characters to remove to include the previous
2199 // binding's trailing comma.
2200 // ie. `use a::b::{c, d};`
2202 if let Some(previous_span) =
2203 extend_span_to_previous_binding(self.r.session, binding_span)
2205 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2206 removal_span = removal_span.with_lo(previous_span.lo());
2209 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2211 // Remove the `removal_span`.
2212 corrections.push((removal_span, "".to_string()));
2214 // Find the span after the crate name and if it has nested imports immediately
2215 // after the crate name already.
2216 // ie. `use a::b::{c, d};`
2218 // or `use a::{b, c, d}};`
2220 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2226 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2227 has_nested, after_crate_name
2230 let source_map = self.r.session.source_map();
2232 // Add the import to the start, with a `{` if required.
2233 let start_point = source_map.start_point(after_crate_name);
2234 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2238 // In this case, `start_snippet` must equal '{'.
2239 format!("{}{}, ", start_snippet, import_snippet)
2241 // In this case, add a `{`, then the moved import, then whatever
2242 // was there before.
2243 format!("{{{}, {}", import_snippet, start_snippet)
2248 // Add a `};` to the end if nested, matching the `{` added at the start.
2250 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2254 let suggestion = Some((
2256 String::from("a macro with this name exists at the root of the crate"),
2257 Applicability::MaybeIncorrect,
2260 "this could be because a macro annotated with `#[macro_export]` will be exported \
2261 at the root of the crate instead of the module where it is defined"
2264 Some((suggestion, note))
2271 /// Given a `binding_span` of a binding within a use statement:
2274 /// use foo::{a, b, c};
2278 /// then return the span until the next binding or the end of the statement:
2281 /// use foo::{a, b, c};
2284 fn find_span_of_binding_until_next_binding(
2289 let source_map = sess.source_map();
2291 // Find the span of everything after the binding.
2292 // ie. `a, e};` or `a};`
2293 let binding_until_end = binding_span.with_hi(use_span.hi());
2295 // Find everything after the binding but not including the binding.
2296 // ie. `, e};` or `};`
2297 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2299 // Keep characters in the span until we encounter something that isn't a comma or
2303 // Also note whether a closing brace character was encountered. If there
2304 // was, then later go backwards to remove any trailing commas that are left.
2305 let mut found_closing_brace = false;
2306 let after_binding_until_next_binding =
2307 source_map.span_take_while(after_binding_until_end, |&ch| {
2309 found_closing_brace = true;
2311 ch == ' ' || ch == ','
2314 // Combine the two spans.
2315 // ie. `a, ` or `a`.
2317 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2318 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2320 (found_closing_brace, span)
2323 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2327 /// use foo::a::{a, b, c};
2328 /// ^^--- binding span
2332 /// use foo::{a, b, c};
2333 /// --- binding span
2335 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2336 let source_map = sess.source_map();
2338 // `prev_source` will contain all of the source that came before the span.
2339 // Then split based on a command and take the first (ie. closest to our span)
2340 // snippet. In the example, this is a space.
2341 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2343 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2344 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2345 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2349 let prev_comma = prev_comma.first().unwrap();
2350 let prev_starting_brace = prev_starting_brace.first().unwrap();
2352 // If the amount of source code before the comma is greater than
2353 // the amount of source code before the starting brace then we've only
2354 // got one item in the nested item (eg. `issue_52891::{self}`).
2355 if prev_comma.len() > prev_starting_brace.len() {
2359 Some(binding_span.with_lo(BytePos(
2360 // Take away the number of bytes for the characters we've found and an
2361 // extra for the comma.
2362 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2366 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2367 /// it is a nested use tree.
2370 /// use foo::a::{b, c};
2371 /// ^^^^^^^^^^ // false
2373 /// use foo::{a, b, c};
2374 /// ^^^^^^^^^^ // true
2376 /// use foo::{a, b::{c, d}};
2377 /// ^^^^^^^^^^^^^^^ // true
2379 fn find_span_immediately_after_crate_name(
2381 module_name: Symbol,
2385 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2386 module_name, use_span
2388 let source_map = sess.source_map();
2390 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2391 let mut num_colons = 0;
2392 // Find second colon.. `use issue_59764:`
2393 let until_second_colon = source_map.span_take_while(use_span, |c| {
2397 !matches!(c, ':' if num_colons == 2)
2399 // Find everything after the second colon.. `foo::{baz, makro};`
2400 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2402 let mut found_a_non_whitespace_character = false;
2403 // Find the first non-whitespace character in `from_second_colon`.. `f`
2404 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2405 if found_a_non_whitespace_character {
2408 if !c.is_whitespace() {
2409 found_a_non_whitespace_character = true;
2414 // Find the first `{` in from_second_colon.. `foo::{`
2415 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2417 (next_left_bracket == after_second_colon, from_second_colon)
2420 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2421 /// independent options.
2427 /// Whether an existing place with an `use` item was found.
2433 /// Whether a binding is part of a pattern or an expression. Used for diagnostics.
2435 /// The binding is part of a pattern
2437 /// The binding is part of an expression
2441 /// When an entity with a given name is not available in scope, we search for
2442 /// entities with that name in all crates. This method allows outputting the
2443 /// results of this search in a programmer-friendly way
2445 definitions: &rustc_hir::definitions::Definitions,
2447 err: &mut Diagnostic,
2448 // This is `None` if all placement locations are inside expansions
2449 use_placement_span: Option<Span>,
2450 candidates: &[ImportSuggestion],
2452 found_use: FoundUse,
2453 is_pattern: IsPattern,
2456 if candidates.is_empty() {
2460 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2462 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2465 candidates.iter().for_each(|c| {
2466 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2467 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2470 // we want consistent results across executions, but candidates are produced
2471 // by iterating through a hash map, so make sure they are ordered:
2472 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2473 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2474 let core_path_strings =
2475 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2476 path_strings.extend(core_path_strings);
2477 path_strings.dedup_by(|a, b| a.0 == b.0);
2480 if !accessible_path_strings.is_empty() {
2481 let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2482 ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2484 ("one of these", "items", String::new())
2487 let tail = if path.len() > 1 { "..." } else { "" };
2488 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2489 let mut msg = if let IsPattern::Yes = is_pattern {
2491 "if you meant to match on {}{}{}, use the full path in the pattern{}",
2492 kind, instead, name, tail
2495 format!("consider importing {} {}{}{}", determiner, kind, instead, tail)
2498 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2502 if let (IsPattern::Yes, Some(span)) = (is_pattern, use_placement_span) {
2503 err.span_suggestions(
2506 accessible_path_strings.into_iter().map(|a| a.0),
2507 Applicability::MaybeIncorrect,
2509 } else if let Some(span) = use_placement_span {
2510 for candidate in &mut accessible_path_strings {
2511 // produce an additional newline to separate the new use statement
2512 // from the directly following item.
2513 let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" };
2514 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
2517 err.span_suggestions(
2520 accessible_path_strings.into_iter().map(|a| a.0),
2521 Applicability::MaybeIncorrect,
2523 if let [first, .., last] = &path[..] {
2524 err.span_suggestion_verbose(
2525 first.ident.span.until(last.ident.span),
2526 "...and refer to it directly",
2528 Applicability::Unspecified,
2534 for candidate in accessible_path_strings {
2536 msg.push_str(&candidate.0);
2542 assert!(!inaccessible_path_strings.is_empty());
2545 if let IsPattern::Yes = is_pattern { "you might have meant to match on " } else { "" };
2546 if inaccessible_path_strings.len() == 1 {
2547 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2549 "{}{} `{}`{} exists but is inaccessible",
2553 if let IsPattern::Yes = is_pattern { ", which" } else { "" }
2556 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2557 let span = definitions.def_span(local_def_id);
2558 let span = session.source_map().guess_head_span(span);
2559 let mut multi_span = MultiSpan::from_span(span);
2560 multi_span.push_span_label(span, "not accessible".to_string());
2561 err.span_note(multi_span, &msg);
2565 if let Some(note) = (*note).as_deref() {
2569 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2570 let descr = if inaccessible_path_strings
2573 .all(|(_, descr, _, _)| descr == descr_first)
2575 descr_first.to_string()
2580 let mut msg = format!("{}these {}s exist but are inaccessible", prefix, descr);
2581 let mut has_colon = false;
2583 let mut spans = Vec::new();
2584 for (name, _, def_id, _) in &inaccessible_path_strings {
2585 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2586 let span = definitions.def_span(local_def_id);
2587 let span = session.source_map().guess_head_span(span);
2588 spans.push((name, span));
2599 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2600 for (name, span) in spans {
2601 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2604 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2608 err.span_note(multi_span, &msg);
2614 struct UsePlacementFinder {
2615 target_module: NodeId,
2616 first_legal_span: Option<Span>,
2617 first_use_span: Option<Span>,
2620 impl UsePlacementFinder {
2621 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2623 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2624 finder.visit_crate(krate);
2625 if let Some(use_span) = finder.first_use_span {
2626 (Some(use_span), FoundUse::Yes)
2628 (finder.first_legal_span, FoundUse::No)
2633 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2634 fn visit_crate(&mut self, c: &Crate) {
2635 if self.target_module == CRATE_NODE_ID {
2636 let inject = c.spans.inject_use_span;
2637 if is_span_suitable_for_use_injection(inject) {
2638 self.first_legal_span = Some(inject);
2640 self.first_use_span = search_for_any_use_in_items(&c.items);
2643 visit::walk_crate(self, c);
2647 fn visit_item(&mut self, item: &'tcx ast::Item) {
2648 if self.target_module == item.id {
2649 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2650 let inject = mod_spans.inject_use_span;
2651 if is_span_suitable_for_use_injection(inject) {
2652 self.first_legal_span = Some(inject);
2654 self.first_use_span = search_for_any_use_in_items(items);
2658 visit::walk_item(self, item);
2663 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2665 if let ItemKind::Use(..) = item.kind {
2666 if is_span_suitable_for_use_injection(item.span) {
2667 return Some(item.span.shrink_to_lo());
2674 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2675 // don't suggest placing a use before the prelude
2676 // import or other generated ones