1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::same_type_and_consts;
4 use clippy_utils::{in_macro, meets_msrv, msrvs};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
11 intravisit::{walk_ty, NestedVisitorMap, Visitor},
12 Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Node, Path, PathSegment,
15 use rustc_lint::{LateContext, LateLintPass, LintContext};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::ty::{AssocKind, Ty};
18 use rustc_semver::RustcVersion;
19 use rustc_session::{declare_tool_lint, impl_lint_pass};
20 use rustc_span::{BytePos, Span};
21 use rustc_typeck::hir_ty_to_ty;
23 declare_clippy_lint! {
24 /// **What it does:** Checks for unnecessary repetition of structure name when a
25 /// replacement with `Self` is applicable.
27 /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
29 /// feels inconsistent.
31 /// **Known problems:**
32 /// - Unaddressed false negative in fn bodies of trait implementations
33 /// - False positive with assotiated types in traits (#4140)
49 /// fn new() -> Self {
56 "unnecessary structure name repetition whereas `Self` is applicable"
61 msrv: Option<RustcVersion>,
62 stack: Vec<StackItem>,
67 pub fn new(msrv: Option<RustcVersion>) -> Self {
79 impl_trait_ref_def_id: Option<LocalDefId>,
80 types_to_skip: Vec<HirId>,
81 types_to_lint: Vec<HirId>,
86 impl_lint_pass!(UseSelf => [USE_SELF]);
88 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
90 impl<'tcx> LateLintPass<'tcx> for UseSelf {
91 fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
92 // We push the self types of `impl`s on a stack here. Only the top type on the stack is
93 // relevant for linting, since this is the self type of the `impl` we're currently in. To
94 // avoid linting on nested items, we push `StackItem::NoCheck` on the stack to signal, that
95 // we're in an `impl` or nested item, that we don't want to lint
97 // NB: If you push something on the stack in this method, remember to also pop it in the
98 // `check_item_post` method.
100 ItemKind::Impl(Impl {
101 self_ty: hir_self_ty,
105 let should_check = if let TyKind::Path(QPath::Resolved(_, item_path)) = hir_self_ty.kind {
106 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
107 parameters.as_ref().map_or(true, |params| {
108 !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
113 let impl_trait_ref_def_id = of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id()));
115 self.stack.push(StackItem::Check {
116 hir_id: hir_self_ty.hir_id,
117 impl_trait_ref_def_id,
118 types_to_lint: Vec::new(),
119 types_to_skip: Vec::new(),
122 self.stack.push(StackItem::NoCheck);
126 | ItemKind::Const(..)
129 | ItemKind::Struct(..)
130 | ItemKind::Union(..)
131 | ItemKind::Trait(..) => {
132 self.stack.push(StackItem::NoCheck);
138 fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) {
139 use ItemKind::{Const, Enum, Fn, Impl, Static, Struct, Trait, Union};
141 Impl { .. } | Static(..) | Const(..) | Fn(..) | Enum(..) | Struct(..) | Union(..) | Trait(..) => {
148 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
149 // We want to skip types in trait `impl`s that aren't declared as `Self` in the trait
150 // declaration. The collection of those types is all this method implementation does.
152 if let ImplItemKind::Fn(FnSig { decl, .. }, ..) = impl_item.kind;
153 if let Some(&mut StackItem::Check {
154 impl_trait_ref_def_id: Some(def_id),
155 ref mut types_to_skip,
157 }) = self.stack.last_mut();
158 if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(def_id);
160 // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be
162 let self_ty = impl_trait_ref.self_ty();
164 // `trait_method_sig` is the signature of the function, how it is declared in the
165 // trait, not in the impl of the trait.
166 let trait_method = cx
168 .associated_items(impl_trait_ref.def_id)
169 .find_by_name_and_kind(cx.tcx, impl_item.ident, AssocKind::Fn, impl_trait_ref.def_id)
170 .expect("impl method matches a trait method");
171 let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
172 let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
174 // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the
175 // implementation of the trait.
176 let output_hir_ty = if let FnRetTy::Return(ty) = &decl.output {
181 let impl_inputs_outputs = decl.inputs.iter().chain(output_hir_ty);
183 // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
185 // `trait_sem_ty` (of type `ty::Ty`) is the semantic type for the signature in the
186 // trait declaration. This is used to check if `Self` was used in the trait
189 // If `any`where in the `trait_sem_ty` the `self_ty` was used verbatim (as opposed
190 // to `Self`), we want to skip linting that type and all subtypes of it. This
191 // avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`, in an `impl Trait
192 // for u8`, when the trait always uses `Vec<u8>`.
194 // See also https://github.com/rust-lang/rust-clippy/issues/2894.
195 for (impl_hir_ty, trait_sem_ty) in impl_inputs_outputs.zip(trait_method_sig.inputs_and_output) {
196 if trait_sem_ty.walk().any(|inner| inner == self_ty.into()) {
197 let mut visitor = SkipTyCollector::default();
198 visitor.visit_ty(impl_hir_ty);
199 types_to_skip.extend(visitor.types_to_skip);
206 fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) {
207 // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies
208 // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`.
209 // However the `node_type()` method can *only* be called in bodies.
211 // This method implementation determines which types should get linted in a `Body` and
212 // which shouldn't, with a visitor. We could directly lint in the visitor, but then we
213 // could only allow this lint on item scope. And we would have to check if those types are
214 // already dealt with in `check_ty` anyway.
215 if let Some(StackItem::Check {
220 }) = self.stack.last_mut()
222 let self_ty = ty_from_hir_id(cx, *hir_id);
224 let mut visitor = LintTyCollector {
227 types_to_lint: vec![],
228 types_to_skip: vec![],
230 visitor.visit_expr(&body.value);
231 types_to_lint.extend(visitor.types_to_lint);
232 types_to_skip.extend(visitor.types_to_skip);
236 fn check_ty(&mut self, cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) {
237 if in_macro(hir_ty.span)
238 || in_impl(cx, hir_ty)
239 || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS)
244 let lint_dependend_on_expr_kind = if let Some(StackItem::Check {
249 }) = self.stack.last()
251 if types_to_skip.contains(&hir_ty.hir_id) {
253 } else if types_to_lint.contains(&hir_ty.hir_id) {
256 let self_ty = ty_from_hir_id(cx, *hir_id);
257 should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty)
263 if lint_dependend_on_expr_kind {
264 // FIXME: this span manipulation should not be necessary
265 // @flip1995 found an ast lowering issue in
266 // https://github.com/rust-lang/rust/blob/master/src/librustc_ast_lowering/path.rs#l142-l162
267 let hir = cx.tcx.hir();
268 let id = hir.get_parent_node(hir_ty.hir_id);
270 if !hir.opt_span(id).map_or(false, in_macro) {
272 Some(Node::Expr(Expr {
273 kind: ExprKind::Path(QPath::TypeRelative(_, segment)),
275 })) => span_lint_until_last_segment(cx, hir_ty.span, segment),
276 _ => span_lint(cx, hir_ty.span),
282 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
283 fn expr_ty_matches(cx: &LateContext<'_>, expr: &Expr<'_>, self_ty: Ty<'_>) -> bool {
284 let def_id = expr.hir_id.owner;
285 if cx.tcx.has_typeck_results(def_id) {
286 cx.tcx.typeck(def_id).expr_ty_opt(expr) == Some(self_ty)
292 if in_macro(expr.span) || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS) {
296 if let Some(StackItem::Check { hir_id, .. }) = self.stack.last() {
297 let self_ty = ty_from_hir_id(cx, *hir_id);
300 ExprKind::Struct(QPath::Resolved(_, path), ..) => {
301 if expr_ty_matches(cx, expr, self_ty) {
303 def::Res::SelfTy(..) => (),
304 def::Res::Def(DefKind::Variant, _) => span_lint_on_path_until_last_segment(cx, path),
306 span_lint(cx, path.span);
311 // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`)
312 ExprKind::Call(fun, _) => {
314 kind: ExprKind::Path(ref qpath),
318 if expr_ty_matches(cx, expr, self_ty) {
319 let res = cx.qpath_res(qpath, fun.hir_id);
321 if let def::Res::Def(DefKind::Ctor(ctor_of, _), ..) = res {
323 def::CtorOf::Variant => {
324 span_lint_on_qpath_resolved(cx, qpath, true);
326 def::CtorOf::Struct => {
327 span_lint_on_qpath_resolved(cx, qpath, false);
334 // unit enum variants (`Enum::A`)
335 ExprKind::Path(qpath) => {
336 if expr_ty_matches(cx, expr, self_ty) {
337 span_lint_on_qpath_resolved(cx, qpath, true);
345 extract_msrv_attr!(LateContext);
349 struct SkipTyCollector {
350 types_to_skip: Vec<HirId>,
353 impl<'tcx> Visitor<'tcx> for SkipTyCollector {
354 type Map = Map<'tcx>;
356 fn visit_ty(&mut self, hir_ty: &hir::Ty<'_>) {
357 self.types_to_skip.push(hir_ty.hir_id);
359 walk_ty(self, hir_ty);
362 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
363 NestedVisitorMap::None
367 struct LintTyCollector<'a, 'tcx> {
368 cx: &'a LateContext<'tcx>,
370 types_to_lint: Vec<HirId>,
371 types_to_skip: Vec<HirId>,
374 impl<'a, 'tcx> Visitor<'tcx> for LintTyCollector<'a, 'tcx> {
375 type Map = Map<'tcx>;
377 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) {
379 if let Some(ty) = self.cx.typeck_results().node_type_opt(hir_ty.hir_id);
380 if should_lint_ty(hir_ty, ty, self.self_ty);
382 self.types_to_lint.push(hir_ty.hir_id);
384 self.types_to_skip.push(hir_ty.hir_id);
388 walk_ty(self, hir_ty);
391 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
392 NestedVisitorMap::None
396 fn span_lint(cx: &LateContext<'_>, span: Span) {
401 "unnecessary structure name repetition",
402 "use the applicable keyword",
404 Applicability::MachineApplicable,
408 #[allow(clippy::cast_possible_truncation)]
409 fn span_lint_until_last_segment(cx: &LateContext<'_>, span: Span, segment: &PathSegment<'_>) {
410 let sp = span.with_hi(segment.ident.span.lo());
411 // remove the trailing ::
412 let span_without_last_segment = match snippet_opt(cx, sp) {
413 Some(snippet) => match snippet.rfind("::") {
414 Some(bidx) => sp.with_hi(sp.lo() + BytePos(bidx as u32)),
419 span_lint(cx, span_without_last_segment);
422 fn span_lint_on_path_until_last_segment(cx: &LateContext<'_>, path: &Path<'_>) {
423 if path.segments.len() > 1 {
424 span_lint_until_last_segment(cx, path.span, path.segments.last().unwrap());
428 fn span_lint_on_qpath_resolved(cx: &LateContext<'_>, qpath: &QPath<'_>, until_last_segment: bool) {
429 if let QPath::Resolved(_, path) = qpath {
430 if until_last_segment {
431 span_lint_on_path_until_last_segment(cx, path);
433 span_lint(cx, path.span);
438 fn ty_from_hir_id<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Ty<'tcx> {
439 if let Some(Node::Ty(hir_ty)) = cx.tcx.hir().find(hir_id) {
440 hir_ty_to_ty(cx.tcx, hir_ty)
442 unreachable!("This function should only be called with `HirId`s that are for sure `Node::Ty`")
446 fn in_impl(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'_>) -> bool {
447 let map = cx.tcx.hir();
448 let parent = map.get_parent_node(hir_ty.hir_id);
450 if let Some(Node::Item(item)) = map.find(parent);
451 if let ItemKind::Impl { .. } = item.kind;
460 fn should_lint_ty(hir_ty: &hir::Ty<'_>, ty: Ty<'_>, self_ty: Ty<'_>) -> bool {
462 if same_type_and_consts(ty, self_ty);
463 if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
465 !matches!(path.res, def::Res::SelfTy(..))