Skip to main content

fallow_engine/
effective_severity.rs

1//! Per-finding rule severity for dead-code results.
2//!
3//! One table in this module maps each dead-code finding to the rule that
4//! decides its severity. Three consumers read it:
5//!
6//! - [`apply_effective_severities`] writes the severity onto each finding for
7//!   the CI formats (SARIF, CodeClimate, GitHub annotations);
8//! - `has_error_severity_issues` in `crates/engine/src/error_severity.rs`
9//!   decides the exit code, the combined verdict and the audit `all` gate;
10//! - the audit ledger in `crates/api/src/audit_keys.rs` decides the audit
11//!   `new-only` gate.
12//!
13//! The rules of the table:
14//!
15//! - a file-scoped finding resolves `overrides[].rules` for its own path;
16//! - a circular dependency takes the highest severity of the files in the
17//!   cycle;
18//! - a project-level finding (dependencies, catalog entries, duplicate
19//!   exports, re-export cycles) uses the base rules.
20//!
21//! Empty catalog groups and dependency overrides are file-scoped: they sit on
22//! the file that declares them (`pnpm-workspace.yaml` or a `package.json`), so
23//! an override for that file decides.
24//!
25//! Policy violations carry their own `severity`. Prop-drilling resolves the
26//! source hop and gates only at explicit error severity. Warning chains stay
27//! advisory under strict flags. Thin-wrapper and duplicate-prop-shape follow the same policy.
28
29use std::path::Path;
30
31use fallow_config::{ResolvedConfig, RulesConfig, Severity};
32use fallow_types::output_dead_code::{
33    AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
34    BoundaryViolationFinding, CircularDependencyFinding, DeprecatedExportInUseFinding,
35    DevDependencyInProductionFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
36    DynamicSegmentNameConflictFinding, EffectiveSeverity, EmptyCatalogGroupFinding, GatedFinding,
37    InvalidClientExportFinding, MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
38    MixedClientServerBarrelFinding, PackageCycleFinding, PolicyViolationFinding,
39    PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding, RouteCollisionFinding,
40    TestOnlyDependencyFinding, ThinWrapperFinding, TypeOnlyDependencyFinding,
41    UnlistedDependencyFinding, UnprovidedInjectFinding, UnrenderedComponentFinding,
42    UnresolvedCatalogReferenceFinding, UnresolvedImportFinding, UnusedCatalogEntryFinding,
43    UnusedClassMemberFinding, UnusedComponentEmitFinding, UnusedComponentInputFinding,
44    UnusedComponentOutputFinding, UnusedComponentPropFinding, UnusedDependencyFinding,
45    UnusedDependencyOverrideFinding, UnusedDevDependencyFinding, UnusedEnumMemberFinding,
46    UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
47    UnusedOptionalDependencyFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
48    UnusedSvelteEventFinding, UnusedTypeFinding,
49};
50use fallow_types::output_dead_code::{
51    UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
52};
53use fallow_types::results::{AnalysisResults, PolicyViolationSeverity, StaleSuppression};
54
55use crate::error_severity::promote_warns_to_errors;
56
57fn gate(severity: Severity) -> Option<EffectiveSeverity> {
58    match severity {
59        Severity::Error => Some(EffectiveSeverity::Error),
60        Severity::Warn => Some(EffectiveSeverity::Warn),
61        Severity::Off => None,
62    }
63}
64
65/// The rules that give a finding its severity.
66#[derive(Clone, Copy)]
67pub struct SeveritySource<'a> {
68    base: &'a RulesConfig,
69    overrides: Option<&'a ResolvedConfig>,
70    promote_warns: bool,
71}
72
73impl<'a> SeveritySource<'a> {
74    /// The rules of `config`, with its `overrides` for file-scoped findings.
75    #[must_use]
76    pub fn from_config(config: &'a ResolvedConfig) -> Self {
77        Self::new(&config.rules, Some(config), false)
78    }
79
80    /// Explicit base rules, with the `overrides` of `config` when it has any.
81    ///
82    /// `promote_warns` raises a `warn` that an override resolves to `error`.
83    /// The caller promotes `base` itself.
84    #[must_use]
85    pub fn new(
86        base: &'a RulesConfig,
87        config: Option<&'a ResolvedConfig>,
88        promote_warns: bool,
89    ) -> Self {
90        Self {
91            base,
92            overrides: config.filter(|config| !config.overrides.is_empty()),
93            promote_warns,
94        }
95    }
96
97    fn for_path(&self, path: &Path, rule: fn(&RulesConfig) -> Severity) -> Severity {
98        let Some(config) = self.overrides else {
99            return rule(self.base);
100        };
101        let mut rules = config.resolve_rules_for_path(path);
102        if self.promote_warns {
103            promote_warns_to_errors(&mut rules);
104        }
105        rule(&rules)
106    }
107
108    fn project(&self, rule: fn(&RulesConfig) -> Severity) -> Severity {
109        rule(self.base)
110    }
111
112    /// The base rule when no `overrides` apply, so every finding of a
113    /// file-scoped kind has the same severity.
114    fn uniform(&self, rule: fn(&RulesConfig) -> Severity) -> Option<Severity> {
115        self.overrides.is_none().then(|| rule(self.base))
116    }
117}
118
119/// A dead-code finding whose severity comes from the configured rules.
120pub trait RuleSeverity {
121    /// The severity of this finding under `source`.
122    fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity;
123
124    /// The severity that every finding of this kind has under `source`, or
125    /// `None` when the severity can differ from finding to finding.
126    ///
127    /// The exit-code check reads this once per collection instead of once
128    /// per finding.
129    fn uniform_severity(_source: &SeveritySource<'_>) -> Option<Severity>
130    where
131        Self: Sized,
132    {
133        None
134    }
135}
136
137macro_rules! file_scoped {
138    ($($finding:ty => $path:ident . $field:ident, $rule:ident;)+) => {
139        $(
140            impl RuleSeverity for $finding {
141                fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity {
142                    source.for_path(&self.$path.$field, |rules| rules.$rule)
143                }
144
145                fn uniform_severity(source: &SeveritySource<'_>) -> Option<Severity> {
146                    source.uniform(|rules| rules.$rule)
147                }
148            }
149        )+
150    };
151}
152
153macro_rules! project_level {
154    ($($finding:ty => $rule:ident;)+) => {
155        $(
156            impl RuleSeverity for $finding {
157                fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity {
158                    source.project(|rules| rules.$rule)
159                }
160
161                fn uniform_severity(source: &SeveritySource<'_>) -> Option<Severity> {
162                    Some(source.project(|rules| rules.$rule))
163                }
164            }
165        )+
166
167        /// The rule fields of this list, for the test that compares it with
168        /// the `override-rule-ineffective` table of `fallow-config`.
169        #[cfg(test)]
170        const PROJECT_LEVEL_RULE_FIELDS: &[&str] = &[$(stringify!($rule)),+];
171    };
172}
173
174file_scoped! {
175    ThinWrapperFinding => wrapper.file, thin_wrapper;
176    DuplicatePropShapeFinding => shape.file, duplicate_prop_shape;
177    UnusedFileFinding => file.path, unused_files;
178    UnusedExportFinding => export.path, unused_exports;
179    UnusedTypeFinding => export.path, unused_types;
180    PrivateTypeLeakFinding => leak.path, private_type_leaks;
181    DeprecatedExportInUseFinding => export.path, deprecated_exports_in_use;
182    UnusedEnumMemberFinding => member.path, unused_enum_members;
183    UnusedClassMemberFinding => member.path, unused_class_members;
184    UnusedStoreMemberFinding => member.path, unused_store_members;
185    UnprovidedInjectFinding => inject.path, unprovided_injects;
186    UnresolvedImportFinding => import.path, unresolved_imports;
187    UnrenderedComponentFinding => component.path, unrendered_components;
188    UnusedComponentPropFinding => prop.path, unused_component_props;
189    AbsentComponentPropFinding => prop.path, absent_component_props;
190    UnusedComponentEmitFinding => emit.path, unused_component_emits;
191    UnusedComponentInputFinding => input.path, unused_component_inputs;
192    UnusedComponentOutputFinding => output.path, unused_component_outputs;
193    UnusedSvelteEventFinding => event.path, unused_svelte_events;
194    UnusedEffectLayerFinding => layer.path, unused_effect_layers;
195    UnusedTaggedErrorFinding => error.path, unused_tagged_errors;
196    UnproducedCatchTagFinding => catch_tag.path, unproduced_catch_tags;
197    UnusedServerActionFinding => action.path, unused_server_actions;
198    UnusedLoadDataKeyFinding => key.path, unused_load_data_keys;
199    InvalidClientExportFinding => export.path, invalid_client_export;
200    MixedClientServerBarrelFinding => barrel.path, mixed_client_server_barrel;
201    MisplacedDirectiveFinding => directive_site.path, misplaced_directive;
202    RouteCollisionFinding => collision.path, route_collision;
203    DynamicSegmentNameConflictFinding => conflict.path, dynamic_segment_name_conflict;
204    BoundaryViolationFinding => violation.from_path, boundary_violation;
205    BoundaryCoverageViolationFinding => violation.path, boundary_violation;
206    BoundaryCallViolationFinding => violation.path, boundary_violation;
207    UnresolvedCatalogReferenceFinding => reference.path, unresolved_catalog_references;
208    EmptyCatalogGroupFinding => group.path, empty_catalog_groups;
209    UnusedDependencyOverrideFinding => entry.path, unused_dependency_overrides;
210    MisconfiguredDependencyOverrideFinding => entry.path, misconfigured_dependency_overrides;
211}
212
213project_level! {
214    UnusedDependencyFinding => unused_dependencies;
215    UnusedDevDependencyFinding => unused_dev_dependencies;
216    UnusedOptionalDependencyFinding => unused_optional_dependencies;
217    UnlistedDependencyFinding => unlisted_dependencies;
218    DuplicateExportFinding => duplicate_exports;
219    TypeOnlyDependencyFinding => type_only_dependencies;
220    TestOnlyDependencyFinding => test_only_dependencies;
221    DevDependencyInProductionFinding => dev_dependencies_in_production;
222    ReExportCycleFinding => re_export_cycle;
223    UnusedCatalogEntryFinding => unused_catalog_entries;
224}
225
226impl RuleSeverity for CircularDependencyFinding {
227    fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity {
228        self.cycle
229            .files
230            .iter()
231            .map(|path| source.for_path(path, |rules| rules.circular_dependencies))
232            .max_by_key(|severity| severity_rank(*severity))
233            .unwrap_or_else(|| source.project(|rules| rules.circular_dependencies))
234    }
235
236    fn uniform_severity(source: &SeveritySource<'_>) -> Option<Severity> {
237        source.uniform(|rules| rules.circular_dependencies)
238    }
239}
240
241impl RuleSeverity for PackageCycleFinding {
242    fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity {
243        self.cycle
244            .edges
245            .iter()
246            .map(|edge| source.for_path(&edge.path, |rules| rules.package_cycle))
247            .max_by_key(|severity| severity_rank(*severity))
248            .unwrap_or_else(|| source.project(|rules| rules.package_cycle))
249    }
250
251    fn uniform_severity(source: &SeveritySource<'_>) -> Option<Severity> {
252        source.uniform(|rules| rules.package_cycle)
253    }
254}
255
256impl RuleSeverity for StaleSuppression {
257    fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity {
258        if self.missing_reason {
259            source.for_path(&self.path, |rules| rules.require_suppression_reason)
260        } else {
261            source.for_path(&self.path, |rules| rules.stale_suppressions)
262        }
263    }
264
265    fn uniform_severity(source: &SeveritySource<'_>) -> Option<Severity> {
266        let stale = source.uniform(|rules| rules.stale_suppressions)?;
267        let missing_reason = source.uniform(|rules| rules.require_suppression_reason)?;
268        (stale == missing_reason).then_some(stale)
269    }
270}
271
272impl RuleSeverity for PolicyViolationFinding {
273    fn rule_severity(&self, _source: &SeveritySource<'_>) -> Severity {
274        match self.violation.severity {
275            PolicyViolationSeverity::Error => Severity::Error,
276            PolicyViolationSeverity::Warn => Severity::Warn,
277        }
278    }
279}
280
281const fn severity_rank(severity: Severity) -> u8 {
282    match severity {
283        Severity::Off => 0,
284        Severity::Warn => 1,
285        Severity::Error => 2,
286    }
287}
288
289impl RuleSeverity for PropDrillingChainFinding {
290    fn rule_severity(&self, source: &SeveritySource<'_>) -> Severity {
291        self.chain.hops.first().map_or_else(
292            || source.project(|rules| rules.prop_drilling),
293            |hop| source.for_path(&hop.file, |rules| rules.prop_drilling),
294        )
295    }
296}
297
298/// A finding that has a rule severity and carries a gate severity.
299trait GatedRuleFinding: GatedFinding + RuleSeverity {}
300
301impl<T: GatedFinding + RuleSeverity> GatedRuleFinding for T {}
302
303/// Write the gate severity onto each dead-code finding in `results`.
304///
305/// Call this after the findings whose rule is `off` are removed. The function
306/// overwrites any earlier value, so a second call with the same config gives
307/// the same result.
308pub fn apply_effective_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
309    let source = SeveritySource::from_config(config);
310    for_each_gated_finding(results, &mut |finding| {
311        let severity = finding.rule_severity(&source);
312        finding.set_effective_severity(gate(severity));
313    });
314    apply_prop_drilling_severities(results, config);
315    apply_component_shape_severities(results, config);
316}
317
318pub fn apply_prop_drilling_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
319    let source = SeveritySource::from_config(config);
320    results.prop_drilling_chains.retain_mut(|finding| {
321        let severity = finding.rule_severity(&source);
322        finding.set_effective_severity(gate(severity));
323        severity != Severity::Off
324    });
325}
326
327/// Resolve source-owned component health severities without promoting warnings.
328fn apply_component_shape_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
329    let source = SeveritySource::from_config(config);
330    retain_component_findings(&mut results.thin_wrappers, &source);
331    retain_component_findings(&mut results.duplicate_prop_shapes, &source);
332}
333
334fn retain_component_findings<T: GatedRuleFinding>(
335    findings: &mut Vec<T>,
336    source: &SeveritySource<'_>,
337) {
338    findings.retain_mut(|finding| {
339        let severity = finding.rule_severity(source);
340        finding.set_effective_severity(gate(severity));
341        severity != Severity::Off
342    });
343}
344
345/// The number of gated dead-code findings in `results` that carry no saved
346/// severity, for example in a report from an older version. A renderer then
347/// takes their level from the configured rules.
348///
349/// Policy violations carry their own severity and do not count.
350#[must_use]
351pub fn findings_without_severity(mut results: AnalysisResults) -> usize {
352    let mut missing = results
353        .prop_drilling_chains
354        .iter()
355        .filter(|finding| finding.effective_severity.is_none())
356        .count()
357        + results
358            .thin_wrappers
359            .iter()
360            .filter(|finding| finding.effective_severity.is_none())
361            .count()
362        + results
363            .duplicate_prop_shapes
364            .iter()
365            .filter(|finding| finding.effective_severity.is_none())
366            .count();
367    for_each_gated_finding(&mut results, &mut |finding| {
368        if finding.effective_severity().is_none() {
369            missing += 1;
370        }
371    });
372    missing
373}
374
375/// Raise every `warn` gate severity to `error`, for `--fail-on-issues`.
376///
377/// Counted warnings become errors in every CI format. Advisory component
378/// health signals retain their saved severity.
379pub fn promote_effective_warns(results: &mut AnalysisResults) {
380    for_each_gated_finding(results, &mut |finding| {
381        if finding.effective_severity() == Some(EffectiveSeverity::Warn) {
382            finding.set_effective_severity(Some(EffectiveSeverity::Error));
383        }
384    });
385}
386
387/// Whether any dead-code finding in `results` has `severity` under `source`.
388///
389/// Policy violations count with their own severity.
390#[must_use]
391pub fn any_finding_with_severity(
392    results: &AnalysisResults,
393    source: &SeveritySource<'_>,
394    severity: Severity,
395) -> bool {
396    count_findings_up_to(results, source, severity, 1) > 0
397}
398
399/// How many dead-code findings in `results` have `severity` under `source`.
400///
401/// The same rule table as [`any_finding_with_severity`], so the count is
402/// zero exactly when that function returns false.
403#[must_use]
404pub fn count_findings_with_severity(
405    results: &AnalysisResults,
406    source: &SeveritySource<'_>,
407    severity: Severity,
408) -> usize {
409    count_findings_up_to(results, source, severity, usize::MAX)
410}
411
412/// Count the findings with `severity`, and stop at `limit`.
413fn count_findings_up_to(
414    results: &AnalysisResults,
415    source: &SeveritySource<'_>,
416    severity: Severity,
417    limit: usize,
418) -> usize {
419    let mut tally = SeverityTally {
420        source,
421        severity,
422        limit,
423        total: 0,
424    };
425    if severity == Severity::Error
426        && (tally.add(&results.prop_drilling_chains)
427            || tally.add(&results.thin_wrappers)
428            || tally.add(&results.duplicate_prop_shapes))
429    {
430        return tally.total;
431    }
432    if !tally.add(&results.policy_violations) {
433        tally_gated_findings(results, &mut tally);
434    }
435    tally.total
436}
437
438/// A running count of the findings with one severity. It stops at `limit`,
439/// so the yes or no question reads no more findings than it needs.
440struct SeverityTally<'s, 'a> {
441    source: &'s SeveritySource<'a>,
442    severity: Severity,
443    limit: usize,
444    total: usize,
445}
446
447impl SeverityTally<'_, '_> {
448    /// Add the matching findings of one collection. Returns true when the
449    /// count reached `limit`.
450    ///
451    /// When every finding of the kind has the same severity, one table lookup
452    /// answers for the whole collection.
453    fn add<T: RuleSeverity>(&mut self, findings: &[T]) -> bool {
454        let remaining = self.limit - self.total;
455        let found = if findings.is_empty() || remaining == 0 {
456            0
457        } else {
458            match T::uniform_severity(self.source) {
459                Some(uniform) if uniform == self.severity => findings.len().min(remaining),
460                Some(_) => 0,
461                None => findings
462                    .iter()
463                    .filter(|finding| finding.rule_severity(self.source) == self.severity)
464                    .take(remaining)
465                    .count(),
466            }
467        };
468        self.total += found;
469        self.total >= self.limit
470    }
471}
472fn visit<T: GatedRuleFinding>(findings: &mut [T], f: &mut dyn FnMut(&mut dyn GatedRuleFinding)) {
473    for finding in findings {
474        f(finding);
475    }
476}
477/// Visit every finding that carries a gate severity.
478///
479/// The destructure has no `..`, so a new field on [`AnalysisResults`] fails to
480/// compile here until it is listed.
481#[expect(
482    clippy::too_many_lines,
483    reason = "one exhaustive list of finding collections; splitting it would lose the compile-time guard"
484)]
485fn for_each_gated_finding(
486    results: &mut AnalysisResults,
487    f: &mut dyn FnMut(&mut dyn GatedRuleFinding),
488) {
489    let AnalysisResults {
490        unused_files,
491        unused_exports,
492        unused_types,
493        private_type_leaks,
494        deprecated_exports_in_use,
495        unused_dependencies,
496        unused_dev_dependencies,
497        unused_optional_dependencies,
498        unused_enum_members,
499        unused_class_members,
500        unused_store_members,
501        unresolved_imports,
502        unlisted_dependencies,
503        duplicate_exports,
504        type_only_dependencies,
505        test_only_dependencies,
506        dev_dependencies_in_production,
507        circular_dependencies,
508        re_export_cycles,
509        package_cycles,
510        boundary_violations,
511        boundary_coverage_violations,
512        boundary_call_violations,
513        stale_suppressions,
514        unused_catalog_entries,
515        empty_catalog_groups,
516        unresolved_catalog_references,
517        unused_dependency_overrides,
518        misconfigured_dependency_overrides,
519        invalid_client_exports,
520        mixed_client_server_barrels,
521        misplaced_directives,
522        unprovided_injects,
523        unrendered_components,
524        route_collisions,
525        dynamic_segment_name_conflicts,
526        unused_component_props,
527        absent_component_props,
528        unused_component_emits,
529        unused_component_inputs,
530        unused_component_outputs,
531        unused_svelte_events,
532        unused_effect_layers,
533        unused_tagged_errors,
534        unproduced_catch_tags,
535        unused_server_actions,
536        unused_load_data_keys,
537        // Policy violations carry their own evaluated `severity`.
538        policy_violations: _,
539        // Prop chains are resolved separately to preserve advisory warnings.
540        prop_drilling_chains: _,
541        thin_wrappers: _,
542        duplicate_prop_shapes: _,
543        // Not findings: counts, flags and metadata.
544        unused_load_data_keys_global_abstain: _,
545        cascade_hidden: _,
546        cascade: _,
547        suppression_count: _,
548        unused_component_props_exempted: _,
549        active_suppressions: _,
550        feature_flags: _,
551        export_usages: _,
552        entry_point_summary: _,
553        render_fan_in: _,
554        react_component_intel: _,
555        semantic_reachable_files: _,
556        semantic_framework_contracts: _,
557        // Security findings belong to `fallow security` and its own gate.
558        security_findings: _,
559        security_unresolved_edge_files: _,
560        security_unresolved_callee_sites: _,
561        security_unresolved_callee_diagnostics: _,
562    } = results;
563    visit(unused_files, f);
564    visit(unused_exports, f);
565    visit(unused_types, f);
566    visit(private_type_leaks, f);
567    visit(deprecated_exports_in_use, f);
568    visit(unused_dependencies, f);
569    visit(unused_dev_dependencies, f);
570    visit(unused_optional_dependencies, f);
571    visit(unused_enum_members, f);
572    visit(unused_class_members, f);
573    visit(unused_store_members, f);
574    visit(unresolved_imports, f);
575    visit(unlisted_dependencies, f);
576    visit(duplicate_exports, f);
577    visit(type_only_dependencies, f);
578    visit(test_only_dependencies, f);
579    visit(dev_dependencies_in_production, f);
580    visit(circular_dependencies, f);
581    visit(re_export_cycles, f);
582    visit(package_cycles, f);
583    visit(boundary_violations, f);
584    visit(boundary_coverage_violations, f);
585    visit(boundary_call_violations, f);
586    visit(stale_suppressions, f);
587    visit(unused_catalog_entries, f);
588    visit(empty_catalog_groups, f);
589    visit(unresolved_catalog_references, f);
590    visit(unused_dependency_overrides, f);
591    visit(misconfigured_dependency_overrides, f);
592    visit(invalid_client_exports, f);
593    visit(mixed_client_server_barrels, f);
594    visit(misplaced_directives, f);
595    visit(unprovided_injects, f);
596    visit(unrendered_components, f);
597    visit(route_collisions, f);
598    visit(dynamic_segment_name_conflicts, f);
599    visit(unused_component_props, f);
600    visit(absent_component_props, f);
601    visit(unused_component_emits, f);
602    visit(unused_component_inputs, f);
603    visit(unused_component_outputs, f);
604    visit(unused_svelte_events, f);
605    visit(unused_effect_layers, f);
606    visit(unused_tagged_errors, f);
607    visit(unproduced_catch_tags, f);
608    visit(unused_server_actions, f);
609    visit(unused_load_data_keys, f);
610}
611
612/// Add every finding that carries a gate severity to `tally`, until it
613/// reaches its limit.
614///
615/// Exhaustive like [`for_each_gated_finding`]: a new field on
616/// [`AnalysisResults`] fails to compile here until it is listed.
617#[expect(
618    clippy::too_many_lines,
619    reason = "one exhaustive list of finding collections; splitting it would lose the compile-time guard"
620)]
621fn tally_gated_findings(results: &AnalysisResults, tally: &mut SeverityTally<'_, '_>) {
622    let AnalysisResults {
623        unused_files,
624        unused_exports,
625        unused_types,
626        private_type_leaks,
627        deprecated_exports_in_use,
628        unused_dependencies,
629        unused_dev_dependencies,
630        unused_optional_dependencies,
631        unused_enum_members,
632        unused_class_members,
633        unused_store_members,
634        unresolved_imports,
635        unlisted_dependencies,
636        duplicate_exports,
637        type_only_dependencies,
638        test_only_dependencies,
639        dev_dependencies_in_production,
640        circular_dependencies,
641        re_export_cycles,
642        package_cycles,
643        boundary_violations,
644        boundary_coverage_violations,
645        boundary_call_violations,
646        stale_suppressions,
647        unused_catalog_entries,
648        empty_catalog_groups,
649        unresolved_catalog_references,
650        unused_dependency_overrides,
651        misconfigured_dependency_overrides,
652        invalid_client_exports,
653        mixed_client_server_barrels,
654        misplaced_directives,
655        unprovided_injects,
656        unrendered_components,
657        route_collisions,
658        dynamic_segment_name_conflicts,
659        unused_component_props,
660        absent_component_props,
661        unused_component_emits,
662        unused_component_inputs,
663        unused_component_outputs,
664        unused_svelte_events,
665        unused_effect_layers,
666        unused_tagged_errors,
667        unproduced_catch_tags,
668        unused_server_actions,
669        unused_load_data_keys,
670        policy_violations: _,
671        prop_drilling_chains: _,
672        thin_wrappers: _,
673        duplicate_prop_shapes: _,
674        unused_load_data_keys_global_abstain: _,
675        cascade_hidden: _,
676        cascade: _,
677        suppression_count: _,
678        unused_component_props_exempted: _,
679        active_suppressions: _,
680        feature_flags: _,
681        export_usages: _,
682        entry_point_summary: _,
683        render_fan_in: _,
684        react_component_intel: _,
685        semantic_reachable_files: _,
686        semantic_framework_contracts: _,
687        security_findings: _,
688        security_unresolved_edge_files: _,
689        security_unresolved_callee_sites: _,
690        security_unresolved_callee_diagnostics: _,
691    } = results;
692    let _reached_limit = tally.add(unused_files)
693        || tally.add(unused_exports)
694        || tally.add(unused_types)
695        || tally.add(private_type_leaks)
696        || tally.add(deprecated_exports_in_use)
697        || tally.add(unused_dependencies)
698        || tally.add(unused_dev_dependencies)
699        || tally.add(unused_optional_dependencies)
700        || tally.add(unused_enum_members)
701        || tally.add(unused_class_members)
702        || tally.add(unused_store_members)
703        || tally.add(unresolved_imports)
704        || tally.add(unlisted_dependencies)
705        || tally.add(duplicate_exports)
706        || tally.add(type_only_dependencies)
707        || tally.add(test_only_dependencies)
708        || tally.add(dev_dependencies_in_production)
709        || tally.add(circular_dependencies)
710        || tally.add(re_export_cycles)
711        || tally.add(package_cycles)
712        || tally.add(boundary_violations)
713        || tally.add(boundary_coverage_violations)
714        || tally.add(boundary_call_violations)
715        || tally.add(stale_suppressions)
716        || tally.add(unused_catalog_entries)
717        || tally.add(empty_catalog_groups)
718        || tally.add(unresolved_catalog_references)
719        || tally.add(unused_dependency_overrides)
720        || tally.add(misconfigured_dependency_overrides)
721        || tally.add(invalid_client_exports)
722        || tally.add(mixed_client_server_barrels)
723        || tally.add(misplaced_directives)
724        || tally.add(unprovided_injects)
725        || tally.add(unrendered_components)
726        || tally.add(route_collisions)
727        || tally.add(dynamic_segment_name_conflicts)
728        || tally.add(unused_component_props)
729        || tally.add(absent_component_props)
730        || tally.add(unused_component_emits)
731        || tally.add(unused_component_inputs)
732        || tally.add(unused_component_outputs)
733        || tally.add(unused_svelte_events)
734        || tally.add(unused_effect_layers)
735        || tally.add(unused_tagged_errors)
736        || tally.add(unproduced_catch_tags)
737        || tally.add(unused_server_actions)
738        || tally.add(unused_load_data_keys);
739}
740
741#[cfg(test)]
742mod tests {
743    use std::path::PathBuf;
744
745    use fallow_types::output_dead_code::{
746        CircularDependencyFinding, MisconfiguredDependencyOverrideFinding, UnusedDependencyFinding,
747        UnusedExportFinding,
748    };
749    use fallow_types::results::StaleSuppression;
750    use serde_json::json;
751
752    use super::*;
753
754    const ROOT: &str = "/project";
755
756    fn config(json: &str) -> ResolvedConfig {
757        serde_json::from_str::<fallow_config::FallowConfig>(json)
758            .expect("config parses")
759            .resolve(
760                PathBuf::from(ROOT),
761                fallow_config::OutputFormat::Human,
762                1,
763                true,
764                true,
765                None,
766            )
767    }
768
769    fn legacy_warn_config() -> ResolvedConfig {
770        config(
771            r#"{
772                "rules": {
773                    "unused-exports": "error",
774                    "circular-dependencies": "error",
775                    "unused-dependencies": "error",
776                    "stale-suppressions": "warn",
777                    "require-suppression-reason": "error"
778                },
779                "overrides": [{
780                    "files": ["src/legacy/**", "package.json"],
781                    "rules": {
782                        "unused-exports": "warn",
783                        "circular-dependencies": "warn",
784                        "unused-dependencies": "warn",
785                        "require-suppression-reason": "warn"
786                    }
787                }]
788            }"#,
789        )
790    }
791
792    fn export(path: &str) -> UnusedExportFinding {
793        serde_json::from_value(json!({
794            "path": format!("{ROOT}/{path}"),
795            "export_name": "unused",
796            "is_type_only": false,
797            "line": 1,
798            "col": 0,
799            "span_start": 0,
800            "is_re_export": false,
801            "actions": [],
802        }))
803        .expect("export finding")
804    }
805
806    fn cycle(files: &[&str]) -> CircularDependencyFinding {
807        serde_json::from_value(json!({
808            "files": files.iter().map(|file| format!("{ROOT}/{file}")).collect::<Vec<_>>(),
809            "length": files.len(),
810            "line": 1,
811            "col": 0,
812            "actions": [],
813        }))
814        .expect("cycle finding")
815    }
816
817    fn stale(path: &str, missing_reason: bool) -> StaleSuppression {
818        serde_json::from_value(json!({
819            "path": format!("{ROOT}/{path}"),
820            "line": 1,
821            "col": 0,
822            "origin": { "type": "comment", "is_file_level": false },
823            "missing_reason": missing_reason,
824            "actions": [],
825        }))
826        .expect("stale suppression")
827    }
828
829    #[test]
830    fn file_scoped_findings_follow_the_override_for_their_path() {
831        let mut results = AnalysisResults::default();
832        results.unused_exports.push(export("src/app.ts"));
833        results.unused_exports.push(export("src/legacy/old.ts"));
834
835        apply_effective_severities(&mut results, &legacy_warn_config());
836
837        let severities: Vec<_> = results
838            .unused_exports
839            .iter()
840            .map(|finding| finding.effective_severity)
841            .collect();
842        assert_eq!(
843            severities,
844            vec![
845                Some(EffectiveSeverity::Error),
846                Some(EffectiveSeverity::Warn)
847            ]
848        );
849    }
850
851    #[test]
852    fn a_cycle_is_error_when_any_file_in_it_resolves_to_error() {
853        let mut results = AnalysisResults::default();
854        results
855            .circular_dependencies
856            .push(cycle(&["src/legacy/a.ts", "src/b.ts"]));
857        results
858            .circular_dependencies
859            .push(cycle(&["src/legacy/a.ts", "src/legacy/b.ts"]));
860
861        apply_effective_severities(&mut results, &legacy_warn_config());
862
863        assert_eq!(
864            results.circular_dependencies[0].effective_severity,
865            Some(EffectiveSeverity::Error)
866        );
867        assert_eq!(
868            results.circular_dependencies[1].effective_severity,
869            Some(EffectiveSeverity::Warn)
870        );
871    }
872
873    /// A new `project_level!` row needs a row in the config table, or its
874    /// override stays silent. A config row without a `project_level!` row
875    /// makes fallow report an override that works. Each row also needs its own
876    /// next step in the note.
877    #[test]
878    fn project_level_list_matches_the_override_rule_table() {
879        let parse = |key: &str| -> fallow_config::PartialRulesConfig {
880            serde_json::from_value(json!({ key: "off" })).expect("rule key")
881        };
882        let mut from_findings: Vec<String> = PROJECT_LEVEL_RULE_FIELDS
883            .iter()
884            .map(|field| field.replace('_', "-"))
885            .collect();
886        for rule in &from_findings {
887            assert_eq!(
888                fallow_config::project_level_override_rules(&parse(rule)),
889                vec![rule.as_str()],
890                "`project_level!` lists {rule}"
891            );
892        }
893        let mut from_table: Vec<String> = fallow_config::KNOWN_RULE_NAMES
894            .iter()
895            .flat_map(|key| fallow_config::project_level_override_rules(&parse(key)))
896            .map(str::to_owned)
897            .collect();
898        from_table.sort_unstable();
899        from_table.dedup();
900        from_findings.sort_unstable();
901        assert_eq!(from_table, from_findings);
902
903        for rule in from_table {
904            let kind = fallow_config::WorkspaceDiagnosticKind::OverrideRuleIneffective {
905                rule: rule.clone(),
906                files: vec!["**".to_owned()],
907                reason: "project-level".to_owned(),
908            };
909            assert_ne!(
910                kind.ineffective_override_hint(),
911                Some("project-level rule; set the top-level rule"),
912                "{rule} needs its own next step"
913            );
914        }
915    }
916
917    #[test]
918    fn project_level_findings_use_the_base_rules() {
919        let mut results = AnalysisResults::default();
920        results.unused_dependencies.push(
921            serde_json::from_value::<UnusedDependencyFinding>(json!({
922                "package_name": "left-pad",
923                "location": "dependencies",
924                "path": format!("{ROOT}/package.json"),
925                "line": 3,
926                "actions": [],
927            }))
928            .expect("dependency finding"),
929        );
930
931        apply_effective_severities(&mut results, &legacy_warn_config());
932
933        assert_eq!(
934            results.unused_dependencies[0].effective_severity,
935            Some(EffectiveSeverity::Error)
936        );
937    }
938
939    #[test]
940    fn a_dependency_override_follows_the_override_for_its_file() {
941        let config = config(
942            r#"{
943                "rules": { "misconfigured-dependency-overrides": "error" },
944                "overrides": [{
945                    "files": ["pnpm-workspace.yaml"],
946                    "rules": { "misconfigured-dependency-overrides": "warn" }
947                }]
948            }"#,
949        );
950        let mut results = AnalysisResults::default();
951        for file in ["pnpm-workspace.yaml", "package.json"] {
952            results.misconfigured_dependency_overrides.push(
953                serde_json::from_value::<MisconfiguredDependencyOverrideFinding>(json!({
954                    "raw_key": "",
955                    "raw_value": "^1.0.0",
956                    "reason": "empty-value",
957                    "source": file,
958                    "path": format!("{ROOT}/{file}"),
959                    "line": 2,
960                    "actions": [],
961                }))
962                .expect("override finding"),
963            );
964        }
965
966        apply_effective_severities(&mut results, &config);
967
968        let severities: Vec<_> = results
969            .misconfigured_dependency_overrides
970            .iter()
971            .map(|finding| finding.effective_severity)
972            .collect();
973        assert_eq!(
974            severities,
975            vec![
976                Some(EffectiveSeverity::Warn),
977                Some(EffectiveSeverity::Error)
978            ]
979        );
980    }
981
982    #[test]
983    fn a_stale_suppression_reads_the_rule_for_its_kind() {
984        let mut results = AnalysisResults::default();
985        results.stale_suppressions.push(stale("src/app.ts", false));
986        results.stale_suppressions.push(stale("src/app.ts", true));
987        results
988            .stale_suppressions
989            .push(stale("src/legacy/old.ts", true));
990
991        apply_effective_severities(&mut results, &legacy_warn_config());
992
993        let severities: Vec<_> = results
994            .stale_suppressions
995            .iter()
996            .map(|finding| finding.effective_severity)
997            .collect();
998        assert_eq!(
999            severities,
1000            vec![
1001                Some(EffectiveSeverity::Warn),
1002                Some(EffectiveSeverity::Error),
1003                Some(EffectiveSeverity::Warn),
1004            ]
1005        );
1006    }
1007
1008    #[test]
1009    fn fail_on_issues_promotion_raises_warn_and_keeps_error() {
1010        let mut results = AnalysisResults::default();
1011        results.unused_exports.push(export("src/app.ts"));
1012        results.unused_exports.push(export("src/legacy/old.ts"));
1013        apply_effective_severities(&mut results, &legacy_warn_config());
1014
1015        promote_effective_warns(&mut results);
1016
1017        assert!(
1018            results
1019                .unused_exports
1020                .iter()
1021                .all(|finding| finding.effective_severity == Some(EffectiveSeverity::Error))
1022        );
1023    }
1024
1025    /// `apply_rule_severities` removes such a cycle before it writes the
1026    /// severities. The table must still agree with itself when a caller
1027    /// skips that filter.
1028    #[test]
1029    fn a_cycle_whose_files_all_resolve_to_off_gets_no_severity() {
1030        let config = config(
1031            r#"{
1032                "rules": { "circular-dependencies": "error" },
1033                "overrides": [{
1034                    "files": ["src/legacy/**"],
1035                    "rules": { "circular-dependencies": "off" }
1036                }]
1037            }"#,
1038        );
1039        let mut results = AnalysisResults::default();
1040        results
1041            .circular_dependencies
1042            .push(cycle(&["src/legacy/a.ts", "src/legacy/b.ts"]));
1043
1044        apply_effective_severities(&mut results, &config);
1045
1046        assert_eq!(results.circular_dependencies[0].effective_severity, None);
1047        assert!(!crate::error_severity::has_error_severity_issues(
1048            &results,
1049            &config.rules,
1050            Some(&config),
1051            false
1052        ));
1053        // The audit ledger reads this value for each finding.
1054        assert_eq!(
1055            results.circular_dependencies[0].rule_severity(&SeveritySource::from_config(&config)),
1056            Severity::Off
1057        );
1058    }
1059
1060    #[test]
1061    fn the_collection_check_agrees_with_the_per_finding_check_without_overrides() {
1062        let configs = [
1063            r#"{ "rules": { "unused-exports": "error", "circular-dependencies": "warn",
1064                 "unused-dependencies": "off", "stale-suppressions": "warn",
1065                 "require-suppression-reason": "warn" } }"#,
1066            r#"{ "rules": { "unused-exports": "warn", "circular-dependencies": "error",
1067                 "unused-dependencies": "error", "stale-suppressions": "warn",
1068                 "require-suppression-reason": "error" } }"#,
1069            r#"{ "rules": { "unused-exports": "off", "circular-dependencies": "off",
1070                 "unused-dependencies": "warn", "stale-suppressions": "error",
1071                 "require-suppression-reason": "off" } }"#,
1072        ];
1073        let mut results = AnalysisResults::default();
1074        results.unused_exports.push(export("src/app.ts"));
1075        results
1076            .circular_dependencies
1077            .push(cycle(&["src/a.ts", "src/b.ts"]));
1078        results.circular_dependencies.push(cycle(&[]));
1079        results.unused_dependencies.push(
1080            serde_json::from_value::<UnusedDependencyFinding>(json!({
1081                "package_name": "left-pad",
1082                "location": "dependencies",
1083                "path": format!("{ROOT}/package.json"),
1084                "line": 3,
1085                "actions": [],
1086            }))
1087            .expect("dependency finding"),
1088        );
1089        results.stale_suppressions.push(stale("src/app.ts", false));
1090        results.stale_suppressions.push(stale("src/app.ts", true));
1091
1092        for json in configs {
1093            let config = config(json);
1094            for promote in [false, true] {
1095                let mut rules = config.rules.clone();
1096                if promote {
1097                    promote_warns_to_errors(&mut rules);
1098                }
1099                let source = SeveritySource::new(&rules, Some(&config), promote);
1100                assert!(source.overrides.is_none());
1101                for severity in [Severity::Error, Severity::Warn, Severity::Off] {
1102                    let mut per_finding = 0_usize;
1103                    for_each_gated_finding(&mut results, &mut |finding| {
1104                        per_finding += usize::from(finding.rule_severity(&source) == severity);
1105                    });
1106                    assert_eq!(
1107                        count_findings_with_severity(&results, &source, severity),
1108                        per_finding,
1109                        "{json} promote={promote} {severity:?}"
1110                    );
1111                    assert_eq!(
1112                        any_finding_with_severity(&results, &source, severity),
1113                        per_finding > 0,
1114                        "{json} promote={promote} {severity:?}"
1115                    );
1116                }
1117            }
1118        }
1119    }
1120
1121    type AddFinding = fn(&mut AnalysisResults);
1122
1123    #[test]
1124    fn the_exit_code_rule_fails_exactly_when_a_finding_is_stamped_error() {
1125        let config = legacy_warn_config();
1126        let cases: [(&str, AddFinding); 4] = [
1127            ("legacy export", |r| {
1128                r.unused_exports.push(export("src/legacy/old.ts"));
1129            }),
1130            ("app export", |r| {
1131                r.unused_exports.push(export("src/app.ts"));
1132            }),
1133            ("legacy cycle", |r| {
1134                r.circular_dependencies
1135                    .push(cycle(&["src/legacy/a.ts", "src/legacy/b.ts"]));
1136            }),
1137            ("stale suppression", |r| {
1138                r.stale_suppressions.push(stale("src/app.ts", false));
1139            }),
1140        ];
1141        for (name, add) in cases {
1142            let mut results = AnalysisResults::default();
1143            add(&mut results);
1144            apply_effective_severities(&mut results, &config);
1145            let mut stamped_error = false;
1146            for_each_gated_finding(&mut results, &mut |finding| {
1147                stamped_error |= finding.effective_severity() == Some(EffectiveSeverity::Error);
1148            });
1149            assert_eq!(
1150                crate::error_severity::has_error_severity_issues(
1151                    &results,
1152                    &config.rules,
1153                    Some(&config),
1154                    false
1155                ),
1156                stamped_error,
1157                "{name}"
1158            );
1159        }
1160    }
1161}