|
| 1 | +// Copyright (c) Aptos Foundation |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//! Cyclomatic complexity measures the number of linearly independent execution paths |
| 5 | +//! through a function. A high value generally correlates with code that is |
| 6 | +//! harder to test and maintain. |
| 7 | +//! |
| 8 | +//! This linter performs an approximation while traversing the Move |
| 9 | +//! expression tree: |
| 10 | +//! 1. The complexity score starts at **1**. |
| 11 | +//! 2. The score is incremented for each control-flow decision point found: |
| 12 | +//! * +1 for each `if` |
| 13 | +//! * +1 for each `else if` |
| 14 | +//! * +1 for each `loop`, `while`, or `for` |
| 15 | +//! * +1 for each `break` or `continue` |
| 16 | +//! * +1 for each `return` statement that is not the final expression in the function |
| 17 | +//! * +n where n = (number of match arms - 1) |
| 18 | +//! |
| 19 | +//! When the accumulated score exceeds `DEFAULT_THRESHOLD` (currently **10**), |
| 20 | +//! the linter emits a diagnostic suggesting that the function be simplified or |
| 21 | +//! decomposed. |
| 22 | +//! |
| 23 | +//! NOTE: The threshold is intentionally conservative. |
| 24 | +
|
| 25 | +use crate::utils::{detect_for_loop, detect_while_loop}; |
| 26 | +use move_compiler_v2::external_checks::ExpChecker; |
| 27 | +use move_model::{ |
| 28 | + ast::ExpData, |
| 29 | + model::{FunctionEnv, Loc, NodeId}, |
| 30 | +}; |
| 31 | + |
| 32 | +const DEFAULT_THRESHOLD: i32 = 10; |
| 33 | + |
| 34 | +pub struct CyclomaticComplexity { |
| 35 | + complexity: i32, |
| 36 | + reported: bool, |
| 37 | + root_node: Option<NodeId>, |
| 38 | + final_return_node: Option<NodeId>, |
| 39 | +} |
| 40 | + |
| 41 | +impl CyclomaticComplexity { |
| 42 | + fn bump(&mut self, delta: i32) { |
| 43 | + self.complexity = self.complexity.saturating_add(delta); |
| 44 | + } |
| 45 | + |
| 46 | + /// Returns the NodeId of the final return statement in the function, if any. |
| 47 | + fn get_final_return(function: &FunctionEnv) -> Option<NodeId> { |
| 48 | + if let Some(def) = function.get_def() { |
| 49 | + return Self::get_final_return_from_exp(def); |
| 50 | + } |
| 51 | + None |
| 52 | + } |
| 53 | + |
| 54 | + /// Helper method to recursively find the final return statement in an expression. |
| 55 | + fn get_final_return_from_exp(expr: &move_model::ast::Exp) -> Option<NodeId> { |
| 56 | + use move_model::ast::ExpData::*; |
| 57 | + match expr.as_ref() { |
| 58 | + Return(id, _) => Some(*id), |
| 59 | + Sequence(_, seq) => seq.last().and_then(Self::get_final_return_from_exp), |
| 60 | + Block(_, _, _, body) => Self::get_final_return_from_exp(body), |
| 61 | + _ => None, |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + fn maybe_report(&mut self, function: &FunctionEnv) { |
| 66 | + if self.reported || self.complexity <= DEFAULT_THRESHOLD { |
| 67 | + return; |
| 68 | + } |
| 69 | + let env = function.env(); |
| 70 | + let loc: Loc = function.get_loc(); |
| 71 | + self.reported = true; |
| 72 | + self.report( |
| 73 | + env, |
| 74 | + &loc, |
| 75 | + &format!( |
| 76 | + "Function `{}` has cyclomatic complexity {}, which exceeds the allowed threshold of {}", |
| 77 | + function.get_full_name_str(), |
| 78 | + self.complexity, |
| 79 | + DEFAULT_THRESHOLD, |
| 80 | + ), |
| 81 | + ); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +impl Default for CyclomaticComplexity { |
| 86 | + fn default() -> Self { |
| 87 | + Self { |
| 88 | + complexity: 1, |
| 89 | + reported: false, |
| 90 | + root_node: None, |
| 91 | + final_return_node: None, |
| 92 | + } |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +impl ExpChecker for CyclomaticComplexity { |
| 97 | + fn get_name(&self) -> String { |
| 98 | + "cyclomatic_complexity".to_string() |
| 99 | + } |
| 100 | + |
| 101 | + fn visit_expr_pre(&mut self, function: &FunctionEnv, expr: &ExpData) { |
| 102 | + if self.root_node.is_none() { |
| 103 | + self.root_node = function.get_def().map(|def| def.node_id()); |
| 104 | + self.final_return_node = Self::get_final_return(function); |
| 105 | + } |
| 106 | + |
| 107 | + use ExpData::*; |
| 108 | + |
| 109 | + match expr { |
| 110 | + // loop, while, for |
| 111 | + Loop(_, _) => { |
| 112 | + let delta = if detect_for_loop(expr, function) { |
| 113 | + // For loop expansion generates: Loop(+1) + IfElse(+1) + IfElse(+1) + IfElse(+1) + LoopCont(+1) + LoopCont(+1) = +6 extra |
| 114 | + // But we want for to count as +1 total, so we subtract 4 here |
| 115 | + -4 |
| 116 | + } else if detect_while_loop(expr) { |
| 117 | + // While loop expansion generates: Loop(+1) + IfElse(+1) + LoopCont(+1) = +3 extra |
| 118 | + // But we want while to count as +1 total, so we subtract 1 here |
| 119 | + -1 |
| 120 | + } else { |
| 121 | + 1 |
| 122 | + }; |
| 123 | + self.bump(delta); |
| 124 | + }, |
| 125 | + // if and else if (+1) |
| 126 | + IfElse(..) => self.bump(1), |
| 127 | + // break and continue (+1) |
| 128 | + LoopCont(..) => self.bump(1), |
| 129 | + |
| 130 | + // return, if is not the last statement (+1) |
| 131 | + Return(_, _) => { |
| 132 | + if self.final_return_node != Some(expr.node_id()) { |
| 133 | + self.bump(1); |
| 134 | + } |
| 135 | + }, |
| 136 | + // match (+n-1) |
| 137 | + Match(_, _, arms) if !arms.is_empty() => self.bump(arms.len() as i32 - 1), |
| 138 | + |
| 139 | + _ => {}, |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + fn visit_expr_post(&mut self, function: &FunctionEnv, expr: &ExpData) { |
| 144 | + if let Some(root) = self.root_node { |
| 145 | + if expr.node_id() == root { |
| 146 | + self.maybe_report(function); |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | +} |
0 commit comments