Skip to content
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

Tweak output of resolve errors #126810

Open
wants to merge 9 commits 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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 2 additions & 1 deletion compiler/rustc_lint/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,8 @@ lint_opaque_hidden_inferred_bound_sugg = add this bound
lint_or_patterns_back_compat = the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro
.suggestion = use pat_param to preserve semantics

lint_out_of_scope_macro_calls = cannot find macro `{$path}` in this scope
Copy link
Contributor

Choose a reason for hiding this comment

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

I disagree with this change, "in this scope" is a meaningful and significant part of the message.
We can lookup names in many places, e.g. in a module, or in extern prelude specifically, and here were are saying where we are looking up the name in this case - in the current scope (which happens when we resolve first segments of paths).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@petrochenkov the primary span label retains that context of the message. I feel like it is bad practice in general to have redundant information in the different parts of the error, and we already get too many complains about "too much text in the errors". This was an attempt to walk that line. In the particular case of "in this scope" you and I know what why that is meaningful, but in practice that wording ends up being more text to say something that is generally implied: if it's not on a specific other scope, it's always "this scope". Whenever we do have additional context from "this scope", then it does make sense to mention it ("in trait Trait"). If we were to actually mention the scope ("cannot find macro foo from method bar"), that would change my opinion on the use of this (because then the message can be read in isolation without having to read the code to understand the context).

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree that "in this scope" is pretty general, and replacing it with "from this specific place called foo" when possible would be better, but it's definitely better than nothing because it still says which resolution mode is used.
If it was entirely useless, then it could be dropped from the label messages as well.

(As for the redundancy, I've answered below.)

lint_out_of_scope_macro_calls = cannot find macro `{$path}` in {$scope}
.label = not found in {$scope}
.help = import `macro_rules` with `use` to make it callable above its definition

lint_overflowing_bin_hex = literal out of range for `{$ty}`
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_lint/src/context/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,8 +434,8 @@ pub(super) fn decorate_lint(sess: &Session, diagnostic: BuiltinLintDiag, diag: &
lints::InnerAttributeUnstable::CustomInnerAttribute
}
.decorate_lint(diag),
BuiltinLintDiag::OutOfScopeMacroCalls { path } => {
lints::OutOfScopeMacroCalls { path }.decorate_lint(diag)
BuiltinLintDiag::OutOfScopeMacroCalls { span, path, scope } => {
lints::OutOfScopeMacroCalls { span, path, scope }.decorate_lint(diag)
}
}
}
3 changes: 3 additions & 0 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2917,5 +2917,8 @@ pub struct UnsafeAttrOutsideUnsafeSuggestion {
#[diag(lint_out_of_scope_macro_calls)]
#[help]
pub struct OutOfScopeMacroCalls {
#[label]
pub span: Span,
pub path: String,
pub scope: String,
}
2 changes: 2 additions & 0 deletions compiler/rustc_lint_defs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,9 @@ pub enum BuiltinLintDiag {
is_macro: bool,
},
OutOfScopeMacroCalls {
span: Span,
path: String,
scope: String,
},
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_resolve/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ resolve_cannot_determine_macro_resolution =
resolve_cannot_find_builtin_macro_with_name =
cannot find a built-in macro with name `{$ident}`

resolve_cannot_find_ident_in_this_scope =
cannot find {$expected} `{$ident}` in this scope
resolve_cannot_find_ident_in_this_scope = cannot find {$expected} `{$ident}` in {$scope}
.label = not found in {$scope}

resolve_cannot_glob_import_possible_crates =
cannot glob-import all possible crates
Expand Down
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 @@ -307,9 +307,15 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, '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
55 changes: 45 additions & 10 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -794,9 +794,32 @@ impl<'a, 'tcx> Resolver<'a, '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(_, _, name) if name == kw::Empty => {
"the crate root".to_string()
}
ModuleKind::Def(kind, def_id, 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 @@ -809,7 +832,6 @@ impl<'a, 'tcx> Resolver<'a, '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 @@ -989,10 +1011,18 @@ impl<'a, 'tcx> Resolver<'a, '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 Expand Up @@ -2001,18 +2031,23 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
Applicability::MaybeIncorrect,
)),
)
} else if ident.is_special() {
(format!("`{ident}` is not a valid item name"), None)
} else if ident.name == sym::core {
(
format!("maybe a missing crate `{ident}`?"),
format!("you might be missing a crate named `{ident}`"),
Some((
vec![(ident.span, "std".to_string())],
"try using `std` instead of `core`".to_string(),
Applicability::MaybeIncorrect,
)),
)
} else if ident.is_raw_guess() {
// We're unlikely to have a crate called `r#super`, don't suggest anything.
("unresolved import".to_string(), None)
} else if self.tcx.sess.is_rust_2015() {
(
format!("maybe a missing crate `{ident}`?"),
format!("you might be missing a crate named `{ident}`"),
Some((
vec![],
format!(
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_resolve/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,8 +635,10 @@ pub(crate) struct ImportsCannotReferTo<'a> {
#[diag(resolve_cannot_find_ident_in_this_scope)]
pub(crate) struct CannotFindIdentInThisScope<'a> {
#[primary_span]
#[label]
pub(crate) span: Span,
pub(crate) expected: &'a str,
pub(crate) scope: &'a str,
pub(crate) ident: Ident,
}

Expand Down
96 changes: 67 additions & 29 deletions compiler/rustc_resolve/src/ident.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
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;
use rustc_middle::ty;
Expand Down Expand Up @@ -1463,9 +1463,28 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
continue;
}
}
return PathResult::failed(ident, false, finalize.is_some(), module, || {
("there are too many leading `super` keywords".to_string(), None)
});
let mut item_type = "module";
let mut suggestion = None;
let label = if path.len() == 1
&& let Some(ribs) = ribs
&& let RibKind::Normal = ribs[ValueNS][ribs[ValueNS].len() - 1].kind
{
item_type = "item";
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"
};
Copy link
Contributor

Choose a reason for hiding this comment

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

All this logic should go into the closure, so it's not executed on a good path (finalize.is_none()).

return PathResult::failed(
ident,
false,
finalize.is_some(),
module,
|| (label.to_string(), suggestion),
item_type,
);
}
if segment_idx == 0 {
if name == kw::SelfLower {
Expand Down Expand Up @@ -1497,19 +1516,26 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {

// Report special messages for path segment keywords in wrong positions.
if ident.is_path_segment_keyword() && segment_idx != 0 {
return PathResult::failed(ident, false, finalize.is_some(), module, || {
let name_str = if name == kw::PathRoot {
"crate root".to_string()
} else {
format!("`{name}`")
};
let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot {
format!("global paths cannot start with {name_str}")
} else {
format!("{name_str} in paths can only be used in start position")
};
(label, None)
});
return PathResult::failed(
ident,
false,
finalize.is_some(),
module,
|| {
let name_str = if name == kw::PathRoot {
"crate root".to_string()
} else {
format!("`{name}`")
};
let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot {
format!("global paths cannot start with {name_str}")
} else {
format!("{name_str} in paths can only be used in start position")
};
(label, None)
},
"module",
);
}

let binding = if let Some(module) = module {
Expand Down Expand Up @@ -1605,6 +1631,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
);
(label, None)
},
"module",
);
}
}
Expand All @@ -1619,18 +1646,29 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}
}

return PathResult::failed(ident, is_last, finalize.is_some(), module, || {
self.report_path_resolution_error(
path,
opt_ns,
parent_scope,
ribs,
ignore_binding,
module,
segment_idx,
ident,
)
});
return PathResult::failed(
ident,
is_last,
finalize.is_some(),
module,
|| {
self.report_path_resolution_error(
path,
opt_ns,
parent_scope,
ribs,
ignore_binding,
module,
segment_idx,
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 @@ -900,16 +900,18 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
label,
suggestion,
module,
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 @@ -4274,14 +4274,16 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
suggestion,
module,
segment_name,
item_type,
} => {
return Err(respan(
span,
ResolutionError::FailedToResolve {
segment: Some(segment_name),
segment: segment_name,
label,
suggestion,
module,
item_type,
},
));
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
} else {
suggestion
};
(format!("not found in {mod_str}"), override_suggestion)
(format!("not found in {mod_prefix}{mod_str}"), override_suggestion)
};

BaseError {
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 @@ -228,10 +228,11 @@ enum ResolutionError<'a> {
SelfImportOnlyInImportListWithNonEmptyPrefix,
/// Error E0433: failed to resolve.
FailedToResolve {
segment: Option<Symbol>,
segment: Symbol,
label: String,
suggestion: Option<Suggestion>,
module: Option<ModuleOrUniformRoot<'a>>,
item_type: &'static str,
},
/// Error E0434: can't capture dynamic environment in a fn item.
CannotCaptureDynamicEnvironmentInFnItem,
Expand Down Expand Up @@ -287,7 +288,7 @@ enum ResolutionError<'a> {
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 @@ -429,6 +430,7 @@ enum PathResult<'a> {
module: Option<ModuleOrUniformRoot<'a>>,
/// The segment name of target
segment_name: Symbol,
item_type: &'static str,
},
}

Expand All @@ -439,6 +441,7 @@ impl<'a> PathResult<'a> {
finalize: bool,
module: Option<ModuleOrUniformRoot<'a>>,
label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
item_type: &'static str,
) -> PathResult<'a> {
let (label, suggestion) =
if finalize { label_and_suggestion() } else { (String::new(), None) };
Expand All @@ -449,6 +452,7 @@ impl<'a> PathResult<'a> {
suggestion,
is_error_from_last_segment,
module,
item_type,
}
}
}
Expand Down
Loading
Loading