Rollup merge of #102085 - chenyukang:code-refactor, r=cjgillot
Code refactoring smart_resolve_report_errors
`smart_resolve_report_errors` 4ecfdfac51/compiler/rustc_resolve/src/late/diagnostics.rs (L143)
is almost 600 lines of code, we should do some code refactoring.
This commit is contained in:
commit
852a152206
1 changed files with 372 additions and 253 deletions
|
@ -130,6 +130,16 @@ pub(super) enum LifetimeElisionCandidate {
|
||||||
Missing(MissingLifetime),
|
Missing(MissingLifetime),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Only used for diagnostics.
|
||||||
|
struct BaseError {
|
||||||
|
msg: String,
|
||||||
|
fallback_label: String,
|
||||||
|
span: Span,
|
||||||
|
span_label: Option<(Span, &'static str)>,
|
||||||
|
could_be_expr: bool,
|
||||||
|
suggestion: Option<(Span, &'static str, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
fn def_span(&self, def_id: DefId) -> Option<Span> {
|
fn def_span(&self, def_id: DefId) -> Option<Span> {
|
||||||
match def_id.krate {
|
match def_id.krate {
|
||||||
|
@ -138,35 +148,18 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles error reporting for `smart_resolve_path_fragment` function.
|
fn make_base_error(
|
||||||
/// Creates base error and amends it with one short label and possibly some longer helps/notes.
|
|
||||||
pub(crate) fn smart_resolve_report_errors(
|
|
||||||
&mut self,
|
&mut self,
|
||||||
path: &[Segment],
|
path: &[Segment],
|
||||||
span: Span,
|
span: Span,
|
||||||
source: PathSource<'_>,
|
source: PathSource<'_>,
|
||||||
res: Option<Res>,
|
res: Option<Res>,
|
||||||
) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
|
) -> BaseError {
|
||||||
let ident_span = path.last().map_or(span, |ident| ident.ident.span);
|
|
||||||
let ns = source.namespace();
|
|
||||||
let is_expected = &|res| source.is_expected(res);
|
|
||||||
let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
|
|
||||||
|
|
||||||
debug!(?res, ?source);
|
|
||||||
|
|
||||||
// Make the base error.
|
// Make the base error.
|
||||||
struct BaseError<'a> {
|
|
||||||
msg: String,
|
|
||||||
fallback_label: String,
|
|
||||||
span: Span,
|
|
||||||
span_label: Option<(Span, &'a str)>,
|
|
||||||
could_be_expr: bool,
|
|
||||||
suggestion: Option<(Span, &'a str, String)>,
|
|
||||||
}
|
|
||||||
let mut expected = source.descr_expected();
|
let mut expected = source.descr_expected();
|
||||||
let path_str = Segment::names_to_string(path);
|
let path_str = Segment::names_to_string(path);
|
||||||
let item_str = path.last().unwrap().ident;
|
let item_str = path.last().unwrap().ident;
|
||||||
let base_error = if let Some(res) = res {
|
if let Some(res) = res {
|
||||||
BaseError {
|
BaseError {
|
||||||
msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
|
msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
|
||||||
fallback_label: format!("not a {expected}"),
|
fallback_label: format!("not a {expected}"),
|
||||||
|
@ -277,8 +270,20 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
could_be_expr: false,
|
could_be_expr: false,
|
||||||
suggestion,
|
suggestion,
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles error reporting for `smart_resolve_path_fragment` function.
|
||||||
|
/// Creates base error and amends it with one short label and possibly some longer helps/notes.
|
||||||
|
pub(crate) fn smart_resolve_report_errors(
|
||||||
|
&mut self,
|
||||||
|
path: &[Segment],
|
||||||
|
span: Span,
|
||||||
|
source: PathSource<'_>,
|
||||||
|
res: Option<Res>,
|
||||||
|
) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) {
|
||||||
|
debug!(?res, ?source);
|
||||||
|
let base_error = self.make_base_error(path, span, source, res);
|
||||||
let code = source.error_code(res.is_some());
|
let code = source.error_code(res.is_some());
|
||||||
let mut err =
|
let mut err =
|
||||||
self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
|
self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
|
||||||
|
@ -289,41 +294,79 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
err.span_label(span, label);
|
err.span_label(span, label);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(sugg) = base_error.suggestion {
|
if let Some(ref sugg) = base_error.suggestion {
|
||||||
err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
|
err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
|
self.suggest_bare_struct_literal(&mut err);
|
||||||
err.multipart_suggestion(
|
self.suggest_pattern_match_with_let(&mut err, source, span);
|
||||||
"you might have meant to write a `struct` literal",
|
|
||||||
vec![
|
self.suggest_self_or_self_ref(&mut err, path, span);
|
||||||
(span.shrink_to_lo(), "{ SomeStruct ".to_string()),
|
self.detect_assoct_type_constraint_meant_as_path(&mut err, &base_error);
|
||||||
(span.shrink_to_hi(), "}".to_string()),
|
if self.suggest_self_ty(&mut err, source, path, span)
|
||||||
],
|
|| self.suggest_self_value(&mut err, source, path, span)
|
||||||
Applicability::HasPlaceholders,
|
{
|
||||||
);
|
return (err, Vec::new());
|
||||||
}
|
}
|
||||||
match (source, self.diagnostic_metadata.in_if_condition) {
|
|
||||||
(
|
let (found, candidates) =
|
||||||
PathSource::Expr(_),
|
self.try_lookup_name_relaxed(&mut err, source, path, span, res, &base_error);
|
||||||
Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }),
|
if found {
|
||||||
) => {
|
return (err, candidates);
|
||||||
// Icky heuristic so we don't suggest:
|
}
|
||||||
// `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
|
|
||||||
// `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
|
if !self.type_ascription_suggestion(&mut err, base_error.span) {
|
||||||
if lhs.is_approximately_pattern() && lhs.span.contains(span) {
|
let mut fallback =
|
||||||
err.span_suggestion_verbose(
|
self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
|
||||||
expr_span.shrink_to_lo(),
|
fallback |= self.suggest_typo(&mut err, source, path, span, &base_error);
|
||||||
"you might have meant to use pattern matching",
|
if fallback {
|
||||||
"let ",
|
// Fallback label.
|
||||||
Applicability::MaybeIncorrect,
|
err.span_label(base_error.span, &base_error.fallback_label);
|
||||||
);
|
}
|
||||||
|
}
|
||||||
|
self.err_code_special_cases(&mut err, source, path, span);
|
||||||
|
|
||||||
|
(err, candidates)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detect_assoct_type_constraint_meant_as_path(
|
||||||
|
&self,
|
||||||
|
err: &mut Diagnostic,
|
||||||
|
base_error: &BaseError,
|
||||||
|
) {
|
||||||
|
let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
|
||||||
|
let TyKind::Path(_, path) = &ty.kind else { return; };
|
||||||
|
for segment in &path.segments {
|
||||||
|
let Some(params) = &segment.args else { continue; };
|
||||||
|
let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
|
||||||
|
for param in ¶ms.args {
|
||||||
|
let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
|
||||||
|
let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for bound in bounds {
|
||||||
|
let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
|
||||||
|
= bound else
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if base_error.span == trait_ref.span {
|
||||||
|
err.span_suggestion_verbose(
|
||||||
|
constraint.ident.span.between(trait_ref.span),
|
||||||
|
"you might have meant to write a path instead of an associated type bound",
|
||||||
|
"::",
|
||||||
|
Applicability::MachineApplicable,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suggest_self_or_self_ref(&mut self, err: &mut Diagnostic, path: &[Segment], span: Span) {
|
||||||
let is_assoc_fn = self.self_type_is_available();
|
let is_assoc_fn = self.self_type_is_available();
|
||||||
|
let Some(path_last_segment) = path.last() else { return };
|
||||||
|
let item_str = path_last_segment.ident;
|
||||||
// Emit help message for fake-self from other languages (e.g., `this` in Javascript).
|
// Emit help message for fake-self from other languages (e.g., `this` in Javascript).
|
||||||
if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
|
if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn {
|
||||||
err.span_suggestion_short(
|
err.span_suggestion_short(
|
||||||
|
@ -358,96 +401,25 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
|
fn try_lookup_name_relaxed(
|
||||||
|
&mut self,
|
||||||
// Emit special messages for unresolved `Self` and `self`.
|
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
|
||||||
if is_self_type(path, ns) {
|
source: PathSource<'_>,
|
||||||
err.code(rustc_errors::error_code!(E0411));
|
path: &[Segment],
|
||||||
err.span_label(
|
span: Span,
|
||||||
span,
|
res: Option<Res>,
|
||||||
"`Self` is only available in impls, traits, and type definitions".to_string(),
|
base_error: &BaseError,
|
||||||
);
|
) -> (bool, Vec<ImportSuggestion>) {
|
||||||
if let Some(item_kind) = self.diagnostic_metadata.current_item {
|
|
||||||
err.span_label(
|
|
||||||
item_kind.ident.span,
|
|
||||||
format!(
|
|
||||||
"`Self` not allowed in {} {}",
|
|
||||||
item_kind.kind.article(),
|
|
||||||
item_kind.kind.descr()
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (err, Vec::new());
|
|
||||||
}
|
|
||||||
if is_self_value(path, ns) {
|
|
||||||
debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
|
|
||||||
|
|
||||||
err.code(rustc_errors::error_code!(E0424));
|
|
||||||
err.span_label(span, match source {
|
|
||||||
PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed",
|
|
||||||
_ => "`self` value is a keyword only available in methods with a `self` parameter",
|
|
||||||
});
|
|
||||||
if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
|
|
||||||
// The current function has a `self' parameter, but we were unable to resolve
|
|
||||||
// a reference to `self`. This can only happen if the `self` identifier we
|
|
||||||
// are resolving came from a different hygiene context.
|
|
||||||
if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
|
|
||||||
err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
|
|
||||||
} else {
|
|
||||||
let doesnt = if is_assoc_fn {
|
|
||||||
let (span, sugg) = fn_kind
|
|
||||||
.decl()
|
|
||||||
.inputs
|
|
||||||
.get(0)
|
|
||||||
.map(|p| (p.span.shrink_to_lo(), "&self, "))
|
|
||||||
.unwrap_or_else(|| {
|
|
||||||
// Try to look for the "(" after the function name, if possible.
|
|
||||||
// This avoids placing the suggestion into the visibility specifier.
|
|
||||||
let span = fn_kind
|
|
||||||
.ident()
|
|
||||||
.map_or(*span, |ident| span.with_lo(ident.span.hi()));
|
|
||||||
(
|
|
||||||
self.r
|
|
||||||
.session
|
|
||||||
.source_map()
|
|
||||||
.span_through_char(span, '(')
|
|
||||||
.shrink_to_hi(),
|
|
||||||
"&self",
|
|
||||||
)
|
|
||||||
});
|
|
||||||
err.span_suggestion_verbose(
|
|
||||||
span,
|
|
||||||
"add a `self` receiver parameter to make the associated `fn` a method",
|
|
||||||
sugg,
|
|
||||||
Applicability::MaybeIncorrect,
|
|
||||||
);
|
|
||||||
"doesn't"
|
|
||||||
} else {
|
|
||||||
"can't"
|
|
||||||
};
|
|
||||||
if let Some(ident) = fn_kind.ident() {
|
|
||||||
err.span_label(
|
|
||||||
ident.span,
|
|
||||||
&format!("this function {} have a `self` parameter", doesnt),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if let Some(item_kind) = self.diagnostic_metadata.current_item {
|
|
||||||
err.span_label(
|
|
||||||
item_kind.ident.span,
|
|
||||||
format!(
|
|
||||||
"`self` not allowed in {} {}",
|
|
||||||
item_kind.kind.article(),
|
|
||||||
item_kind.kind.descr()
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (err, Vec::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to lookup name in more relaxed fashion for better error reporting.
|
// Try to lookup name in more relaxed fashion for better error reporting.
|
||||||
let ident = path.last().unwrap().ident;
|
let ident = path.last().unwrap().ident;
|
||||||
|
let is_expected = &|res| source.is_expected(res);
|
||||||
|
let ns = source.namespace();
|
||||||
|
let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
|
||||||
|
let path_str = Segment::names_to_string(path);
|
||||||
|
let ident_span = path.last().map_or(span, |ident| ident.ident.span);
|
||||||
|
|
||||||
let mut candidates = self
|
let mut candidates = self
|
||||||
.r
|
.r
|
||||||
.lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
|
.lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
|
||||||
|
@ -494,7 +466,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
{
|
{
|
||||||
// Already reported this issue on the lhs of the type ascription.
|
// Already reported this issue on the lhs of the type ascription.
|
||||||
err.delay_as_bug();
|
err.delay_as_bug();
|
||||||
return (err, candidates);
|
return (true, candidates);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -522,8 +494,9 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try Levenshtein algorithm.
|
// Try Levenshtein algorithm.
|
||||||
let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected);
|
let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
|
||||||
if path.len() == 1 && self.self_type_is_available() {
|
if path.len() == 1 && self.self_type_is_available() {
|
||||||
if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
|
if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
|
||||||
let self_is_available = self.self_value_is_available(path[0].ident.span);
|
let self_is_available = self.self_value_is_available(path[0].ident.span);
|
||||||
|
@ -560,8 +533,8 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
|
self.r.add_typo_suggestion(err, typo_sugg, ident_span);
|
||||||
return (err, candidates);
|
return (true, candidates);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If the first argument in call is `self` suggest calling a method.
|
// If the first argument in call is `self` suggest calling a method.
|
||||||
|
@ -579,14 +552,14 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
format!("self.{path_str}({args_snippet})"),
|
format!("self.{path_str}({args_snippet})"),
|
||||||
Applicability::MachineApplicable,
|
Applicability::MachineApplicable,
|
||||||
);
|
);
|
||||||
return (err, candidates);
|
return (true, candidates);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try context-dependent help if relaxed lookup didn't work.
|
// Try context-dependent help if relaxed lookup didn't work.
|
||||||
if let Some(res) = res {
|
if let Some(res) = res {
|
||||||
if self.smart_resolve_context_dependent_help(
|
if self.smart_resolve_context_dependent_help(
|
||||||
&mut err,
|
err,
|
||||||
span,
|
span,
|
||||||
source,
|
source,
|
||||||
res,
|
res,
|
||||||
|
@ -594,106 +567,135 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
&base_error.fallback_label,
|
&base_error.fallback_label,
|
||||||
) {
|
) {
|
||||||
// We do this to avoid losing a secondary span when we override the main error span.
|
// We do this to avoid losing a secondary span when we override the main error span.
|
||||||
self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
|
self.r.add_typo_suggestion(err, typo_sugg, ident_span);
|
||||||
return (err, candidates);
|
return (true, candidates);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return (false, candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suggest_trait_and_bounds(
|
||||||
|
&mut self,
|
||||||
|
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
|
||||||
|
source: PathSource<'_>,
|
||||||
|
res: Option<Res>,
|
||||||
|
span: Span,
|
||||||
|
base_error: &BaseError,
|
||||||
|
) -> bool {
|
||||||
let is_macro =
|
let is_macro =
|
||||||
base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
|
base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
|
||||||
if !self.type_ascription_suggestion(&mut err, base_error.span) {
|
let mut fallback = false;
|
||||||
let mut fallback = false;
|
|
||||||
if let (
|
|
||||||
PathSource::Trait(AliasPossibility::Maybe),
|
|
||||||
Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
|
|
||||||
false,
|
|
||||||
) = (source, res, is_macro)
|
|
||||||
{
|
|
||||||
if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
|
|
||||||
fallback = true;
|
|
||||||
let spans: Vec<Span> = bounds
|
|
||||||
.iter()
|
|
||||||
.map(|bound| bound.span())
|
|
||||||
.filter(|&sp| sp != base_error.span)
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let start_span = bounds[0].span();
|
if let (
|
||||||
// `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
|
PathSource::Trait(AliasPossibility::Maybe),
|
||||||
let end_span = bounds.last().unwrap().span();
|
Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
|
||||||
// `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
|
false,
|
||||||
let last_bound_span = spans.last().cloned().unwrap();
|
) = (source, res, is_macro)
|
||||||
let mut multi_span: MultiSpan = spans.clone().into();
|
{
|
||||||
for sp in spans {
|
if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object {
|
||||||
let msg = if sp == last_bound_span {
|
|
||||||
format!(
|
|
||||||
"...because of {these} bound{s}",
|
|
||||||
these = pluralize!("this", bounds.len() - 1),
|
|
||||||
s = pluralize!(bounds.len() - 1),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
};
|
|
||||||
multi_span.push_span_label(sp, msg);
|
|
||||||
}
|
|
||||||
multi_span
|
|
||||||
.push_span_label(base_error.span, "expected this type to be a trait...");
|
|
||||||
err.span_help(
|
|
||||||
multi_span,
|
|
||||||
"`+` is used to constrain a \"trait object\" type with lifetimes or \
|
|
||||||
auto-traits; structs and enums can't be bound in that way",
|
|
||||||
);
|
|
||||||
if bounds.iter().all(|bound| match bound {
|
|
||||||
ast::GenericBound::Outlives(_) => true,
|
|
||||||
ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
|
|
||||||
}) {
|
|
||||||
let mut sugg = vec![];
|
|
||||||
if base_error.span != start_span {
|
|
||||||
sugg.push((start_span.until(base_error.span), String::new()));
|
|
||||||
}
|
|
||||||
if base_error.span != end_span {
|
|
||||||
sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
|
|
||||||
}
|
|
||||||
|
|
||||||
err.multipart_suggestion(
|
|
||||||
"if you meant to use a type and not a trait here, remove the bounds",
|
|
||||||
sugg,
|
|
||||||
Applicability::MaybeIncorrect,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err);
|
|
||||||
|
|
||||||
if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) {
|
|
||||||
fallback = true;
|
fallback = true;
|
||||||
match self.diagnostic_metadata.current_let_binding {
|
let spans: Vec<Span> = bounds
|
||||||
Some((pat_sp, Some(ty_sp), None))
|
.iter()
|
||||||
if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
|
.map(|bound| bound.span())
|
||||||
{
|
.filter(|&sp| sp != base_error.span)
|
||||||
err.span_suggestion_short(
|
.collect();
|
||||||
pat_sp.between(ty_sp),
|
|
||||||
"use `=` if you meant to assign",
|
|
||||||
" = ",
|
|
||||||
Applicability::MaybeIncorrect,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the trait has a single item (which wasn't matched by Levenshtein), suggest it
|
let start_span = bounds[0].span();
|
||||||
let suggestion = self.get_single_associated_item(&path, &source, is_expected);
|
// `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><)
|
||||||
self.r.add_typo_suggestion(&mut err, suggestion, ident_span);
|
let end_span = bounds.last().unwrap().span();
|
||||||
}
|
// `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar)
|
||||||
if fallback {
|
let last_bound_span = spans.last().cloned().unwrap();
|
||||||
// Fallback label.
|
let mut multi_span: MultiSpan = spans.clone().into();
|
||||||
err.span_label(base_error.span, base_error.fallback_label);
|
for sp in spans {
|
||||||
|
let msg = if sp == last_bound_span {
|
||||||
|
format!(
|
||||||
|
"...because of {these} bound{s}",
|
||||||
|
these = pluralize!("this", bounds.len() - 1),
|
||||||
|
s = pluralize!(bounds.len() - 1),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
multi_span.push_span_label(sp, msg);
|
||||||
|
}
|
||||||
|
multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
|
||||||
|
err.span_help(
|
||||||
|
multi_span,
|
||||||
|
"`+` is used to constrain a \"trait object\" type with lifetimes or \
|
||||||
|
auto-traits; structs and enums can't be bound in that way",
|
||||||
|
);
|
||||||
|
if bounds.iter().all(|bound| match bound {
|
||||||
|
ast::GenericBound::Outlives(_) => true,
|
||||||
|
ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
|
||||||
|
}) {
|
||||||
|
let mut sugg = vec![];
|
||||||
|
if base_error.span != start_span {
|
||||||
|
sugg.push((start_span.until(base_error.span), String::new()));
|
||||||
|
}
|
||||||
|
if base_error.span != end_span {
|
||||||
|
sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
|
||||||
|
}
|
||||||
|
|
||||||
|
err.multipart_suggestion(
|
||||||
|
"if you meant to use a type and not a trait here, remove the bounds",
|
||||||
|
sugg,
|
||||||
|
Applicability::MaybeIncorrect,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fallback |= self.restrict_assoc_type_in_where_clause(span, err);
|
||||||
|
fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suggest_typo(
|
||||||
|
&mut self,
|
||||||
|
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
|
||||||
|
source: PathSource<'_>,
|
||||||
|
path: &[Segment],
|
||||||
|
span: Span,
|
||||||
|
base_error: &BaseError,
|
||||||
|
) -> bool {
|
||||||
|
let is_expected = &|res| source.is_expected(res);
|
||||||
|
let ident_span = path.last().map_or(span, |ident| ident.ident.span);
|
||||||
|
let typo_sugg = self.lookup_typo_candidate(path, source.namespace(), is_expected);
|
||||||
|
let mut fallback = false;
|
||||||
|
if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
|
||||||
|
fallback = true;
|
||||||
|
match self.diagnostic_metadata.current_let_binding {
|
||||||
|
Some((pat_sp, Some(ty_sp), None))
|
||||||
|
if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
|
||||||
|
{
|
||||||
|
err.span_suggestion_short(
|
||||||
|
pat_sp.between(ty_sp),
|
||||||
|
"use `=` if you meant to assign",
|
||||||
|
" = ",
|
||||||
|
Applicability::MaybeIncorrect,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the trait has a single item (which wasn't matched by Levenshtein), suggest it
|
||||||
|
let suggestion = self.get_single_associated_item(&path, &source, is_expected);
|
||||||
|
self.r.add_typo_suggestion(err, suggestion, ident_span);
|
||||||
|
}
|
||||||
|
fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
fn err_code_special_cases(
|
||||||
|
&mut self,
|
||||||
|
err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>,
|
||||||
|
source: PathSource<'_>,
|
||||||
|
path: &[Segment],
|
||||||
|
span: Span,
|
||||||
|
) {
|
||||||
if let Some(err_code) = &err.code {
|
if let Some(err_code) = &err.code {
|
||||||
if err_code == &rustc_errors::error_code!(E0425) {
|
if err_code == &rustc_errors::error_code!(E0425) {
|
||||||
for label_rib in &self.label_ribs {
|
for label_rib in &self.label_ribs {
|
||||||
for (label_ident, node_id) in &label_rib.bindings {
|
for (label_ident, node_id) in &label_rib.bindings {
|
||||||
|
let ident = path.last().unwrap().ident;
|
||||||
if format!("'{}", ident) == label_ident.to_string() {
|
if format!("'{}", ident) == label_ident.to_string() {
|
||||||
err.span_label(label_ident.span, "a label with a similar name exists");
|
err.span_label(label_ident.span, "a label with a similar name exists");
|
||||||
if let PathSource::Expr(Some(Expr {
|
if let PathSource::Expr(Some(Expr {
|
||||||
|
@ -724,38 +726,116 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
(err, candidates)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) {
|
/// Emit special messages for unresolved `Self` and `self`.
|
||||||
let Some(ty) = self.diagnostic_metadata.current_type_path else { return; };
|
fn suggest_self_ty(
|
||||||
let TyKind::Path(_, path) = &ty.kind else { return; };
|
&mut self,
|
||||||
for segment in &path.segments {
|
err: &mut Diagnostic,
|
||||||
let Some(params) = &segment.args else { continue; };
|
source: PathSource<'_>,
|
||||||
let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; };
|
path: &[Segment],
|
||||||
for param in ¶ms.args {
|
span: Span,
|
||||||
let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; };
|
) -> bool {
|
||||||
let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else {
|
if !is_self_type(path, source.namespace()) {
|
||||||
continue;
|
return false;
|
||||||
|
}
|
||||||
|
err.code(rustc_errors::error_code!(E0411));
|
||||||
|
err.span_label(
|
||||||
|
span,
|
||||||
|
"`Self` is only available in impls, traits, and type definitions".to_string(),
|
||||||
|
);
|
||||||
|
if let Some(item_kind) = self.diagnostic_metadata.current_item {
|
||||||
|
err.span_label(
|
||||||
|
item_kind.ident.span,
|
||||||
|
format!(
|
||||||
|
"`Self` not allowed in {} {}",
|
||||||
|
item_kind.kind.article(),
|
||||||
|
item_kind.kind.descr()
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suggest_self_value(
|
||||||
|
&mut self,
|
||||||
|
err: &mut Diagnostic,
|
||||||
|
source: PathSource<'_>,
|
||||||
|
path: &[Segment],
|
||||||
|
span: Span,
|
||||||
|
) -> bool {
|
||||||
|
if !is_self_value(path, source.namespace()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
|
||||||
|
err.code(rustc_errors::error_code!(E0424));
|
||||||
|
err.span_label(
|
||||||
|
span,
|
||||||
|
match source {
|
||||||
|
PathSource::Pat => {
|
||||||
|
"`self` value is a keyword and may not be bound to variables or shadowed"
|
||||||
|
}
|
||||||
|
_ => "`self` value is a keyword only available in methods with a `self` parameter",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let is_assoc_fn = self.self_type_is_available();
|
||||||
|
if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function {
|
||||||
|
// The current function has a `self' parameter, but we were unable to resolve
|
||||||
|
// a reference to `self`. This can only happen if the `self` identifier we
|
||||||
|
// are resolving came from a different hygiene context.
|
||||||
|
if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) {
|
||||||
|
err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters");
|
||||||
|
} else {
|
||||||
|
let doesnt = if is_assoc_fn {
|
||||||
|
let (span, sugg) = fn_kind
|
||||||
|
.decl()
|
||||||
|
.inputs
|
||||||
|
.get(0)
|
||||||
|
.map(|p| (p.span.shrink_to_lo(), "&self, "))
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
// Try to look for the "(" after the function name, if possible.
|
||||||
|
// This avoids placing the suggestion into the visibility specifier.
|
||||||
|
let span = fn_kind
|
||||||
|
.ident()
|
||||||
|
.map_or(*span, |ident| span.with_lo(ident.span.hi()));
|
||||||
|
(
|
||||||
|
self.r
|
||||||
|
.session
|
||||||
|
.source_map()
|
||||||
|
.span_through_char(span, '(')
|
||||||
|
.shrink_to_hi(),
|
||||||
|
"&self",
|
||||||
|
)
|
||||||
|
});
|
||||||
|
err.span_suggestion_verbose(
|
||||||
|
span,
|
||||||
|
"add a `self` receiver parameter to make the associated `fn` a method",
|
||||||
|
sugg,
|
||||||
|
Applicability::MaybeIncorrect,
|
||||||
|
);
|
||||||
|
"doesn't"
|
||||||
|
} else {
|
||||||
|
"can't"
|
||||||
};
|
};
|
||||||
for bound in bounds {
|
if let Some(ident) = fn_kind.ident() {
|
||||||
let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)
|
err.span_label(
|
||||||
= bound else
|
ident.span,
|
||||||
{
|
&format!("this function {} have a `self` parameter", doesnt),
|
||||||
continue;
|
);
|
||||||
};
|
|
||||||
if base_span == trait_ref.span {
|
|
||||||
err.span_suggestion_verbose(
|
|
||||||
constraint.ident.span.between(trait_ref.span),
|
|
||||||
"you might have meant to write a path instead of an associated type bound",
|
|
||||||
"::",
|
|
||||||
Applicability::MachineApplicable,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else if let Some(item_kind) = self.diagnostic_metadata.current_item {
|
||||||
|
err.span_label(
|
||||||
|
item_kind.ident.span,
|
||||||
|
format!(
|
||||||
|
"`self` not allowed in {} {}",
|
||||||
|
item_kind.kind.article(),
|
||||||
|
item_kind.kind.descr()
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn suggest_swapping_misplaced_self_ty_and_trait(
|
fn suggest_swapping_misplaced_self_ty_and_trait(
|
||||||
|
@ -787,6 +867,45 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn suggest_bare_struct_literal(&mut self, err: &mut Diagnostic) {
|
||||||
|
if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
|
||||||
|
err.multipart_suggestion(
|
||||||
|
"you might have meant to write a `struct` literal",
|
||||||
|
vec![
|
||||||
|
(span.shrink_to_lo(), "{ SomeStruct ".to_string()),
|
||||||
|
(span.shrink_to_hi(), "}".to_string()),
|
||||||
|
],
|
||||||
|
Applicability::HasPlaceholders,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suggest_pattern_match_with_let(
|
||||||
|
&mut self,
|
||||||
|
err: &mut Diagnostic,
|
||||||
|
source: PathSource<'_>,
|
||||||
|
span: Span,
|
||||||
|
) {
|
||||||
|
if let PathSource::Expr(_) = source &&
|
||||||
|
let Some(Expr {
|
||||||
|
span: expr_span,
|
||||||
|
kind: ExprKind::Assign(lhs, _, _),
|
||||||
|
..
|
||||||
|
}) = self.diagnostic_metadata.in_if_condition {
|
||||||
|
// Icky heuristic so we don't suggest:
|
||||||
|
// `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern)
|
||||||
|
// `if 2 = i` => `if let 2 = i` (lhs needs to contain error span)
|
||||||
|
if lhs.is_approximately_pattern() && lhs.span.contains(span) {
|
||||||
|
err.span_suggestion_verbose(
|
||||||
|
expr_span.shrink_to_lo(),
|
||||||
|
"you might have meant to use pattern matching",
|
||||||
|
"let ",
|
||||||
|
Applicability::MaybeIncorrect,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn get_single_associated_item(
|
fn get_single_associated_item(
|
||||||
&mut self,
|
&mut self,
|
||||||
path: &[Segment],
|
path: &[Segment],
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue