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