]> git.lizzy.rs Git - rust.git/blob - src/cyclomatic_complexity.rs
Remove * dep
[rust.git] / src / cyclomatic_complexity.rs
1 //! calculate cyclomatic complexity and warn about overly complex functions
2
3 use rustc::lint::*;
4 use rustc_front::hir::*;
5 use rustc::middle::cfg::CFG;
6 use rustc::middle::ty;
7 use syntax::codemap::Span;
8 use syntax::attr::*;
9 use syntax::ast::Attribute;
10 use rustc_front::intravisit::{Visitor, walk_expr};
11
12 use utils::{in_macro, LimitStack};
13
14 /// **What it does:** It `Warn`s on methods with high cyclomatic complexity
15 ///
16 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly readable. Also LLVM will usually optimize small methods better.
17 ///
18 /// **Known problems:** Sometimes it's hard to find a way to reduce the complexity
19 ///
20 /// **Example:** No. You'll see it when you get the warning.
21 declare_lint! { pub CYCLOMATIC_COMPLEXITY, Warn,
22     "finds functions that should be split up into multiple functions" }
23
24 pub struct CyclomaticComplexity {
25     limit: LimitStack,
26 }
27
28 impl CyclomaticComplexity {
29     pub fn new(limit: u64) -> Self {
30         CyclomaticComplexity {
31             limit: LimitStack::new(limit),
32         }
33     }
34 }
35
36 impl LintPass for CyclomaticComplexity {
37     fn get_lints(&self) -> LintArray {
38         lint_array!(CYCLOMATIC_COMPLEXITY)
39     }
40 }
41
42 impl CyclomaticComplexity {
43     fn check<'a, 'tcx>(&mut self, cx: &'a LateContext<'a, 'tcx>, block: &Block, span: Span) {
44         if in_macro(cx, span) { return; }
45         let cfg = CFG::new(cx.tcx, block);
46         let n = cfg.graph.len_nodes() as u64;
47         let e = cfg.graph.len_edges() as u64;
48         let cc = e + 2 - n;
49         let mut arm_counter = MatchArmCounter(0);
50         arm_counter.visit_block(block);
51         let narms = arm_counter.0;
52
53         let mut diverge_counter = DivergenceCounter(0, &cx.tcx);
54         diverge_counter.visit_block(block);
55         let divergence = diverge_counter.0;
56
57         if cc + divergence < narms {
58             report_cc_bug(cx, cc, narms, divergence, span);
59         } else {
60             let rust_cc = cc + divergence - narms;
61             if rust_cc > self.limit.limit() {
62                 cx.span_lint_help(CYCLOMATIC_COMPLEXITY, span,
63                 &format!("The function has a cyclomatic complexity of {}.", rust_cc),
64                 "You could split it up into multiple smaller functions");
65             }
66         }
67     }
68 }
69
70 impl LateLintPass for CyclomaticComplexity {
71     fn check_item(&mut self, cx: &LateContext, item: &Item) {
72         if let ItemFn(_, _, _, _, _, ref block) = item.node {
73             self.check(cx, block, item.span);
74         }
75     }
76
77     fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
78         if let ImplItemKind::Method(_, ref block) = item.node {
79             self.check(cx, block, item.span);
80         }
81     }
82
83     fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
84         if let MethodTraitItem(_, Some(ref block)) = item.node {
85             self.check(cx, block, item.span);
86         }
87     }
88
89     fn enter_lint_attrs(&mut self, cx: &LateContext, attrs: &[Attribute]) {
90         self.limit.push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
91     }
92     fn exit_lint_attrs(&mut self, cx: &LateContext, attrs: &[Attribute]) {
93         self.limit.pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
94     }
95 }
96
97 struct MatchArmCounter(u64);
98
99 impl<'a> Visitor<'a> for MatchArmCounter {
100     fn visit_expr(&mut self, e: &'a Expr) {
101         match e.node {
102             ExprMatch(_, ref arms, _) => {
103                 walk_expr(self, e);
104                 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
105                 if arms_n > 1 {
106                     self.0 += arms_n - 2;
107                 }
108             },
109             ExprClosure(..) => {},
110             _ => walk_expr(self, e),
111         }
112     }
113 }
114
115 struct DivergenceCounter<'a, 'tcx: 'a>(u64, &'a ty::ctxt<'tcx>);
116
117 impl<'a, 'b, 'tcx> Visitor<'a> for DivergenceCounter<'b, 'tcx> {
118     fn visit_expr(&mut self, e: &'a Expr) {
119         match e.node {
120             ExprCall(ref callee, _) => {
121                 walk_expr(self, e);
122                 let ty = self.1.node_id_to_type(callee.id);
123                 if let ty::TyBareFn(_, ty) = ty.sty {
124                     if ty.sig.skip_binder().output.diverges() {
125                         self.0 += 1;
126                     }
127                 }
128             },
129             ExprClosure(..) => {},
130             _ => walk_expr(self, e),
131         }
132     }
133 }
134
135 #[cfg(feature="debugging")]
136 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, span: Span) {
137     cx.sess().span_bug(span, &format!("Clippy encountered a bug calculating cyclomatic complexity: \
138                                        cc = {}, arms = {}, div = {}. Please file a bug report.", cc, narms, div));;
139 }
140 #[cfg(not(feature="debugging"))]
141 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, span: Span) {
142     if cx.current_level(CYCLOMATIC_COMPLEXITY) != Level::Allow {
143         cx.sess().span_note(span, &format!("Clippy encountered a bug calculating cyclomatic complexity \
144                                             (hide this message with `#[allow(cyclomatic_complexity)]`): \
145                                             cc = {}, arms = {}, div = {}. Please file a bug report.", cc, narms, div));
146     }
147 }