Skip to main content

code_split_core/
stats.rs

1use crate::graph::{AvgCoupling, Graph, GraphStats, Halstead, Loc, Maintainability, Node};
2
3pub fn annotate_stats(graph: &mut Graph) {
4    fn avg<F>(nodes: &[Node], f: F) -> f64
5    where
6        F: Fn(&Node) -> Option<f64>,
7    {
8        let vals: Vec<f64> = nodes
9            .iter()
10            .filter_map(f)
11            .filter(|v| v.is_finite() && *v > 0.0)
12            .collect();
13        if vals.is_empty() {
14            return 0.0;
15        }
16        vals.iter().sum::<f64>() / vals.len() as f64
17    }
18
19    let nodes = &graph.nodes;
20
21    let cyclomatic = avg(nodes, |n| n.complexity.as_ref().map(|c| c.cyclomatic));
22    let cognitive = avg(nodes, |n| n.complexity.as_ref().map(|c| c.cognitive));
23
24    let fan_in = avg(nodes, |n| {
25        n.complexity
26            .as_ref()
27            .and_then(|c| c.coupling.as_ref())
28            .map(|c| c.fan_in as f64)
29    });
30    let fan_out = avg(nodes, |n| {
31        n.complexity
32            .as_ref()
33            .and_then(|c| c.coupling.as_ref())
34            .map(|c| c.fan_out as f64)
35    });
36    let hk = avg(nodes, |n| {
37        n.complexity
38            .as_ref()
39            .and_then(|c| c.coupling.as_ref())
40            .map(|c| c.hk)
41    });
42    let coupling = (fan_in > 0.0 || fan_out > 0.0 || hk > 0.0).then_some(AvgCoupling {
43        fan_in,
44        fan_out,
45        hk,
46    });
47
48    let mi = avg(nodes, |n| {
49        n.complexity
50            .as_ref()
51            .and_then(|c| c.maintainability.as_ref())
52            .map(|m| m.mi)
53    });
54    let mi_sei = avg(nodes, |n| {
55        n.complexity
56            .as_ref()
57            .and_then(|c| c.maintainability.as_ref())
58            .map(|m| m.mi_sei)
59    });
60    let maintainability = (mi > 0.0).then_some(Maintainability { mi, mi_sei });
61
62    let loc_source = avg(nodes, |n| {
63        n.complexity
64            .as_ref()
65            .and_then(|c| c.loc.as_ref())
66            .map(|l| l.source)
67    });
68    let loc_comments = avg(nodes, |n| {
69        n.complexity
70            .as_ref()
71            .and_then(|c| c.loc.as_ref())
72            .map(|l| l.comments)
73    });
74    let loc_blank = avg(nodes, |n| {
75        n.complexity
76            .as_ref()
77            .and_then(|c| c.loc.as_ref())
78            .map(|l| l.blank)
79    });
80    let loc = (loc_source > 0.0).then_some(Loc {
81        source: loc_source,
82        logical: 0.0,
83        comments: loc_comments,
84        blank: loc_blank,
85    });
86
87    let h_length = avg(nodes, |n| {
88        n.complexity
89            .as_ref()
90            .and_then(|c| c.halstead.as_ref())
91            .map(|h| h.length)
92    });
93    let h_vocabulary = avg(nodes, |n| {
94        n.complexity
95            .as_ref()
96            .and_then(|c| c.halstead.as_ref())
97            .map(|h| h.vocabulary)
98    });
99    let h_volume = avg(nodes, |n| {
100        n.complexity
101            .as_ref()
102            .and_then(|c| c.halstead.as_ref())
103            .map(|h| h.volume)
104    });
105    let h_effort = avg(nodes, |n| {
106        n.complexity
107            .as_ref()
108            .and_then(|c| c.halstead.as_ref())
109            .map(|h| h.effort)
110    });
111    let h_time = avg(nodes, |n| {
112        n.complexity
113            .as_ref()
114            .and_then(|c| c.halstead.as_ref())
115            .map(|h| h.time)
116    });
117    let h_bugs = avg(nodes, |n| {
118        n.complexity
119            .as_ref()
120            .and_then(|c| c.halstead.as_ref())
121            .map(|h| h.bugs)
122    });
123    let halstead = (h_volume > 0.0).then_some(Halstead {
124        length: h_length,
125        vocabulary: h_vocabulary,
126        volume: h_volume,
127        effort: h_effort,
128        time: h_time,
129        bugs: h_bugs,
130    });
131
132    if cyclomatic == 0.0
133        && cognitive == 0.0
134        && coupling.is_none()
135        && maintainability.is_none()
136        && loc.is_none()
137        && halstead.is_none()
138    {
139        return;
140    }
141
142    graph.stats = Some(GraphStats {
143        cyclomatic,
144        cognitive,
145        coupling,
146        maintainability,
147        loc,
148        halstead,
149    });
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::graph::{Complexity, Coupling, NodeKind};
156
157    fn node(id: &str, complexity: Option<Complexity>) -> Node {
158        Node {
159            id: id.into(),
160            kind: NodeKind::Fn,
161            name: id.into(),
162            path: String::new(),
163            parent: None,
164            external: None,
165            visibility: None,
166            loc: None,
167            line: None,
168            item_count: None,
169            method_count: None,
170            complexity,
171            cycle_kind: None,
172        }
173    }
174
175    fn graph_of(nodes: Vec<Node>) -> Graph {
176        Graph {
177            nodes,
178            edges: Vec::new(),
179            cycles: Vec::new(),
180            stats: None,
181        }
182    }
183
184    #[test]
185    fn empty_graph_leaves_stats_none() {
186        let mut g = graph_of(vec![]);
187        annotate_stats(&mut g);
188        assert!(g.stats.is_none());
189    }
190
191    #[test]
192    fn nodes_without_complexity_leave_stats_none() {
193        let mut g = graph_of(vec![node("a", None), node("b", None)]);
194        annotate_stats(&mut g);
195        assert!(g.stats.is_none(), "no metrics → no stats block");
196    }
197
198    #[test]
199    fn all_zero_metrics_leave_stats_none() {
200        let mut g = graph_of(vec![node(
201            "a",
202            Some(Complexity {
203                cyclomatic: 0.0,
204                ..Default::default()
205            }),
206        )]);
207        annotate_stats(&mut g);
208        assert!(g.stats.is_none(), "all-zero metrics → early return");
209    }
210
211    #[test]
212    fn cyclomatic_average_excludes_zero_and_missing() {
213        // 2.0 and 4.0 count; the 0.0 node is filtered (avg over > 0 only) and
214        // the complexity-less node contributes nothing → (2+4)/2 = 3.0.
215        let mut g = graph_of(vec![
216            node(
217                "a",
218                Some(Complexity {
219                    cyclomatic: 2.0,
220                    ..Default::default()
221                }),
222            ),
223            node(
224                "b",
225                Some(Complexity {
226                    cyclomatic: 4.0,
227                    ..Default::default()
228                }),
229            ),
230            node(
231                "z",
232                Some(Complexity {
233                    cyclomatic: 0.0,
234                    ..Default::default()
235                }),
236            ),
237            node("n", None),
238        ]);
239        annotate_stats(&mut g);
240        let stats = g.stats.expect("metrics present → stats block");
241        assert_eq!(stats.cyclomatic, 3.0, "(2+4)/2, zero excluded");
242    }
243
244    #[test]
245    fn coupling_is_averaged_and_attached() {
246        let mut g = graph_of(vec![
247            node(
248                "a",
249                Some(Complexity {
250                    coupling: Some(Coupling {
251                        fan_in: 2,
252                        fan_out: 4,
253                        hk: 10.0,
254                    }),
255                    ..Default::default()
256                }),
257            ),
258            node(
259                "b",
260                Some(Complexity {
261                    coupling: Some(Coupling {
262                        fan_in: 4,
263                        fan_out: 8,
264                        hk: 30.0,
265                    }),
266                    ..Default::default()
267                }),
268            ),
269        ]);
270        annotate_stats(&mut g);
271        let c = g.stats.unwrap().coupling.expect("coupling averaged");
272        assert_eq!(c.fan_in, 3.0);
273        assert_eq!(c.fan_out, 6.0);
274        assert_eq!(c.hk, 20.0);
275    }
276
277    #[test]
278    fn maintainability_attached_when_mi_positive() {
279        let mut g = graph_of(vec![node(
280            "a",
281            Some(Complexity {
282                maintainability: Some(Maintainability {
283                    mi: 80.0,
284                    mi_sei: 70.0,
285                }),
286                ..Default::default()
287            }),
288        )]);
289        annotate_stats(&mut g);
290        let m = g.stats.unwrap().maintainability.expect("mi > 0 → attached");
291        assert_eq!(m.mi, 80.0);
292        assert_eq!(m.mi_sei, 70.0);
293    }
294
295    #[test]
296    fn halstead_attached_when_volume_positive() {
297        let mut g = graph_of(vec![node(
298            "a",
299            Some(Complexity {
300                halstead: Some(Halstead {
301                    length: 10.0,
302                    vocabulary: 6.0,
303                    volume: 40.0,
304                    effort: 100.0,
305                    time: 5.0,
306                    bugs: 0.1,
307                }),
308                ..Default::default()
309            }),
310        )]);
311        annotate_stats(&mut g);
312        let h = g.stats.unwrap().halstead.expect("volume > 0 → attached");
313        assert_eq!(h.volume, 40.0);
314        assert_eq!(h.length, 10.0);
315    }
316
317    #[test]
318    fn halstead_absent_when_volume_zero_but_other_metrics_present() {
319        // cyclomatic keeps the stats block alive; volume 0 closes the halstead gate.
320        let mut g = graph_of(vec![node(
321            "a",
322            Some(Complexity {
323                cyclomatic: 3.0,
324                halstead: Some(Halstead {
325                    length: 5.0,
326                    vocabulary: 0.0,
327                    volume: 0.0,
328                    effort: 0.0,
329                    time: 0.0,
330                    bugs: 0.0,
331                }),
332                ..Default::default()
333            }),
334        )]);
335        annotate_stats(&mut g);
336        let stats = g.stats.expect("cyclomatic keeps stats present");
337        assert_eq!(stats.cyclomatic, 3.0);
338        assert!(stats.halstead.is_none(), "volume 0 → halstead gate closed");
339    }
340}