]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/cyclomatic_complexity.rs
Merge pull request #1862 from messense/feature/fix-nightly-06-28
[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::hir::*;
6 use rustc::ty;
7 use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
8 use syntax::ast::{Attribute, NodeId};
9 use syntax::codemap::Span;
10
11 use utils::{in_macro, LimitStack, span_help_and_lint, paths, match_type};
12
13 /// **What it does:** Checks for methods with high cyclomatic complexity.
14 ///
15 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly
16 /// 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! {
22     pub CYCLOMATIC_COMPLEXITY,
23     Warn,
24     "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: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
45         if in_macro(span) {
46             return;
47         }
48
49         let cfg = CFG::new(cx.tcx, body);
50         let expr = &body.value;
51         let n = cfg.graph.len_nodes() as u64;
52         let e = cfg.graph.len_edges() as u64;
53         if e + 2 < n {
54             // the function has unreachable code, other lints should catch this
55             return;
56         }
57         let cc = e + 2 - n;
58         let mut helper = CCHelper {
59             match_arms: 0,
60             divergence: 0,
61             short_circuits: 0,
62             returns: 0,
63             cx: cx,
64         };
65         helper.visit_expr(expr);
66         let CCHelper { match_arms, divergence, short_circuits, returns, .. } = helper;
67         let ret_ty = cx.tables.node_id_to_type(expr.id);
68         let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
69             returns
70         } else {
71             returns / 2
72         };
73
74         if cc + divergence < match_arms + short_circuits {
75             report_cc_bug(cx, cc, match_arms, divergence, short_circuits, ret_adjust, span);
76         } else {
77             let mut rust_cc = cc + divergence - match_arms - short_circuits;
78             // prevent degenerate cases where unreachable code contains `return` statements
79             if rust_cc >= ret_adjust {
80                 rust_cc -= ret_adjust;
81             }
82             if rust_cc > self.limit.limit() {
83                 span_help_and_lint(cx,
84                                    CYCLOMATIC_COMPLEXITY,
85                                    span,
86                                    &format!("the function has a cyclomatic complexity of {}", rust_cc),
87                                    "you could split it up into multiple smaller functions");
88             }
89         }
90     }
91 }
92
93 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity {
94     fn check_fn(
95         &mut self,
96         cx: &LateContext<'a, 'tcx>,
97         _: intravisit::FnKind<'tcx>,
98         _: &'tcx FnDecl,
99         body: &'tcx Body,
100         span: Span,
101         node_id: NodeId
102     ) {
103         let def_id = cx.tcx.hir.local_def_id(node_id);
104         if !cx.tcx.has_attr(def_id, "test") {
105             self.check(cx, body, span);
106         }
107     }
108
109     fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
110         self.limit.push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
111     }
112     fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
113         self.limit.pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
114     }
115 }
116
117 struct CCHelper<'a, 'tcx: 'a> {
118     match_arms: u64,
119     divergence: u64,
120     returns: u64,
121     short_circuits: u64, // && and ||
122     cx: &'a LateContext<'a, 'tcx>,
123 }
124
125 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
126     fn visit_expr(&mut self, e: &'tcx Expr) {
127         match e.node {
128             ExprMatch(_, ref arms, _) => {
129                 walk_expr(self, e);
130                 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
131                 if arms_n > 1 {
132                     self.match_arms += arms_n - 2;
133                 }
134             },
135             ExprCall(ref callee, _) => {
136                 walk_expr(self, e);
137                 let ty = self.cx.tables.node_id_to_type(callee.id);
138                 match ty.sty {
139                     ty::TyFnDef(..) | ty::TyFnPtr(_) => {
140                         let sig = ty.fn_sig(self.cx.tcx);
141                         if sig.skip_binder().output().sty == ty::TyNever {
142                             self.divergence += 1;
143                         }
144                     },
145                     _ => (),
146                 }
147             },
148             ExprClosure(..) => (),
149             ExprBinary(op, _, _) => {
150                 walk_expr(self, e);
151                 match op.node {
152                     BiAnd | BiOr => self.short_circuits += 1,
153                     _ => (),
154                 }
155             },
156             ExprRet(_) => self.returns += 1,
157             _ => walk_expr(self, e),
158         }
159     }
160     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
161         NestedVisitorMap::None
162     }
163 }
164
165 #[cfg(feature="debugging")]
166 fn report_cc_bug(_: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span) {
167     span_bug!(span,
168               "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \
169                div = {}, shorts = {}, returns = {}. Please file a bug report.",
170               cc,
171               narms,
172               div,
173               shorts,
174               returns);
175 }
176 #[cfg(not(feature="debugging"))]
177 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span) {
178     if cx.current_level(CYCLOMATIC_COMPLEXITY) != Level::Allow {
179         cx.sess().span_note_without_error(span,
180                                           &format!("Clippy encountered a bug calculating cyclomatic complexity \
181                                                     (hide this message with `#[allow(cyclomatic_complexity)]`): \
182                                                     cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
183                                                     Please file a bug report.",
184                                                    cc,
185                                                    narms,
186                                                    div,
187                                                    shorts,
188                                                    returns));
189     }
190 }