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