lean_ctx/core/
cyclomatic.rs1use serde::Serialize;
7
8#[cfg(feature = "tree-sitter")]
9use tree_sitter::Node;
10
11#[derive(Debug, Clone, PartialEq, Serialize)]
13pub struct FunctionComplexity {
14 pub name: String,
15 pub line: usize,
17 pub cyclomatic: u32,
18}
19
20pub fn cyclomatic_per_function(source: &str, extension: &str) -> Option<Vec<FunctionComplexity>> {
24 #[cfg(feature = "tree-sitter")]
25 {
26 cyclomatic_per_function_impl(source, extension)
27 }
28 #[cfg(not(feature = "tree-sitter"))]
29 {
30 let _ = (source, extension);
31 None
32 }
33}
34
35#[cfg(feature = "tree-sitter")]
36fn cyclomatic_per_function_impl(source: &str, extension: &str) -> Option<Vec<FunctionComplexity>> {
37 let mut out = Vec::new();
38 let src_bytes = source.as_bytes();
39
40 super::chunks_ts::for_each_chunk_node(
41 source,
42 extension,
43 |chunk_root, _chunk_name, _kind, _, _| {
44 let mut fn_nodes = Vec::new();
45 crate::core::ast_walk::for_each_descendant(chunk_root, |node| {
46 if is_fn_like(node.kind()) {
47 fn_nodes.push(node);
48 }
49 });
50
51 for fn_node in fn_nodes {
52 let name = fn_name(fn_node, src_bytes).unwrap_or_else(|| "<anonymous>".to_string());
53 let cyclomatic = cyclomatic_for_fn_like(fn_node, src_bytes, extension);
54 let fn_line = fn_node.start_position().row.saturating_add(1);
55 out.push(FunctionComplexity {
56 name,
57 line: fn_line,
58 cyclomatic,
59 });
60 }
61 },
62 )?;
63
64 if out.is_empty() { None } else { Some(out) }
65}
66
67#[cfg(feature = "tree-sitter")]
68fn is_fn_like(kind: &str) -> bool {
69 matches!(
70 kind,
71 "function_item"
72 | "function_declaration"
73 | "function_definition"
74 | "closure_expression"
75 | "arrow_function"
76 | "method_definition"
77 | "method_declaration"
78 | "constructor_declaration"
79 | "lambda"
80 | "func_literal"
81 )
82}
83
84#[cfg(feature = "tree-sitter")]
85fn fn_name(node: Node, source: &[u8]) -> Option<String> {
86 let mut cursor = node.walk();
87 for child in node.children(&mut cursor) {
88 match child.kind() {
89 "identifier" | "type_identifier" | "property_identifier" | "field_identifier" => {
90 if let Ok(t) = child.utf8_text(source) {
91 return Some(t.to_string());
92 }
93 }
94 _ => {}
95 }
96 }
97 None
98}
99
100#[cfg(feature = "tree-sitter")]
101fn logical_body_root(fn_like: Node<'_>) -> Node<'_> {
102 fn_like
103 .child_by_field_name("body")
104 .or_else(|| fn_like.child_by_field_name("value"))
105 .unwrap_or(fn_like)
106}
107
108#[cfg(feature = "tree-sitter")]
109fn cyclomatic_for_fn_like(fn_node: Node, source: &[u8], ext: &str) -> u32 {
110 let root = logical_body_root(fn_node);
111 1 + count_decisions_skip_nested_fn(root, source, ext)
112}
113
114#[cfg(feature = "tree-sitter")]
115fn count_decisions_skip_nested_fn(root: Node, source: &[u8], ext: &str) -> u32 {
116 let mut sum = 0;
119 crate::core::ast_walk::for_each_descendant_pruned(root, |node| {
120 if node != root && skip_nested_fn_root(node) {
121 return false;
122 }
123 sum += tally_decision(node, source, ext);
124 true
125 });
126 sum
127}
128
129#[cfg(feature = "tree-sitter")]
130fn skip_nested_fn_root(node: Node) -> bool {
131 is_fn_like(node.kind())
132}
133
134#[cfg(feature = "tree-sitter")]
135fn tally_decision(node: Node, source: &[u8], ext: &str) -> u32 {
136 match node.kind() {
137 "if_statement"
138 | "if_expression"
139 | "while_statement"
140 | "while_expression"
141 | "for_statement"
142 | "for_expression"
143 | "do_statement"
144 | "loop_expression"
145 | "case_statement"
146 | "switch_case"
147 | "switch_rule"
148 | "catch_clause"
149 | "except_clause"
150 | "conditional_expression"
151 | "ternary_expression" => 1,
152 "match_arm" => u32::from(matches!(ext, "rs")),
153 "boolean_operator" => python_boolean_operator(node, source),
154 "binary_expression" => binary_boolean_shortcircuit(node, source),
155 _ => 0,
156 }
157}
158
159#[cfg(feature = "tree-sitter")]
160fn python_boolean_operator(node: Node, source: &[u8]) -> u32 {
161 let mut cursor = node.walk();
162 for child in node.children(&mut cursor) {
163 if let Ok(t) = child.utf8_text(source)
164 && (t == "and" || t == "or")
165 {
166 return 1;
167 }
168 }
169 0
170}
171
172#[cfg(feature = "tree-sitter")]
173fn binary_boolean_shortcircuit(node: Node, source: &[u8]) -> u32 {
174 node.child_by_field_name("operator")
175 .and_then(|op| op.utf8_text(source).ok())
176 .map_or(0, |t| u32::from(matches!(t, "&&" | "||" | "and" | "or")))
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 #[cfg(feature = "tree-sitter")]
184 #[test]
185 fn cyclomatic_counts_branches_rust() {
186 let src = r"pub fn f(x: i32) -> i32 {
187 if x > 0 {
188 1
189 } else if x < 0 {
190 -1
191 } else {
192 0
193 }
194}";
195 let v = cyclomatic_per_function(src, "rs").expect("parse");
196 let f = v.iter().find(|e| e.name == "f").expect("fn f");
197 assert!(
198 f.cyclomatic >= 3,
199 "expected >=3 (McCabe paths), got {}",
200 f.cyclomatic
201 );
202 }
203
204 #[cfg(feature = "tree-sitter")]
205 #[test]
206 fn cyclomatic_match_arms_rust() {
207 let src = r"pub fn g(e: u8) -> u8 {
208 match e {
209 0 => 0,
210 1 => 1,
211 _ => 2,
212 }
213}";
214 let v = cyclomatic_per_function(src, "rs").expect("parse");
215 let g = v.iter().find(|e| e.name == "g").expect("fn g");
216 assert!(g.cyclomatic >= 4, "match + arms: got {}", g.cyclomatic);
217 }
218
219 #[cfg(not(feature = "tree-sitter"))]
220 #[test]
221 fn cyclomatic_disabled_returns_none() {
222 assert!(cyclomatic_per_function("fn a() {}", "rs").is_none());
223 }
224}