]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/functions/mod.rs
Auto merge of #85344 - cbeuw:remap-across-cwd, r=michaelwoerister
[rust.git] / src / tools / clippy / clippy_lints / src / functions / mod.rs
1 mod must_use;
2 mod not_unsafe_ptr_arg_deref;
3 mod result_unit_err;
4 mod too_many_arguments;
5 mod too_many_lines;
6
7 use rustc_hir as hir;
8 use rustc_hir::intravisit;
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::Span;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for functions with too many parameters.
16     ///
17     /// ### Why is this bad?
18     /// Functions with lots of parameters are considered bad
19     /// style and reduce readability (“what does the 5th parameter mean?”). Consider
20     /// grouping some parameters into a new type.
21     ///
22     /// ### Example
23     /// ```rust
24     /// # struct Color;
25     /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
26     ///     // ..
27     /// }
28     /// ```
29     pub TOO_MANY_ARGUMENTS,
30     complexity,
31     "functions with too many arguments"
32 }
33
34 declare_clippy_lint! {
35     /// ### What it does
36     /// Checks for functions with a large amount of lines.
37     ///
38     /// ### Why is this bad?
39     /// Functions with a lot of lines are harder to understand
40     /// due to having to look at a larger amount of code to understand what the
41     /// function is doing. Consider splitting the body of the function into
42     /// multiple functions.
43     ///
44     /// ### Example
45     /// ```rust
46     /// fn im_too_long() {
47     ///     println!("");
48     ///     // ... 100 more LoC
49     ///     println!("");
50     /// }
51     /// ```
52     pub TOO_MANY_LINES,
53     pedantic,
54     "functions with too many lines"
55 }
56
57 declare_clippy_lint! {
58     /// ### What it does
59     /// Checks for public functions that dereference raw pointer
60     /// arguments but are not marked `unsafe`.
61     ///
62     /// ### Why is this bad?
63     /// The function should probably be marked `unsafe`, since
64     /// for an arbitrary raw pointer, there is no way of telling for sure if it is
65     /// valid.
66     ///
67     /// ### Known problems
68     /// * It does not check functions recursively so if the pointer is passed to a
69     /// private non-`unsafe` function which does the dereferencing, the lint won't
70     /// trigger.
71     /// * It only checks for arguments whose type are raw pointers, not raw pointers
72     /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
73     /// `some_argument.get_raw_ptr()`).
74     ///
75     /// ### Example
76     /// ```rust,ignore
77     /// // Bad
78     /// pub fn foo(x: *const u8) {
79     ///     println!("{}", unsafe { *x });
80     /// }
81     ///
82     /// // Good
83     /// pub unsafe fn foo(x: *const u8) {
84     ///     println!("{}", unsafe { *x });
85     /// }
86     /// ```
87     pub NOT_UNSAFE_PTR_ARG_DEREF,
88     correctness,
89     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
90 }
91
92 declare_clippy_lint! {
93     /// ### What it does
94     /// Checks for a [`#[must_use]`] attribute on
95     /// unit-returning functions and methods.
96     ///
97     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
98     ///
99     /// ### Why is this bad?
100     /// Unit values are useless. The attribute is likely
101     /// a remnant of a refactoring that removed the return type.
102     ///
103     /// ### Examples
104     /// ```rust
105     /// #[must_use]
106     /// fn useless() { }
107     /// ```
108     pub MUST_USE_UNIT,
109     style,
110     "`#[must_use]` attribute on a unit-returning function / method"
111 }
112
113 declare_clippy_lint! {
114     /// ### What it does
115     /// Checks for a [`#[must_use]`] attribute without
116     /// further information on functions and methods that return a type already
117     /// marked as `#[must_use]`.
118     ///
119     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
120     ///
121     /// ### Why is this bad?
122     /// The attribute isn't needed. Not using the result
123     /// will already be reported. Alternatively, one can add some text to the
124     /// attribute to improve the lint message.
125     ///
126     /// ### Examples
127     /// ```rust
128     /// #[must_use]
129     /// fn double_must_use() -> Result<(), ()> {
130     ///     unimplemented!();
131     /// }
132     /// ```
133     pub DOUBLE_MUST_USE,
134     style,
135     "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
136 }
137
138 declare_clippy_lint! {
139     /// ### What it does
140     /// Checks for public functions that have no
141     /// [`#[must_use]`] attribute, but return something not already marked
142     /// must-use, have no mutable arg and mutate no statics.
143     ///
144     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
145     ///
146     /// ### Why is this bad?
147     /// Not bad at all, this lint just shows places where
148     /// you could add the attribute.
149     ///
150     /// ### Known problems
151     /// The lint only checks the arguments for mutable
152     /// types without looking if they are actually changed. On the other hand,
153     /// it also ignores a broad range of potentially interesting side effects,
154     /// because we cannot decide whether the programmer intends the function to
155     /// be called for the side effect or the result. Expect many false
156     /// positives. At least we don't lint if the result type is unit or already
157     /// `#[must_use]`.
158     ///
159     /// ### Examples
160     /// ```rust
161     /// // this could be annotated with `#[must_use]`.
162     /// fn id<T>(t: T) -> T { t }
163     /// ```
164     pub MUST_USE_CANDIDATE,
165     pedantic,
166     "function or method that could take a `#[must_use]` attribute"
167 }
168
169 declare_clippy_lint! {
170     /// ### What it does
171     /// Checks for public functions that return a `Result`
172     /// with an `Err` type of `()`. It suggests using a custom type that
173     /// implements `std::error::Error`.
174     ///
175     /// ### Why is this bad?
176     /// Unit does not implement `Error` and carries no
177     /// further information about what went wrong.
178     ///
179     /// ### Known problems
180     /// Of course, this lint assumes that `Result` is used
181     /// for a fallible operation (which is after all the intended use). However
182     /// code may opt to (mis)use it as a basic two-variant-enum. In that case,
183     /// the suggestion is misguided, and the code should use a custom enum
184     /// instead.
185     ///
186     /// ### Examples
187     /// ```rust
188     /// pub fn read_u8() -> Result<u8, ()> { Err(()) }
189     /// ```
190     /// should become
191     /// ```rust,should_panic
192     /// use std::fmt;
193     ///
194     /// #[derive(Debug)]
195     /// pub struct EndOfStream;
196     ///
197     /// impl fmt::Display for EndOfStream {
198     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199     ///         write!(f, "End of Stream")
200     ///     }
201     /// }
202     ///
203     /// impl std::error::Error for EndOfStream { }
204     ///
205     /// pub fn read_u8() -> Result<u8, EndOfStream> { Err(EndOfStream) }
206     ///# fn main() {
207     ///#     read_u8().unwrap();
208     ///# }
209     /// ```
210     ///
211     /// Note that there are crates that simplify creating the error type, e.g.
212     /// [`thiserror`](https://docs.rs/thiserror).
213     pub RESULT_UNIT_ERR,
214     style,
215     "public function returning `Result` with an `Err` type of `()`"
216 }
217
218 #[derive(Copy, Clone)]
219 pub struct Functions {
220     too_many_arguments_threshold: u64,
221     too_many_lines_threshold: u64,
222 }
223
224 impl Functions {
225     pub fn new(too_many_arguments_threshold: u64, too_many_lines_threshold: u64) -> Self {
226         Self {
227             too_many_arguments_threshold,
228             too_many_lines_threshold,
229         }
230     }
231 }
232
233 impl_lint_pass!(Functions => [
234     TOO_MANY_ARGUMENTS,
235     TOO_MANY_LINES,
236     NOT_UNSAFE_PTR_ARG_DEREF,
237     MUST_USE_UNIT,
238     DOUBLE_MUST_USE,
239     MUST_USE_CANDIDATE,
240     RESULT_UNIT_ERR,
241 ]);
242
243 impl<'tcx> LateLintPass<'tcx> for Functions {
244     fn check_fn(
245         &mut self,
246         cx: &LateContext<'tcx>,
247         kind: intravisit::FnKind<'tcx>,
248         decl: &'tcx hir::FnDecl<'_>,
249         body: &'tcx hir::Body<'_>,
250         span: Span,
251         hir_id: hir::HirId,
252     ) {
253         too_many_arguments::check_fn(cx, kind, decl, span, hir_id, self.too_many_arguments_threshold);
254         too_many_lines::check_fn(cx, kind, span, body, self.too_many_lines_threshold);
255         not_unsafe_ptr_arg_deref::check_fn(cx, kind, decl, body, hir_id);
256     }
257
258     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
259         must_use::check_item(cx, item);
260         result_unit_err::check_item(cx, item);
261     }
262
263     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
264         must_use::check_impl_item(cx, item);
265         result_unit_err::check_impl_item(cx, item);
266     }
267
268     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
269         too_many_arguments::check_trait_item(cx, item, self.too_many_arguments_threshold);
270         not_unsafe_ptr_arg_deref::check_trait_item(cx, item);
271         must_use::check_trait_item(cx, item);
272         result_unit_err::check_trait_item(cx, item);
273     }
274 }