]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/use_self.rs
Detect match statement intended to be tail expression
[rust.git] / src / tools / clippy / clippy_lints / src / use_self.rs
1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
3 use rustc_hir as hir;
4 use rustc_hir::def::{DefKind, Res};
5 use rustc_hir::intravisit::{walk_item, walk_path, walk_ty, NestedVisitorMap, Visitor};
6 use rustc_hir::{
7     def, FnDecl, FnRetTy, FnSig, GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, Path, PathSegment, QPath,
8     TyKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::hir::map::Map;
12 use rustc_middle::lint::in_external_macro;
13 use rustc_middle::ty;
14 use rustc_middle::ty::{DefIdTree, Ty};
15 use rustc_semver::RustcVersion;
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::symbol::kw;
18 use rustc_typeck::hir_ty_to_ty;
19
20 use crate::utils::{differing_macro_contexts, meets_msrv, span_lint_and_sugg};
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for unnecessary repetition of structure name when a
24     /// replacement with `Self` is applicable.
25     ///
26     /// **Why is this bad?** Unnecessary repetition. Mixed use of `Self` and struct
27     /// name
28     /// feels inconsistent.
29     ///
30     /// **Known problems:**
31     /// - False positive when using associated types ([#2843](https://github.com/rust-lang/rust-clippy/issues/2843))
32     /// - False positives in some situations when using generics ([#3410](https://github.com/rust-lang/rust-clippy/issues/3410))
33     ///
34     /// **Example:**
35     /// ```rust
36     /// struct Foo {}
37     /// impl Foo {
38     ///     fn new() -> Foo {
39     ///         Foo {}
40     ///     }
41     /// }
42     /// ```
43     /// could be
44     /// ```rust
45     /// struct Foo {}
46     /// impl Foo {
47     ///     fn new() -> Self {
48     ///         Self {}
49     ///     }
50     /// }
51     /// ```
52     pub USE_SELF,
53     nursery,
54     "unnecessary structure name repetition whereas `Self` is applicable"
55 }
56
57 impl_lint_pass!(UseSelf => [USE_SELF]);
58
59 const SEGMENTS_MSG: &str = "segments should be composed of at least 1 element";
60
61 fn span_use_self_lint(cx: &LateContext<'_>, path: &Path<'_>, last_segment: Option<&PathSegment<'_>>) {
62     let last_segment = last_segment.unwrap_or_else(|| path.segments.last().expect(SEGMENTS_MSG));
63
64     // Path segments only include actual path, no methods or fields.
65     let last_path_span = last_segment.ident.span;
66
67     if differing_macro_contexts(path.span, last_path_span) {
68         return;
69     }
70
71     // Only take path up to the end of last_path_span.
72     let span = path.span.with_hi(last_path_span.hi());
73
74     span_lint_and_sugg(
75         cx,
76         USE_SELF,
77         span,
78         "unnecessary structure name repetition",
79         "use the applicable keyword",
80         "Self".to_owned(),
81         Applicability::MachineApplicable,
82     );
83 }
84
85 // FIXME: always use this (more correct) visitor, not just in method signatures.
86 struct SemanticUseSelfVisitor<'a, 'tcx> {
87     cx: &'a LateContext<'tcx>,
88     self_ty: Ty<'tcx>,
89 }
90
91 impl<'a, 'tcx> Visitor<'tcx> for SemanticUseSelfVisitor<'a, 'tcx> {
92     type Map = Map<'tcx>;
93
94     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'_>) {
95         if let TyKind::Path(QPath::Resolved(_, path)) = &hir_ty.kind {
96             match path.res {
97                 def::Res::SelfTy(..) => {},
98                 _ => {
99                     if hir_ty_to_ty(self.cx.tcx, hir_ty) == self.self_ty {
100                         span_use_self_lint(self.cx, path, None);
101                     }
102                 },
103             }
104         }
105
106         walk_ty(self, hir_ty)
107     }
108
109     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
110         NestedVisitorMap::None
111     }
112 }
113
114 fn check_trait_method_impl_decl<'tcx>(
115     cx: &LateContext<'tcx>,
116     impl_item: &ImplItem<'_>,
117     impl_decl: &'tcx FnDecl<'_>,
118     impl_trait_ref: ty::TraitRef<'tcx>,
119 ) {
120     let trait_method = cx
121         .tcx
122         .associated_items(impl_trait_ref.def_id)
123         .find_by_name_and_kind(cx.tcx, impl_item.ident, ty::AssocKind::Fn, impl_trait_ref.def_id)
124         .expect("impl method matches a trait method");
125
126     let trait_method_sig = cx.tcx.fn_sig(trait_method.def_id);
127     let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig);
128
129     let output_hir_ty = if let FnRetTy::Return(ty) = &impl_decl.output {
130         Some(&**ty)
131     } else {
132         None
133     };
134
135     // `impl_hir_ty` (of type `hir::Ty`) represents the type written in the signature.
136     // `trait_ty` (of type `ty::Ty`) is the semantic type for the signature in the trait.
137     // We use `impl_hir_ty` to see if the type was written as `Self`,
138     // `hir_ty_to_ty(...)` to check semantic types of paths, and
139     // `trait_ty` to determine which parts of the signature in the trait, mention
140     // the type being implemented verbatim (as opposed to `Self`).
141     for (impl_hir_ty, trait_ty) in impl_decl
142         .inputs
143         .iter()
144         .chain(output_hir_ty)
145         .zip(trait_method_sig.inputs_and_output)
146     {
147         // Check if the input/output type in the trait method specifies the implemented
148         // type verbatim, and only suggest `Self` if that isn't the case.
149         // This avoids suggestions to e.g. replace `Vec<u8>` with `Vec<Self>`,
150         // in an `impl Trait for u8`, when the trait always uses `Vec<u8>`.
151         // See also https://github.com/rust-lang/rust-clippy/issues/2894.
152         let self_ty = impl_trait_ref.self_ty();
153         if !trait_ty.walk().any(|inner| inner == self_ty.into()) {
154             let mut visitor = SemanticUseSelfVisitor { cx, self_ty };
155
156             visitor.visit_ty(&impl_hir_ty);
157         }
158     }
159 }
160
161 const USE_SELF_MSRV: RustcVersion = RustcVersion::new(1, 37, 0);
162
163 pub struct UseSelf {
164     msrv: Option<RustcVersion>,
165 }
166
167 impl UseSelf {
168     #[must_use]
169     pub fn new(msrv: Option<RustcVersion>) -> Self {
170         Self { msrv }
171     }
172 }
173
174 impl<'tcx> LateLintPass<'tcx> for UseSelf {
175     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
176         if !meets_msrv(self.msrv.as_ref(), &USE_SELF_MSRV) {
177             return;
178         }
179
180         if in_external_macro(cx.sess(), item.span) {
181             return;
182         }
183         if_chain! {
184             if let ItemKind::Impl(impl_) = &item.kind;
185             if let TyKind::Path(QPath::Resolved(_, ref item_path)) = impl_.self_ty.kind;
186             then {
187                 let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args;
188                 let should_check = parameters.as_ref().map_or(
189                     true,
190                     |params| !params.parenthesized
191                         &&!params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
192                 );
193
194                 if should_check {
195                     let visitor = &mut UseSelfVisitor {
196                         item_path,
197                         cx,
198                     };
199                     let impl_trait_ref = cx.tcx.impl_trait_ref(item.def_id);
200
201                     if let Some(impl_trait_ref) = impl_trait_ref {
202                         for impl_item_ref in impl_.items {
203                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
204                             if let ImplItemKind::Fn(FnSig{ decl: impl_decl, .. }, impl_body_id)
205                                     = &impl_item.kind {
206                                 check_trait_method_impl_decl(cx, impl_item, impl_decl, impl_trait_ref);
207
208                                 let body = cx.tcx.hir().body(*impl_body_id);
209                                 visitor.visit_body(body);
210                             } else {
211                                 visitor.visit_impl_item(impl_item);
212                             }
213                         }
214                     } else {
215                         for impl_item_ref in impl_.items {
216                             let impl_item = cx.tcx.hir().impl_item(impl_item_ref.id);
217                             visitor.visit_impl_item(impl_item);
218                         }
219                     }
220                 }
221             }
222         }
223     }
224     extract_msrv_attr!(LateContext);
225 }
226
227 struct UseSelfVisitor<'a, 'tcx> {
228     item_path: &'a Path<'a>,
229     cx: &'a LateContext<'tcx>,
230 }
231
232 impl<'a, 'tcx> Visitor<'tcx> for UseSelfVisitor<'a, 'tcx> {
233     type Map = Map<'tcx>;
234
235     fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
236         if !path.segments.iter().any(|p| p.ident.span.is_dummy()) {
237             if path.segments.len() >= 2 {
238                 let last_but_one = &path.segments[path.segments.len() - 2];
239                 if last_but_one.ident.name != kw::SelfUpper {
240                     let enum_def_id = match path.res {
241                         Res::Def(DefKind::Variant, variant_def_id) => self.cx.tcx.parent(variant_def_id),
242                         Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), ctor_def_id) => {
243                             let variant_def_id = self.cx.tcx.parent(ctor_def_id);
244                             variant_def_id.and_then(|def_id| self.cx.tcx.parent(def_id))
245                         },
246                         _ => None,
247                     };
248
249                     if self.item_path.res.opt_def_id() == enum_def_id {
250                         span_use_self_lint(self.cx, path, Some(last_but_one));
251                     }
252                 }
253             }
254
255             if path.segments.last().expect(SEGMENTS_MSG).ident.name != kw::SelfUpper {
256                 if self.item_path.res == path.res {
257                     span_use_self_lint(self.cx, path, None);
258                 } else if let Res::Def(DefKind::Ctor(def::CtorOf::Struct, _), ctor_def_id) = path.res {
259                     if self.item_path.res.opt_def_id() == self.cx.tcx.parent(ctor_def_id) {
260                         span_use_self_lint(self.cx, path, None);
261                     }
262                 }
263             }
264         }
265
266         walk_path(self, path);
267     }
268
269     fn visit_item(&mut self, item: &'tcx Item<'_>) {
270         match item.kind {
271             ItemKind::Use(..)
272             | ItemKind::Static(..)
273             | ItemKind::Enum(..)
274             | ItemKind::Struct(..)
275             | ItemKind::Union(..)
276             | ItemKind::Impl { .. }
277             | ItemKind::Fn(..) => {
278                 // Don't check statements that shadow `Self` or where `Self` can't be used
279             },
280             _ => walk_item(self, item),
281         }
282     }
283
284     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
285         NestedVisitorMap::All(self.cx.tcx.hir())
286     }
287 }