Skip to content

Commit 54dba15

Browse files
authored
[ty] Improve debug messages when imports fail (#21555)
1 parent 1af3185 commit 54dba15

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

crates/ty_python_semantic/resources/mdtest/snapshots/unresolved_import.md_-_Unresolved_import_di…_-_Using_`from`_with_to…_(4b8ba6ee48180cdd).snap

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ error[unresolved-import]: Cannot resolve imported module `....foo`
4040
2 |
4141
3 | stat = add(10, 15)
4242
|
43+
help: The module can be resolved if the number of leading dots is reduced
44+
help: Did you mean `...foo`?
4345
info: Searched in the following paths during module resolution:
4446
info: 1. /src (first-party code)
4547
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)

crates/ty_python_semantic/src/types/infer/builder.rs

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5799,9 +5799,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
57995799
return;
58005800
};
58015801
let mut diagnostic = builder.into_diagnostic(format_args!(
5802-
"Cannot resolve imported module `{}{}`",
5803-
".".repeat(level as usize),
5804-
module.unwrap_or_default()
5802+
"Cannot resolve imported module `{}`",
5803+
format_import_from_module(level, module)
58055804
));
58065805

58075806
if level == 0 {
@@ -5832,6 +5831,30 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
58325831
}
58335832
}
58345833
}
5834+
} else {
5835+
if let Some(better_level) = (0..level).rev().find(|reduced_level| {
5836+
let Ok(module_name) = ModuleName::from_identifier_parts(
5837+
self.db(),
5838+
self.file(),
5839+
module,
5840+
*reduced_level,
5841+
) else {
5842+
return false;
5843+
};
5844+
resolve_module(self.db(), &module_name).is_some()
5845+
}) {
5846+
diagnostic
5847+
.help("The module can be resolved if the number of leading dots is reduced");
5848+
diagnostic.help(format_args!(
5849+
"Did you mean `{}`?",
5850+
format_import_from_module(better_level, module)
5851+
));
5852+
diagnostic.set_concise_message(format_args!(
5853+
"Cannot resolve imported module `{}` - did you mean `{}`?",
5854+
format_import_from_module(level, module),
5855+
format_import_from_module(better_level, module)
5856+
));
5857+
}
58355858
}
58365859

58375860
// Add search paths information to the diagnostic
@@ -6039,7 +6062,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
60396062
}
60406063
Err(ModuleNameResolutionError::UnknownCurrentModule) => {
60416064
tracing::debug!(
6042-
"Relative module resolution `{}` failed; could not resolve file `{}` to a module",
6065+
"Relative module resolution `{}` failed: could not resolve file `{}` to a module \
6066+
(try adjusting configured search paths?)",
60436067
format_import_from_module(*level, module),
60446068
self.file().path(self.db())
60456069
);

0 commit comments

Comments
 (0)