diff --git a/compiler/rustc_error_messages/locales/en-US/hir_analysis.ftl b/compiler/rustc_error_messages/locales/en-US/hir_analysis.ftl index 855866be627..62f004da0ca 100644 --- a/compiler/rustc_error_messages/locales/en-US/hir_analysis.ftl +++ b/compiler/rustc_error_messages/locales/en-US/hir_analysis.ftl @@ -147,6 +147,6 @@ hir_analysis_const_impl_for_non_const_trait = hir_analysis_const_bound_for_non_const_trait = ~const can only be applied to `#[const_trait]` traits -hir_analysis_self_in_impl_self = +hir_analysis_self_in_impl_self = `Self` is not valid in the self type of an impl block - .note = replace `Self` with a different type \ No newline at end of file + .note = replace `Self` with a different type diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index bc149e48d89..9a9e40a3f43 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2418,6 +2418,30 @@ impl<'hir> Ty<'hir> { } final_ty } + + pub fn find_self_aliases(&self) -> Vec { + use crate::intravisit::Visitor; + struct MyVisitor(Vec); + impl<'v> Visitor<'v> for MyVisitor { + fn visit_ty(&mut self, t: &'v Ty<'v>) { + if matches!( + &t.kind, + TyKind::Path(QPath::Resolved( + _, + Path { res: crate::def::Res::SelfTyAlias { .. }, .. }, + )) + ) { + self.0.push(t.span); + return; + } + crate::intravisit::walk_ty(self, t); + } + } + + let mut my_visitor = MyVisitor(vec![]); + my_visitor.visit_ty(self); + my_visitor.0 + } } /// Not represented directly in the AST; referred to by name through a `ty_path`. diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 2032a4bce60..20903a68d6d 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -319,36 +319,11 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { } } ItemKind::TyAlias(self_ty, _) => icx.to_ty(self_ty), - ItemKind::Impl( - hir::Impl { self_ty, .. } - ) => { - struct MyVisitor(Vec); - impl<'v> hir::intravisit::Visitor<'v> for MyVisitor { - fn visit_ty(&mut self, t: &'v Ty<'v>) { - if matches!( - &t.kind, - TyKind::Path(hir::QPath::Resolved( - _, - Path { - res: hir::def::Res::SelfTyAlias { .. }, - .. - }, - )) - ) { - self.0.push(t.span); - return; - } - hir::intravisit::walk_ty(self, t); - } - } - - let mut my_visitor = MyVisitor(vec![]); - my_visitor.visit_ty(self_ty); - - match my_visitor.0 { - spans if spans.len() > 0 => { + ItemKind::Impl(hir::Impl { self_ty, .. }) => { + match self_ty.find_self_aliases() { + spans if spans.len() > 0 => { tcx.sess.emit_err(crate::errors::SelfInImplSelf { span: spans.into(), note: (), }); - tcx.ty_error() + tcx.ty_error() }, _ => icx.to_ty(*self_ty), }