1 use crate::utils::paths;
3 is_automatically_derived, is_copy, match_path, span_lint_and_help, span_lint_and_note, span_lint_and_then,
5 use if_chain::if_chain;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, NestedVisitorMap, Visitor};
9 BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Item, ItemKind, TraitRef, UnsafeSource, Unsafety,
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::ty::{self, Ty};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::source_map::Span;
17 declare_clippy_lint! {
18 /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
19 /// explicitly or vice versa.
21 /// **Why is this bad?** The implementation of these traits must agree (for
22 /// example for use with `HashMap`) so it’s probably a bad idea to use a
23 /// default-generated `Hash` implementation with an explicitly defined
24 /// `PartialEq`. In particular, the following must hold for any type:
27 /// k1 == k2 ⇒ hash(k1) == hash(k2)
30 /// **Known problems:** None.
37 /// impl PartialEq for Foo {
41 pub DERIVE_HASH_XOR_EQ,
43 "deriving `Hash` but implementing `PartialEq` explicitly"
46 declare_clippy_lint! {
47 /// **What it does:** Checks for explicit `Clone` implementations for `Copy`
50 /// **Why is this bad?** To avoid surprising behaviour, these traits should
51 /// agree and the behaviour of `Copy` cannot be overridden. In almost all
52 /// situations a `Copy` type should have a `Clone` implementation that does
53 /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
56 /// **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925
63 /// impl Clone for Foo {
67 pub EXPL_IMPL_CLONE_ON_COPY,
69 "implementing `Clone` explicitly on `Copy` types"
72 declare_clippy_lint! {
73 /// **What it does:** Checks for deriving `serde::Deserialize` on a type that
74 /// has methods using `unsafe`.
76 /// **Why is this bad?** Deriving `serde::Deserialize` will create a constructor
77 /// that may violate invariants hold by another constructor.
79 /// **Known problems:** None.
84 /// use serde::Deserialize;
86 /// #[derive(Deserialize)]
92 /// pub fn new() -> Self {
96 /// pub unsafe fn parts() -> (&str, &str) {
97 /// // assumes invariants hold
101 pub UNSAFE_DERIVE_DESERIALIZE,
103 "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
106 declare_lint_pass!(Derive => [EXPL_IMPL_CLONE_ON_COPY, DERIVE_HASH_XOR_EQ, UNSAFE_DERIVE_DESERIALIZE]);
108 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Derive {
109 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
110 if let ItemKind::Impl {
111 of_trait: Some(ref trait_ref),
115 let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id));
116 let is_automatically_derived = is_automatically_derived(&*item.attrs);
118 check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
120 if is_automatically_derived {
121 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
123 check_copy_clone(cx, item, trait_ref, ty);
129 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
130 fn check_hash_peq<'a, 'tcx>(
131 cx: &LateContext<'a, 'tcx>,
133 trait_ref: &TraitRef<'_>,
135 hash_is_automatically_derived: bool,
138 if match_path(&trait_ref.path, &paths::HASH);
139 if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
140 if let Some(def_id) = &trait_ref.trait_def_id();
141 if !def_id.is_local();
143 // Look for the PartialEq implementations for `ty`
144 cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
145 let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
147 if peq_is_automatically_derived == hash_is_automatically_derived {
151 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
153 // Only care about `impl PartialEq<Foo> for Foo`
154 // For `impl PartialEq<B> for A, input_types is [A, B]
155 if trait_ref.substs.type_at(1) == ty {
156 let mess = if peq_is_automatically_derived {
157 "you are implementing `Hash` explicitly but have derived `PartialEq`"
159 "you are deriving `Hash` but have implemented `PartialEq` explicitly"
168 if let Some(local_def_id) = impl_id.as_local() {
169 let hir_id = cx.tcx.hir().as_local_hir_id(local_def_id);
171 cx.tcx.hir().span(hir_id),
172 "`PartialEq` implemented here"
183 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
184 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
185 if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
186 if !is_copy(cx, ty) {
191 ty::Adt(def, _) if def.is_union() => return,
193 // Some types are not Clone by default but could be cloned “by hand” if necessary
194 ty::Adt(def, substs) => {
195 for variant in &def.variants {
196 for field in &variant.fields {
197 if let ty::FnDef(..) = field.ty(cx.tcx, substs).kind {
201 for subst in substs {
202 if let ty::subst::GenericArgKind::Type(subst) = subst.unpack() {
203 if let ty::Param(_) = subst.kind {
215 EXPL_IMPL_CLONE_ON_COPY,
217 "you are implementing `Clone` explicitly on a `Copy` type",
219 "consider deriving `Clone` or removing `Copy`",
224 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
225 fn check_unsafe_derive_deserialize<'a, 'tcx>(
226 cx: &LateContext<'a, 'tcx>,
228 trait_ref: &TraitRef<'_>,
231 fn item_from_def_id<'tcx>(cx: &LateContext<'_, 'tcx>, def_id: DefId) -> &'tcx Item<'tcx> {
232 let hir_id = cx.tcx.hir().as_local_hir_id(def_id.expect_local());
233 cx.tcx.hir().expect_item(hir_id)
236 fn has_unsafe<'tcx>(cx: &LateContext<'_, 'tcx>, item: &'tcx Item<'_>) -> bool {
237 let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
238 walk_item(&mut visitor, item);
243 if match_path(&trait_ref.path, &paths::SERDE_DESERIALIZE);
244 if let ty::Adt(def, _) = ty.kind;
245 if def.did.is_local();
246 if cx.tcx.inherent_impls(def.did)
248 .map(|imp_did| item_from_def_id(cx, *imp_did))
249 .any(|imp| has_unsafe(cx, imp));
253 UNSAFE_DERIVE_DESERIALIZE,
255 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
257 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
263 struct UnsafeVisitor<'a, 'tcx> {
264 cx: &'a LateContext<'a, 'tcx>,
268 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
269 type Map = Map<'tcx>;
271 fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
277 if let Some(header) = kind.header();
278 if let Unsafety::Unsafe = header.unsafety;
280 self.has_unsafe = true;
284 walk_fn(self, kind, decl, body_id, span, id);
287 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
292 if let ExprKind::Block(block, _) = expr.kind {
294 BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
295 | BlockCheckMode::PushUnsafeBlock(UnsafeSource::UserProvided)
296 | BlockCheckMode::PopUnsafeBlock(UnsafeSource::UserProvided) => {
297 self.has_unsafe = true;
303 walk_expr(self, expr);
306 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
307 NestedVisitorMap::All(self.cx.tcx.hir())