Structured suggestion for extern crate foo when foo isn't resolved in import

When encountering a name in an import that could have come from a crate that wasn't imported, use a structured suggestion to suggest `extern crate foo;` pointing at the right place in the crate.

When encountering `_` in an import, do not suggest `extern crate _;`.

```
error[E0432]: unresolved import `spam`
  --> $DIR/import-from-missing-star-3.rs:2:9
   |
LL |     use spam::*;
   |         ^^^^ maybe a missing crate `spam`?
   |
help: consider importing the `spam` crate
   |
LL + extern crate spam;
   |
```
This commit is contained in:
Esteban Küber 2024-07-24 19:31:02 +00:00
parent 4db3d12e6f
commit b61570ac11
33 changed files with 192 additions and 64 deletions

View file

@ -2026,14 +2026,17 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
Applicability::MaybeIncorrect,
)),
)
} else if ident.name == kw::Underscore {
(format!("`_` is not a valid crate or module name"), None)
} else if self.tcx.sess.is_rust_2015() {
(
format!("you might be missing crate `{ident}`"),
Some((
vec![],
format!(
"consider adding `extern crate {ident}` to use the `{ident}` crate"
),
vec![(
self.current_crate_outer_attr_insert_span,
format!("extern crate {ident};\n"),
)],
format!("consider importing the `{ident}` crate"),
Applicability::MaybeIncorrect,
)),
)

View file

@ -1180,6 +1180,10 @@ pub struct Resolver<'a, 'tcx> {
/// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
/// Needed because glob delegations exclude explicitly defined names.
impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
/// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
/// could be a crate that wasn't imported. For diagnostics use only.
current_crate_outer_attr_insert_span: Span,
}
/// Nothing really interesting here; it just provides memory for the rest of the crate.
@ -1342,6 +1346,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
attrs: &[ast::Attribute],
crate_span: Span,
current_crate_outer_attr_insert_span: Span,
arenas: &'a ResolverArenas<'a>,
) -> Resolver<'a, 'tcx> {
let root_def_id = CRATE_DEF_ID.to_def_id();
@ -1525,6 +1530,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
glob_delegation_invoc_ids: Default::default(),
impl_unexpanded_invocations: Default::default(),
impl_binding_keys: Default::default(),
current_crate_outer_attr_insert_span,
};
let root_parent_scope = ParentScope::module(graph_root, &resolver);