[ty] Improve debug messages when imports fail (#21555)

This commit is contained in:
Alex Waygood 2025-11-21 13:45:57 +00:00 committed by GitHub
parent 1af318534a
commit 54dba15088
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 4 deletions

View File

@ -40,6 +40,8 @@ error[unresolved-import]: Cannot resolve imported module `....foo`
2 |
3 | stat = add(10, 15)
|
help: The module can be resolved if the number of leading dots is reduced
help: Did you mean `...foo`?
info: Searched in the following paths during module resolution:
info: 1. /src (first-party code)
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)

View File

@ -5799,9 +5799,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
return;
};
let mut diagnostic = builder.into_diagnostic(format_args!(
"Cannot resolve imported module `{}{}`",
".".repeat(level as usize),
module.unwrap_or_default()
"Cannot resolve imported module `{}`",
format_import_from_module(level, module)
));
if level == 0 {
@ -5832,6 +5831,30 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}
}
}
} else {
if let Some(better_level) = (0..level).rev().find(|reduced_level| {
let Ok(module_name) = ModuleName::from_identifier_parts(
self.db(),
self.file(),
module,
*reduced_level,
) else {
return false;
};
resolve_module(self.db(), &module_name).is_some()
}) {
diagnostic
.help("The module can be resolved if the number of leading dots is reduced");
diagnostic.help(format_args!(
"Did you mean `{}`?",
format_import_from_module(better_level, module)
));
diagnostic.set_concise_message(format_args!(
"Cannot resolve imported module `{}` - did you mean `{}`?",
format_import_from_module(level, module),
format_import_from_module(better_level, module)
));
}
}
// Add search paths information to the diagnostic
@ -6039,7 +6062,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}
Err(ModuleNameResolutionError::UnknownCurrentModule) => {
tracing::debug!(
"Relative module resolution `{}` failed; could not resolve file `{}` to a module",
"Relative module resolution `{}` failed: could not resolve file `{}` to a module \
(try adjusting configured search paths?)",
format_import_from_module(*level, module),
self.file().path(self.db())
);