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