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 } 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 },
139 } else if let Some((span, msg, sugg, appl)) = suggestion {
140 err.span_suggestion(span, msg, sugg, appl);
146 crate fn report_conflict<'b>(
151 new_binding: &NameBinding<'b>,
152 old_binding: &NameBinding<'b>,
154 // Error on the second of two conflicting names
155 if old_binding.span.lo() > new_binding.span.lo() {
156 return self.report_conflict(parent, ident, ns, old_binding, new_binding);
159 let container = match parent.kind {
160 ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()),
161 ModuleKind::Block(..) => "block",
164 let old_noun = match old_binding.is_import() {
166 false => "definition",
169 let new_participle = match new_binding.is_import() {
175 (ident.name, self.session.source_map().guess_head_span(new_binding.span));
177 if let Some(s) = self.name_already_seen.get(&name) {
183 let old_kind = match (ns, old_binding.module()) {
184 (ValueNS, _) => "value",
185 (MacroNS, _) => "macro",
186 (TypeNS, _) if old_binding.is_extern_crate() => "extern crate",
187 (TypeNS, Some(module)) if module.is_normal() => "module",
188 (TypeNS, Some(module)) if module.is_trait() => "trait",
189 (TypeNS, _) => "type",
192 let msg = format!("the name `{}` is defined multiple times", name);
194 let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) {
195 (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg),
196 (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() {
197 true => struct_span_err!(self.session, span, E0254, "{}", msg),
198 false => struct_span_err!(self.session, span, E0260, "{}", msg),
200 _ => match (old_binding.is_import(), new_binding.is_import()) {
201 (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg),
202 (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg),
203 _ => struct_span_err!(self.session, span, E0255, "{}", msg),
208 "`{}` must be defined only once in the {} namespace of this {}",
214 err.span_label(span, format!("`{}` re{} here", name, new_participle));
216 self.session.source_map().guess_head_span(old_binding.span),
217 format!("previous {} of the {} `{}` here", old_noun, old_kind, name),
220 // See https://github.com/rust-lang/rust/issues/32354
221 use NameBindingKind::Import;
222 let import = match (&new_binding.kind, &old_binding.kind) {
223 // If there are two imports where one or both have attributes then prefer removing the
224 // import without attributes.
225 (Import { import: new, .. }, Import { import: old, .. })
227 !new_binding.span.is_dummy()
228 && !old_binding.span.is_dummy()
229 && (new.has_attributes || old.has_attributes)
232 if old.has_attributes {
233 Some((new, new_binding.span, true))
235 Some((old, old_binding.span, true))
238 // Otherwise prioritize the new binding.
239 (Import { import, .. }, other) if !new_binding.span.is_dummy() => {
240 Some((import, new_binding.span, other.is_import()))
242 (other, Import { import, .. }) if !old_binding.span.is_dummy() => {
243 Some((import, old_binding.span, other.is_import()))
248 // Check if the target of the use for both bindings is the same.
249 let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id();
250 let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy();
252 self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item);
253 // Only suggest removing an import if both bindings are to the same def, if both spans
254 // aren't dummy spans. Further, if both bindings are imports, then the ident must have
255 // been introduced by an item.
256 let should_remove_import = duplicate
258 && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item);
261 Some((import, span, true)) if should_remove_import && import.is_nested() => {
262 self.add_suggestion_for_duplicate_nested_use(&mut err, import, span)
264 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
265 // Simple case - remove the entire import. Due to the above match arm, this can
266 // only be a single use so just remove it entirely.
267 err.tool_only_span_suggestion(
268 import.use_span_with_attributes,
269 "remove unnecessary import",
271 Applicability::MaybeIncorrect,
274 Some((import, span, _)) => {
275 self.add_suggestion_for_rename_of_use(&mut err, name, import, span)
281 self.name_already_seen.insert(name, span);
284 /// This function adds a suggestion to change the binding name of a new import that conflicts
285 /// with an existing import.
287 /// ```text,ignore (diagnostic)
288 /// help: you can use `as` to change the binding name of the import
290 /// LL | use foo::bar as other_bar;
291 /// | ^^^^^^^^^^^^^^^^^^^^^
293 fn add_suggestion_for_rename_of_use(
295 err: &mut Diagnostic,
300 let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() {
301 format!("Other{}", name)
303 format!("other_{}", name)
306 let mut suggestion = None;
308 ImportKind::Single { type_ns_only: true, .. } => {
309 suggestion = Some(format!("self as {}", suggested_name))
311 ImportKind::Single { source, .. } => {
313 source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
315 if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) {
316 if pos <= snippet.len() {
317 suggestion = Some(format!(
321 if snippet.ends_with(';') { ";" } else { "" }
327 ImportKind::ExternCrate { source, target } => {
328 suggestion = Some(format!(
329 "extern crate {} as {};",
330 source.unwrap_or(target.name),
337 let rename_msg = "you can use `as` to change the binding name of the import";
338 if let Some(suggestion) = suggestion {
343 Applicability::MaybeIncorrect,
346 err.span_label(binding_span, rename_msg);
350 /// This function adds a suggestion to remove an unnecessary binding from an import that is
351 /// nested. In the following example, this function will be invoked to remove the `a` binding
352 /// in the second use statement:
354 /// ```ignore (diagnostic)
355 /// use issue_52891::a;
356 /// use issue_52891::{d, a, e};
359 /// The following suggestion will be added:
361 /// ```ignore (diagnostic)
362 /// use issue_52891::{d, a, e};
363 /// ^-- help: remove unnecessary import
366 /// If the nested use contains only one import then the suggestion will remove the entire
369 /// It is expected that the provided import is nested - this isn't checked by the
370 /// function. If this invariant is not upheld, this function's behaviour will be unexpected
371 /// as characters expected by span manipulations won't be present.
372 fn add_suggestion_for_duplicate_nested_use(
374 err: &mut Diagnostic,
378 assert!(import.is_nested());
379 let message = "remove unnecessary import";
381 // Two examples will be used to illustrate the span manipulations we're doing:
383 // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is
384 // `a` and `import.use_span` is `issue_52891::{d, a, e};`.
385 // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is
386 // `a` and `import.use_span` is `issue_52891::{d, e, a};`.
388 let (found_closing_brace, span) =
389 find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span);
391 // If there was a closing brace then identify the span to remove any trailing commas from
393 if found_closing_brace {
394 if let Some(span) = extend_span_to_previous_binding(self.session, span) {
395 err.tool_only_span_suggestion(
399 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, String::new(), Applicability::MachineApplicable);
418 crate fn lint_if_path_starts_with_module(
422 second_binding: Option<&NameBinding<'_>>,
424 let (diag_id, diag_span) = match finalize {
425 Finalize::No => return,
426 Finalize::SimplePath(id, path_span) => (id, path_span),
427 Finalize::UsePath { root_id, root_span, .. } => (root_id, root_span),
428 Finalize::QPathTrait { qpath_id, qpath_span, .. } => (qpath_id, qpath_span),
431 let first_name = match path.get(0) {
432 // In the 2018 edition this lint is a hard error, so nothing to do
433 Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name,
437 // We're only interested in `use` paths which should start with
438 // `{{root}}` currently.
439 if first_name != kw::PathRoot {
444 // If this import looks like `crate::...` it's already good
445 Some(Segment { ident, .. }) if ident.name == kw::Crate => return,
446 // Otherwise go below to see if it's an extern crate
448 // If the path has length one (and it's `PathRoot` most likely)
449 // then we don't know whether we're gonna be importing a crate or an
450 // item in our crate. Defer this lint to elsewhere
454 // If the first element of our path was actually resolved to an
455 // `ExternCrate` (also used for `crate::...`) then no need to issue a
456 // warning, this looks all good!
457 if let Some(binding) = second_binding {
458 if let NameBindingKind::Import { import, .. } = binding.kind {
459 // Careful: we still want to rewrite paths from renamed extern crates.
460 if let ImportKind::ExternCrate { source: None, .. } = import.kind {
466 let diag = BuiltinLintDiagnostics::AbsPathWithModule(diag_span);
467 self.lint_buffer.buffer_lint_with_diagnostic(
468 ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
471 "absolute paths must start with `self`, `super`, \
472 `crate`, or an external crate name in the 2018 edition",
477 crate fn add_module_candidates(
480 names: &mut Vec<TypoSuggestion>,
481 filter_fn: &impl Fn(Res) -> bool,
483 for (key, resolution) in self.resolutions(module).borrow().iter() {
484 if let Some(binding) = resolution.borrow().binding {
485 let res = binding.res();
487 names.push(TypoSuggestion::typo_from_res(key.ident.name, res));
493 /// Combines an error with provided span and emits it.
495 /// This takes the error provided, combines it with the span and any additional spans inside the
496 /// error and emits it.
497 crate fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
498 self.into_struct_error(span, resolution_error).emit();
501 crate fn into_struct_error(
504 resolution_error: ResolutionError<'a>,
505 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
506 match resolution_error {
507 ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => {
508 let mut err = struct_span_err!(
512 "can't use generic parameters from outer function",
514 err.span_label(span, "use of generic parameter from outer function".to_string());
516 let sm = self.session.source_map();
518 Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => {
519 if let Some(impl_span) =
520 maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id))
523 reduce_impl_span_to_impl_keyword(sm, impl_span),
524 "`Self` type implicitly declared here, by this `impl`",
527 match (maybe_trait_defid, maybe_impl_defid) {
529 err.span_label(span, "can't use `Self` here");
532 err.span_label(span, "use a type here instead");
534 (None, None) => bug!("`impl` without trait nor type?"),
538 Res::Def(DefKind::TyParam, def_id) => {
539 if let Some(span) = self.opt_span(def_id) {
540 err.span_label(span, "type parameter from outer function");
543 Res::Def(DefKind::ConstParam, def_id) => {
544 if let Some(span) = self.opt_span(def_id) {
545 err.span_label(span, "const parameter from outer function");
550 "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \
551 DefKind::TyParam or DefKind::ConstParam"
556 if has_generic_params == HasGenericParams::Yes {
557 // Try to retrieve the span of the function signature and generate a new
558 // message with a local type or const parameter.
559 let sugg_msg = "try using a local generic parameter instead";
560 if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) {
561 // Suggest the modification to the user
566 Applicability::MachineApplicable,
568 } else if let Some(sp) = sm.generate_fn_name_span(span) {
571 "try adding a local generic parameter in this method instead"
575 err.help("try using a local generic parameter instead");
581 ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
582 let mut err = struct_span_err!(
586 "the name `{}` is already used for a generic \
587 parameter in this item's generic parameters",
590 err.span_label(span, "already used");
591 err.span_label(first_use_span, format!("first use of `{}`", name));
594 ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => {
595 let mut err = struct_span_err!(
599 "method `{}` is not a member of trait `{}`",
603 err.span_label(span, format!("not a member of trait `{}`", trait_));
604 if let Some(candidate) = candidate {
607 "there is an associated function with a similar name",
608 candidate.to_ident_string(),
609 Applicability::MaybeIncorrect,
614 ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => {
615 let mut err = struct_span_err!(
619 "type `{}` is not a member of trait `{}`",
623 err.span_label(span, format!("not a member of trait `{}`", trait_));
624 if let Some(candidate) = candidate {
627 "there is an associated type with a similar name",
628 candidate.to_ident_string(),
629 Applicability::MaybeIncorrect,
634 ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => {
635 let mut err = struct_span_err!(
639 "const `{}` is not a member of trait `{}`",
643 err.span_label(span, format!("not a member of trait `{}`", trait_));
644 if let Some(candidate) = candidate {
647 "there is an associated constant with a similar name",
648 candidate.to_ident_string(),
649 Applicability::MaybeIncorrect,
654 ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => {
655 let BindingError { name, target, origin, could_be_path } = binding_error;
657 let target_sp = target.iter().copied().collect::<Vec<_>>();
658 let origin_sp = origin.iter().copied().collect::<Vec<_>>();
660 let msp = MultiSpan::from_spans(target_sp.clone());
661 let mut err = struct_span_err!(
665 "variable `{}` is not bound in all patterns",
668 for sp in target_sp {
669 err.span_label(sp, format!("pattern doesn't bind `{}`", name));
671 for sp in origin_sp {
672 err.span_label(sp, "variable not in all patterns");
675 let import_suggestions = self.lookup_import_candidates(
676 Ident::with_dummy_span(name),
679 &|res: Res| match res {
681 DefKind::Ctor(CtorOf::Variant, CtorKind::Const)
682 | DefKind::Ctor(CtorOf::Struct, CtorKind::Const)
684 | DefKind::AssocConst,
691 if import_suggestions.is_empty() {
692 let help_msg = format!(
693 "if you meant to match on a variant or a `const` item, consider \
694 making the path in the pattern qualified: `path::to::ModOrType::{}`",
697 err.span_help(span, &help_msg);
712 ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => {
713 let mut err = struct_span_err!(
717 "variable `{}` is bound inconsistently across alternatives separated by `|`",
720 err.span_label(span, "bound in different ways");
721 err.span_label(first_binding_span, "first binding");
724 ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
725 let mut err = struct_span_err!(
729 "identifier `{}` is bound more than once in this parameter list",
732 err.span_label(span, "used as parameter more than once");
735 ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
736 let mut err = struct_span_err!(
740 "identifier `{}` is bound more than once in the same pattern",
743 err.span_label(span, "used in a pattern more than once");
746 ResolutionError::UndeclaredLabel { name, suggestion } => {
747 let mut err = struct_span_err!(
751 "use of undeclared label `{}`",
755 err.span_label(span, format!("undeclared label `{}`", name));
758 // A reachable label with a similar name exists.
759 Some((ident, true)) => {
760 err.span_label(ident.span, "a label with a similar name is reachable");
763 "try using similarly named label",
764 ident.name.to_string(),
765 Applicability::MaybeIncorrect,
768 // An unreachable label with a similar name exists.
769 Some((ident, false)) => {
772 "a label with a similar name exists but is unreachable",
775 // No similarly-named labels exist.
781 ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => {
782 let mut err = struct_span_err!(
787 "`self` imports are only allowed within a { } list"
790 // None of the suggestions below would help with a case like `use self`.
792 // use foo::bar::self -> foo::bar
793 // use foo::bar::self as abc -> foo::bar as abc
796 "consider importing the module directly",
798 Applicability::MachineApplicable,
801 // use foo::bar::self -> foo::bar::{self}
802 // use foo::bar::self as abc -> foo::bar::{self as abc}
804 (span_with_rename.shrink_to_lo(), "{".to_string()),
805 (span_with_rename.shrink_to_hi(), "}".to_string()),
807 err.multipart_suggestion(
808 "alternatively, use the multi-path `use` syntax to import `self`",
810 Applicability::MachineApplicable,
815 ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
816 let mut err = struct_span_err!(
820 "`self` import can only appear once in an import list"
822 err.span_label(span, "can only appear once in an import list");
825 ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
826 let mut err = struct_span_err!(
830 "`self` import can only appear in an import list with \
833 err.span_label(span, "can only appear in an import list with a non-empty prefix");
836 ResolutionError::FailedToResolve { label, suggestion } => {
838 struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label);
839 err.span_label(span, label);
841 if let Some((suggestions, msg, applicability)) = suggestion {
842 if suggestions.is_empty() {
846 err.multipart_suggestion(&msg, suggestions, applicability);
851 ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
852 let mut err = struct_span_err!(
857 "can't capture dynamic environment in a fn item"
859 err.help("use the `|| { ... }` closure form instead");
862 ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => {
863 let mut err = struct_span_err!(
867 "attempt to use a non-constant value in a constant"
870 // ^^^ given this Span
871 // ------- get this Span to have an applicable suggestion
874 // only do this if the const and usage of the non-constant value are on the same line
875 // the further the two are apart, the higher the chance of the suggestion being wrong
880 .span_extend_to_prev_str(ident.span, current, true, false);
883 Some(sp) if !self.session.source_map().is_multiline(sp) => {
884 let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32)));
887 &format!("consider using `{}` instead of `{}`", sugg, current),
888 format!("{} {}", sugg, ident),
889 Applicability::MaybeIncorrect,
891 err.span_label(span, "non-constant value");
894 err.span_label(ident.span, &format!("this would need to be a `{}`", sugg));
900 ResolutionError::BindingShadowsSomethingUnacceptable {
901 shadowing_binding_descr,
905 shadowed_binding_descr,
906 shadowed_binding_span,
908 let mut err = struct_span_err!(
912 "{}s cannot shadow {}s",
913 shadowing_binding_descr,
914 shadowed_binding_descr,
918 format!("cannot be named the same as {} {}", article, shadowed_binding_descr),
921 format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle);
922 err.span_label(shadowed_binding_span, msg);
925 ResolutionError::ForwardDeclaredGenericParam => {
926 let mut err = struct_span_err!(
930 "generic parameters with a default cannot use \
931 forward declared identifiers"
935 "defaulted generic parameters cannot be forward declared".to_string(),
939 ResolutionError::ParamInTyOfConstParam(name) => {
940 let mut err = struct_span_err!(
944 "the type of const parameters must not depend on other generic parameters"
948 format!("the type must not depend on the parameter `{}`", name),
952 ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => {
953 let mut err = self.session.struct_span_err(
955 "generic parameters may not be used in const operations",
957 err.span_label(span, &format!("cannot perform const operation using `{}`", name));
960 err.note("type parameters may not be used in const expressions");
963 "const parameters may only be used as standalone arguments, i.e. `{}`",
968 if self.session.is_nightly_build() {
970 "use `#![feature(generic_const_exprs)]` to allow generic const expressions",
976 ResolutionError::SelfInGenericParamDefault => {
977 let mut err = struct_span_err!(
981 "generic parameters cannot use `Self` in their defaults"
983 err.span_label(span, "`Self` in generic parameter default".to_string());
986 ResolutionError::UnreachableLabel { name, definition_span, suggestion } => {
987 let mut err = struct_span_err!(
991 "use of unreachable label `{}`",
995 err.span_label(definition_span, "unreachable label defined here");
996 err.span_label(span, format!("unreachable label `{}`", name));
998 "labels are unreachable through functions, closures, async blocks and modules",
1002 // A reachable label with a similar name exists.
1003 Some((ident, true)) => {
1004 err.span_label(ident.span, "a label with a similar name is reachable");
1005 err.span_suggestion(
1007 "try using similarly named label",
1008 ident.name.to_string(),
1009 Applicability::MaybeIncorrect,
1012 // An unreachable label with a similar name exists.
1013 Some((ident, false)) => {
1016 "a label with a similar name exists but is also unreachable",
1019 // No similarly-named labels exist.
1025 ResolutionError::TraitImplMismatch {
1032 let mut err = self.session.struct_span_err_with_code(
1035 "item `{}` is an associated {}, which doesn't match its trait `{}`",
1036 name, kind, trait_path,
1040 err.span_label(span, "does not match trait");
1041 err.span_label(trait_item_span, "item in trait");
1044 ResolutionError::InvalidAsmSym => {
1045 let mut err = self.session.struct_span_err(span, "invalid `sym` operand");
1046 err.span_label(span, "is a local variable");
1047 err.help("`sym` operands must refer to either a function or a static");
1053 crate fn report_vis_error(
1055 vis_resolution_error: VisResolutionError<'_>,
1056 ) -> ErrorGuaranteed {
1057 match vis_resolution_error {
1058 VisResolutionError::Relative2018(span, path) => {
1059 let mut err = self.session.struct_span_err(
1061 "relative paths are not supported in visibilities in 2018 edition or later",
1063 err.span_suggestion(
1066 format!("crate::{}", pprust::path_to_string(&path)),
1067 Applicability::MaybeIncorrect,
1071 VisResolutionError::AncestorOnly(span) => struct_span_err!(
1075 "visibilities can only be restricted to ancestor modules"
1077 VisResolutionError::FailedToResolve(span, label, suggestion) => {
1078 self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion })
1080 VisResolutionError::ExpectedFound(span, path_str, res) => {
1081 let mut err = struct_span_err!(
1085 "expected module, found {} `{}`",
1089 err.span_label(span, "not a module");
1092 VisResolutionError::Indeterminate(span) => struct_span_err!(
1096 "cannot determine resolution for the visibility"
1098 VisResolutionError::ModuleOnly(span) => {
1099 self.session.struct_span_err(span, "visibility must resolve to a module")
1105 /// Lookup typo candidate in scope for a macro or import.
1106 fn early_lookup_typo_candidate(
1108 scope_set: ScopeSet<'a>,
1109 parent_scope: &ParentScope<'a>,
1111 filter_fn: &impl Fn(Res) -> bool,
1112 ) -> Option<TypoSuggestion> {
1113 let mut suggestions = Vec::new();
1114 let ctxt = ident.span.ctxt();
1115 self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| {
1117 Scope::DeriveHelpers(expn_id) => {
1118 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
1125 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1129 Scope::DeriveHelpersCompat => {
1130 let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
1132 for derive in parent_scope.derives {
1133 let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
1134 if let Ok((Some(ext), _)) = this.resolve_macro_path(
1136 Some(MacroKind::Derive),
1144 .map(|name| TypoSuggestion::typo_from_res(*name, res)),
1150 Scope::MacroRules(macro_rules_scope) => {
1151 if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
1152 let res = macro_rules_binding.binding.res();
1154 suggestions.push(TypoSuggestion::typo_from_res(
1155 macro_rules_binding.ident.name,
1161 Scope::CrateRoot => {
1162 let root_ident = Ident::new(kw::PathRoot, ident.span);
1163 let root_module = this.resolve_crate_root(root_ident);
1164 this.add_module_candidates(root_module, &mut suggestions, filter_fn);
1166 Scope::Module(module, _) => {
1167 this.add_module_candidates(module, &mut suggestions, filter_fn);
1169 Scope::RegisteredAttrs => {
1170 let res = Res::NonMacroAttr(NonMacroAttrKind::Registered);
1173 this.registered_attrs
1175 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1179 Scope::MacroUsePrelude => {
1180 suggestions.extend(this.macro_use_prelude.iter().filter_map(
1182 let res = binding.res();
1183 filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res))
1187 Scope::BuiltinAttrs => {
1188 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty));
1193 .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)),
1197 Scope::ExternPrelude => {
1198 suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| {
1199 let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id());
1200 filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res))
1203 Scope::ToolPrelude => {
1204 let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1206 this.registered_tools
1208 .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)),
1211 Scope::StdLibPrelude => {
1212 if let Some(prelude) = this.prelude {
1213 let mut tmp_suggestions = Vec::new();
1214 this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
1218 .filter(|s| use_prelude || this.is_builtin_macro(s.res)),
1222 Scope::BuiltinTypes => {
1223 suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| {
1224 let res = Res::PrimTy(*prim_ty);
1225 filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res))
1233 // Make sure error reporting is deterministic.
1234 suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());
1236 match find_best_match_for_name(
1237 &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
1241 Some(found) if found != ident.name => {
1242 suggestions.into_iter().find(|suggestion| suggestion.candidate == found)
1248 fn lookup_import_candidates_from_module<FilterFn>(
1250 lookup_ident: Ident,
1251 namespace: Namespace,
1252 parent_scope: &ParentScope<'a>,
1253 start_module: Module<'a>,
1255 filter_fn: FilterFn,
1256 ) -> Vec<ImportSuggestion>
1258 FilterFn: Fn(Res) -> bool,
1260 let mut candidates = Vec::new();
1261 let mut seen_modules = FxHashSet::default();
1262 let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)];
1263 let mut worklist_via_import = vec![];
1265 while let Some((in_module, path_segments, accessible)) = match worklist.pop() {
1266 None => worklist_via_import.pop(),
1269 let in_module_is_extern = !in_module.def_id().is_local();
1270 // We have to visit module children in deterministic order to avoid
1271 // instabilities in reported imports (#43552).
1272 in_module.for_each_child(self, |this, ident, ns, name_binding| {
1273 // avoid non-importable candidates
1274 if !name_binding.is_importable() {
1278 let child_accessible =
1279 accessible && this.is_accessible_from(name_binding.vis, parent_scope.module);
1281 // do not venture inside inaccessible items of other crates
1282 if in_module_is_extern && !child_accessible {
1286 let via_import = name_binding.is_import() && !name_binding.is_extern_crate();
1288 // There is an assumption elsewhere that paths of variants are in the enum's
1289 // declaration and not imported. With this assumption, the variant component is
1290 // chopped and the rest of the path is assumed to be the enum's own path. For
1291 // errors where a variant is used as the type instead of the enum, this causes
1292 // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`.
1293 if via_import && name_binding.is_possibly_imported_variant() {
1297 // #90113: Do not count an inaccessible reexported item as a candidate.
1298 if let NameBindingKind::Import { binding, .. } = name_binding.kind {
1299 if this.is_accessible_from(binding.vis, parent_scope.module)
1300 && !this.is_accessible_from(name_binding.vis, parent_scope.module)
1306 // collect results based on the filter function
1307 // avoid suggesting anything from the same module in which we are resolving
1308 // avoid suggesting anything with a hygienic name
1309 if ident.name == lookup_ident.name
1311 && !ptr::eq(in_module, parent_scope.module)
1312 && !ident.span.normalize_to_macros_2_0().from_expansion()
1314 let res = name_binding.res();
1317 let mut segms = path_segments.clone();
1318 if lookup_ident.span.rust_2018() {
1319 // crate-local absolute paths start with `crate::` in edition 2018
1320 // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660)
1321 segms.insert(0, ast::PathSegment::from_ident(crate_name));
1324 segms.push(ast::PathSegment::from_ident(ident));
1325 let path = Path { span: name_binding.span, segments: segms, tokens: None };
1326 let did = match res {
1327 Res::Def(DefKind::Ctor(..), did) => this.parent(did),
1328 _ => res.opt_def_id(),
1331 if child_accessible {
1332 // Remove invisible match if exists
1333 if let Some(idx) = candidates
1335 .position(|v: &ImportSuggestion| v.did == did && !v.accessible)
1337 candidates.remove(idx);
1341 if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
1342 // See if we're recommending TryFrom, TryInto, or FromIterator and add
1343 // a note about editions
1344 let note = if let Some(did) = did {
1345 let requires_note = !did.is_local()
1346 && this.cstore().item_attrs_untracked(did, this.session).any(
1348 if attr.has_name(sym::rustc_diagnostic_item) {
1349 [sym::TryInto, sym::TryFrom, sym::FromIterator]
1351 .contains(&attr.value_str())
1358 requires_note.then(|| {
1360 "'{}' is included in the prelude starting in Edition 2021",
1361 path_names_to_string(&path)
1368 candidates.push(ImportSuggestion {
1372 accessible: child_accessible,
1379 // collect submodules to explore
1380 if let Some(module) = name_binding.module() {
1382 let mut path_segments = path_segments.clone();
1383 path_segments.push(ast::PathSegment::from_ident(ident));
1385 let is_extern_crate_that_also_appears_in_prelude =
1386 name_binding.is_extern_crate() && lookup_ident.span.rust_2018();
1388 if !is_extern_crate_that_also_appears_in_prelude {
1389 // add the module to the lookup
1390 if seen_modules.insert(module.def_id()) {
1391 if via_import { &mut worklist_via_import } else { &mut worklist }
1392 .push((module, path_segments, child_accessible));
1399 // If only some candidates are accessible, take just them
1400 if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) {
1401 candidates = candidates.into_iter().filter(|x| x.accessible).collect();
1407 /// When name resolution fails, this method can be used to look up candidate
1408 /// entities with the expected name. It allows filtering them using the
1409 /// supplied predicate (which should be used to only accept the types of
1410 /// definitions expected, e.g., traits). The lookup spans across all crates.
1412 /// N.B., the method does not look into imports, but this is not a problem,
1413 /// since we report the definitions (thus, the de-aliased imports).
1414 crate fn lookup_import_candidates<FilterFn>(
1416 lookup_ident: Ident,
1417 namespace: Namespace,
1418 parent_scope: &ParentScope<'a>,
1419 filter_fn: FilterFn,
1420 ) -> Vec<ImportSuggestion>
1422 FilterFn: Fn(Res) -> bool,
1424 let mut suggestions = self.lookup_import_candidates_from_module(
1429 Ident::with_dummy_span(kw::Crate),
1433 if lookup_ident.span.rust_2018() {
1434 let extern_prelude_names = self.extern_prelude.clone();
1435 for (ident, _) in extern_prelude_names.into_iter() {
1436 if ident.span.from_expansion() {
1437 // Idents are adjusted to the root context before being
1438 // resolved in the extern prelude, so reporting this to the
1439 // user is no help. This skips the injected
1440 // `extern crate std` in the 2018 edition, which would
1441 // otherwise cause duplicate suggestions.
1444 if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) {
1445 let crate_root = self.expect_module(crate_id.as_def_id());
1446 suggestions.extend(self.lookup_import_candidates_from_module(
1461 crate fn unresolved_macro_suggestions(
1463 err: &mut Diagnostic,
1464 macro_kind: MacroKind,
1465 parent_scope: &ParentScope<'a>,
1468 let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind);
1469 let suggestion = self.early_lookup_typo_candidate(
1470 ScopeSet::Macro(macro_kind),
1475 self.add_typo_suggestion(err, suggestion, ident.span);
1477 let import_suggestions =
1478 self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected);
1484 &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),
1509 let desc = match binding.res() {
1510 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1511 "a function-like macro".to_string()
1513 Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
1514 format!("an attribute: `#[{}]`", ident)
1516 Res::Def(DefKind::Macro(MacroKind::Derive), _) => {
1517 format!("a derive macro: `#[derive({})]`", ident)
1520 // Don't confuse the user with tool modules.
1523 Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
1524 "only a trait, without a derive macro".to_string()
1530 macro_kind.article(),
1531 macro_kind.descr_expected(),
1534 if let crate::NameBindingKind::Import { import, .. } = binding.kind {
1535 if !import.span.is_dummy() {
1538 &format!("`{}` is imported here, but it is {}", ident, desc),
1540 // Silence the 'unused import' warning we might get,
1541 // since this diagnostic already covers that import.
1542 self.record_use(ident, binding, false);
1546 err.note(&format!("`{}` is in scope, but it is {}", ident, desc));
1552 crate fn add_typo_suggestion(
1554 err: &mut Diagnostic,
1555 suggestion: Option<TypoSuggestion>,
1558 let suggestion = match suggestion {
1559 None => return false,
1560 // We shouldn't suggest underscore.
1561 Some(suggestion) if suggestion.candidate == kw::Underscore => return false,
1562 Some(suggestion) => suggestion,
1564 let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate {
1565 LOCAL_CRATE => self.opt_span(def_id),
1569 .guess_head_span(self.cstore().get_span_untracked(def_id, self.session)),
1572 if let Some(def_span) = def_span {
1573 if span.overlaps(def_span) {
1574 // Don't suggest typo suggestion for itself like in the following:
1575 // error[E0423]: expected function, tuple struct or tuple variant, found struct `X`
1576 // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14
1579 // | ----------- `X` defined here
1581 // LL | const Y: X = X("ö");
1582 // | -------------^^^^^^- similarly named constant `Y` defined here
1584 // help: use struct literal syntax instead
1586 // LL | const Y: X = X {};
1588 // help: a constant with a similar name exists
1590 // LL | const Y: X = Y("ö");
1594 let prefix = match suggestion.target {
1595 SuggestionTarget::SimilarlyNamed => "similarly named ",
1596 SuggestionTarget::SingleItem => "",
1600 self.session.source_map().guess_head_span(def_span),
1602 "{}{} `{}` defined here",
1604 suggestion.res.descr(),
1605 suggestion.candidate.as_str(),
1609 let msg = match suggestion.target {
1610 SuggestionTarget::SimilarlyNamed => format!(
1611 "{} {} with a similar name exists",
1612 suggestion.res.article(),
1613 suggestion.res.descr()
1615 SuggestionTarget::SingleItem => {
1616 format!("maybe you meant this {}", suggestion.res.descr())
1619 err.span_suggestion(
1622 suggestion.candidate.to_string(),
1623 Applicability::MaybeIncorrect,
1628 fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
1630 if b.span.is_dummy() || self.session.source_map().span_to_snippet(b.span).is_err() {
1631 // These already contain the "built-in" prefix or look bad with it.
1633 !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
1634 let (built_in, from) = if from_prelude {
1635 ("", " from prelude")
1636 } else if b.is_extern_crate()
1638 && self.session.opts.externs.get(ident.as_str()).is_some()
1640 ("", " passed with `--extern`")
1641 } else if add_built_in {
1647 let a = if built_in.is_empty() { res.article() } else { "a" };
1648 format!("{a}{built_in} {thing}{from}", thing = res.descr())
1650 let introduced = if b.is_import() { "imported" } else { "defined" };
1651 format!("the {thing} {introduced} here", thing = res.descr())
1655 fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) {
1656 let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error;
1657 let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() {
1658 // We have to print the span-less alternative first, otherwise formatting looks bad.
1659 (b2, b1, misc2, misc1, true)
1661 (b1, b2, misc1, misc2, false)
1664 let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous");
1665 err.span_label(ident.span, "ambiguous name");
1666 err.note(&format!("ambiguous because of {}", kind.descr()));
1668 let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| {
1669 let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude);
1670 let note_msg = format!("`{ident}` could{also} refer to {what}");
1672 let thing = b.res().descr();
1673 let mut help_msgs = Vec::new();
1674 if b.is_glob_import()
1675 && (kind == AmbiguityKind::GlobVsGlob
1676 || kind == AmbiguityKind::GlobVsExpanded
1677 || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty())
1679 help_msgs.push(format!(
1680 "consider adding an explicit import of `{ident}` to disambiguate"
1683 if b.is_extern_crate() && ident.span.rust_2018() {
1684 help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously"))
1686 if misc == AmbiguityErrorMisc::SuggestCrate {
1688 .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously"))
1689 } else if misc == AmbiguityErrorMisc::SuggestSelf {
1691 .push(format!("use `self::{ident}` to refer to this {thing} unambiguously"))
1694 err.span_note(b.span, ¬e_msg);
1695 for (i, help_msg) in help_msgs.iter().enumerate() {
1696 let or = if i == 0 { "" } else { "or " };
1697 err.help(&format!("{}{}", or, help_msg));
1701 could_refer_to(b1, misc1, "");
1702 could_refer_to(b2, misc2, " also");
1706 /// If the binding refers to a tuple struct constructor with fields,
1707 /// returns the span of its fields.
1708 fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> {
1709 if let NameBindingKind::Res(
1710 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id),
1714 let def_id = self.parent(ctor_def_id).expect("no parent for a constructor");
1715 let fields = self.field_names.get(&def_id)?;
1716 return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()`
1721 fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) {
1722 let PrivacyError { ident, binding, .. } = *privacy_error;
1724 let res = binding.res();
1725 let ctor_fields_span = self.ctor_fields_span(binding);
1726 let plain_descr = res.descr().to_string();
1727 let nonimport_descr =
1728 if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr };
1729 let import_descr = nonimport_descr.clone() + " import";
1731 |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr };
1733 // Print the primary message.
1734 let descr = get_descr(binding);
1736 struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident);
1737 err.span_label(ident.span, &format!("private {}", descr));
1738 if let Some(span) = ctor_fields_span {
1739 err.span_label(span, "a constructor is private if any of the fields is private");
1742 // Print the whole import chain to make it easier to see what happens.
1743 let first_binding = binding;
1744 let mut next_binding = Some(binding);
1745 let mut next_ident = ident;
1746 while let Some(binding) = next_binding {
1747 let name = next_ident;
1748 next_binding = match binding.kind {
1749 _ if res == Res::Err => None,
1750 NameBindingKind::Import { binding, import, .. } => match import.kind {
1751 _ if binding.span.is_dummy() => None,
1752 ImportKind::Single { source, .. } => {
1753 next_ident = source;
1756 ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding),
1757 ImportKind::ExternCrate { .. } => None,
1762 let first = ptr::eq(binding, first_binding);
1764 "{and_refers_to}the {item} `{name}`{which} is defined here{dots}",
1765 and_refers_to = if first { "" } else { "...and refers to " },
1766 item = get_descr(binding),
1767 which = if first { "" } else { " which" },
1768 dots = if next_binding.is_some() { "..." } else { "" },
1770 let def_span = self.session.source_map().guess_head_span(binding.span);
1771 let mut note_span = MultiSpan::from_span(def_span);
1772 if !first && binding.vis.is_public() {
1773 note_span.push_span_label(def_span, "consider importing it directly");
1775 err.span_note(note_span, &msg);
1781 crate fn find_similarly_named_module_or_crate(
1784 current_module: &Module<'a>,
1785 ) -> Option<Symbol> {
1786 let mut candidates = self
1789 .map(|(ident, _)| ident.name)
1793 .filter(|(_, module)| {
1794 current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
1796 .flat_map(|(_, module)| module.kind.name()),
1798 .filter(|c| !c.to_string().is_empty())
1799 .collect::<Vec<_>>();
1802 match find_best_match_for_name(&candidates, ident, None) {
1803 Some(sugg) if sugg == ident => None,
1808 crate fn report_path_resolution_error(
1811 opt_ns: Option<Namespace>, // `None` indicates a module path in import
1812 parent_scope: &ParentScope<'a>,
1813 ribs: Option<&PerNS<Vec<Rib<'a>>>>,
1814 unusable_binding: Option<&'a NameBinding<'a>>,
1815 module: Option<ModuleOrUniformRoot<'a>>,
1818 ) -> (String, Option<Suggestion>) {
1819 let is_last = i == path.len() - 1;
1820 let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1821 let module_res = match module {
1822 Some(ModuleOrUniformRoot::Module(module)) => module.res(),
1825 if module_res == self.graph_root.res() {
1826 let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
1827 let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod);
1829 .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
1830 if let Some(candidate) = candidates.get(0) {
1832 String::from("unresolved import"),
1834 vec![(ident.span, pprust::path_to_string(&candidate.path))],
1835 String::from("a similar path exists"),
1836 Applicability::MaybeIncorrect,
1839 } else if self.session.edition() == Edition::Edition2015 {
1840 (format!("maybe a missing crate `{}`?", ident), None)
1842 (format!("could not find `{}` in the crate root", ident), None)
1845 let parent = path[i - 1].ident.name;
1846 let parent = match parent {
1847 // ::foo is mounted at the crate root for 2015, and is the extern
1848 // prelude for 2018+
1849 kw::PathRoot if self.session.edition() > Edition::Edition2015 => {
1850 "the list of imported crates".to_owned()
1852 kw::PathRoot | kw::Crate => "the crate root".to_owned(),
1853 _ => format!("`{}`", parent),
1856 let mut msg = format!("could not find `{}` in {}", ident, parent);
1857 if ns == TypeNS || ns == ValueNS {
1858 let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS };
1859 let binding = if let Some(module) = module {
1860 self.resolve_ident_in_module(
1869 } else if let Some(ribs) = ribs
1870 && let Some(TypeNS | ValueNS) = opt_ns
1872 match self.resolve_ident_in_lexical_scope(
1880 // we found a locally-imported or available item/module
1881 Some(LexicalScopeBinding::Item(binding)) => Some(binding),
1885 let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none());
1886 self.early_resolve_ident_in_lexical_scope(
1896 if let Some(binding) = binding {
1897 let mut found = |what| {
1899 "expected {}, found {} `{}` in {}",
1906 if binding.module().is_some() {
1909 match binding.res() {
1910 Res::Def(kind, id) => found(kind.descr(id)),
1911 _ => found(ns_to_try.descr()),
1917 } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) {
1918 // Check whether the name refers to an item in the value namespace.
1919 let binding = if let Some(ribs) = ribs {
1920 self.resolve_ident_in_lexical_scope(
1931 let match_span = match binding {
1932 // Name matches a local variable. For example:
1935 // let Foo: &str = "";
1936 // println!("{}", Foo::Bar); // Name refers to local
1937 // // variable `Foo`.
1940 Some(LexicalScopeBinding::Res(Res::Local(id))) => {
1941 Some(*self.pat_span_map.get(&id).unwrap())
1943 // Name matches item from a local name binding
1944 // created by `use` declaration. For example:
1946 // pub Foo: &str = "";
1950 // println!("{}", Foo::Bar); // Name refers to local
1951 // // binding `Foo`.
1954 Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span),
1957 let suggestion = if let Some(span) = match_span {
1959 vec![(span, String::from(""))],
1960 format!("`{}` is defined here, but is not a type", ident),
1961 Applicability::MaybeIncorrect,
1967 (format!("use of undeclared type `{}`", ident), suggestion)
1969 let suggestion = if ident.name == sym::alloc {
1972 String::from("add `extern crate alloc` to use the `alloc` crate"),
1973 Applicability::MaybeIncorrect,
1976 self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map(
1979 vec![(ident.span, sugg.to_string())],
1980 String::from("there is a crate or module with a similar name"),
1981 Applicability::MaybeIncorrect,
1986 (format!("use of undeclared crate or module `{}`", ident), suggestion)
1991 impl<'a, 'b> ImportResolver<'a, 'b> {
1992 /// Adds suggestions for a path that cannot be resolved.
1993 pub(crate) fn make_path_suggestion(
1996 mut path: Vec<Segment>,
1997 parent_scope: &ParentScope<'b>,
1998 ) -> Option<(Vec<Segment>, Vec<String>)> {
1999 debug!("make_path_suggestion: span={:?} path={:?}", span, path);
2001 match (path.get(0), path.get(1)) {
2002 // `{{root}}::ident::...` on both editions.
2003 // On 2015 `{{root}}` is usually added implicitly.
2004 (Some(fst), Some(snd))
2005 if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {}
2006 // `ident::...` on 2018.
2008 if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() =>
2010 // Insert a placeholder that's later replaced by `self`/`super`/etc.
2011 path.insert(0, Segment::from_ident(Ident::empty()));
2016 self.make_missing_self_suggestion(path.clone(), parent_scope)
2017 .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope))
2018 .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope))
2019 .or_else(|| self.make_external_crate_suggestion(path, parent_scope))
2022 /// Suggest a missing `self::` if that resolves to an correct module.
2026 /// LL | use foo::Bar;
2027 /// | ^^^ did you mean `self::foo`?
2029 fn make_missing_self_suggestion(
2031 mut path: Vec<Segment>,
2032 parent_scope: &ParentScope<'b>,
2033 ) -> Option<(Vec<Segment>, Vec<String>)> {
2034 // Replace first ident with `self` and check if that is valid.
2035 path[0].ident.name = kw::SelfLower;
2036 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2037 debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
2038 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2041 /// Suggests a missing `crate::` if that resolves to an correct module.
2045 /// LL | use foo::Bar;
2046 /// | ^^^ did you mean `crate::foo`?
2048 fn make_missing_crate_suggestion(
2050 mut path: Vec<Segment>,
2051 parent_scope: &ParentScope<'b>,
2052 ) -> Option<(Vec<Segment>, Vec<String>)> {
2053 // Replace first ident with `crate` and check if that is valid.
2054 path[0].ident.name = kw::Crate;
2055 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2056 debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
2057 if let PathResult::Module(..) = result {
2061 "`use` statements changed in Rust 2018; read more at \
2062 <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\
2072 /// Suggests a missing `super::` if that resolves to an correct module.
2076 /// LL | use foo::Bar;
2077 /// | ^^^ did you mean `super::foo`?
2079 fn make_missing_super_suggestion(
2081 mut path: Vec<Segment>,
2082 parent_scope: &ParentScope<'b>,
2083 ) -> Option<(Vec<Segment>, Vec<String>)> {
2084 // Replace first ident with `crate` and check if that is valid.
2085 path[0].ident.name = kw::Super;
2086 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2087 debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
2088 if let PathResult::Module(..) = result { Some((path, Vec::new())) } else { None }
2091 /// Suggests a missing external crate name if that resolves to an correct module.
2095 /// LL | use foobar::Baz;
2096 /// | ^^^^^^ did you mean `baz::foobar`?
2099 /// Used when importing a submodule of an external crate but missing that crate's
2100 /// name as the first part of path.
2101 fn make_external_crate_suggestion(
2103 mut path: Vec<Segment>,
2104 parent_scope: &ParentScope<'b>,
2105 ) -> Option<(Vec<Segment>, Vec<String>)> {
2106 if path[1].ident.span.rust_2015() {
2110 // Sort extern crate names in *reverse* order to get
2111 // 1) some consistent ordering for emitted diagnostics, and
2112 // 2) `std` suggestions before `core` suggestions.
2113 let mut extern_crate_names =
2114 self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
2115 extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
2117 for name in extern_crate_names.into_iter() {
2118 // Replace first ident with a crate name and check if that is valid.
2119 path[0].ident.name = name;
2120 let result = self.r.maybe_resolve_path(&path, None, parent_scope);
2122 "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
2125 if let PathResult::Module(..) = result {
2126 return Some((path, Vec::new()));
2133 /// Suggests importing a macro from the root of the crate rather than a module within
2137 /// help: a macro with this name exists at the root of the crate
2139 /// LL | use issue_59764::makro;
2140 /// | ^^^^^^^^^^^^^^^^^^
2142 /// = note: this could be because a macro annotated with `#[macro_export]` will be exported
2143 /// at the root of the crate instead of the module where it is defined
2145 pub(crate) fn check_for_module_export_macro(
2147 import: &'b Import<'b>,
2148 module: ModuleOrUniformRoot<'b>,
2150 ) -> Option<(Option<Suggestion>, Vec<String>)> {
2151 let ModuleOrUniformRoot::Module(mut crate_module) = module else {
2155 while let Some(parent) = crate_module.parent {
2156 crate_module = parent;
2159 if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) {
2160 // Don't make a suggestion if the import was already from the root of the
2165 let resolutions = self.r.resolutions(crate_module).borrow();
2166 let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?;
2167 let binding = resolution.borrow().binding()?;
2168 if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
2169 let module_name = crate_module.kind.name().unwrap();
2170 let import_snippet = match import.kind {
2171 ImportKind::Single { source, target, .. } if source != target => {
2172 format!("{} as {}", source, target)
2174 _ => format!("{}", ident),
2177 let mut corrections: Vec<(Span, String)> = Vec::new();
2178 if !import.is_nested() {
2179 // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove
2180 // intermediate segments.
2181 corrections.push((import.span, format!("{}::{}", module_name, import_snippet)));
2183 // Find the binding span (and any trailing commas and spaces).
2184 // ie. `use a::b::{c, d, e};`
2186 let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
2192 "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}",
2193 found_closing_brace, binding_span
2196 let mut removal_span = binding_span;
2197 if found_closing_brace {
2198 // If the binding span ended with a closing brace, as in the below example:
2199 // ie. `use a::b::{c, d};`
2201 // Then expand the span of characters to remove to include the previous
2202 // binding's trailing comma.
2203 // ie. `use a::b::{c, d};`
2205 if let Some(previous_span) =
2206 extend_span_to_previous_binding(self.r.session, binding_span)
2208 debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
2209 removal_span = removal_span.with_lo(previous_span.lo());
2212 debug!("check_for_module_export_macro: removal_span={:?}", removal_span);
2214 // Remove the `removal_span`.
2215 corrections.push((removal_span, "".to_string()));
2217 // Find the span after the crate name and if it has nested imports immediately
2218 // after the crate name already.
2219 // ie. `use a::b::{c, d};`
2221 // or `use a::{b, c, d}};`
2223 let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
2229 "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}",
2230 has_nested, after_crate_name
2233 let source_map = self.r.session.source_map();
2235 // Add the import to the start, with a `{` if required.
2236 let start_point = source_map.start_point(after_crate_name);
2237 if let Ok(start_snippet) = source_map.span_to_snippet(start_point) {
2241 // In this case, `start_snippet` must equal '{'.
2242 format!("{}{}, ", start_snippet, import_snippet)
2244 // In this case, add a `{`, then the moved import, then whatever
2245 // was there before.
2246 format!("{{{}, {}", import_snippet, start_snippet)
2251 // Add a `};` to the end if nested, matching the `{` added at the start.
2253 corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
2257 let suggestion = Some((
2259 String::from("a macro with this name exists at the root of the crate"),
2260 Applicability::MaybeIncorrect,
2263 "this could be because a macro annotated with `#[macro_export]` will be exported \
2264 at the root of the crate instead of the module where it is defined"
2267 Some((suggestion, note))
2274 /// Given a `binding_span` of a binding within a use statement:
2277 /// use foo::{a, b, c};
2281 /// then return the span until the next binding or the end of the statement:
2284 /// use foo::{a, b, c};
2287 fn find_span_of_binding_until_next_binding(
2292 let source_map = sess.source_map();
2294 // Find the span of everything after the binding.
2295 // ie. `a, e};` or `a};`
2296 let binding_until_end = binding_span.with_hi(use_span.hi());
2298 // Find everything after the binding but not including the binding.
2299 // ie. `, e};` or `};`
2300 let after_binding_until_end = binding_until_end.with_lo(binding_span.hi());
2302 // Keep characters in the span until we encounter something that isn't a comma or
2306 // Also note whether a closing brace character was encountered. If there
2307 // was, then later go backwards to remove any trailing commas that are left.
2308 let mut found_closing_brace = false;
2309 let after_binding_until_next_binding =
2310 source_map.span_take_while(after_binding_until_end, |&ch| {
2312 found_closing_brace = true;
2314 ch == ' ' || ch == ','
2317 // Combine the two spans.
2318 // ie. `a, ` or `a`.
2320 // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };`
2321 let span = binding_span.with_hi(after_binding_until_next_binding.hi());
2323 (found_closing_brace, span)
2326 /// Given a `binding_span`, return the span through to the comma or opening brace of the previous
2330 /// use foo::a::{a, b, c};
2331 /// ^^--- binding span
2335 /// use foo::{a, b, c};
2336 /// --- binding span
2338 fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> {
2339 let source_map = sess.source_map();
2341 // `prev_source` will contain all of the source that came before the span.
2342 // Then split based on a command and take the first (ie. closest to our span)
2343 // snippet. In the example, this is a space.
2344 let prev_source = source_map.span_to_prev_source(binding_span).ok()?;
2346 let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>();
2347 let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>();
2348 if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 {
2352 let prev_comma = prev_comma.first().unwrap();
2353 let prev_starting_brace = prev_starting_brace.first().unwrap();
2355 // If the amount of source code before the comma is greater than
2356 // the amount of source code before the starting brace then we've only
2357 // got one item in the nested item (eg. `issue_52891::{self}`).
2358 if prev_comma.len() > prev_starting_brace.len() {
2362 Some(binding_span.with_lo(BytePos(
2363 // Take away the number of bytes for the characters we've found and an
2364 // extra for the comma.
2365 binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1,
2369 /// Given a `use_span` of a binding within a use statement, returns the highlighted span and if
2370 /// it is a nested use tree.
2373 /// use foo::a::{b, c};
2374 /// ^^^^^^^^^^ // false
2376 /// use foo::{a, b, c};
2377 /// ^^^^^^^^^^ // true
2379 /// use foo::{a, b::{c, d}};
2380 /// ^^^^^^^^^^^^^^^ // true
2382 fn find_span_immediately_after_crate_name(
2384 module_name: Symbol,
2388 "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}",
2389 module_name, use_span
2391 let source_map = sess.source_map();
2393 // Using `use issue_59764::foo::{baz, makro};` as an example throughout..
2394 let mut num_colons = 0;
2395 // Find second colon.. `use issue_59764:`
2396 let until_second_colon = source_map.span_take_while(use_span, |c| {
2400 !matches!(c, ':' if num_colons == 2)
2402 // Find everything after the second colon.. `foo::{baz, makro};`
2403 let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));
2405 let mut found_a_non_whitespace_character = false;
2406 // Find the first non-whitespace character in `from_second_colon`.. `f`
2407 let after_second_colon = source_map.span_take_while(from_second_colon, |c| {
2408 if found_a_non_whitespace_character {
2411 if !c.is_whitespace() {
2412 found_a_non_whitespace_character = true;
2417 // Find the first `{` in from_second_colon.. `foo::{`
2418 let next_left_bracket = source_map.span_through_char(from_second_colon, '{');
2420 (next_left_bracket == after_second_colon, from_second_colon)
2423 /// A suggestion has already been emitted, change the wording slightly to clarify that both are
2424 /// independent options.
2430 /// Whether an existing place with an `use` item was found.
2436 /// Whether a binding is part of a pattern or an expression. Used for diagnostics.
2438 /// The binding is part of a pattern
2440 /// The binding is part of an expression
2444 /// When an entity with a given name is not available in scope, we search for
2445 /// entities with that name in all crates. This method allows outputting the
2446 /// results of this search in a programmer-friendly way
2448 definitions: &rustc_hir::definitions::Definitions,
2450 err: &mut Diagnostic,
2451 // This is `None` if all placement locations are inside expansions
2452 use_placement_span: Option<Span>,
2453 candidates: &[ImportSuggestion],
2455 found_use: FoundUse,
2456 is_pattern: IsPattern,
2458 if candidates.is_empty() {
2462 let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2464 let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> =
2467 candidates.iter().for_each(|c| {
2468 (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings })
2469 .push((path_names_to_string(&c.path), c.descr, c.did, &c.note))
2472 // we want consistent results across executions, but candidates are produced
2473 // by iterating through a hash map, so make sure they are ordered:
2474 for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] {
2475 path_strings.sort_by(|a, b| a.0.cmp(&b.0));
2476 let core_path_strings =
2477 path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>();
2478 path_strings.extend(core_path_strings);
2479 path_strings.dedup_by(|a, b| a.0 == b.0);
2482 if !accessible_path_strings.is_empty() {
2483 let (determiner, kind, name) = if accessible_path_strings.len() == 1 {
2484 ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0))
2486 ("one of these", "items", String::new())
2489 let instead = if let Instead::Yes = instead { " instead" } else { "" };
2490 let mut msg = if let IsPattern::Yes = is_pattern {
2492 "if you meant to match on {}{}{}, use the full path in the pattern",
2496 format!("consider importing {} {}{}", determiner, kind, instead)
2499 for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2503 if let (IsPattern::Yes, Some(span)) = (is_pattern, use_placement_span) {
2504 err.span_suggestions(
2507 accessible_path_strings.into_iter().map(|a| a.0),
2508 Applicability::MaybeIncorrect,
2510 } else if let Some(span) = use_placement_span {
2511 for candidate in &mut accessible_path_strings {
2512 // produce an additional newline to separate the new use statement
2513 // from the directly following item.
2514 let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" };
2515 candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline);
2518 err.span_suggestions(
2521 accessible_path_strings.into_iter().map(|a| a.0),
2522 Applicability::MaybeIncorrect,
2527 for candidate in accessible_path_strings {
2529 msg.push_str(&candidate.0);
2535 assert!(!inaccessible_path_strings.is_empty());
2538 if let IsPattern::Yes = is_pattern { "you might have meant to match on " } else { "" };
2539 if inaccessible_path_strings.len() == 1 {
2540 let (name, descr, def_id, note) = &inaccessible_path_strings[0];
2542 "{}{} `{}`{} exists but is inaccessible",
2546 if let IsPattern::Yes = is_pattern { ", which" } else { "" }
2549 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2550 let span = definitions.def_span(local_def_id);
2551 let span = session.source_map().guess_head_span(span);
2552 let mut multi_span = MultiSpan::from_span(span);
2553 multi_span.push_span_label(span, "not accessible".to_string());
2554 err.span_note(multi_span, &msg);
2558 if let Some(note) = (*note).as_deref() {
2562 let (_, descr_first, _, _) = &inaccessible_path_strings[0];
2563 let descr = if inaccessible_path_strings
2566 .all(|(_, descr, _, _)| descr == descr_first)
2568 descr_first.to_string()
2573 let mut msg = format!("{}these {}s exist but are inaccessible", prefix, descr);
2574 let mut has_colon = false;
2576 let mut spans = Vec::new();
2577 for (name, _, def_id, _) in &inaccessible_path_strings {
2578 if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) {
2579 let span = definitions.def_span(local_def_id);
2580 let span = session.source_map().guess_head_span(span);
2581 spans.push((name, span));
2592 let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect());
2593 for (name, span) in spans {
2594 multi_span.push_span_label(span, format!("`{}`: not accessible", name));
2597 for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
2601 err.span_note(multi_span, &msg);
2607 struct UsePlacementFinder {
2608 target_module: NodeId,
2609 first_legal_span: Option<Span>,
2610 first_use_span: Option<Span>,
2613 impl UsePlacementFinder {
2614 fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) {
2616 UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None };
2617 finder.visit_crate(krate);
2618 if let Some(use_span) = finder.first_use_span {
2619 (Some(use_span), FoundUse::Yes)
2621 (finder.first_legal_span, FoundUse::No)
2626 impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
2627 fn visit_crate(&mut self, c: &Crate) {
2628 if self.target_module == CRATE_NODE_ID {
2629 let inject = c.spans.inject_use_span;
2630 if is_span_suitable_for_use_injection(inject) {
2631 self.first_legal_span = Some(inject);
2633 self.first_use_span = search_for_any_use_in_items(&c.items);
2636 visit::walk_crate(self, c);
2640 fn visit_item(&mut self, item: &'tcx ast::Item) {
2641 if self.target_module == item.id {
2642 if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind {
2643 let inject = mod_spans.inject_use_span;
2644 if is_span_suitable_for_use_injection(inject) {
2645 self.first_legal_span = Some(inject);
2647 self.first_use_span = search_for_any_use_in_items(items);
2651 visit::walk_item(self, item);
2656 fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
2658 if let ItemKind::Use(..) = item.kind {
2659 if is_span_suitable_for_use_injection(item.span) {
2660 return Some(item.span.shrink_to_lo());
2667 fn is_span_suitable_for_use_injection(s: Span) -> bool {
2668 // don't suggest placing a use before the prelude
2669 // import or other generated ones