fallow_types/extract_function_metrics.rs
1//! Branch counts of a file, the kinds of anonymous functions, and the
2//! complexity of a function.
3
4use super::*;
5
6/// Branching totals for one file: the quantity that survives extraction, and
7/// the number of units now holding it.
8///
9/// A per-function cyclomatic ceiling constrains a partition, not a quantity.
10/// `McCabe` gives a function `1 + one increment per decision point`, so across
11/// a set of units the summed cyclomatic score is `functions + branch_points`.
12/// Moving an `if` from one function into a new one removes an increment from
13/// the first and adds it to the second: `branch_points` is unchanged and
14/// `functions` rises. Reporting the two terms separately is what distinguishes
15/// branching that left from branching that only moved.
16///
17/// Module scope is accounted for. Extraction pushes a root frame per program
18/// and emits it as a synthetic `<module>` unit whenever it branches, so a
19/// branch hoisted out of a function to the top level of the module keeps its
20/// increment in `branch_points` and adds one to `functions`, exactly as moving
21/// it into a new function would. A fall in `branch_points` is therefore a
22/// statement about the file's measured decision points, not about a partition.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
24pub struct FileBranching {
25 /// Summed weight of `Cyclomatic` contributions. The conserved quantity.
26 pub branch_points: u32,
27 /// Number of accounted units. The tax a split adds.
28 pub functions: u32,
29 /// Highest single-unit cyclomatic score. Reported, never a verdict input:
30 /// a split lowers it by construction.
31 pub peak_cyclomatic: u16,
32 /// Summed weight of `Cognitive` contributions, excluding `PropCount` and
33 /// `HookDensity`. Both are cognitive-only with no cyclomatic counterpart,
34 /// and `PropCount` records the excess over a floor, so it is superlinear in
35 /// a split: one 14-prop component contributes `+10` while the same props
36 /// across two 7-prop components contribute `+3` and `+3`. Including them
37 /// would move this number with both `branch_points` and nesting flat.
38 /// This therefore does NOT equal the sum of `FunctionComplexity::cognitive`.
39 pub cognitive: u32,
40 /// Summed `nesting` over the same cognitive contributions. Extraction
41 /// rebases nesting to zero on every new frame, so a cognitive improvement
42 /// that shows up here and not in `branch_points` came from repartitioning,
43 /// not from removing branching.
44 pub cognitive_nesting_weight: u32,
45 /// Whether one of the counted units is the module body. Its branching is
46 /// real and belongs in `branch_points`, but it is not a function anyone
47 /// split into, so a consumer judging whether a file was split must not
48 /// count it towards the function tax.
49 pub has_module_unit: bool,
50 /// Whether the file carried a synthetic template unit that these counts
51 /// exclude. When it did, the numbers describe the file's script only, so a
52 /// consumer must not present them as describing the whole file. The
53 /// synthetic `<module>` unit is NOT a template unit and does not set this
54 /// flag: it is counted like any other unit, because module-scope branching
55 /// is part of the script the numbers describe.
56 pub has_synthetic_units: bool,
57}
58
59impl FileBranching {
60 /// Aggregate one file's units.
61 ///
62 /// Synthetic template units are excluded: they are suppressed entirely when
63 /// trivial, which would silently move any denominator that counted them.
64 /// Suppression is deliberately not consulted, so a
65 /// `fallow-ignore-next-line complexity` comment cannot remove a unit's
66 /// branches from the total.
67 ///
68 /// The synthetic `<module>` unit IS counted. It carries the file's
69 /// module-scope decision points, and leaving it out would restore the blind
70 /// spot that let a branch disappear from the total by being hoisted out of
71 /// every function.
72 #[must_use]
73 pub fn from_units(units: &[FunctionComplexity]) -> Self {
74 let mut totals = Self {
75 has_module_unit: units
76 .iter()
77 .any(|unit| is_synthetic_module_unit(&unit.name)),
78 has_synthetic_units: units
79 .iter()
80 .any(|unit| is_synthetic_template_unit(&unit.name)),
81 ..Self::default()
82 };
83 for unit in units
84 .iter()
85 .filter(|unit| !is_synthetic_template_unit(&unit.name))
86 {
87 totals.functions += 1;
88 totals.peak_cyclomatic = totals.peak_cyclomatic.max(unit.cyclomatic);
89 for contribution in &unit.contributions {
90 match contribution.metric {
91 ComplexityMetric::Cyclomatic => {
92 totals.branch_points += u32::from(contribution.weight);
93 }
94 ComplexityMetric::Cognitive => {
95 if matches!(
96 contribution.kind,
97 ComplexityContributionKind::PropCount
98 | ComplexityContributionKind::HookDensity
99 ) {
100 continue;
101 }
102 totals.cognitive += u32::from(contribution.weight);
103 totals.cognitive_nesting_weight += u32::from(contribution.nesting);
104 }
105 }
106 }
107 }
108 totals
109 }
110
111 /// Summed cyclomatic score implied by the identity `functions + branch_points`.
112 ///
113 /// Equals the direct sum of `FunctionComplexity::cyclomatic` over the same
114 /// units unless a unit saturated `u16`, which is the one way the identity
115 /// can break.
116 #[must_use]
117 pub const fn implied_cyclomatic(&self) -> u32 {
118 self.functions + self.branch_points
119 }
120}
121
122/// The kind of function that has no name of its own, which selects its
123/// placeholder name.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
125pub enum AnonymousFunctionKind {
126 /// A function expression: `<anonymous>`.
127 Function,
128 /// An arrow function: `<arrow>`.
129 Arrow,
130}
131
132impl AnonymousFunctionKind {
133 /// The placeholder name of this kind.
134 #[must_use]
135 pub const fn placeholder(self) -> &'static str {
136 match self {
137 Self::Function => ANONYMOUS_FUNCTION_NAME,
138 Self::Arrow => ANONYMOUS_ARROW_NAME,
139 }
140 }
141}
142
143/// Complexity metrics for a single function/method/arrow.
144#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
145pub struct FunctionComplexity {
146 /// Function name, or a placeholder (`"<anonymous>"`, `"<arrow>"`) for a
147 /// function that has no name.
148 pub name: String,
149 /// Whether this function is an ECMAScript `#`-private class member.
150 ///
151 /// Kept separately from `name` because a public string-named method may
152 /// legally begin with `#` and remains eligible for runtime coverage.
153 pub is_private_member: bool,
154 /// `Some` when `name` comes from the call or the function that holds this
155 /// function, not from its own declaration, binding, or key. Examples:
156 /// `Command.make("setup")` for a callback argument, the `Effect.fn` span
157 /// name, or the name of the function that returns `Effect.gen(...)`. The
158 /// value is the kind of placeholder that the function had before.
159 ///
160 /// Coverage producers and runtime identities record such a function
161 /// without a name, so they use [`Self::identity_name`].
162 pub context_named: Option<AnonymousFunctionKind>,
163 /// 1-based line number where the function starts.
164 pub line: u32,
165 /// 0-based byte column where the function starts.
166 pub col: u32,
167 /// `McCabe` cyclomatic complexity (1 + decision points).
168 pub cyclomatic: u16,
169 /// `SonarSource` cognitive complexity (structural + nesting penalty).
170 pub cognitive: u16,
171 /// Number of lines in the function body.
172 pub line_count: u32,
173 /// Number of parameters (excluding TypeScript's `this` parameter).
174 pub param_count: u8,
175 /// Number of React hook calls (`useState` / `useEffect` / `useMemo` /
176 /// `useCallback` / custom `use*`) made directly in this function's body.
177 /// Non-zero only for React components/hooks; descriptive context surfaced in
178 /// the hotspot drill-down, never a tunable threshold (anti-numerology).
179 pub react_hook_count: u16,
180 /// Maximum JSX element nesting depth reached in this function's body (the
181 /// deepest chain of element-inside-element). `0` when the function renders
182 /// no JSX. Descriptive context surfaced in the hotspot drill-down, never a
183 /// tunable threshold (anti-numerology).
184 pub react_jsx_max_depth: u16,
185 /// Number of props destructured from this component's first parameter (the
186 /// `{ a, b, c }` props object). `0` for non-component functions and for
187 /// components taking a bare `props` identifier (not statically countable).
188 /// Descriptive context surfaced in the hotspot drill-down, never a tunable
189 /// threshold (anti-numerology).
190 pub react_prop_count: u16,
191 /// Content digest of the function's full-span source slice.
192 pub source_hash: Option<String>,
193 /// Per-decision-point breakdown explaining WHICH constructs drove the
194 /// cyclomatic and cognitive scores. One entry per increment event (an `if`
195 /// emits one cyclomatic and one cognitive entry at the same line, because
196 /// the two metrics accrue at different granularities). Always computed and
197 /// cached; surfaced in JSON only behind `health --complexity-breakdown`.
198 pub contributions: Vec<ComplexityContribution>,
199}
200
201impl FunctionComplexity {
202 /// The name that coverage producers and runtime identities use: the
203 /// placeholder for a function with a context name, else `name`.
204 #[must_use]
205 pub fn identity_name(&self) -> &str {
206 match self.context_named {
207 Some(kind) => kind.placeholder(),
208 None => &self.name,
209 }
210 }
211}