]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/cyclomatic_complexity.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / tools / clippy / 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::{walk_expr, NestedVisitorMap, Visitor};
8 use syntax::ast::{Attribute, NodeId};
9 use syntax::codemap::Span;
10
11 use utils::{in_macro, is_allowed, match_type, paths, span_help_and_lint, LimitStack};
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
19 /// complexity.
20 ///
21 /// **Example:** No. You'll see it when you get the warning.
22 declare_lint! {
23 pub CYCLOMATIC_COMPLEXITY,
24 Warn,
25 "functions that should be split up into multiple functions"
26 }
27
28 pub struct CyclomaticComplexity {
29 limit: LimitStack,
30 }
31
32 impl CyclomaticComplexity {
33 pub fn new(limit: u64) -> Self {
34 Self {
35 limit: LimitStack::new(limit),
36 }
37 }
38 }
39
40 impl LintPass for CyclomaticComplexity {
41 fn get_lints(&self) -> LintArray {
42 lint_array!(CYCLOMATIC_COMPLEXITY)
43 }
44 }
45
46 impl CyclomaticComplexity {
47 fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
48 if in_macro(span) {
49 return;
50 }
51
52 let cfg = CFG::new(cx.tcx, body);
53 let expr = &body.value;
54 let n = cfg.graph.len_nodes() as u64;
55 let e = cfg.graph.len_edges() as u64;
56 if e + 2 < n {
57 // the function has unreachable code, other lints should catch this
58 return;
59 }
60 let cc = e + 2 - n;
61 let mut helper = CCHelper {
62 match_arms: 0,
63 divergence: 0,
64 short_circuits: 0,
65 returns: 0,
66 cx: cx,
67 };
68 helper.visit_expr(expr);
69 let CCHelper {
70 match_arms,
71 divergence,
72 short_circuits,
73 returns,
74 ..
75 } = helper;
76 let ret_ty = cx.tables.node_id_to_type(expr.hir_id);
77 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
78 returns
79 } else {
80 returns / 2
81 };
82
83 if cc + divergence < match_arms + short_circuits {
84 report_cc_bug(
85 cx,
86 cc,
87 match_arms,
88 divergence,
89 short_circuits,
90 ret_adjust,
91 span,
92 body.id().node_id,
93 );
94 } else {
95 let mut rust_cc = cc + divergence - match_arms - short_circuits;
96 // prevent degenerate cases where unreachable code contains `return` statements
97 if rust_cc >= ret_adjust {
98 rust_cc -= ret_adjust;
99 }
100 if rust_cc > self.limit.limit() {
101 span_help_and_lint(
102 cx,
103 CYCLOMATIC_COMPLEXITY,
104 span,
105 &format!("the function has a cyclomatic complexity of {}", rust_cc),
106 "you could split it up into multiple smaller functions",
107 );
108 }
109 }
110 }
111 }
112
113 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity {
114 fn check_fn(
115 &mut self,
116 cx: &LateContext<'a, 'tcx>,
117 _: intravisit::FnKind<'tcx>,
118 _: &'tcx FnDecl,
119 body: &'tcx Body,
120 span: Span,
121 node_id: NodeId,
122 ) {
123 let def_id = cx.tcx.hir.local_def_id(node_id);
124 if !cx.tcx.has_attr(def_id, "test") {
125 self.check(cx, body, span);
126 }
127 }
128
129 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
130 self.limit
131 .push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
132 }
133 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
134 self.limit
135 .pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
136 }
137 }
138
139 struct CCHelper<'a, 'tcx: 'a> {
140 match_arms: u64,
141 divergence: u64,
142 returns: u64,
143 short_circuits: u64, // && and ||
144 cx: &'a LateContext<'a, 'tcx>,
145 }
146
147 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
148 fn visit_expr(&mut self, e: &'tcx Expr) {
149 match e.node {
150 ExprMatch(_, ref arms, _) => {
151 walk_expr(self, e);
152 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
153 if arms_n > 1 {
154 self.match_arms += arms_n - 2;
155 }
156 },
157 ExprCall(ref callee, _) => {
158 walk_expr(self, e);
159 let ty = self.cx.tables.node_id_to_type(callee.hir_id);
160 match ty.sty {
161 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
162 let sig = ty.fn_sig(self.cx.tcx);
163 if sig.skip_binder().output().sty == ty::TyNever {
164 self.divergence += 1;
165 }
166 },
167 _ => (),
168 }
169 },
170 ExprClosure(.., _) => (),
171 ExprBinary(op, _, _) => {
172 walk_expr(self, e);
173 match op.node {
174 BiAnd | BiOr => self.short_circuits += 1,
175 _ => (),
176 }
177 },
178 ExprRet(_) => self.returns += 1,
179 _ => walk_expr(self, e),
180 }
181 }
182 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
183 NestedVisitorMap::None
184 }
185 }
186
187 #[cfg(feature = "debugging")]
188 #[allow(too_many_arguments)]
189 fn report_cc_bug(_: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, _: NodeId) {
190 span_bug!(
191 span,
192 "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \
193 div = {}, shorts = {}, returns = {}. Please file a bug report.",
194 cc,
195 narms,
196 div,
197 shorts,
198 returns
199 );
200 }
201 #[cfg(not(feature = "debugging"))]
202 #[allow(too_many_arguments)]
203 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, id: NodeId) {
204 if !is_allowed(cx, CYCLOMATIC_COMPLEXITY, id) {
205 cx.sess().span_note_without_error(
206 span,
207 &format!(
208 "Clippy encountered a bug calculating cyclomatic complexity \
209 (hide this message with `#[allow(cyclomatic_complexity)]`): \
210 cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
211 Please file a bug report.",
212 cc,
213 narms,
214 div,
215 shorts,
216 returns
217 ),
218 );
219 }
220 }