]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Adding lint for too many lines.
[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::{LateContext, LateLintPass, LintArray, 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 /// ```
44 declare_clippy_lint! {
45     pub TOO_MANY_LINES,
46     pedantic,
47     "functions with too many lines"
48 }
49
50 /// **What it does:** Checks for public functions that dereferences raw pointer
51 /// arguments but are not marked unsafe.
52 ///
53 /// **Why is this bad?** The function should probably be marked `unsafe`, since
54 /// for an arbitrary raw pointer, there is no way of telling for sure if it is
55 /// valid.
56 ///
57 /// **Known problems:**
58 ///
59 /// * It does not check functions recursively so if the pointer is passed to a
60 /// private non-`unsafe` function which does the dereferencing, the lint won't
61 /// trigger.
62 /// * It only checks for arguments whose type are raw pointers, not raw pointers
63 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
64 /// `some_argument.get_raw_ptr()`).
65 ///
66 /// **Example:**
67 /// ```rust
68 /// pub fn foo(x: *const u8) {
69 ///     println!("{}", unsafe { *x });
70 /// }
71 /// ```
72 declare_clippy_lint! {
73     pub NOT_UNSAFE_PTR_ARG_DEREF,
74     correctness,
75     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
76 }
77
78 #[derive(Copy, Clone)]
79 pub struct Functions {
80     threshold: u64,
81     max_lines: u64
82 }
83
84 impl Functions {
85     pub fn new(threshold: u64, max_lines: u64) -> Self {
86         Self {
87             threshold,
88             max_lines
89         }
90     }
91 }
92
93 impl LintPass for Functions {
94     fn get_lints(&self) -> LintArray {
95         lint_array!(TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF)
96     }
97
98     fn name(&self) -> &'static str {
99         "Functions"
100     }
101 }
102
103 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
104     fn check_fn(
105         &mut self,
106         cx: &LateContext<'a, 'tcx>,
107         kind: intravisit::FnKind<'tcx>,
108         decl: &'tcx hir::FnDecl,
109         body: &'tcx hir::Body,
110         span: Span,
111         nodeid: ast::NodeId,
112     ) {
113         let is_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(nodeid)) {
114             matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
115         } else {
116             false
117         };
118
119         let unsafety = match kind {
120             hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
121             hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
122             hir::intravisit::FnKind::Closure(_) => return,
123         };
124
125         // don't warn for implementations, it's not their fault
126         if !is_impl {
127             // don't lint extern functions decls, it's not their fault either
128             match kind {
129                 hir::intravisit::FnKind::Method(
130                     _,
131                     &hir::MethodSig {
132                         header: hir::FnHeader { abi: Abi::Rust, .. },
133                         ..
134                     },
135                     _,
136                     _,
137                 )
138                 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
139                     self.check_arg_number(cx, decl, span)
140                 },
141                 _ => {},
142             }
143         }
144
145         self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
146         self.check_line_number(cx, span);
147     }
148
149     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
150         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
151             // don't lint extern functions decls, it's not their fault
152             if sig.header.abi == Abi::Rust {
153                 self.check_arg_number(cx, &sig.decl, item.span);
154             }
155
156             if let hir::TraitMethod::Provided(eid) = *eid {
157                 let body = cx.tcx.hir().body(eid);
158                 self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.id);
159             }
160         }
161     }
162 }
163
164 impl<'a, 'tcx> Functions {
165     fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
166         let args = decl.inputs.len() as u64;
167         if args > self.threshold {
168             span_lint(
169                 cx,
170                 TOO_MANY_ARGUMENTS,
171                 span,
172                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
173             );
174         }
175     }
176
177     fn check_line_number(self, cx: &LateContext, span: Span) {
178         let code_snippet = snippet(cx, span, "..");
179         let mut line_count = 0;
180         let mut in_comment = false;
181         for mut line in code_snippet.lines() {
182             if in_comment {
183                 let end_comment_loc = match line.find("*/") {
184                     Some(i) => i,
185                     None => continue
186                 };
187                 in_comment = false;
188                 line = &line[end_comment_loc..];
189             }
190             line = line.trim_left();
191             if line.is_empty() || line.starts_with("//") { continue; }
192             if line.contains("/*") {
193                 let mut count_line: bool = !line.starts_with("/*");
194                 let close_counts = line.match_indices("*/").count();
195                 let open_counts = line.match_indices("/*").count();
196
197                 if close_counts > 1 || open_counts > 1 {
198                     line_count += 1;
199                 } else if close_counts == 1 {
200                     match line.find("*/") {
201                         Some(i) => {
202                             line = line[i..].trim_left();
203                             if !line.is_empty() && !line.starts_with("//") {
204                                 count_line = true;
205                             }
206                         },
207                         None => continue
208                     }
209                 } else {
210                     in_comment = true;
211                 }
212                 if count_line { line_count += 1; }
213             } else {
214                 // No multipart comment, no single comment, non-empty string.
215                 line_count += 1;
216             }
217         }
218
219         if line_count > self.max_lines {
220             span_lint(cx, TOO_MANY_LINES, span,
221                       "This function has a large number of lines.")
222         }
223     }
224
225     fn check_raw_ptr(
226         self,
227         cx: &LateContext<'a, 'tcx>,
228         unsafety: hir::Unsafety,
229         decl: &'tcx hir::FnDecl,
230         body: &'tcx hir::Body,
231         nodeid: ast::NodeId,
232     ) {
233         let expr = &body.value;
234         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
235             let raw_ptrs = iter_input_pats(decl, body)
236                 .zip(decl.inputs.iter())
237                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
238                 .collect::<FxHashSet<_>>();
239
240             if !raw_ptrs.is_empty() {
241                 let tables = cx.tcx.body_tables(body.id());
242                 let mut v = DerefVisitor {
243                     cx,
244                     ptrs: raw_ptrs,
245                     tables,
246                 };
247
248                 hir::intravisit::walk_expr(&mut v, expr);
249             }
250         }
251     }
252 }
253
254 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<ast::NodeId> {
255     if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
256         Some(id)
257     } else {
258         None
259     }
260 }
261
262 struct DerefVisitor<'a, 'tcx: 'a> {
263     cx: &'a LateContext<'a, 'tcx>,
264     ptrs: FxHashSet<ast::NodeId>,
265     tables: &'a ty::TypeckTables<'tcx>,
266 }
267
268 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
269     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
270         match expr.node {
271             hir::ExprKind::Call(ref f, ref args) => {
272                 let ty = self.tables.expr_ty(f);
273
274                 if type_is_unsafe_function(self.cx, ty) {
275                     for arg in args {
276                         self.check_arg(arg);
277                     }
278                 }
279             },
280             hir::ExprKind::MethodCall(_, _, ref args) => {
281                 let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
282                 let base_type = self.cx.tcx.type_of(def_id);
283
284                 if type_is_unsafe_function(self.cx, base_type) {
285                     for arg in args {
286                         self.check_arg(arg);
287                     }
288                 }
289             },
290             hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
291             _ => (),
292         }
293
294         hir::intravisit::walk_expr(self, expr);
295     }
296     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
297         intravisit::NestedVisitorMap::None
298     }
299 }
300
301 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
302     fn check_arg(&self, ptr: &hir::Expr) {
303         if let hir::ExprKind::Path(ref qpath) = ptr.node {
304             if let Def::Local(id) = self.cx.tables.qpath_def(qpath, ptr.hir_id) {
305                 if self.ptrs.contains(&id) {
306                     span_lint(
307                         self.cx,
308                         NOT_UNSAFE_PTR_ARG_DEREF,
309                         ptr.span,
310                         "this public function dereferences a raw pointer but is not marked `unsafe`",
311                     );
312                 }
313             }
314         }
315     }
316 }