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