Skip to main content

cha_core/plugins/
switch_statement.rs

1use crate::{AnalysisContext, Finding, Location, Plugin, Severity, SmellCategory};
2
3/// Detect functions with excessive switch/match arms.
4pub struct SwitchStatementAnalyzer {
5    pub max_arms: usize,
6}
7
8impl Default for SwitchStatementAnalyzer {
9    fn default() -> Self {
10        Self { max_arms: 8 }
11    }
12}
13
14impl Plugin for SwitchStatementAnalyzer {
15    fn name(&self) -> &str {
16        "switch_statement"
17    }
18
19    fn smells(&self) -> Vec<String> {
20        vec!["switch_statement".into()]
21    }
22
23    fn description(&self) -> &str {
24        "Excessive switch/match arms"
25    }
26
27    fn analyze(&self, ctx: &AnalysisContext) -> Vec<Finding> {
28        ctx.model
29            .functions
30            .iter()
31            .filter(|f| f.switch_arms > self.max_arms)
32            .map(|f| Finding {
33                smell_name: "switch_statement".into(),
34                category: SmellCategory::OoAbusers,
35                severity: Severity::Warning,
36                location: Location {
37                    path: ctx.file.path.clone(),
38                    start_line: f.start_line,
39                    start_col: f.name_col,
40                    end_line: f.start_line,
41                    end_col: f.name_end_col,
42                    name: Some(f.name.clone()),
43                },
44                message: format!(
45                    "Function `{}` has {} switch/match arms (threshold: {})",
46                    f.name, f.switch_arms, self.max_arms
47                ),
48                suggested_refactorings: vec!["Replace Conditional with Polymorphism".into()],
49                actual_value: Some(f.switch_arms as f64),
50                threshold: Some(self.max_arms as f64),
51            })
52            .collect()
53    }
54}