Skip to content

Commit a219ad6

Browse files
committed
extend is_ty_or_ty_ctxt to self types
1 parent f7d5080 commit a219ad6

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

compiler/rustc_lint/src/internal.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}
55
use rustc_ast::{Item, ItemKind};
66
use rustc_data_structures::fx::FxHashMap;
77
use rustc_errors::Applicability;
8+
use rustc_hir::def::Res;
89
use rustc_hir::{GenericArg, HirId, MutTy, Mutability, Path, PathSegment, QPath, Ty, TyKind};
10+
use rustc_middle::ty;
911
use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
1012
use rustc_span::hygiene::{ExpnKind, MacroKind};
1113
use rustc_span::symbol::{sym, Ident, Symbol};
@@ -177,11 +179,25 @@ fn lint_ty_kind_usage(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> bool {
177179
fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, ty: &Ty<'_>) -> Option<String> {
178180
if let TyKind::Path(qpath) = &ty.kind {
179181
if let QPath::Resolved(_, path) = qpath {
180-
let did = path.res.opt_def_id()?;
181-
if cx.tcx.is_diagnostic_item(sym::Ty, did) {
182-
return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
183-
} else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) {
184-
return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
182+
match path.res {
183+
Res::Def(_, did) => {
184+
if cx.tcx.is_diagnostic_item(sym::Ty, did) {
185+
return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
186+
} else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) {
187+
return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
188+
}
189+
}
190+
// Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
191+
Res::SelfTy(None, Some((did, _))) => {
192+
if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
193+
if cx.tcx.is_diagnostic_item(sym::Ty, adt.did) {
194+
return Some(format!("Ty<{}>", substs[0]));
195+
} else if cx.tcx.is_diagnostic_item(sym::TyCtxt, adt.did) {
196+
return Some(format!("TyCtxt<{}>", substs[0]));
197+
}
198+
}
199+
}
200+
_ => (),
185201
}
186202
}
187203
}

0 commit comments

Comments
 (0)