Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix import suggestion error when path segment failed not from starting #127203

Merged
merged 1 commit into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)),
Expand Down
11 changes: 11 additions & 0 deletions tests/ui/imports/suggest-import-issue-120074.rs
Original file line number Diff line number Diff line change
@@ -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
}
23 changes: 23 additions & 0 deletions tests/ui/imports/suggest-import-issue-120074.stderr
Original file line number Diff line number Diff line change
@@ -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`.
Loading