1 //! calculate cyclomatic complexity and warn about overly complex functions
7 use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
8 use syntax::ast::{Attribute, NodeId};
9 use syntax::codemap::Span;
11 use utils::{in_macro, LimitStack, span_help_and_lint, paths, match_type, is_allowed};
13 /// **What it does:** Checks for methods with high cyclomatic complexity.
15 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly
16 /// readable. Also LLVM will usually optimize small methods better.
18 /// **Known problems:** Sometimes it's hard to find a way to reduce the
21 /// **Example:** No. You'll see it when you get the warning.
23 pub CYCLOMATIC_COMPLEXITY,
25 "functions that should be split up into multiple functions"
28 pub struct CyclomaticComplexity {
32 impl CyclomaticComplexity {
33 pub fn new(limit: u64) -> Self {
34 Self { limit: LimitStack::new(limit) }
38 impl LintPass for CyclomaticComplexity {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(CYCLOMATIC_COMPLEXITY)
44 impl CyclomaticComplexity {
45 fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
50 let cfg = CFG::new(cx.tcx, body);
51 let expr = &body.value;
52 let n = cfg.graph.len_nodes() as u64;
53 let e = cfg.graph.len_edges() as u64;
55 // the function has unreachable code, other lints should catch this
59 let mut helper = CCHelper {
66 helper.visit_expr(expr);
74 let ret_ty = cx.tables.node_id_to_type(expr.hir_id);
75 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
81 if cc + divergence < match_arms + short_circuits {
93 let mut rust_cc = cc + divergence - match_arms - short_circuits;
94 // prevent degenerate cases where unreachable code contains `return` statements
95 if rust_cc >= ret_adjust {
96 rust_cc -= ret_adjust;
98 if rust_cc > self.limit.limit() {
101 CYCLOMATIC_COMPLEXITY,
103 &format!("the function has a cyclomatic complexity of {}", rust_cc),
104 "you could split it up into multiple smaller functions",
111 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity {
114 cx: &LateContext<'a, 'tcx>,
115 _: intravisit::FnKind<'tcx>,
121 let def_id = cx.tcx.hir.local_def_id(node_id);
122 if !cx.tcx.has_attr(def_id, "test") {
123 self.check(cx, body, span);
127 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
128 self.limit.push_attrs(
131 "cyclomatic_complexity",
134 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
135 self.limit.pop_attrs(
138 "cyclomatic_complexity",
143 struct CCHelper<'a, 'tcx: 'a> {
147 short_circuits: u64, // && and ||
148 cx: &'a LateContext<'a, 'tcx>,
151 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
152 fn visit_expr(&mut self, e: &'tcx Expr) {
154 ExprMatch(_, ref arms, _) => {
156 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
158 self.match_arms += arms_n - 2;
161 ExprCall(ref callee, _) => {
163 let ty = self.cx.tables.node_id_to_type(callee.hir_id);
165 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
166 let sig = ty.fn_sig(self.cx.tcx);
167 if sig.skip_binder().output().sty == ty::TyNever {
168 self.divergence += 1;
174 ExprClosure(..) => (),
175 ExprBinary(op, _, _) => {
178 BiAnd | BiOr => self.short_circuits += 1,
182 ExprRet(_) => self.returns += 1,
183 _ => walk_expr(self, e),
186 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
187 NestedVisitorMap::None
191 #[cfg(feature = "debugging")]
192 #[allow(too_many_arguments)]
193 fn report_cc_bug(_: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, _: NodeId) {
196 "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \
197 div = {}, shorts = {}, returns = {}. Please file a bug report.",
205 #[cfg(not(feature = "debugging"))]
206 #[allow(too_many_arguments)]
207 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, id: NodeId) {
208 if !is_allowed(cx, CYCLOMATIC_COMPLEXITY, id) {
209 cx.sess().span_note_without_error(
212 "Clippy encountered a bug calculating cyclomatic complexity \
213 (hide this message with `#[allow(cyclomatic_complexity)]`): \
214 cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
215 Please file a bug report.",