From 8cc1ed81dfd9e6eeb50d3621e0c862e9d3b4fe92 Mon Sep 17 00:00:00 2001 From: yukang Date: Mon, 1 Jul 2024 13:05:23 +0800 Subject: [PATCH] Fix import suggestion error when failed not from starting --- compiler/rustc_resolve/src/diagnostics.rs | 12 +++++++++- .../ui/imports/suggest-import-issue-120074.rs | 11 +++++++++ .../suggest-import-issue-120074.stderr | 23 +++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 tests/ui/imports/suggest-import-issue-120074.rs create mode 100644 tests/ui/imports/suggest-import-issue-120074.stderr diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 263daa11ec316..50a4e03d233a7 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1987,10 +1987,20 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { candidates .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path))); if let Some(candidate) = candidates.get(0) { + let path = { + // remove the possible common prefix of the path + let start_index = (0..failed_segment_idx) + .find(|&i| path[i].ident != candidate.path.segments[i].ident) + .unwrap_or_default(); + let segments = (start_index..=failed_segment_idx) + .map(|s| candidate.path.segments[s].clone()) + .collect(); + Path { segments, span: Span::default(), tokens: None } + }; ( String::from("unresolved import"), Some(( - vec![(ident.span, pprust::path_to_string(&candidate.path))], + vec![(ident.span, pprust::path_to_string(&path))], String::from("a similar path exists"), Applicability::MaybeIncorrect, )), diff --git a/tests/ui/imports/suggest-import-issue-120074.rs b/tests/ui/imports/suggest-import-issue-120074.rs new file mode 100644 index 0000000000000..a798e9eeeb809 --- /dev/null +++ b/tests/ui/imports/suggest-import-issue-120074.rs @@ -0,0 +1,11 @@ +pub mod foo { + pub mod bar { + pub fn do_the_thing() -> usize { + 42 + } + } +} + +fn main() { + println!("Hello, {}!", crate::bar::do_the_thing); //~ ERROR failed to resolve: unresolved import +} diff --git a/tests/ui/imports/suggest-import-issue-120074.stderr b/tests/ui/imports/suggest-import-issue-120074.stderr new file mode 100644 index 0000000000000..c1dff93bbdbff --- /dev/null +++ b/tests/ui/imports/suggest-import-issue-120074.stderr @@ -0,0 +1,23 @@ +error[E0433]: failed to resolve: unresolved import + --> $DIR/suggest-import-issue-120074.rs:10:35 + | +LL | println!("Hello, {}!", crate::bar::do_the_thing); + | ^^^ unresolved import + | +help: a similar path exists + | +LL | println!("Hello, {}!", crate::foo::bar::do_the_thing); + | ~~~~~~~~ +help: consider importing this module + | +LL + use foo::bar; + | +help: if you import `bar`, refer to it directly + | +LL - println!("Hello, {}!", crate::bar::do_the_thing); +LL + println!("Hello, {}!", bar::do_the_thing); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0433`.