]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions/mod.rs
Auto merge of #9148 - arieluy:then_some_unwrap_or, r=Jarcho
[rust.git] / 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     #[clippy::version = "pre 1.29.0"]
30     pub TOO_MANY_ARGUMENTS,
31     complexity,
32     "functions with too many arguments"
33 }
34
35 declare_clippy_lint! {
36     /// ### What it does
37     /// Checks for functions with a large amount of lines.
38     ///
39     /// ### Why is this bad?
40     /// Functions with a lot of lines are harder to understand
41     /// due to having to look at a larger amount of code to understand what the
42     /// function is doing. Consider splitting the body of the function into
43     /// multiple functions.
44     ///
45     /// ### Example
46     /// ```rust
47     /// fn im_too_long() {
48     ///     println!("");
49     ///     // ... 100 more LoC
50     ///     println!("");
51     /// }
52     /// ```
53     #[clippy::version = "1.34.0"]
54     pub TOO_MANY_LINES,
55     pedantic,
56     "functions with too many lines"
57 }
58
59 declare_clippy_lint! {
60     /// ### What it does
61     /// Checks for public functions that dereference raw pointer
62     /// arguments but are not marked `unsafe`.
63     ///
64     /// ### Why is this bad?
65     /// The function should probably be marked `unsafe`, since
66     /// for an arbitrary raw pointer, there is no way of telling for sure if it is
67     /// valid.
68     ///
69     /// ### Known problems
70     /// * It does not check functions recursively so if the pointer is passed to a
71     /// private non-`unsafe` function which does the dereferencing, the lint won't
72     /// trigger.
73     /// * It only checks for arguments whose type are raw pointers, not raw pointers
74     /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
75     /// `some_argument.get_raw_ptr()`).
76     ///
77     /// ### Example
78     /// ```rust,ignore
79     /// pub fn foo(x: *const u8) {
80     ///     println!("{}", unsafe { *x });
81     /// }
82     /// ```
83     ///
84     /// Use instead:
85     /// ```rust,ignore
86     /// pub unsafe fn foo(x: *const u8) {
87     ///     println!("{}", unsafe { *x });
88     /// }
89     /// ```
90     #[clippy::version = "pre 1.29.0"]
91     pub NOT_UNSAFE_PTR_ARG_DEREF,
92     correctness,
93     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
94 }
95
96 declare_clippy_lint! {
97     /// ### What it does
98     /// Checks for a `#[must_use]` attribute on
99     /// unit-returning functions and methods.
100     ///
101     /// ### Why is this bad?
102     /// Unit values are useless. The attribute is likely
103     /// a remnant of a refactoring that removed the return type.
104     ///
105     /// ### Examples
106     /// ```rust
107     /// #[must_use]
108     /// fn useless() { }
109     /// ```
110     #[clippy::version = "1.40.0"]
111     pub MUST_USE_UNIT,
112     style,
113     "`#[must_use]` attribute on a unit-returning function / method"
114 }
115
116 declare_clippy_lint! {
117     /// ### What it does
118     /// Checks for a `#[must_use]` attribute without
119     /// further information on functions and methods that return a type already
120     /// marked as `#[must_use]`.
121     ///
122     /// ### Why is this bad?
123     /// The attribute isn't needed. Not using the result
124     /// will already be reported. Alternatively, one can add some text to the
125     /// attribute to improve the lint message.
126     ///
127     /// ### Examples
128     /// ```rust
129     /// #[must_use]
130     /// fn double_must_use() -> Result<(), ()> {
131     ///     unimplemented!();
132     /// }
133     /// ```
134     #[clippy::version = "1.40.0"]
135     pub DOUBLE_MUST_USE,
136     style,
137     "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
138 }
139
140 declare_clippy_lint! {
141     /// ### What it does
142     /// Checks for public functions that have no
143     /// `#[must_use]` attribute, but return something not already marked
144     /// must-use, have no mutable arg and mutate no statics.
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     #[clippy::version = "1.40.0"]
165     pub MUST_USE_CANDIDATE,
166     pedantic,
167     "function or method that could take a `#[must_use]` attribute"
168 }
169
170 declare_clippy_lint! {
171     /// ### What it does
172     /// Checks for public functions that return a `Result`
173     /// with an `Err` type of `()`. It suggests using a custom type that
174     /// implements `std::error::Error`.
175     ///
176     /// ### Why is this bad?
177     /// Unit does not implement `Error` and carries no
178     /// further information about what went wrong.
179     ///
180     /// ### Known problems
181     /// Of course, this lint assumes that `Result` is used
182     /// for a fallible operation (which is after all the intended use). However
183     /// code may opt to (mis)use it as a basic two-variant-enum. In that case,
184     /// the suggestion is misguided, and the code should use a custom enum
185     /// instead.
186     ///
187     /// ### Examples
188     /// ```rust
189     /// pub fn read_u8() -> Result<u8, ()> { Err(()) }
190     /// ```
191     /// should become
192     /// ```rust,should_panic
193     /// use std::fmt;
194     ///
195     /// #[derive(Debug)]
196     /// pub struct EndOfStream;
197     ///
198     /// impl fmt::Display for EndOfStream {
199     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200     ///         write!(f, "End of Stream")
201     ///     }
202     /// }
203     ///
204     /// impl std::error::Error for EndOfStream { }
205     ///
206     /// pub fn read_u8() -> Result<u8, EndOfStream> { Err(EndOfStream) }
207     ///# fn main() {
208     ///#     read_u8().unwrap();
209     ///# }
210     /// ```
211     ///
212     /// Note that there are crates that simplify creating the error type, e.g.
213     /// [`thiserror`](https://docs.rs/thiserror).
214     #[clippy::version = "1.49.0"]
215     pub RESULT_UNIT_ERR,
216     style,
217     "public function returning `Result` with an `Err` type of `()`"
218 }
219
220 #[derive(Copy, Clone)]
221 pub struct Functions {
222     too_many_arguments_threshold: u64,
223     too_many_lines_threshold: u64,
224 }
225
226 impl Functions {
227     pub fn new(too_many_arguments_threshold: u64, too_many_lines_threshold: u64) -> Self {
228         Self {
229             too_many_arguments_threshold,
230             too_many_lines_threshold,
231         }
232     }
233 }
234
235 impl_lint_pass!(Functions => [
236     TOO_MANY_ARGUMENTS,
237     TOO_MANY_LINES,
238     NOT_UNSAFE_PTR_ARG_DEREF,
239     MUST_USE_UNIT,
240     DOUBLE_MUST_USE,
241     MUST_USE_CANDIDATE,
242     RESULT_UNIT_ERR,
243 ]);
244
245 impl<'tcx> LateLintPass<'tcx> for Functions {
246     fn check_fn(
247         &mut self,
248         cx: &LateContext<'tcx>,
249         kind: intravisit::FnKind<'tcx>,
250         decl: &'tcx hir::FnDecl<'_>,
251         body: &'tcx hir::Body<'_>,
252         span: Span,
253         hir_id: hir::HirId,
254     ) {
255         too_many_arguments::check_fn(cx, kind, decl, span, hir_id, self.too_many_arguments_threshold);
256         too_many_lines::check_fn(cx, kind, span, body, self.too_many_lines_threshold);
257         not_unsafe_ptr_arg_deref::check_fn(cx, kind, decl, body, hir_id);
258     }
259
260     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
261         must_use::check_item(cx, item);
262         result_unit_err::check_item(cx, item);
263     }
264
265     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
266         must_use::check_impl_item(cx, item);
267         result_unit_err::check_impl_item(cx, item);
268     }
269
270     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
271         too_many_arguments::check_trait_item(cx, item, self.too_many_arguments_threshold);
272         not_unsafe_ptr_arg_deref::check_trait_item(cx, item);
273         must_use::check_trait_item(cx, item);
274         result_unit_err::check_trait_item(cx, item);
275     }
276 }