big_code_analysis/metric_set.rs
1//! Per-metric selection: the [`Metric`] enum and the
2//! [`MetricSet`] bitfield it gates.
3//!
4//! Used by [`MetricsOptions::with_only`](crate::MetricsOptions::with_only)
5//! to restrict which metrics are computed during a walk, and by
6//! [`CodeMetrics`](crate::CodeMetrics)'s `Serialize` impl to elide
7//! fields the caller did not select.
8
9use std::fmt;
10use std::str::FromStr;
11
12/// One metric computed by the analysis walker.
13///
14/// Pass a slice of these to
15/// [`MetricsOptions::with_only`](crate::MetricsOptions::with_only) to
16/// restrict computation to the listed metrics.
17///
18/// `#[non_exhaustive]` so future metrics can land additively. Use
19/// `match` against the existing variants and either a wildcard arm or
20/// the `m if !MetricSet::all().contains(m)` guard to stay
21/// forwards-compatible.
22///
23/// `Ord` follows declaration order, not the [`Display`](fmt::Display)
24/// spelling. It exists so [`Metric`] can key a `BTreeSet` — notably the
25/// suppression scope (`SuppressionScope::Some`) — with a deterministic,
26/// stable iteration order across runs. Do not rely on the ordering being
27/// alphabetical; reorder the variants only with a deliberate review of
28/// every serialized `BTreeSet<Metric>` snapshot.
29#[non_exhaustive]
30#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
31pub enum Metric {
32 /// Cognitive complexity ([`crate::cognitive::Stats`]).
33 Cognitive,
34 /// Cyclomatic complexity ([`crate::cyclomatic::Stats`]).
35 Cyclomatic,
36 /// Halstead ([`crate::halstead::Stats`]).
37 Halstead,
38 /// LoC family ([`crate::loc::Stats`]).
39 Loc,
40 /// Number of methods ([`crate::nom::Stats`]).
41 Nom,
42 /// Token counts ([`crate::tokens::Stats`]).
43 Tokens,
44 /// Number of arguments ([`crate::nargs::Stats`]).
45 Nargs,
46 /// Exit-point count ([`crate::nexits::Stats`]).
47 Nexits,
48 /// ABC ([`crate::abc::Stats`]).
49 Abc,
50 /// Number of public methods ([`crate::npm::Stats`]).
51 Npm,
52 /// Number of public attributes ([`crate::npa::Stats`]).
53 Npa,
54 /// Maintainability index ([`crate::mi::Stats`]). Derived metric:
55 /// selecting only `Mi` via
56 /// [`MetricsOptions::with_only`](crate::MetricsOptions::with_only)
57 /// also pulls in [`Metric::Loc`], [`Metric::Cyclomatic`], and
58 /// [`Metric::Halstead`].
59 Mi,
60 /// Weighted methods per class ([`crate::wmc::Stats`]). Derived
61 /// metric: selecting `Wmc` also pulls in [`Metric::Cyclomatic`]
62 /// and [`Metric::Nom`].
63 Wmc,
64}
65
66impl Metric {
67 // Bit position used inside [`MetricSet`]. The ordering is
68 // intentionally arbitrary — the only contract is that each
69 // variant maps to a distinct bit.
70 //
71 // Returns `u32` to match [`MetricSet`]'s storage width: at `u16`
72 // the bitfield would overflow once a 17th variant landed (debug
73 // panic / release wrap), and `Metric` is `#[non_exhaustive]`
74 // specifically so new variants can land additively.
75 #[inline]
76 const fn bit(self) -> u32 {
77 1 << (self as u32)
78 }
79
80 /// Returns the slice of metrics this metric depends on.
81 ///
82 /// Derived and averaged metrics consume the outputs of other
83 /// metrics during the finalize step; selecting one without its
84 /// dependencies would leave the dependency's `Stats` at default
85 /// (zero) values and silently corrupt the result. Callers
86 /// typically reach this through
87 /// [`MetricsOptions::with_only`](crate::MetricsOptions::with_only),
88 /// which auto-resolves the closure transparently.
89 #[must_use]
90 pub const fn dependencies(self) -> &'static [Metric] {
91 match self {
92 // Mi = function(Loc, Cyclomatic, Halstead). All three must
93 // be computed for the MI formula to be meaningful.
94 Self::Mi => &[Self::Loc, Self::Cyclomatic, Self::Halstead],
95 // Wmc aggregates per-method cyclomatic complexity and
96 // needs Nom to count those methods.
97 Self::Wmc => &[Self::Cyclomatic, Self::Nom],
98 // Cognitive, Nexits, and Nargs each expose a per-function
99 // average whose divisor is the function/closure count
100 // sourced from Nom (see `spaces::compute_averages`).
101 // Without Nom the divisor would be the `Stats` default
102 // (zero), producing inf/NaN averages (#428).
103 Self::Cognitive | Self::Nexits | Self::Nargs => &[Self::Nom],
104 _ => &[],
105 }
106 }
107
108 /// Canonical user-facing name for each metric — the single
109 /// source of truth shared by the Python bindings'
110 /// `bca.METRIC_NAMES` constant, the `unknown metric: <bad>;
111 /// valid: …` error message, and any downstream Rust consumer
112 /// that parses user input into a [`MetricSet`].
113 ///
114 /// Each entry round-trips through [`Metric::from_str`]. Every
115 /// metric uses one canonical spelling end-to-end:
116 /// [`Metric::Nexits`] is `"nexits"` in `Display`, in this table,
117 /// and as the JSON output key (the `CodeMetrics::Serialize` impl
118 /// in `src/spaces.rs`).
119 ///
120 /// Alphabetised. The drift between this table and the
121 /// `FromStr` arms (or the `Metric` enum itself) is guarded by
122 /// `names_table_parses_to_every_variant` and
123 /// `names_table_is_alphabetised` in the test module below.
124 pub const NAMES: &'static [&'static str] = &[
125 "abc",
126 "cognitive",
127 "cyclomatic",
128 "halstead",
129 "loc",
130 "mi",
131 "nargs",
132 "nexits",
133 "nom",
134 "npa",
135 "npm",
136 "tokens",
137 "wmc",
138 ];
139
140 /// Every metric except [`Metric::Tokens`], in declaration order.
141 ///
142 /// `tokens` is the one metric with no configurable threshold, so it
143 /// is the one metric that cannot be named in a suppression marker
144 /// (`bca: suppress(tokens)` is rejected). This is the single source
145 /// of truth for the suppressible vocabulary: the suppression
146 /// parser's "known metrics" hint and the threshold-name resolver
147 /// both derive from it rather than hardcoding the list.
148 pub fn suppressible() -> impl Iterator<Item = Metric> {
149 Self::ALL.iter().copied().filter(|m| *m != Self::Tokens)
150 }
151
152 /// Every [`Metric`] variant, in declaration order. Drives
153 /// [`Metric::suppressible`] and any consumer that needs to iterate
154 /// the full set without re-deriving it from `NAMES`.
155 const ALL: &'static [Self] = &[
156 Self::Cognitive,
157 Self::Cyclomatic,
158 Self::Halstead,
159 Self::Loc,
160 Self::Nom,
161 Self::Tokens,
162 Self::Nargs,
163 Self::Nexits,
164 Self::Abc,
165 Self::Npm,
166 Self::Npa,
167 Self::Mi,
168 Self::Wmc,
169 ];
170}
171
172impl fmt::Display for Metric {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 let s = match self {
175 Self::Cognitive => "cognitive",
176 Self::Cyclomatic => "cyclomatic",
177 Self::Halstead => "halstead",
178 Self::Loc => "loc",
179 Self::Nom => "nom",
180 Self::Tokens => "tokens",
181 Self::Nargs => "nargs",
182 Self::Nexits => "nexits",
183 Self::Abc => "abc",
184 Self::Npm => "npm",
185 Self::Npa => "npa",
186 Self::Mi => "mi",
187 Self::Wmc => "wmc",
188 };
189 f.write_str(s)
190 }
191}
192
193/// Error returned by [`Metric::from_str`] when the input
194/// is not a recognised metric name.
195///
196/// Holds the offending input verbatim. Downstream consumers that own
197/// the canonical name table (e.g. the `bca` Python bindings'
198/// `METRIC_NAMES` constant) typically compose this with a
199/// `valid: <list>` suffix from their own source of truth; this type
200/// deliberately stays out of that policy and only carries the
201/// rejected input so the wrapper layer can format the user-facing
202/// message however it wants.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct ParseMetricError(String);
205
206impl ParseMetricError {
207 /// The rejected input that failed to parse as a [`Metric`] name.
208 ///
209 /// Lets callers recover the offending string programmatically
210 /// rather than scraping it out of the [`Display`](fmt::Display)
211 /// output.
212 #[must_use]
213 pub fn input(&self) -> &str {
214 &self.0
215 }
216}
217
218impl fmt::Display for ParseMetricError {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 write!(f, "unknown metric: {}", self.0)
221 }
222}
223
224impl std::error::Error for ParseMetricError {}
225
226impl FromStr for Metric {
227 type Err = ParseMetricError;
228
229 /// Parse a [`Metric`] from its [`fmt::Display`] spelling.
230 ///
231 /// Strict lowercase: `"Loc"` is rejected. Every metric has exactly
232 /// one accepted spelling, matching its `Display` form, `NAMES`
233 /// entry, and JSON output key.
234 fn from_str(s: &str) -> Result<Self, Self::Err> {
235 match s {
236 "cognitive" => Ok(Self::Cognitive),
237 "cyclomatic" => Ok(Self::Cyclomatic),
238 "halstead" => Ok(Self::Halstead),
239 "loc" => Ok(Self::Loc),
240 "nom" => Ok(Self::Nom),
241 "tokens" => Ok(Self::Tokens),
242 "nargs" => Ok(Self::Nargs),
243 "nexits" => Ok(Self::Nexits),
244 "abc" => Ok(Self::Abc),
245 "npm" => Ok(Self::Npm),
246 "npa" => Ok(Self::Npa),
247 "mi" => Ok(Self::Mi),
248 "wmc" => Ok(Self::Wmc),
249 _ => Err(ParseMetricError(s.to_owned())),
250 }
251 }
252}
253
254// Serialize/Deserialize are hand-written rather than derived so the wire
255// form is the canonical [`Display`] spelling (`nargs`, `nexits`,
256// `tokens`, …) — the same vocabulary used in JSON output keys, error
257// messages, and `Metric::NAMES`. A `#[derive(Serialize)]` with
258// `rename_all = "snake_case"` would emit `n_args` / `n_exits` instead,
259// diverging from every other surface. Routing through `Display`/`FromStr`
260// keeps the spelling single-sourced. `Metric` reaches the wire as the
261// element type of `SuppressionScope::Some`'s `BTreeSet`.
262impl serde::Serialize for Metric {
263 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
264 serializer.serialize_str(&self.to_string())
265 }
266}
267
268impl<'de> serde::Deserialize<'de> for Metric {
269 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
270 // `Cow<str>` borrows from self-describing, zero-copy formats
271 // (JSON without escapes) and owns from reader-based or
272 // non-borrowing ones (CBOR, YAML, TOML, JSON with escapes).
273 // `<&str>` would reject every non-borrowing format, which is
274 // exactly how `BTreeSet<Metric>` reaches the wire inside a
275 // `SuppressionScope::Some` CBOR/YAML/TOML payload.
276 let s = std::borrow::Cow::<str>::deserialize(deserializer)?;
277 s.parse().map_err(serde::de::Error::custom)
278 }
279}
280
281/// Bitfield of selected metrics.
282///
283/// Stored on [`MetricsOptions`](crate::MetricsOptions) (controls
284/// which metrics the walker computes) and on
285/// [`CodeMetrics`](crate::CodeMetrics) (controls which fields the
286/// `Serialize` impl emits).
287///
288/// `MetricSet::all()` is the default: every metric enabled, matching
289/// the pre-#257 behaviour.
290#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
291pub struct MetricSet(u32);
292
293impl MetricSet {
294 // All-metrics mask: OR together every variant's bit. Kept
295 // explicit (rather than `(1 << N) - 1`) so adding a new variant
296 // requires a deliberate edit here and surfaces in code review.
297 const ALL_BITS: u32 = Metric::Cognitive.bit()
298 | Metric::Cyclomatic.bit()
299 | Metric::Halstead.bit()
300 | Metric::Loc.bit()
301 | Metric::Nom.bit()
302 | Metric::Tokens.bit()
303 | Metric::Nargs.bit()
304 | Metric::Nexits.bit()
305 | Metric::Abc.bit()
306 | Metric::Npm.bit()
307 | Metric::Npa.bit()
308 | Metric::Mi.bit()
309 | Metric::Wmc.bit();
310
311 /// Empty set (no metrics selected).
312 #[inline]
313 #[must_use]
314 pub const fn empty() -> Self {
315 Self(0)
316 }
317
318 /// Full set (every metric selected). This is the default for
319 /// [`MetricsOptions`](crate::MetricsOptions), preserving the
320 /// pre-#257 "compute everything" behaviour.
321 #[inline]
322 #[must_use]
323 pub const fn all() -> Self {
324 Self(Self::ALL_BITS)
325 }
326
327 /// Returns `true` if `metric` is in the set.
328 #[inline]
329 #[must_use]
330 pub const fn contains(self, metric: Metric) -> bool {
331 (self.0 & metric.bit()) != 0
332 }
333
334 /// Returns a new set with `metric` inserted.
335 #[inline]
336 #[must_use]
337 pub const fn with(self, metric: Metric) -> Self {
338 Self(self.0 | metric.bit())
339 }
340
341 /// Returns the union of two sets.
342 #[inline]
343 #[must_use]
344 pub const fn union(self, other: Self) -> Self {
345 Self(self.0 | other.0)
346 }
347
348 /// Insert `metric` (in place).
349 #[inline]
350 pub fn insert(&mut self, metric: Metric) {
351 self.0 |= metric.bit();
352 }
353
354 /// Build a `MetricSet` from a slice, auto-adding the transitive
355 /// dependencies of each selected metric.
356 ///
357 /// This is the workhorse behind
358 /// [`MetricsOptions::with_only`](crate::MetricsOptions::with_only):
359 /// the caller-facing builder enforces the full dependency closure
360 /// so a request for `Mi` alone still computes
361 /// `Loc + Cyclomatic + Halstead`. Exposed `pub` because
362 /// downstream consumers (notably the `bca` Python bindings'
363 /// `parse_metric_names` helper) parse user input into a
364 /// `Vec<Metric>` and need the same closure-resolution semantics
365 /// without re-implementing the worklist.
366 ///
367 /// Implementation note: uses a worklist rather than a single pass
368 /// so a future derived metric whose dependency is itself derived
369 /// still resolves the complete closure. The loop terminates
370 /// because each iteration either inserts a new bit or the
371 /// worklist drains; the bitfield is bounded at `Metric` variant
372 /// count.
373 #[must_use]
374 pub fn from_slice_with_deps(metrics: &[Metric]) -> Self {
375 let mut set = Self::empty();
376 for &m in metrics {
377 set.insert(m);
378 }
379 set.resolved()
380 }
381
382 /// Returns this set closed under [`Metric::dependencies`].
383 ///
384 /// Every selected metric's transitive dependencies are added so a
385 /// set carrying a derived metric (e.g. [`Metric::Mi`]) also carries
386 /// the inputs that metric's finalize step consumes
387 /// ([`Metric::Loc`], [`Metric::Cyclomatic`], [`Metric::Halstead`]).
388 /// Resolving an already-closed set is a no-op, so the operation is
389 /// idempotent: `set.resolved().resolved() == set.resolved()`.
390 ///
391 /// This is the set-in/set-out counterpart of
392 /// [`MetricSet::from_slice_with_deps`] and is what
393 /// [`MetricsOptions::with_metric_set`](crate::MetricsOptions::with_metric_set)
394 /// applies so a caller-supplied set can never select a derived
395 /// metric without its prerequisites (#743).
396 ///
397 /// Implementation note: uses a worklist rather than a single pass
398 /// so a future derived metric whose dependency is itself derived
399 /// still resolves the complete closure. The loop terminates
400 /// because each iteration either inserts a new bit or the worklist
401 /// drains; the bitfield is bounded at `Metric` variant count.
402 #[must_use]
403 pub fn resolved(self) -> Self {
404 let mut set = self;
405 let mut worklist: Vec<Metric> = Metric::ALL
406 .iter()
407 .copied()
408 .filter(|&m| self.contains(m))
409 .collect();
410 while let Some(m) = worklist.pop() {
411 for &dep in m.dependencies() {
412 if !set.contains(dep) {
413 set.insert(dep);
414 worklist.push(dep);
415 }
416 }
417 }
418 set
419 }
420}
421
422impl Default for MetricSet {
423 /// Default = every metric selected, matching the pre-#257
424 /// behaviour of [`MetricsOptions::default`](crate::MetricsOptions::default).
425 #[inline]
426 fn default() -> Self {
427 Self::all()
428 }
429}
430
431#[cfg(test)]
432#[path = "metric_set_tests.rs"]
433mod tests;