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