1
Fork 0

Rollup merge of #97812 - TaKO8Ki:suggest-to-swap-struct-and-trait, r=estebank

Suggest to swap a struct and a trait in trait impls

closes #89590
This commit is contained in:
Dylan DPC 2022-06-11 07:42:14 +02:00 committed by GitHub
commit 640019ba6e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 185 additions and 2 deletions

View file

@ -146,6 +146,8 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
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.
struct BaseError<'a> {
msg: String,
@ -250,6 +252,8 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
let mut err =
self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
if let Some(sugg) = base_error.suggestion {
err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
}
@ -692,6 +696,35 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
}
}
fn suggest_swapping_misplaced_self_ty_and_trait(
&mut self,
err: &mut Diagnostic,
source: PathSource<'_>,
res: Option<Res>,
span: Span,
) {
if let Some((trait_ref, self_ty)) =
self.diagnostic_metadata.currently_processing_impl_trait.clone()
&& let TyKind::Path(_, self_ty_path) = &self_ty.kind
&& let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None)
&& let ModuleKind::Def(DefKind::Trait, ..) = module.kind
&& trait_ref.path.span == span
&& let PathSource::Trait(_) = source
&& let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
&& let Ok(self_ty_str) =
self.r.session.source_map().span_to_snippet(self_ty.span)
&& let Ok(trait_ref_str) =
self.r.session.source_map().span_to_snippet(trait_ref.path.span)
{
err.multipart_suggestion(
"`impl` items mention the trait being implemented first and the type it is being implemented for second",
vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
Applicability::MaybeIncorrect,
);
}
}
fn get_single_associated_item(
&mut self,
path: &[Segment],