Skip to content

Unify wording of "failed to resolve" errors with "cannot find" resolution errors #128086

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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: 9 additions & 3 deletions compiler/rustc_resolve/src/build_reduced_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,9 +382,15 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
PathResult::NonModule(partial_res) => {
expected_found_error(partial_res.expect_full_res())
}
PathResult::Failed { span, label, suggestion, .. } => {
Err(VisResolutionError::FailedToResolve(span, label, suggestion))
}
PathResult::Failed {
span, label, suggestion, segment_name, item_type, ..
} => Err(VisResolutionError::FailedToResolve(
span,
segment_name,
label,
suggestion,
item_type,
)),
PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
}
}
Expand Down
44 changes: 36 additions & 8 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,9 +792,30 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
self.dcx().create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span })
}
ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
let mut err =
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
ResolutionError::FailedToResolve { segment, label, suggestion, module, item_type } => {
let mut err = struct_span_code_err!(
self.dcx(),
span,
E0433,
"cannot find {item_type} `{segment}` in {}",
match module {
Some(ModuleOrUniformRoot::CurrentScope) | None => "this scope".to_string(),
Some(ModuleOrUniformRoot::Module(module)) => {
match module.kind {
ModuleKind::Def(_, _, None) => "the crate root".to_string(),
ModuleKind::Def(kind, def_id, Some(name)) => {
format!("{} `{name}`", kind.descr(def_id))
}
ModuleKind::Block => "this scope".to_string(),
}
}
Some(ModuleOrUniformRoot::CrateRootAndExternPrelude) => {
"the crate root or the list of imported crates".to_string()
}
Some(ModuleOrUniformRoot::ExternPrelude) =>
"the list of imported crates".to_string(),
},
);
err.span_label(span, label);

if let Some((suggestions, msg, applicability)) = suggestion {
Expand All @@ -806,7 +827,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
}
if let Some(ModuleOrUniformRoot::Module(module)) = module
&& let Some(module) = module.opt_def_id()
&& let Some(segment) = segment
{
self.find_cfg_stripped(&mut err, &segment, module);
}
Expand Down Expand Up @@ -1003,10 +1023,18 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
VisResolutionError::AncestorOnly(span) => {
self.dcx().create_err(errs::AncestorOnly(span))
}
VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error(
span,
ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None },
),
VisResolutionError::FailedToResolve(span, segment, label, suggestion, item_type) => {
self.into_struct_error(
span,
ResolutionError::FailedToResolve {
segment,
label,
suggestion,
module: None,
item_type,
},
)
}
VisResolutionError::ExpectedFound(span, path_str, res) => {
self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str })
}
Expand Down
40 changes: 38 additions & 2 deletions compiler/rustc_resolve/src/ident.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use Determinacy::*;
use Namespace::*;
use rustc_ast::{self as ast, NodeId};
use rustc_errors::ErrorGuaranteed;
use rustc_errors::{Applicability, ErrorGuaranteed};
use rustc_hir::def::{DefKind, Namespace, NonMacroAttrKind, PartialRes, PerNS};
use rustc_middle::{bug, ty};
use rustc_session::lint::BuiltinLintDiag;
Expand Down Expand Up @@ -1483,13 +1483,42 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
Some(ModuleOrUniformRoot::Module(self.resolve_self(&mut ctxt, parent)));
continue;
}
let mut item_type = "module";
if path.len() == 1
&& let Some(ribs) = ribs
&& let RibKind::Normal = ribs[ValueNS][ribs[ValueNS].len() - 1].kind
{
item_type = "item";
}
return PathResult::failed(
ident,
false,
finalize.is_some(),
module_had_parse_errors,
module,
|| ("there are too many leading `super` keywords".to_string(), None),
|| {
let mut suggestion = None;
let label = if path.len() == 1
&& let Some(ribs) = ribs
&& let RibKind::Normal = ribs[ValueNS][ribs[ValueNS].len() - 1].kind
{
suggestion = Some((
vec![(ident.span.shrink_to_lo(), "r#".to_string())],
"if you still want to call your identifier `super`, use the \
raw identifier format"
.to_string(),
Applicability::MachineApplicable,
));
"can't use `super` as an identifier"
} else if segment_idx == 0 {
"can't use `super` on the crate root, there are no further modules \
to go \"up\" to"
} else {
"there are too many leading `super` keywords"
};
(label.to_string(), suggestion)
},
item_type,
);
}
if segment_idx == 0 {
Expand Down Expand Up @@ -1547,6 +1576,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
};
(label, None)
},
"module",
);
}

Expand Down Expand Up @@ -1651,6 +1681,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
);
(label, None)
},
"module",
);
}
}
Expand Down Expand Up @@ -1685,6 +1716,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
ident,
)
},
match opt_ns {
Some(ValueNS) if path.len() == 1 => "item or value",
Some(ns) if path.len() - 1 == segment_idx => ns.descr(),
Some(_) | None => "item",
},
);
}
}
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_resolve/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -920,16 +920,18 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
suggestion,
module,
error_implied_by_parse_error: _,
item_type,
} => {
if no_ambiguity {
assert!(import.imported_module.get().is_none());
self.report_error(
span,
ResolutionError::FailedToResolve {
segment: Some(segment_name),
segment: segment_name,
label,
suggestion,
module,
item_type,
},
);
}
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4696,14 +4696,16 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
module,
segment_name,
error_implied_by_parse_error: _,
item_type,
} => {
return Err(respan(
span,
ResolutionError::FailedToResolve {
segment: Some(segment_name),
segment: segment_name,
label,
suggestion,
module,
item_type,
},
));
}
Expand Down
8 changes: 6 additions & 2 deletions compiler/rustc_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,11 @@ enum ResolutionError<'ra> {
SelfImportOnlyInImportListWithNonEmptyPrefix,
/// Error E0433: failed to resolve.
FailedToResolve {
segment: Option<Symbol>,
segment: Symbol,
label: String,
suggestion: Option<Suggestion>,
module: Option<ModuleOrUniformRoot<'ra>>,
item_type: &'static str,
},
/// Error E0434: can't capture dynamic environment in a fn item.
CannotCaptureDynamicEnvironmentInFnItem,
Expand Down Expand Up @@ -315,7 +316,7 @@ enum ResolutionError<'ra> {
enum VisResolutionError<'a> {
Relative2018(Span, &'a ast::Path),
AncestorOnly(Span),
FailedToResolve(Span, String, Option<Suggestion>),
FailedToResolve(Span, Symbol, String, Option<Suggestion>, &'static str),
ExpectedFound(Span, String, Res),
Indeterminate(Span),
ModuleOnly(Span),
Expand Down Expand Up @@ -458,6 +459,7 @@ enum PathResult<'ra> {
/// The segment name of target
segment_name: Symbol,
error_implied_by_parse_error: bool,
item_type: &'static str,
},
}

Expand All @@ -469,6 +471,7 @@ impl<'ra> PathResult<'ra> {
error_implied_by_parse_error: bool,
module: Option<ModuleOrUniformRoot<'ra>>,
label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
item_type: &'static str,
) -> PathResult<'ra> {
let (label, suggestion) =
if finalize { label_and_suggestion() } else { (String::new(), None) };
Expand All @@ -480,6 +483,7 @@ impl<'ra> PathResult<'ra> {
is_error_from_last_segment,
module,
error_implied_by_parse_error,
item_type,
}
}
}
Expand Down
67 changes: 35 additions & 32 deletions compiler/rustc_resolve/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,47 +856,50 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
),
path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
let mut suggestion = None;
let (span, label, module, segment) =
if let PathResult::Failed { span, label, module, segment_name, .. } =
path_res
let (span, label, module, segment, item_type) = if let PathResult::Failed {
span,
label,
module,
segment_name,
item_type,
..
} = path_res
{
// try to suggest if it's not a macro, maybe a function
if let PathResult::NonModule(partial_res) =
self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
&& partial_res.unresolved_segments() == 0
{
// try to suggest if it's not a macro, maybe a function
if let PathResult::NonModule(partial_res) =
self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope, None)
&& partial_res.unresolved_segments() == 0
{
let sm = self.tcx.sess.source_map();
let exclamation_span = sm.next_point(span);
suggestion = Some((
vec![(exclamation_span, "".to_string())],
format!(
"{} is not a macro, but a {}, try to remove `!`",
Segment::names_to_string(&path),
partial_res.base_res().descr()
),
Applicability::MaybeIncorrect,
));
}
(span, label, module, segment_name)
} else {
(
path_span,
let sm = self.tcx.sess.source_map();
let exclamation_span = sm.next_point(span);
suggestion = Some((
vec![(exclamation_span, "".to_string())],
format!(
"partially resolved path in {} {}",
kind.article(),
kind.descr()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could give a more precise description, like "attribute macro" or "derive macro".

"{} is not a macro, but a {}, try to remove `!`",
Segment::names_to_string(&path),
partial_res.base_res().descr()
),
None,
path.last().map(|segment| segment.ident.name).unwrap(),
)
};
Applicability::MaybeIncorrect,
));
}
(span, label, module, segment_name, item_type)
} else {
(
path_span,
"partially resolved path in a macro".to_string(),
None,
path.last().map(|segment| segment.ident.name).unwrap(),
"macro",
)
};
self.report_error(
span,
ResolutionError::FailedToResolve {
segment: Some(segment),
segment,
label,
suggestion,
module,
item_type,
},
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0433]: failed to resolve: `Self` is only available in impls, traits, and type definitions
error[E0433]: cannot find item `Self` in this scope
--> tests/ui/crashes/unreachable-array-or-slice.rs:4:9
|
LL | let Self::anything_here_kills_it(a, b, ..) = Foo(5, 5, 5, 5);
Expand Down
2 changes: 1 addition & 1 deletion tests/rustdoc-ui/intra-doc/unresolved-import-recovery.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Regression test for issue #95879.

use unresolved_crate::module::Name; //~ ERROR failed to resolve
use unresolved_crate::module::Name; //~ ERROR cannot find item

/// [Name]
pub struct S;
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0433]: failed to resolve: use of unresolved module or unlinked crate `unresolved_crate`
error[E0433]: cannot find item `unresolved_crate` in the crate root
--> $DIR/unresolved-import-recovery.rs:3:5
|
LL | use unresolved_crate::module::Name;
Expand Down
2 changes: 1 addition & 1 deletion tests/rustdoc-ui/issues/issue-61732.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// This previously triggered an ICE.

pub(in crate::r#mod) fn main() {}
//~^ ERROR failed to resolve: use of unresolved module or unlinked crate `r#mod`
//~^ ERROR cannot find item `mod`
2 changes: 1 addition & 1 deletion tests/rustdoc-ui/issues/issue-61732.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0433]: failed to resolve: use of unresolved module or unlinked crate `r#mod`
error[E0433]: cannot find item `mod` in this scope
--> $DIR/issue-61732.rs:3:15
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
error[E0433]: cannot find item `mod` in this scope
error[E0433]: cannot find item `mod` in the crate root

r#mod in crate::r#mod is not resolved in the current scope.

|
LL | pub(in crate::r#mod) fn main() {}
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/asm/naked-invalid-attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn main() {
// Check that the path of an attribute without a name is printed correctly (issue #140082)
#[::a]
//~^ ERROR attribute incompatible with `#[unsafe(naked)]`
//~| ERROR failed to resolve: use of unresolved module or unlinked crate `a`
//~| ERROR cannot find macro `a` in the crate root
#[unsafe(naked)]
extern "C" fn issue_140082() {
naked_asm!("")
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/asm/naked-invalid-attr.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0433]: failed to resolve: use of unresolved module or unlinked crate `a`
error[E0433]: cannot find macro `a` in the crate root
--> $DIR/naked-invalid-attr.rs:56:5
|
LL | #[::a]
Expand Down
Loading
Loading