]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/cyclomatic_complexity.rs
Make the lint docstrings more consistent.
[rust.git] / clippy_lints / src / cyclomatic_complexity.rs
1 //! calculate cyclomatic complexity and warn about overly complex functions
2
3 use rustc::cfg::CFG;
4 use rustc::lint::*;
5 use rustc::ty;
6 use rustc::hir::*;
7 use rustc::hir::intravisit::{Visitor, walk_expr};
8 use syntax::ast::Attribute;
9 use syntax::attr;
10 use syntax::codemap::Span;
11
12 use utils::{in_macro, LimitStack, span_help_and_lint, paths, match_type};
13
14 /// **What it does:** Checks for methods with high cyclomatic complexity.
15 ///
16 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly
17 /// readable. Also LLVM will usually optimize small methods better.
18 ///
19 /// **Known problems:** Sometimes it's hard to find a way to reduce the complexity.
20 ///
21 /// **Example:** No. You'll see it when you get the warning.
22 declare_lint! {
23     pub CYCLOMATIC_COMPLEXITY, Warn,
24     "finds functions that should be split up into multiple functions"
25 }
26
27 pub struct CyclomaticComplexity {
28     limit: LimitStack,
29 }
30
31 impl CyclomaticComplexity {
32     pub fn new(limit: u64) -> Self {
33         CyclomaticComplexity { limit: LimitStack::new(limit) }
34     }
35 }
36
37 impl LintPass for CyclomaticComplexity {
38     fn get_lints(&self) -> LintArray {
39         lint_array!(CYCLOMATIC_COMPLEXITY)
40     }
41 }
42
43 impl CyclomaticComplexity {
44     fn check<'a, 'tcx>(&mut self, cx: &'a LateContext<'a, 'tcx>, block: &Block, span: Span) {
45         if in_macro(cx, span) {
46             return;
47         }
48
49         let cfg = CFG::new(cx.tcx, block);
50         let n = cfg.graph.len_nodes() as u64;
51         let e = cfg.graph.len_edges() as u64;
52         if e + 2 < n {
53             // the function has unreachable code, other lints should catch this
54             return;
55         }
56         let cc = e + 2 - n;
57         let mut helper = CCHelper {
58             match_arms: 0,
59             divergence: 0,
60             short_circuits: 0,
61             returns: 0,
62             tcx: &cx.tcx,
63         };
64         helper.visit_block(block);
65         let CCHelper { match_arms, divergence, short_circuits, returns, .. } = helper;
66         let ret_ty = cx.tcx.node_id_to_type(block.id);
67         let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
68             returns
69         } else {
70             returns / 2
71         };
72
73         if cc + divergence < match_arms + short_circuits {
74             report_cc_bug(cx, cc, match_arms, divergence, short_circuits, ret_adjust, span);
75         } else {
76             let mut rust_cc = cc + divergence - match_arms - short_circuits;
77             // prevent degenerate cases where unreachable code contains `return` statements
78             if rust_cc >= ret_adjust {
79                 rust_cc -= ret_adjust;
80             }
81             if rust_cc > self.limit.limit() {
82                 span_help_and_lint(cx,
83                                    CYCLOMATIC_COMPLEXITY,
84                                    span,
85                                    &format!("the function has a cyclomatic complexity of {}", rust_cc),
86                                    "you could split it up into multiple smaller functions");
87             }
88         }
89     }
90 }
91
92 impl LateLintPass for CyclomaticComplexity {
93     fn check_item(&mut self, cx: &LateContext, item: &Item) {
94         if let ItemFn(_, _, _, _, _, ref block) = item.node {
95             if !attr::contains_name(&item.attrs, "test") {
96                 self.check(cx, block, item.span);
97             }
98         }
99     }
100
101     fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
102         if let ImplItemKind::Method(_, ref block) = item.node {
103             self.check(cx, block, item.span);
104         }
105     }
106
107     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
108         if let MethodTraitItem(_, Some(ref block)) = item.node {
109             self.check(cx, block, item.span);
110         }
111     }
112
113     fn enter_lint_attrs(&mut self, cx: &LateContext, attrs: &[Attribute]) {
114         self.limit.push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
115     }
116     fn exit_lint_attrs(&mut self, cx: &LateContext, attrs: &[Attribute]) {
117         self.limit.pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
118     }
119 }
120
121 struct CCHelper<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
122     match_arms: u64,
123     divergence: u64,
124     returns: u64,
125     short_circuits: u64, // && and ||
126     tcx: &'a ty::TyCtxt<'a, 'gcx, 'tcx>,
127 }
128
129 impl<'a, 'b, 'tcx, 'gcx> Visitor<'a> for CCHelper<'b, 'gcx, 'tcx> {
130     fn visit_expr(&mut self, e: &'a Expr) {
131         match e.node {
132             ExprMatch(_, ref arms, _) => {
133                 walk_expr(self, e);
134                 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
135                 if arms_n > 1 {
136                     self.match_arms += arms_n - 2;
137                 }
138             }
139             ExprCall(ref callee, _) => {
140                 walk_expr(self, e);
141                 let ty = self.tcx.node_id_to_type(callee.id);
142                 match ty.sty {
143                     ty::TyFnDef(_, _, ty) |
144                     ty::TyFnPtr(ty) if ty.sig.skip_binder().output.diverges() => {
145                         self.divergence += 1;
146                     }
147                     _ => (),
148                 }
149             }
150             ExprClosure(..) => (),
151             ExprBinary(op, _, _) => {
152                 walk_expr(self, e);
153                 match op.node {
154                     BiAnd | BiOr => self.short_circuits += 1,
155                     _ => (),
156                 }
157             }
158             ExprRet(_) => self.returns += 1,
159             _ => walk_expr(self, e),
160         }
161     }
162 }
163
164 #[cfg(feature="debugging")]
165 fn report_cc_bug(_: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span) {
166     span_bug!(span,
167               "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \
168                div = {}, shorts = {}, returns = {}. Please file a bug report.",
169               cc,
170               narms,
171               div,
172               shorts,
173               returns);
174 }
175 #[cfg(not(feature="debugging"))]
176 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span) {
177     if cx.current_level(CYCLOMATIC_COMPLEXITY) != Level::Allow {
178         cx.sess().span_note_without_error(span,
179                                           &format!("Clippy encountered a bug calculating cyclomatic complexity \
180                                                     (hide this message with `#[allow(cyclomatic_complexity)]`): \
181                                                     cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
182                                                     Please file a bug report.",
183                                                    cc,
184                                                    narms,
185                                                    div,
186                                                    shorts,
187                                                    returns));
188     }
189 }