big_code_analysis/spaces/code_metrics.rs
1//! Inherent and `Display` impl blocks for [`super::CodeMetrics`].
2//!
3//! Split out of `spaces.rs` to keep that module focused on the public
4//! API type definitions. The blocks are moved verbatim; method and
5//! trait resolution is by type, so `crate::spaces::CodeMetrics`'s
6//! methods and `Display` impl resolve unchanged.
7
8use super::*;
9
10impl CodeMetrics {
11 /// Construct a `CodeMetrics` whose `selected` mask is the given
12 /// [`MetricSet`]. All metric fields are at their `Default` value;
13 /// the walker fills them in for whichever metrics the mask
14 /// admits.
15 #[inline]
16 #[must_use]
17 pub fn with_selected(selected: MetricSet) -> Self {
18 Self {
19 selected,
20 ..Self::default()
21 }
22 }
23
24 /// Returns the set of metrics that were computed for this space.
25 #[inline]
26 #[must_use]
27 pub fn selected(&self) -> MetricSet {
28 self.selected
29 }
30}
31
32impl fmt::Display for CodeMetrics {
33 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 writeln!(f, "{}", self.nargs)?;
35 writeln!(f, "{}", self.nexits)?;
36 writeln!(f, "{}", self.cognitive)?;
37 writeln!(f, "{}", self.cyclomatic)?;
38 writeln!(f, "{}", self.halstead)?;
39 writeln!(f, "{}", self.loc)?;
40 writeln!(f, "{}", self.nom)?;
41 writeln!(f, "{}", self.tokens)?;
42 write!(f, "{}", self.mi)
43 }
44}
45
46impl CodeMetrics {
47 /// Project these metrics into their [`crate::wire::CodeMetrics`] form,
48 /// eliding metrics not in [`CodeMetrics::selected`] (and disabled
49 /// class-only metrics) exactly as the serialized output does.
50 #[must_use]
51 pub fn to_wire(&self) -> crate::wire::CodeMetrics {
52 crate::wire::CodeMetrics::from(self)
53 }
54
55 /// Sum each metric component from `other` into `self` in place. Used to
56 /// roll nested function-space metrics into their parent space.
57 pub fn merge(&mut self, other: &CodeMetrics) {
58 self.cognitive.merge(&other.cognitive);
59 self.cyclomatic.merge(&other.cyclomatic);
60 self.halstead.merge(&other.halstead);
61 self.loc.merge(&other.loc);
62 self.nom.merge(&other.nom);
63 self.tokens.merge(&other.tokens);
64 self.mi.merge(&other.mi);
65 self.nargs.merge(&other.nargs);
66 self.nexits.merge(&other.nexits);
67 self.abc.merge(&other.abc);
68 self.wmc.merge(&other.wmc);
69 self.npm.merge(&other.npm);
70 self.npa.merge(&other.npa);
71 // Union the selection masks so a parent space's emitted
72 // fields are the union of every nested space's selection.
73 // In practice every nested space shares the same mask (set
74 // once from `MetricsOptions::metrics`), so this is the
75 // identity operation; we union rather than assign to keep
76 // `merge` correct under future callers that mix
77 // independently-built `FuncSpace` values.
78 self.selected = self.selected.union(other.selected);
79 }
80}