1 //! calculate cyclomatic complexity and warn about overly complex functions
3 use crate::rustc::cfg::CFG;
4 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, LintContext};
5 use crate::rustc::{declare_tool_lint, lint_array};
6 use crate::rustc::hir::*;
8 use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
9 use crate::syntax::ast::{Attribute, NodeId};
10 use crate::syntax::source_map::Span;
12 use crate::utils::{in_macro, is_allowed, match_type, paths, span_help_and_lint, LimitStack};
14 /// **What it does:** Checks for methods with high cyclomatic complexity.
16 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly
17 /// readable. Also LLVM will usually optimize small methods better.
19 /// **Known problems:** Sometimes it's hard to find a way to reduce the
22 /// **Example:** No. You'll see it when you get the warning.
23 declare_clippy_lint! {
24 pub CYCLOMATIC_COMPLEXITY,
26 "functions that should be split up into multiple functions"
29 pub struct CyclomaticComplexity {
33 impl CyclomaticComplexity {
34 pub fn new(limit: u64) -> Self {
36 limit: LimitStack::new(limit),
41 impl LintPass for CyclomaticComplexity {
42 fn get_lints(&self) -> LintArray {
43 lint_array!(CYCLOMATIC_COMPLEXITY)
47 impl CyclomaticComplexity {
48 fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
53 let cfg = CFG::new(cx.tcx, body);
54 let expr = &body.value;
55 let n = cfg.graph.len_nodes() as u64;
56 let e = cfg.graph.len_edges() as u64;
58 // the function has unreachable code, other lints should catch this
62 let mut helper = CCHelper {
69 helper.visit_expr(expr);
77 let ret_ty = cx.tables.node_id_to_type(expr.hir_id);
78 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
84 if cc + divergence < match_arms + short_circuits {
96 let mut rust_cc = cc + divergence - match_arms - short_circuits;
97 // prevent degenerate cases where unreachable code contains `return` statements
98 if rust_cc >= ret_adjust {
99 rust_cc -= ret_adjust;
101 if rust_cc > self.limit.limit() {
104 CYCLOMATIC_COMPLEXITY,
106 &format!("the function has a cyclomatic complexity of {}", rust_cc),
107 "you could split it up into multiple smaller functions",
114 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CyclomaticComplexity {
117 cx: &LateContext<'a, 'tcx>,
118 _: intravisit::FnKind<'tcx>,
124 let def_id = cx.tcx.hir.local_def_id(node_id);
125 if !cx.tcx.has_attr(def_id, "test") {
126 self.check(cx, body, span);
130 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
132 .push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
134 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
136 .pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
140 struct CCHelper<'a, 'tcx: 'a> {
144 short_circuits: u64, // && and ||
145 cx: &'a LateContext<'a, 'tcx>,
148 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
149 fn visit_expr(&mut self, e: &'tcx Expr) {
151 ExprKind::Match(_, ref arms, _) => {
153 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
155 self.match_arms += arms_n - 2;
158 ExprKind::Call(ref callee, _) => {
160 let ty = self.cx.tables.node_id_to_type(callee.hir_id);
162 ty::FnDef(..) | ty::FnPtr(_) => {
163 let sig = ty.fn_sig(self.cx.tcx);
164 if sig.skip_binder().output().sty == ty::Never {
165 self.divergence += 1;
171 ExprKind::Closure(.., _) => (),
172 ExprKind::Binary(op, _, _) => {
175 BinOpKind::And | BinOpKind::Or => self.short_circuits += 1,
179 ExprKind::Ret(_) => self.returns += 1,
180 _ => walk_expr(self, e),
183 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
184 NestedVisitorMap::None
188 #[cfg(feature = "debugging")]
189 #[allow(clippy::too_many_arguments)]
190 fn report_cc_bug(_: &LateContext<'_, '_>, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, _: NodeId) {
193 "Clippy encountered a bug calculating cyclomatic complexity: cc = {}, arms = {}, \
194 div = {}, shorts = {}, returns = {}. Please file a bug report.",
202 #[cfg(not(feature = "debugging"))]
203 #[allow(clippy::too_many_arguments)]
204 fn report_cc_bug(cx: &LateContext<'_, '_>, cc: u64, narms: u64, div: u64, shorts: u64, returns: u64, span: Span, id: NodeId) {
205 if !is_allowed(cx, CYCLOMATIC_COMPLEXITY, id) {
206 cx.sess().span_note_without_error(
209 "Clippy encountered a bug calculating cyclomatic complexity \
210 (hide this message with `#[allow(cyclomatic_complexity)]`): \
211 cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
212 Please file a bug report.",