Skip to content

Commit 4d2a049

Browse files
authored
Rollup merge of #127203 - chenyukang:yukang-fix-120074-import, r=Nadrieril
Fix import suggestion error when path segment failed not from starting Fixes #120074
2 parents 33b0238 + 8cc1ed8 commit 4d2a049

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

compiler/rustc_resolve/src/diagnostics.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -1987,10 +1987,20 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
19871987
candidates
19881988
.sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path)));
19891989
if let Some(candidate) = candidates.get(0) {
1990+
let path = {
1991+
// remove the possible common prefix of the path
1992+
let start_index = (0..failed_segment_idx)
1993+
.find(|&i| path[i].ident != candidate.path.segments[i].ident)
1994+
.unwrap_or_default();
1995+
let segments = (start_index..=failed_segment_idx)
1996+
.map(|s| candidate.path.segments[s].clone())
1997+
.collect();
1998+
Path { segments, span: Span::default(), tokens: None }
1999+
};
19902000
(
19912001
String::from("unresolved import"),
19922002
Some((
1993-
vec![(ident.span, pprust::path_to_string(&candidate.path))],
2003+
vec![(ident.span, pprust::path_to_string(&path))],
19942004
String::from("a similar path exists"),
19952005
Applicability::MaybeIncorrect,
19962006
)),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
pub mod foo {
2+
pub mod bar {
3+
pub fn do_the_thing() -> usize {
4+
42
5+
}
6+
}
7+
}
8+
9+
fn main() {
10+
println!("Hello, {}!", crate::bar::do_the_thing); //~ ERROR failed to resolve: unresolved import
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
error[E0433]: failed to resolve: unresolved import
2+
--> $DIR/suggest-import-issue-120074.rs:10:35
3+
|
4+
LL | println!("Hello, {}!", crate::bar::do_the_thing);
5+
| ^^^ unresolved import
6+
|
7+
help: a similar path exists
8+
|
9+
LL | println!("Hello, {}!", crate::foo::bar::do_the_thing);
10+
| ~~~~~~~~
11+
help: consider importing this module
12+
|
13+
LL + use foo::bar;
14+
|
15+
help: if you import `bar`, refer to it directly
16+
|
17+
LL - println!("Hello, {}!", crate::bar::do_the_thing);
18+
LL + println!("Hello, {}!", bar::do_the_thing);
19+
|
20+
21+
error: aborting due to 1 previous error
22+
23+
For more information about this error, try `rustc --explain E0433`.

0 commit comments

Comments
 (0)