1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 //! calculate cyclomatic complexity and warn about overly complex functions
12 use crate::rustc::cfg::CFG;
13 use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
14 use crate::rustc::hir::*;
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
17 use crate::rustc::{declare_tool_lint, lint_array};
18 use crate::syntax::ast::{Attribute, NodeId};
19 use crate::syntax::source_map::Span;
21 use crate::utils::{in_macro, is_allowed, match_type, paths, span_help_and_lint, LimitStack};
23 /// **What it does:** Checks for methods with high cyclomatic complexity.
25 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly
26 /// readable. Also LLVM will usually optimize small methods better.
28 /// **Known problems:** Sometimes it's hard to find a way to reduce the
31 /// **Example:** No. You'll see it when you get the warning.
32 declare_clippy_lint! {
33 pub CYCLOMATIC_COMPLEXITY,
35 "functions that should be split up into multiple functions"
38 pub struct CyclomaticComplexity {
42 impl CyclomaticComplexity {
43 pub fn new(limit: u64) -> Self {
45 limit: LimitStack::new(limit),
50 impl LintPass for CyclomaticComplexity {
51 fn get_lints(&self) -> LintArray {
52 lint_array!(CYCLOMATIC_COMPLEXITY)
56 impl CyclomaticComplexity {
57 fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
62 let cfg = CFG::new(cx.tcx, body);
63 let expr = &body.value;
64 let n = cfg.graph.len_nodes() as u64;
65 let e = cfg.graph.len_edges() as u64;
67 // the function has unreachable code, other lints should catch this
71 let mut helper = CCHelper {
78 helper.visit_expr(expr);
86 let ret_ty = cx.tables.node_id_to_type(expr.hir_id);
87 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
93 if cc + divergence < match_arms + short_circuits {
105 let mut rust_cc = cc + divergence - match_arms - short_circuits;
106 // prevent degenerate cases where unreachable code contains `return` statements
107 if rust_cc >= ret_adjust {
108 rust_cc -= ret_adjust;
110 if rust_cc > self.limit.limit() {
113 CYCLOMATIC_COMPLEXITY,
115 &format!("the function has a cyclomatic complexity of {}", rust_cc),
116 "you could split it up into multiple smaller functions",
123 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity {
126 cx: &LateContext<'a, 'tcx>,
127 _: intravisit::FnKind<'tcx>,
133 let def_id = cx.tcx.hir().local_def_id(node_id);
134 if !cx.tcx.has_attr(def_id, "test") {
135 self.check(cx, body, span);
139 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
140 self.limit.push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
142 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
143 self.limit.pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
147 struct CCHelper<'a, 'tcx: 'a> {
151 short_circuits: u64, // && and ||
152 cx: &'a LateContext<'a, 'tcx>,
155 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
156 fn visit_expr(&mut self, e: &'tcx Expr) {
158 ExprKind::Match(_, ref arms, _) => {
160 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
162 self.match_arms += arms_n - 2;
165 ExprKind::Call(ref callee, _) => {
167 let ty = self.cx.tables.node_id_to_type(callee.hir_id);
169 ty::FnDef(..) | ty::FnPtr(_) => {
170 let sig = ty.fn_sig(self.cx.tcx);
171 if sig.skip_binder().output().sty == ty::Never {
172 self.divergence += 1;
178 ExprKind::Closure(.., _) => (),
179 ExprKind::Binary(op, _, _) => {
182 BinOpKind::And | BinOpKind::Or => self.short_circuits += 1,
186 ExprKind::Ret(_) => self.returns += 1,
187 _ => walk_expr(self, e),
190 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
191 NestedVisitorMap::None
195 #[cfg(feature = "debugging")]
196 #[allow(clippy::too_many_arguments)]
198 _: &LateContext<'_, '_>,
209 "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \
210 div = {}, shorts = {}, returns = {}. Please file a bug report.",
218 #[cfg(not(feature = "debugging"))]
219 #[allow(clippy::too_many_arguments)]
221 cx: &LateContext<'_, '_>,
230 if !is_allowed(cx, CYCLOMATIC_COMPLEXITY, id) {
231 cx.sess().span_note_without_error(
234 "Clippy encountered a bug calculating cyclomatic complexity \
235 (hide this message with `#[allow(cyclomatic_complexity)]`): \
236 cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
237 Please file a bug report.",
238 cc, narms, div, shorts, returns