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