1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note, span_lint_and_then};
2 use clippy_utils::paths;
3 use clippy_utils::ty::{implements_trait, is_copy};
4 use clippy_utils::{get_trait_def_id, is_automatically_derived, is_lint_allowed, match_def_path};
5 use if_chain::if_chain;
6 use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, NestedVisitorMap, Visitor};
8 BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Impl, Item, ItemKind, TraitRef, UnsafeSource, Unsafety,
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::hir::map::Map;
12 use rustc_middle::ty::{self, Ty};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::source_map::Span;
16 declare_clippy_lint! {
18 /// Checks for deriving `Hash` but implementing `PartialEq`
19 /// explicitly or vice versa.
21 /// ### Why is this bad?
22 /// The implementation of these traits must agree (for
23 /// example for use with `HashMap`) so it’s probably a bad idea to use a
24 /// default-generated `Hash` implementation with an explicitly defined
25 /// `PartialEq`. In particular, the following must hold for any type:
28 /// k1 == k2 ⇒ hash(k1) == hash(k2)
36 /// impl PartialEq for Foo {
40 pub DERIVE_HASH_XOR_EQ,
42 "deriving `Hash` but implementing `PartialEq` explicitly"
45 declare_clippy_lint! {
47 /// Checks for deriving `Ord` but implementing `PartialOrd`
48 /// explicitly or vice versa.
50 /// ### Why is this bad?
51 /// The implementation of these traits must agree (for
52 /// example for use with `sort`) so it’s probably a bad idea to use a
53 /// default-generated `Ord` implementation with an explicitly defined
54 /// `PartialOrd`. In particular, the following must hold for any type
55 /// implementing `Ord`:
58 /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
63 /// #[derive(Ord, PartialEq, Eq)]
66 /// impl PartialOrd for Foo {
72 /// #[derive(PartialEq, Eq)]
75 /// impl PartialOrd for Foo {
76 /// fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
77 /// Some(self.cmp(other))
81 /// impl Ord for Foo {
85 /// or, if you don't need a custom ordering:
87 /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
90 pub DERIVE_ORD_XOR_PARTIAL_ORD,
92 "deriving `Ord` but implementing `PartialOrd` explicitly"
95 declare_clippy_lint! {
97 /// Checks for explicit `Clone` implementations for `Copy`
100 /// ### Why is this bad?
101 /// To avoid surprising behaviour, these traits should
102 /// agree and the behaviour of `Copy` cannot be overridden. In almost all
103 /// situations a `Copy` type should have a `Clone` implementation that does
104 /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
112 /// impl Clone for Foo {
116 pub EXPL_IMPL_CLONE_ON_COPY,
118 "implementing `Clone` explicitly on `Copy` types"
121 declare_clippy_lint! {
123 /// Checks for deriving `serde::Deserialize` on a type that
124 /// has methods using `unsafe`.
126 /// ### Why is this bad?
127 /// Deriving `serde::Deserialize` will create a constructor
128 /// that may violate invariants hold by another constructor.
132 /// use serde::Deserialize;
134 /// #[derive(Deserialize)]
140 /// pub fn new() -> Self {
144 /// pub unsafe fn parts() -> (&str, &str) {
145 /// // assumes invariants hold
149 pub UNSAFE_DERIVE_DESERIALIZE,
151 "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
154 declare_lint_pass!(Derive => [
155 EXPL_IMPL_CLONE_ON_COPY,
157 DERIVE_ORD_XOR_PARTIAL_ORD,
158 UNSAFE_DERIVE_DESERIALIZE
161 impl<'tcx> LateLintPass<'tcx> for Derive {
162 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
163 if let ItemKind::Impl(Impl {
164 of_trait: Some(ref trait_ref),
168 let ty = cx.tcx.type_of(item.def_id);
169 let attrs = cx.tcx.hir().attrs(item.hir_id());
170 let is_automatically_derived = is_automatically_derived(attrs);
172 check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
173 check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
175 if is_automatically_derived {
176 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
178 check_copy_clone(cx, item, trait_ref, ty);
184 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
185 fn check_hash_peq<'tcx>(
186 cx: &LateContext<'tcx>,
188 trait_ref: &TraitRef<'_>,
190 hash_is_automatically_derived: bool,
193 if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
194 if let Some(def_id) = trait_ref.trait_def_id();
195 if match_def_path(cx, def_id, &paths::HASH);
197 // Look for the PartialEq implementations for `ty`
198 cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
199 let peq_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
201 if peq_is_automatically_derived == hash_is_automatically_derived {
205 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
207 // Only care about `impl PartialEq<Foo> for Foo`
208 // For `impl PartialEq<B> for A, input_types is [A, B]
209 if trait_ref.substs.type_at(1) == ty {
210 let mess = if peq_is_automatically_derived {
211 "you are implementing `Hash` explicitly but have derived `PartialEq`"
213 "you are deriving `Hash` but have implemented `PartialEq` explicitly"
222 if let Some(local_def_id) = impl_id.as_local() {
223 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
225 cx.tcx.hir().span(hir_id),
226 "`PartialEq` implemented here"
237 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
238 fn check_ord_partial_ord<'tcx>(
239 cx: &LateContext<'tcx>,
241 trait_ref: &TraitRef<'_>,
243 ord_is_automatically_derived: bool,
246 if let Some(ord_trait_def_id) = get_trait_def_id(cx, &paths::ORD);
247 if let Some(partial_ord_trait_def_id) = cx.tcx.lang_items().partial_ord_trait();
248 if let Some(def_id) = &trait_ref.trait_def_id();
249 if *def_id == ord_trait_def_id;
251 // Look for the PartialOrd implementations for `ty`
252 cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
253 let partial_ord_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
255 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
259 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
261 // Only care about `impl PartialOrd<Foo> for Foo`
262 // For `impl PartialOrd<B> for A, input_types is [A, B]
263 if trait_ref.substs.type_at(1) == ty {
264 let mess = if partial_ord_is_automatically_derived {
265 "you are implementing `Ord` explicitly but have derived `PartialOrd`"
267 "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
272 DERIVE_ORD_XOR_PARTIAL_ORD,
276 if let Some(local_def_id) = impl_id.as_local() {
277 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
279 cx.tcx.hir().span(hir_id),
280 "`PartialOrd` implemented here"
291 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
292 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
293 let clone_id = match cx.tcx.lang_items().clone_trait() {
294 Some(id) if trait_ref.trait_def_id() == Some(id) => id,
297 let copy_id = match cx.tcx.lang_items().copy_trait() {
301 let (ty_adt, ty_subs) = match *ty.kind() {
302 // Unions can't derive clone.
303 ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
306 // If the current self type doesn't implement Copy (due to generic constraints), search to see if
307 // there's a Copy impl for any instance of the adt.
308 if !is_copy(cx, ty) {
309 if ty_subs.non_erasable_generics().next().is_some() {
310 let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(©_id).map_or(false, |impls| {
313 .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did == adt.did))
322 // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
324 if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
330 EXPL_IMPL_CLONE_ON_COPY,
332 "you are implementing `Clone` explicitly on a `Copy` type",
334 "consider deriving `Clone` or removing `Copy`",
338 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
339 fn check_unsafe_derive_deserialize<'tcx>(
340 cx: &LateContext<'tcx>,
342 trait_ref: &TraitRef<'_>,
345 fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
346 let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
347 walk_item(&mut visitor, item);
352 if let Some(trait_def_id) = trait_ref.trait_def_id();
353 if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
354 if let ty::Adt(def, _) = ty.kind();
355 if let Some(local_def_id) = def.did.as_local();
356 let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
357 if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
358 if cx.tcx.inherent_impls(def.did)
360 .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
361 .any(|imp| has_unsafe(cx, imp));
365 UNSAFE_DERIVE_DESERIALIZE,
367 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
369 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
375 struct UnsafeVisitor<'a, 'tcx> {
376 cx: &'a LateContext<'tcx>,
380 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
381 type Map = Map<'tcx>;
383 fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
389 if let Some(header) = kind.header();
390 if header.unsafety == Unsafety::Unsafe;
392 self.has_unsafe = true;
396 walk_fn(self, kind, decl, body_id, span, id);
399 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
404 if let ExprKind::Block(block, _) = expr.kind {
405 if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
406 self.has_unsafe = true;
410 walk_expr(self, expr);
413 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
414 NestedVisitorMap::All(self.cx.tcx.hir())