]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/traits.rs
2e778cf0d0fe07bf958f5fd1ee144a747a633367
[rust.git] / compiler / rustc_lint / src / traits.rs
1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 use crate::lints::{DropGlue, DropTraitConstraintsDiag};
4 use crate::LateContext;
5 use crate::LateLintPass;
6 use crate::LintContext;
7 use rustc_hir as hir;
8 use rustc_span::symbol::sym;
9
10 declare_lint! {
11     /// The `drop_bounds` lint checks for generics with `std::ops::Drop` as
12     /// bounds.
13     ///
14     /// ### Example
15     ///
16     /// ```rust
17     /// fn foo<T: Drop>() {}
18     /// ```
19     ///
20     /// {{produces}}
21     ///
22     /// ### Explanation
23     ///
24     /// A generic trait bound of the form `T: Drop` is most likely misleading
25     /// and not what the programmer intended (they probably should have used
26     /// `std::mem::needs_drop` instead).
27     ///
28     /// `Drop` bounds do not actually indicate whether a type can be trivially
29     /// dropped or not, because a composite type containing `Drop` types does
30     /// not necessarily implement `Drop` itself. Naïvely, one might be tempted
31     /// to write an implementation that assumes that a type can be trivially
32     /// dropped while also supplying a specialization for `T: Drop` that
33     /// actually calls the destructor. However, this breaks down e.g. when `T`
34     /// is `String`, which does not implement `Drop` itself but contains a
35     /// `Vec`, which does implement `Drop`, so assuming `T` can be trivially
36     /// dropped would lead to a memory leak here.
37     ///
38     /// Furthermore, the `Drop` trait only contains one method, `Drop::drop`,
39     /// which may not be called explicitly in user code (`E0040`), so there is
40     /// really no use case for using `Drop` in trait bounds, save perhaps for
41     /// some obscure corner cases, which can use `#[allow(drop_bounds)]`.
42     pub DROP_BOUNDS,
43     Warn,
44     "bounds of the form `T: Drop` are most likely incorrect"
45 }
46
47 declare_lint! {
48     /// The `dyn_drop` lint checks for trait objects with `std::ops::Drop`.
49     ///
50     /// ### Example
51     ///
52     /// ```rust
53     /// fn foo(_x: Box<dyn Drop>) {}
54     /// ```
55     ///
56     /// {{produces}}
57     ///
58     /// ### Explanation
59     ///
60     /// A trait object bound of the form `dyn Drop` is most likely misleading
61     /// and not what the programmer intended.
62     ///
63     /// `Drop` bounds do not actually indicate whether a type can be trivially
64     /// dropped or not, because a composite type containing `Drop` types does
65     /// not necessarily implement `Drop` itself. Naïvely, one might be tempted
66     /// to write a deferred drop system, to pull cleaning up memory out of a
67     /// latency-sensitive code path, using `dyn Drop` trait objects. However,
68     /// this breaks down e.g. when `T` is `String`, which does not implement
69     /// `Drop`, but should probably be accepted.
70     ///
71     /// To write a trait object bound that accepts anything, use a placeholder
72     /// trait with a blanket implementation.
73     ///
74     /// ```rust
75     /// trait Placeholder {}
76     /// impl<T> Placeholder for T {}
77     /// fn foo(_x: Box<dyn Placeholder>) {}
78     /// ```
79     pub DYN_DROP,
80     Warn,
81     "trait objects of the form `dyn Drop` are useless"
82 }
83
84 declare_lint_pass!(
85     /// Lint for bounds of the form `T: Drop`, which usually
86     /// indicate an attempt to emulate `std::mem::needs_drop`.
87     DropTraitConstraints => [DROP_BOUNDS, DYN_DROP]
88 );
89
90 impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints {
91     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
92         use rustc_middle::ty::Clause;
93         use rustc_middle::ty::PredicateKind::*;
94
95         let predicates = cx.tcx.explicit_predicates_of(item.owner_id);
96         for &(predicate, span) in predicates.predicates {
97             let Clause(Clause::Trait(trait_predicate)) = predicate.kind().skip_binder() else {
98                 continue
99             };
100             let def_id = trait_predicate.trait_ref.def_id;
101             if cx.tcx.lang_items().drop_trait() == Some(def_id) {
102                 // Explicitly allow `impl Drop`, a drop-guards-as-Voldemort-type pattern.
103                 if trait_predicate.trait_ref.self_ty().is_impl_trait() {
104                     continue;
105                 }
106                 let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else {
107                     return
108                 };
109                 cx.emit_spanned_lint(
110                     DROP_BOUNDS,
111                     span,
112                     DropTraitConstraintsDiag { predicate, tcx: cx.tcx, def_id },
113                 );
114             }
115         }
116     }
117
118     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) {
119         let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else {
120             return
121         };
122         for bound in &bounds[..] {
123             let def_id = bound.trait_ref.trait_def_id();
124             if cx.tcx.lang_items().drop_trait() == def_id {
125                 let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else {
126                     return
127                 };
128                 cx.emit_spanned_lint(DYN_DROP, bound.span, DropGlue { tcx: cx.tcx, def_id });
129             }
130         }
131     }
132 }