]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
fmt
[rust.git] / clippy_lints / src / functions.rs
1 use std::convert::TryFrom;
2
3 use crate::utils::{iter_input_pats, snippet, snippet_opt, span_lint, type_is_unsafe_function};
4 use matches::matches;
5 use rustc::hir;
6 use rustc::hir::def::Res;
7 use rustc::hir::intravisit;
8 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
9 use rustc::ty;
10 use rustc::{declare_tool_lint, impl_lint_pass};
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_target::spec::abi::Abi;
13 use syntax::source_map::{BytePos, Span};
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for functions with too many parameters.
17     ///
18     /// **Why is this bad?** 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     /// **Known problems:** None.
23     ///
24     /// **Example:**
25     /// ```rust
26     /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
27     ///     ..
28     /// }
29     /// ```
30     pub TOO_MANY_ARGUMENTS,
31     complexity,
32     "functions with too many arguments"
33 }
34
35 declare_clippy_lint! {
36     /// **What it does:** Checks for functions with a large amount of lines.
37     ///
38     /// **Why is this bad?** Functions with a lot of lines are harder to understand
39     /// due to having to look at a larger amount of code to understand what the
40     /// function is doing. Consider splitting the body of the function into
41     /// multiple functions.
42     ///
43     /// **Known problems:** None.
44     ///
45     /// **Example:**
46     /// ``` rust
47     /// fn im_too_long() {
48     /// println!("");
49     /// // ... 100 more LoC
50     /// println!("");
51     /// }
52     /// ```
53     pub TOO_MANY_LINES,
54     pedantic,
55     "functions with too many lines"
56 }
57
58 declare_clippy_lint! {
59     /// **What it does:** Checks for public functions that dereference raw pointer
60     /// arguments but are not marked unsafe.
61     ///
62     /// **Why is this bad?** The function should probably be marked `unsafe`, since
63     /// for an arbitrary raw pointer, there is no way of telling for sure if it is
64     /// valid.
65     ///
66     /// **Known problems:**
67     ///
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
77     /// pub fn foo(x: *const u8) {
78     ///     println!("{}", unsafe { *x });
79     /// }
80     /// ```
81     pub NOT_UNSAFE_PTR_ARG_DEREF,
82     correctness,
83     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
84 }
85
86 #[derive(Copy, Clone)]
87 pub struct Functions {
88     threshold: u64,
89     max_lines: u64,
90 }
91
92 impl Functions {
93     pub fn new(threshold: u64, max_lines: u64) -> Self {
94         Self { threshold, max_lines }
95     }
96 }
97
98 impl_lint_pass!(Functions => [TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF]);
99
100 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
101     fn check_fn(
102         &mut self,
103         cx: &LateContext<'a, 'tcx>,
104         kind: intravisit::FnKind<'tcx>,
105         decl: &'tcx hir::FnDecl,
106         body: &'tcx hir::Body,
107         span: Span,
108         hir_id: hir::HirId,
109     ) {
110         let is_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
111             matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
112         } else {
113             false
114         };
115
116         let unsafety = match kind {
117             hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
118             hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
119             hir::intravisit::FnKind::Closure(_) => return,
120         };
121
122         // don't warn for implementations, it's not their fault
123         if !is_impl {
124             // don't lint extern functions decls, it's not their fault either
125             match kind {
126                 hir::intravisit::FnKind::Method(
127                     _,
128                     &hir::MethodSig {
129                         header: hir::FnHeader { abi: Abi::Rust, .. },
130                         ..
131                     },
132                     _,
133                     _,
134                 )
135                 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
136                     self.check_arg_number(cx, decl, span)
137                 },
138                 _ => {},
139             }
140         }
141
142         self.check_raw_ptr(cx, unsafety, decl, body, hir_id);
143         self.check_line_number(cx, span, body);
144     }
145
146     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
147         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
148             // don't lint extern functions decls, it's not their fault
149             if sig.header.abi == Abi::Rust {
150                 self.check_arg_number(cx, &sig.decl, item.span);
151             }
152
153             if let hir::TraitMethod::Provided(eid) = *eid {
154                 let body = cx.tcx.hir().body(eid);
155                 self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
156             }
157         }
158     }
159 }
160
161 impl<'a, 'tcx> Functions {
162     fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
163         // Remove the function body from the span. We can't use `SourceMap::def_span` because the
164         // argument list might span multiple lines.
165         let span = if let Some(snippet) = snippet_opt(cx, span) {
166             let snippet = snippet.split('{').nth(0).unwrap_or("").trim_end();
167             if snippet.is_empty() {
168                 span
169             } else {
170                 span.with_hi(BytePos(span.lo().0 + u32::try_from(snippet.len()).unwrap()))
171             }
172         } else {
173             span
174         };
175
176         let args = decl.inputs.len() as u64;
177         if args > self.threshold {
178             span_lint(
179                 cx,
180                 TOO_MANY_ARGUMENTS,
181                 span,
182                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
183             );
184         }
185     }
186
187     fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
188         if in_external_macro(cx.sess(), span) {
189             return;
190         }
191
192         let code_snippet = snippet(cx, body.value.span, "..");
193         let mut line_count: u64 = 0;
194         let mut in_comment = false;
195         let mut code_in_line;
196
197         // Skip the surrounding function decl.
198         let start_brace_idx = match code_snippet.find('{') {
199             Some(i) => i + 1,
200             None => 0,
201         };
202         let end_brace_idx = match code_snippet.find('}') {
203             Some(i) => i,
204             None => code_snippet.len(),
205         };
206         let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
207
208         for mut line in function_lines {
209             code_in_line = false;
210             loop {
211                 line = line.trim_start();
212                 if line.is_empty() {
213                     break;
214                 }
215                 if in_comment {
216                     match line.find("*/") {
217                         Some(i) => {
218                             line = &line[i + 2..];
219                             in_comment = false;
220                             continue;
221                         },
222                         None => break,
223                     }
224                 } else {
225                     let multi_idx = match line.find("/*") {
226                         Some(i) => i,
227                         None => line.len(),
228                     };
229                     let single_idx = match line.find("//") {
230                         Some(i) => i,
231                         None => line.len(),
232                     };
233                     code_in_line |= multi_idx > 0 && single_idx > 0;
234                     // Implies multi_idx is below line.len()
235                     if multi_idx < single_idx {
236                         line = &line[multi_idx + 2..];
237                         in_comment = true;
238                         continue;
239                     }
240                     break;
241                 }
242             }
243             if code_in_line {
244                 line_count += 1;
245             }
246         }
247
248         if line_count > self.max_lines {
249             span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
250         }
251     }
252
253     fn check_raw_ptr(
254         self,
255         cx: &LateContext<'a, 'tcx>,
256         unsafety: hir::Unsafety,
257         decl: &'tcx hir::FnDecl,
258         body: &'tcx hir::Body,
259         hir_id: hir::HirId,
260     ) {
261         let expr = &body.value;
262         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
263             let raw_ptrs = iter_input_pats(decl, body)
264                 .zip(decl.inputs.iter())
265                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
266                 .collect::<FxHashSet<_>>();
267
268             if !raw_ptrs.is_empty() {
269                 let tables = cx.tcx.body_tables(body.id());
270                 let mut v = DerefVisitor {
271                     cx,
272                     ptrs: raw_ptrs,
273                     tables,
274                 };
275
276                 hir::intravisit::walk_expr(&mut v, expr);
277             }
278         }
279     }
280 }
281
282 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<hir::HirId> {
283     if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
284         Some(id)
285     } else {
286         None
287     }
288 }
289
290 struct DerefVisitor<'a, 'tcx> {
291     cx: &'a LateContext<'a, 'tcx>,
292     ptrs: FxHashSet<hir::HirId>,
293     tables: &'a ty::TypeckTables<'tcx>,
294 }
295
296 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
297     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
298         match expr.node {
299             hir::ExprKind::Call(ref f, ref args) => {
300                 let ty = self.tables.expr_ty(f);
301
302                 if type_is_unsafe_function(self.cx, ty) {
303                     for arg in args {
304                         self.check_arg(arg);
305                     }
306                 }
307             },
308             hir::ExprKind::MethodCall(_, _, ref args) => {
309                 let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap();
310                 let base_type = self.cx.tcx.type_of(def_id);
311
312                 if type_is_unsafe_function(self.cx, base_type) {
313                     for arg in args {
314                         self.check_arg(arg);
315                     }
316                 }
317             },
318             hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
319             _ => (),
320         }
321
322         hir::intravisit::walk_expr(self, expr);
323     }
324     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
325         intravisit::NestedVisitorMap::None
326     }
327 }
328
329 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
330     fn check_arg(&self, ptr: &hir::Expr) {
331         if let hir::ExprKind::Path(ref qpath) = ptr.node {
332             if let Res::Local(id) = self.cx.tables.qpath_res(qpath, ptr.hir_id) {
333                 if self.ptrs.contains(&id) {
334                     span_lint(
335                         self.cx,
336                         NOT_UNSAFE_PTR_ARG_DEREF,
337                         ptr.span,
338                         "this public function dereferences a raw pointer but is not marked `unsafe`",
339                     );
340                 }
341             }
342         }
343     }
344 }