]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
d93344472269dad0546f50827f41605445cf375a
[rust.git] / clippy_lints / src / functions.rs
1 use rustc::lint::*;
2 use rustc::hir;
3 use rustc::hir::intravisit;
4 use syntax::ast;
5 use syntax::codemap::Span;
6 use utils::span_lint;
7
8 /// **What it does:** Check for functions with too many parameters.
9 ///
10 /// **Why is this bad?** Functions with lots of parameters are considered bad style and reduce
11 /// readability (“what does the 5th parameter mean?”). Consider grouping some parameters into a
12 /// new type.
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 ///
18 /// ```
19 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) { .. }
20 /// ```
21 declare_lint! {
22     pub TOO_MANY_ARGUMENTS,
23     Warn,
24     "functions with too many arguments"
25 }
26
27 #[derive(Copy,Clone)]
28 pub struct Functions {
29     threshold: u64,
30 }
31
32 impl Functions {
33     pub fn new(threshold: u64) -> Functions {
34         Functions { threshold: threshold }
35     }
36 }
37
38 impl LintPass for Functions {
39     fn get_lints(&self) -> LintArray {
40         lint_array!(TOO_MANY_ARGUMENTS)
41     }
42 }
43
44 impl LateLintPass for Functions {
45     fn check_fn(&mut self, cx: &LateContext, _: intravisit::FnKind, decl: &hir::FnDecl, _: &hir::Block, span: Span, nodeid: ast::NodeId) {
46         use rustc::hir::map::Node::*;
47
48         if let Some(NodeItem(ref item)) = cx.tcx.map.find(cx.tcx.map.get_parent_node(nodeid)) {
49             match item.node {
50                 hir::ItemImpl(_, _, _, Some(_), _, _) |
51                 hir::ItemDefaultImpl(..) => return,
52                 _ => (),
53             }
54         }
55
56         self.check_arg_number(cx, decl, span);
57     }
58
59     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
60         if let hir::MethodTraitItem(ref sig, _) = item.node {
61             self.check_arg_number(cx, &sig.decl, item.span);
62         }
63     }
64 }
65
66 impl Functions {
67     fn check_arg_number(&self, cx: &LateContext, decl: &hir::FnDecl, span: Span) {
68         let args = decl.inputs.len() as u64;
69         if args > self.threshold {
70             span_lint(cx,
71                       TOO_MANY_ARGUMENTS,
72                       span,
73                       &format!("this function has too many arguments ({}/{})", args, self.threshold));
74         }
75     }
76 }