Skip to main content

fallow_types/
results.rs

1//! Analysis result types for all issue categories.
2
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::extract::{
8    MemberKind, SecurityControlKind, SecurityUrlShape, SkippedSecurityCalleeExpressionKind,
9    SkippedSecurityCalleeReason,
10};
11use crate::output::{
12    FixAction, FixActionType, IssueAction, SuppressLineAction, SuppressLineKind, SuppressLineScope,
13};
14use crate::output_dead_code::{
15    BoundaryCallViolationFinding, BoundaryCoverageViolationFinding, BoundaryViolationFinding,
16    CircularDependencyFinding, DeprecatedExportInUseFinding, DevDependencyInProductionFinding,
17    DuplicateExportAliasFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
18    DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding, InvalidClientExportFinding,
19    MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
20    MixedClientServerBarrelFinding, NamespaceEscapeFinding, PackageCycleFinding,
21    PolicyViolationFinding, PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding,
22    RouteCollisionFinding, TestOnlyDependencyFinding, TestOnlyExportFinding, ThinWrapperFinding,
23    TypeOnlyDependencyFinding, UnlistedBinaryFinding, UnlistedDependencyFinding,
24    UnprovidedInjectFinding, UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding,
25    UnresolvedImportFinding, UnusedCatalogEntryFinding, UnusedClassMemberFinding,
26    UnusedComponentEmitFinding, UnusedComponentInputFinding, UnusedComponentOutputFinding,
27    UnusedComponentPropFinding, UnusedDependencyFinding, UnusedDependencyOverrideFinding,
28    UnusedDevDependencyFinding, UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding,
29    UnusedLoadDataKeyFinding, UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding,
30    UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
31    UnusedSvelteEventFinding, UnusedTypeFinding,
32};
33pub use crate::output_dead_code::{
34    UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
35};
36#[path = "results_boundary.rs"]
37mod boundary;
38#[path = "results_cycles.rs"]
39mod cycles;
40pub use cycles::{
41    CircularDependency, CircularDependencyEdge, PackageCycle, PackageCycleEdge, ReExportCycle,
42    ReExportCycleKind,
43};
44#[path = "results_namespace_escape.rs"]
45mod namespace_escape;
46pub use namespace_escape::{NamespaceEscape, NamespaceEscapeReason};
47#[path = "results_security_finding.rs"]
48mod security_finding;
49pub use security_finding::SecurityFinding;
50#[path = "results_test_only_export.rs"]
51mod test_only_export;
52pub use test_only_export::TestOnlyExport;
53#[path = "results_trace_hop.rs"]
54mod trace_hop;
55pub use trace_hop::{TraceHop, TraceHopRole, TraceSecretRead};
56#[path = "results_caller_review.rs"]
57mod caller_review;
58#[path = "results_component_health.rs"]
59mod component_health;
60pub use boundary::{BoundaryViolation, BoundaryViolationReason};
61pub use caller_review::*;
62
63pub use component_health::ERROR_ONLY_RESULT_KEYS;
64
65use crate::serde_path;
66#[path = "results_ignore_findings.rs"]
67mod ignore_findings;
68#[path = "results_stale_suppression_text.rs"]
69mod stale_suppression_text;
70use ignore_findings::classify_ignore_findings_fields;
71
72#[path = "results_active_suppression.rs"]
73mod active_suppression;
74pub use active_suppression::ActiveSuppression;
75#[path = "results_inventory_merge.rs"]
76mod inventory_merge;
77#[path = "results_merge_parts.rs"]
78mod merge_parts;
79use merge_parts::split_merge_parts;
80
81/// Summary of detected entry points, grouped by discovery source.
82///
83/// Used to surface entry-point detection status in human and JSON output,
84/// so library authors can verify that fallow found the right entry points.
85#[derive(Debug, Clone, Default)]
86#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
87pub struct EntryPointSummary {
88    /// Total number of entry points detected.
89    pub total: usize,
90    /// Breakdown by source category (e.g., "package.json" -> 3, "plugin" -> 12).
91    /// Sorted by key for deterministic output.
92    pub by_source: Vec<(String, usize)>,
93}
94
95#[path = "results_component_intel.rs"]
96mod component_intel;
97pub use component_intel::*;
98
99/// Complete analysis results.
100///
101/// # Examples
102///
103/// ```
104/// use fallow_types::output_dead_code::UnusedFileFinding;
105/// use fallow_types::results::{AnalysisResults, UnusedFile};
106/// use std::path::PathBuf;
107///
108/// let mut results = AnalysisResults::default();
109/// assert_eq!(results.total_issues(), 0);
110/// assert!(!results.has_issues());
111///
112/// results
113///     .unused_files
114///     .push(UnusedFileFinding::with_actions(UnusedFile {
115///         path: PathBuf::from("src/dead.ts"),
116///     }));
117/// assert_eq!(results.total_issues(), 1);
118/// assert!(results.has_issues());
119/// ```
120#[derive(Debug, Default, Clone, Serialize, Deserialize)]
121#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
122pub struct AnalysisResults {
123    /// Optional architecture inventory, excluded from issue totals and gates.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub shared_state: Option<crate::shared_state::SharedStateInventory>,
126    /// Files not reachable from any entry point. Wrapped in
127    /// [`UnusedFileFinding`] so each entry carries a typed `actions` array
128    /// natively, replacing the pre-2.76 post-pass injection.
129    pub unused_files: Vec<UnusedFileFinding>,
130    /// Exports never imported by other modules. Wrapped in
131    /// [`UnusedExportFinding`] so each entry carries a typed `actions`
132    /// array natively.
133    pub unused_exports: Vec<UnusedExportFinding>,
134    /// Type exports never imported by other modules. Wrapped in
135    /// [`UnusedTypeFinding`]: the inner [`UnusedExport`] struct is shared
136    /// with `unused_exports` but the wrapper emits a type-targeted fix
137    /// description.
138    pub unused_types: Vec<UnusedTypeFinding>,
139    /// Exported symbols whose public signature references same-file private
140    /// types. Wrapped in [`PrivateTypeLeakFinding`] so each entry carries a
141    /// typed `actions` array natively.
142    pub private_type_leaks: Vec<PrivateTypeLeakFinding>,
143    /// Exports marked `@deprecated` that still have at least one consumer in
144    /// a reachable file. Wrapped in [`DeprecatedExportInUseFinding`]. Opt-in: the
145    /// `deprecated-exports-in-use` rule defaults to `off`.
146    #[serde(default)]
147    pub deprecated_exports_in_use: Vec<DeprecatedExportInUseFinding>,
148    /// Dependencies listed in package.json but never imported. Wrapped in
149    /// [`UnusedDependencyFinding`] so each entry carries a typed `actions`
150    /// array natively. The fix action swaps from `remove-dependency` to
151    /// `move-dependency` when `used_in_workspaces` is non-empty.
152    pub unused_dependencies: Vec<UnusedDependencyFinding>,
153    /// Dev dependencies listed in package.json but never imported. Wrapped
154    /// in [`UnusedDevDependencyFinding`]: same bare struct as
155    /// `unused_dependencies` with a `devDependencies`-targeted fix
156    /// description.
157    pub unused_dev_dependencies: Vec<UnusedDevDependencyFinding>,
158    /// Optional dependencies listed in package.json but never imported.
159    /// Wrapped in [`UnusedOptionalDependencyFinding`] with an
160    /// `optionalDependencies`-targeted fix description.
161    pub unused_optional_dependencies: Vec<UnusedOptionalDependencyFinding>,
162    /// Enum members never accessed. Wrapped in
163    /// [`UnusedEnumMemberFinding`] so each entry carries a typed `actions`
164    /// array natively.
165    pub unused_enum_members: Vec<UnusedEnumMemberFinding>,
166    /// Class members never accessed. Wrapped in
167    /// [`UnusedClassMemberFinding`]: same inner [`UnusedMember`] struct as
168    /// `unused_enum_members`, with a class-targeted fix description and the
169    /// `auto_fixable: false` default to reflect dependency-injection
170    /// patterns.
171    pub unused_class_members: Vec<UnusedClassMemberFinding>,
172    /// Exported members of an exported TypeScript namespace that no code
173    /// reads. Wrapped in [`UnusedNamespaceMemberFinding`]: same inner
174    /// [`UnusedMember`] struct as `unused_enum_members`. `member_name` is the
175    /// dotted path from the exported namespace (`Inner.x`).
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub unused_namespace_members: Vec<UnusedNamespaceMemberFinding>,
178    /// `protected` class members that neither the class nor a subclass
179    /// reads. Wrapped in [`UnusedProtectedClassMemberFinding`]: same inner
180    /// [`UnusedMember`] struct as `unused_class_members`. The rule is `off`
181    /// by default, so this array is empty unless a config turns it on.
182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
183    pub unused_protected_class_members: Vec<UnusedProtectedClassMemberFinding>,
184    /// Namespace bindings that the code uses as a whole value, so every
185    /// export of the target module gets credit and stays unchecked. The rule
186    /// is `off` by default, so this array is empty unless a config turns it on.
187    #[serde(default, skip_serializing_if = "Vec::is_empty")]
188    pub namespace_escapes: Vec<NamespaceEscapeFinding>,
189    /// Exported values that only test-side files use. Default-scope runs
190    /// only: a production run reports such an export as an unused export.
191    /// The rule is `off` by default, so this array is empty unless a config
192    /// turns it on.
193    #[serde(default, skip_serializing_if = "Vec::is_empty")]
194    pub test_only_exports: Vec<TestOnlyExportFinding>,
195    /// Store members (Pinia `state` / `getters` / `actions` key, or a
196    /// setup-store returned key) declared but never accessed by any consumer
197    /// project-wide. Wrapped in [`UnusedStoreMemberFinding`]: same inner
198    /// [`UnusedMember`] struct as `unused_class_members`, with a
199    /// store-targeted fix description. Cross-graph: the store binding is
200    /// imported (the module is reachable) yet a specific member is dead.
201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
202    pub unused_store_members: Vec<UnusedStoreMemberFinding>,
203    /// Import specifiers that could not be resolved. Wrapped in
204    /// [`UnresolvedImportFinding`] so each entry carries a typed `actions`
205    /// array natively.
206    pub unresolved_imports: Vec<UnresolvedImportFinding>,
207    /// Dependencies used in code but not listed in package.json. Wrapped in
208    /// [`UnlistedDependencyFinding`].
209    pub unlisted_dependencies: Vec<UnlistedDependencyFinding>,
210    /// Binaries that package.json scripts or process calls run, but that no
211    /// installed or listed package provides. Wrapped in
212    /// [`UnlistedBinaryFinding`].
213    #[serde(default)]
214    pub unlisted_binaries: Vec<UnlistedBinaryFinding>,
215    /// Exports with the same name across multiple modules. Wrapped in
216    /// [`DuplicateExportFinding`] so each entry carries a typed `actions`
217    /// array natively, with the position-0 `add-to-config` `ignoreExports`
218    /// snippet wired in at wrapper construction.
219    pub duplicate_exports: Vec<DuplicateExportFinding>,
220    /// One module that exports one binding under two or more names. Wrapped
221    /// in [`DuplicateExportAliasFinding`]. Default severity is `warn`.
222    #[serde(default, skip_serializing_if = "Vec::is_empty")]
223    pub duplicate_export_aliases: Vec<DuplicateExportAliasFinding>,
224    /// Production dependencies only used via type-only imports (could be
225    /// devDependencies). Only populated in production mode. Wrapped in
226    /// [`TypeOnlyDependencyFinding`].
227    pub type_only_dependencies: Vec<TypeOnlyDependencyFinding>,
228    /// Production dependencies only imported by test files (could be
229    /// devDependencies). Wrapped in [`TestOnlyDependencyFinding`].
230    #[serde(default)]
231    pub test_only_dependencies: Vec<TestOnlyDependencyFinding>,
232    /// devDependencies imported by production (non-test, non-config) source code
233    /// via a runtime/value import; they should be promoted to dependencies.
234    /// The promote-side mirror of [`TestOnlyDependencyFinding`]. Wrapped in
235    /// [`DevDependencyInProductionFinding`].
236    #[serde(default)]
237    pub dev_dependencies_in_production: Vec<DevDependencyInProductionFinding>,
238    /// Circular dependency chains detected in the module graph. Wrapped in
239    /// [`CircularDependencyFinding`] so each entry carries a typed `actions`
240    /// array natively.
241    pub circular_dependencies: Vec<CircularDependencyFinding>,
242    /// Cycles or self-loops in the re-export edge subgraph (barrel files
243    /// re-exporting from each other in a loop). Wrapped in
244    /// [`ReExportCycleFinding`] so each entry carries a typed `actions`
245    /// array natively (a `refactor-re-export-cycle` informational primary
246    /// plus a `suppress-file` secondary; cycles are file-scoped so a single
247    /// suppression breaks the cycle).
248    #[serde(default)]
249    pub re_export_cycles: Vec<ReExportCycleFinding>,
250    /// Dependency cycles between workspace packages, built from resolved
251    /// cross-package imports. Wrapped in [`PackageCycleFinding`] so each
252    /// entry carries a typed `actions` array natively.
253    #[serde(default)]
254    pub package_cycles: Vec<PackageCycleFinding>,
255    /// Imports that cross architecture boundary rules. Wrapped in
256    /// [`BoundaryViolationFinding`] so each entry carries a typed `actions`
257    /// array natively.
258    #[serde(default)]
259    pub boundary_violations: Vec<BoundaryViolationFinding>,
260    /// Files that matched no architecture boundary zone while
261    /// `boundaries.coverage.requireAllFiles` was enabled.
262    #[serde(default)]
263    pub boundary_coverage_violations: Vec<BoundaryCoverageViolationFinding>,
264    /// Calls from zoned files to callees forbidden for that zone via
265    /// `boundaries.calls.forbidden`. Wrapped in
266    /// [`BoundaryCallViolationFinding`] so each entry carries a typed
267    /// `actions` array natively.
268    #[serde(default)]
269    pub boundary_call_violations: Vec<BoundaryCallViolationFinding>,
270    /// Banned calls, imports, and catalogue-derived effects matched by
271    /// declarative rule packs
272    /// (`rulePacks` config). Wrapped in [`PolicyViolationFinding`] so each
273    /// entry carries a typed `actions` array natively. Each finding carries
274    /// its effective per-rule severity.
275    #[serde(default)]
276    pub policy_violations: Vec<PolicyViolationFinding>,
277    /// Suppression comments or JSDoc tags that no longer match any issue.
278    #[serde(default)]
279    pub stale_suppressions: Vec<StaleSuppression>,
280    /// Entries in package manager catalog sections not referenced by any
281    /// workspace package via the catalog: protocol. Supports
282    /// `pnpm-workspace.yaml` catalogs and Bun root `package.json` catalogs.
283    /// Wrapped in [`UnusedCatalogEntryFinding`] so each entry carries a typed
284    /// `actions` array natively, with per-instance `auto_fixable` derived
285    /// from `hardcoded_consumers` and the catalog source file.
286    #[serde(default)]
287    pub unused_catalog_entries: Vec<UnusedCatalogEntryFinding>,
288    /// Named groups under package manager catalogs sections that declare no
289    /// package entries. The top-level catalog: map is not reported. Wrapped in
290    /// [`EmptyCatalogGroupFinding`].
291    #[serde(default)]
292    pub empty_catalog_groups: Vec<EmptyCatalogGroupFinding>,
293    /// Workspace package.json references to catalogs (`catalog:` or
294    /// `catalog:<name>`) that do not declare the consumed package. The package
295    /// manager install will error until the named catalog grows to include the
296    /// package or the reference is switched / removed. Wrapped in
297    /// [`UnresolvedCatalogReferenceFinding`] with the discriminated
298    /// `add-catalog-entry` / `update-catalog-reference` primary at position 0.
299    #[serde(default)]
300    pub unresolved_catalog_references: Vec<UnresolvedCatalogReferenceFinding>,
301    /// Entries in pnpm-workspace.yaml's overrides section, package.json's
302    /// pnpm.overrides block, npm or Bun's top-level overrides object, or Bun's
303    /// top-level resolutions object,
304    /// whose target package is not declared by any workspace package and is
305    /// not present in pnpm-lock.yaml, package-lock.json, npm-shrinkwrap.json,
306    /// or bun.lock. Default severity is warn because projects without a
307    /// readable lockfile fall back to manifest-only checks; the hint field
308    /// flags those conservative cases. When the only lockfile is bun's binary
309    /// bun.lockb, resolution cannot be read and the check emits nothing.
310    /// Wrapped in [`UnusedDependencyOverrideFinding`].
311    #[serde(default)]
312    pub unused_dependency_overrides: Vec<UnusedDependencyOverrideFinding>,
313    /// Package-manager override or resolution entries whose key or value does
314    /// not parse in the declaration source's grammar (empty key, empty value,
315    /// malformed selector, unbalanced parent matcher). The package manager may
316    /// reject or ignore these at install time. Default severity is error. Wrapped in
317    /// [`MisconfiguredDependencyOverrideFinding`].
318    #[serde(default)]
319    pub misconfigured_dependency_overrides: Vec<MisconfiguredDependencyOverrideFinding>,
320    /// `"use client"` files that export a Next.js server-only / route-segment
321    /// config name (e.g. `metadata`, `revalidate`, `GET`). Next.js rejects this
322    /// at build time. Wrapped in [`InvalidClientExportFinding`] so each entry
323    /// carries a typed `actions` array natively. Default severity is `warn`.
324    #[serde(default)]
325    pub invalid_client_exports: Vec<InvalidClientExportFinding>,
326    /// Barrel files that re-export both a `"use client"` origin module and a
327    /// server-only origin module (the Next.js App Router footgun). Wrapped in
328    /// [`MixedClientServerBarrelFinding`] so each entry carries a typed
329    /// `actions` array natively. Default severity is `warn`.
330    #[serde(default)]
331    pub mixed_client_server_barrels: Vec<MixedClientServerBarrelFinding>,
332    /// `"use client"` / `"use server"` directives written as expression
333    /// statements after a non-directive statement, so the RSC bundler parses
334    /// them as ordinary strings and silently ignores them. Wrapped in
335    /// [`MisplacedDirectiveFinding`] so each entry carries a typed `actions`
336    /// array natively. Default severity is `warn`.
337    #[serde(default)]
338    pub misplaced_directives: Vec<MisplacedDirectiveFinding>,
339    /// Vue `inject(KEY)` / Svelte `getContext(KEY)` calls whose symbol KEY is
340    /// provided nowhere in the project (the injected-never-provided dead-half).
341    /// Wrapped in [`UnprovidedInjectFinding`] so each entry carries a typed
342    /// `actions` array natively. Default severity is `warn`.
343    #[serde(default, skip_serializing_if = "Vec::is_empty")]
344    pub unprovided_injects: Vec<UnprovidedInjectFinding>,
345    /// Vue/Svelte single-file components that are reachable but rendered nowhere
346    /// (the imported-but-never-rendered dead-half). Wrapped in
347    /// [`UnrenderedComponentFinding`] so each entry carries a typed `actions`
348    /// array natively. Default severity is `warn`.
349    #[serde(default, skip_serializing_if = "Vec::is_empty")]
350    pub unrendered_components: Vec<UnrenderedComponentFinding>,
351    /// Next.js App Router route files that resolve to the same URL within one
352    /// app-root (a guaranteed `next build` failure). Wrapped in
353    /// [`RouteCollisionFinding`] so each entry carries a typed `actions` array
354    /// natively. One finding per colliding file. Default severity is `warn`.
355    #[serde(default)]
356    pub route_collisions: Vec<RouteCollisionFinding>,
357    /// Sibling Next.js dynamic route segments at one tree position using
358    /// different param spellings (a dev / runtime error; `next build` does NOT
359    /// catch it). Wrapped in [`DynamicSegmentNameConflictFinding`] so each entry
360    /// carries a typed `actions` array natively. Default severity is `warn`.
361    #[serde(default)]
362    pub dynamic_segment_name_conflicts: Vec<DynamicSegmentNameConflictFinding>,
363    /// Vue `<script setup>` `defineProps`, Svelte 5 `$props()`, and React props
364    /// referenced nowhere in their own component. Wrapped in
365    /// [`UnusedComponentPropFinding`] so each entry carries a typed `actions`
366    /// array natively. Default severity is `warn`.
367    #[serde(default, skip_serializing_if = "Vec::is_empty")]
368    pub unused_component_props: Vec<UnusedComponentPropFinding>,
369    /// Used optional component inputs absent from inspected reachable callers. Off by default.
370    #[serde(default, skip_serializing_if = "Vec::is_empty")]
371    pub absent_component_props: Vec<AbsentComponentPropFinding>,
372    /// Parameters that each visible call passes in one way. Off by default.
373    #[serde(default, skip_serializing_if = "Vec::is_empty")]
374    pub constant_parameters: Vec<ConstantParameterFinding>,
375    /// Vue `<script setup>` `defineEmits` events emitted nowhere in their own SFC
376    /// (no `emit('<name>')` call). Wrapped in [`UnusedComponentEmitFinding`] so
377    /// each entry carries a typed `actions` array natively. Default severity is
378    /// `warn`.
379    #[serde(default, skip_serializing_if = "Vec::is_empty")]
380    pub unused_component_emits: Vec<UnusedComponentEmitFinding>,
381    /// Angular `@Input()` / signal `input()` / `model()` inputs read nowhere in
382    /// their own component (neither the template nor the class body). Wrapped in
383    /// [`UnusedComponentInputFinding`] so each entry carries a typed `actions`
384    /// array natively. Default severity is `warn`.
385    #[serde(default, skip_serializing_if = "Vec::is_empty")]
386    pub unused_component_inputs: Vec<UnusedComponentInputFinding>,
387    /// Angular `@Output()` / signal `output()` outputs emitted nowhere in their
388    /// own component (no `this.<output>.emit(...)`). Wrapped in
389    /// [`UnusedComponentOutputFinding`] so each entry carries a typed `actions`
390    /// array natively. Default severity is `warn`.
391    #[serde(default, skip_serializing_if = "Vec::is_empty")]
392    pub unused_component_outputs: Vec<UnusedComponentOutputFinding>,
393    /// Svelte components dispatching a custom event via `createEventDispatcher()`
394    /// whose event name is listened to nowhere project-wide (cross-file
395    /// dead-output direction). Wrapped in [`UnusedSvelteEventFinding`] so each
396    /// entry carries a typed `actions` array natively. Default severity is
397    /// `warn`.
398    #[serde(default, skip_serializing_if = "Vec::is_empty")]
399    pub unused_svelte_events: Vec<UnusedSvelteEventFinding>,
400    /// Effect layers composed only into other layers that nothing uses.
401    /// Gated on the project declaring `effect`. Default severity is `warn`.
402    #[serde(default, skip_serializing_if = "Vec::is_empty")]
403    pub unused_effect_layers: Vec<UnusedEffectLayerFinding>,
404    /// Effect tagged error classes that only type positions or `catchTag`
405    /// handlers reference. Gated on the project declaring `effect`. Default
406    /// severity is `warn`.
407    #[serde(default, skip_serializing_if = "Vec::is_empty")]
408    pub unused_tagged_errors: Vec<UnusedTaggedErrorFinding>,
409    /// `catchTag` / `catchTags` handlers for a project tag that no code
410    /// produces and that no `unused_tagged_errors` entry covers. Gated on the
411    /// project declaring `effect`. Default severity is `warn`.
412    #[serde(default, skip_serializing_if = "Vec::is_empty")]
413    pub unproduced_catch_tags: Vec<UnproducedCatchTagFinding>,
414    /// Next.js Server Actions (exports of `"use server"` files) that no code in
415    /// the project references. Reclassified out of `unused_exports` for
416    /// `"use server"` files. Wrapped in [`UnusedServerActionFinding`] so each
417    /// entry carries a typed `actions` array natively. Default severity is
418    /// `warn`.
419    #[serde(default, skip_serializing_if = "Vec::is_empty")]
420    pub unused_server_actions: Vec<UnusedServerActionFinding>,
421    /// SvelteKit `+page.{ts,server.ts,js,server.js}` `load()` return-object keys
422    /// read by no consumer. Wrapped in [`UnusedLoadDataKeyFinding`] so each entry
423    /// carries a typed `actions` array natively. Default severity is `warn`.
424    #[serde(default, skip_serializing_if = "Vec::is_empty")]
425    pub unused_load_data_keys: Vec<UnusedLoadDataKeyFinding>,
426    /// `true` when the `unused-load-data-key` detector abstained project-wide
427    /// because a whole-object use of `page.data` / `$page.data` was seen
428    /// somewhere (S1 observability: an empty `unused_load_data_keys` with this
429    /// flag set is NOT a clean bill, it means the rule could not run safely).
430    /// Serialized only when `true` so the default JSON contract is unchanged.
431    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
432    pub unused_load_data_keys_global_abstain: bool,
433    /// React/Preact props forwarded unchanged through `>= N` intermediate
434    /// pass-through components until a consumer (located per-chain records).
435    /// Wrapped in [`PropDrillingChainFinding`] so each entry carries a typed
436    /// `actions` array natively. Health signal: the rule defaults to `off`
437    /// (opt-in), so this is dormant and populated only when the user enables it.
438    #[serde(default, skip_serializing_if = "Vec::is_empty")]
439    pub prop_drilling_chains: Vec<PropDrillingChainFinding>,
440    /// React/Preact components whose entire body is a single spread-forwarded
441    /// child render (`return <Child {...props}/>`): pure structural indirection,
442    /// a candidate for inlining at call sites. Wrapped in [`ThinWrapperFinding`]
443    /// so each entry carries a typed `actions` array natively. Health signal: the
444    /// rule defaults to `off` (opt-in), so this is dormant and populated only
445    /// when the user enables it.
446    #[serde(default, skip_serializing_if = "Vec::is_empty")]
447    pub thin_wrappers: Vec<ThinWrapperFinding>,
448    /// React/Preact components that participate in a duplicate-prop-shape group:
449    /// three or more components across two or more files whose statically-known
450    /// prop NAME set is identical after stripping ubiquitous DOM / passthrough
451    /// names (a missing shared `Props` type / base component). Wrapped in
452    /// [`DuplicatePropShapeFinding`] so each entry carries a typed `actions`
453    /// array and its sibling roster natively. Health signal: the rule defaults to
454    /// `off` (opt-in), so this is dormant and populated only when the user
455    /// enables it.
456    #[serde(default, skip_serializing_if = "Vec::is_empty")]
457    pub duplicate_prop_shapes: Vec<DuplicatePropShapeFinding>,
458    /// Number of `unused_exports`, `unused_types`, `unused_class_members` and
459    /// `unused_enum_members` findings that this run did not report because
460    /// their file is an unused file. Deleting the file removes them, so they
461    /// add no information. `--show-cascade` or the `showCascade` config key
462    /// keeps them in the report, and then this count is zero. The count is
463    /// taken after the scope and the rules and before a baseline. Serialized
464    /// only when not zero, so a run without such findings keeps its JSON.
465    #[serde(default, skip_serializing_if = "is_zero")]
466    pub cascade_hidden: usize,
467    /// In-process state of the unused-file cascade filter: the unused-file
468    /// candidates of the detector and the findings that the filter removed.
469    /// Skipped in machine output; [`Self::cascade_hidden`] is the public count.
470    #[serde(skip)]
471    #[cfg_attr(feature = "schema", schemars(skip))]
472    pub cascade: CascadeState,
473    /// Number of suppression entries that matched an issue during analysis.
474    /// Human output uses this for the suppression footer; it is skipped in
475    /// machine output to avoid changing the public JSON issue contract.
476    #[serde(skip)]
477    pub suppression_count: usize,
478    /// Number of component props exempted from `unused-component-props` this run
479    /// because their local destructure binding name matched
480    /// `unusedComponentProps.ignorePattern`. Drives a human-output note so a
481    /// mistyped pattern (matching nothing) is not a silent no-op; skipped in
482    /// machine output, like [`Self::suppression_count`].
483    #[serde(skip)]
484    pub unused_component_props_exempted: usize,
485    /// Suppression comments present in analyzed files this run (every present
486    /// marker, all kinds, not only consumed ones). Internal: read in-process by
487    /// `fallow impact` to distinguish a genuinely resolved finding from one
488    /// silenced by a `fallow-ignore`. Skipped during serialization, like
489    /// [`Self::suppression_count`], so the public JSON output contract is
490    /// unchanged.
491    #[serde(skip)]
492    pub active_suppressions: Vec<ActiveSuppression>,
493    /// Detected feature flag patterns. Advisory output, not included in issue counts.
494    /// Skipped during default serialization: injected separately in JSON output when enabled.
495    #[serde(skip)]
496    pub feature_flags: Vec<FeatureFlag>,
497    /// Security candidates to verify, not verified vulnerabilities. Set only when a `security_*`
498    /// rule is on (`fallow security` turns them on). Skipped in serialization and not counted in
499    /// `total_issues`, so bare `fallow` never shows them; `fallow security` has its own envelope.
500    #[serde(skip)]
501    pub security_findings: Vec<SecurityFinding>,
502    /// Inline-suppressed security candidates. The stable id ordinals count them; then cleared.
503    #[serde(skip)]
504    pub suppressed_security_findings: Vec<SecurityFinding>,
505    /// In-band blind-spot count: number of `"use client"` files whose transitive
506    /// import cone contains a dynamic `import()` the reachability BFS cannot
507    /// follow. Surfaced by `fallow security` so a leak hidden behind an
508    /// unresolved edge is never silently reported as "clean". Skipped during
509    /// serialization like [`Self::security_findings`].
510    #[serde(skip)]
511    pub security_unresolved_edge_files: usize,
512    /// In-band blind-spot count: number of sink-shaped nodes the catalogue
513    /// detector could not flatten to a static callee path (dynamic dispatch,
514    /// computed members, aliased bindings). Surfaced by `fallow security` so an
515    /// empty catalogue result with a non-zero count is not reported as "clean".
516    /// Skipped during serialization like [`Self::security_findings`].
517    #[serde(skip)]
518    pub security_unresolved_callee_sites: usize,
519    /// Location samples for sink-shaped nodes the catalogue detector could not
520    /// flatten to a static callee path. Skipped during default serialization;
521    /// `fallow security` summarizes this metadata in its own envelope.
522    #[serde(skip)]
523    pub security_unresolved_callee_diagnostics: Vec<SecurityUnresolvedCalleeDiagnostic>,
524    /// Usage counts for all exports across the project. Used by the LSP for Code Lens.
525    /// Not included in issue counts -- this is metadata, not an issue type.
526    /// Skipped during serialization: this is internal LSP data, not part of the JSON output schema.
527    #[serde(skip)]
528    pub export_usages: Vec<ExportUsage>,
529    /// The type exports that `unused-type` keeps because a same-file
530    /// signature uses them. Internal: the trace reads it to give the same
531    /// reason as the report. Skipped in machine output.
532    #[serde(skip)]
533    #[cfg_attr(feature = "schema", schemars(skip))]
534    pub signature_backed_types: Vec<crate::trace::SignatureBackedType>,
535    /// Summary of detected entry points, grouped by discovery source.
536    /// Not included in issue counts -- this is informational metadata.
537    /// Skipped during serialization: rendered separately in JSON output.
538    #[serde(skip)]
539    pub entry_point_summary: Option<EntryPointSummary>,
540    /// Internal component render metrics, exposed through health aggregates.
541    #[serde(skip)]
542    pub render_fan_in: Option<RenderFanInMetric>,
543    /// Internal component intelligence used by editor overlays.
544    #[serde(skip)]
545    pub react_component_intel: Vec<ReactComponentIntel>,
546    /// Reachable files in the discovery scope, captured before report filters.
547    /// Empty or deserialized scope cannot grant semantic usage credit.
548    #[serde(skip)]
549    #[cfg_attr(feature = "schema", schemars(skip))]
550    pub semantic_reachable_files: rustc_hash::FxHashSet<PathBuf>,
551    /// Plugin-owned framework contracts carried only into the optional
552    /// semantic reconciliation pass.
553    #[serde(skip)]
554    #[cfg_attr(feature = "schema", schemars(skip))]
555    pub semantic_framework_contracts: Vec<crate::semantic::SemanticFrameworkContract>,
556    /// `constant-parameter` candidates for the optional semantic pass.
557    #[serde(skip)]
558    #[cfg_attr(feature = "schema", schemars(skip))]
559    pub constant_parameter_candidates: ConstantParameterCandidates,
560}
561
562#[expect(
563    clippy::trivially_copy_pass_by_ref,
564    reason = "serde `skip_serializing_if` passes the field by reference"
565)]
566const fn is_zero(count: &usize) -> bool {
567    *count == 0
568}
569
570/// In-process state of the unused-file cascade filter.
571///
572/// An unused file in the report makes every export and member finding in it
573/// redundant: deleting the file removes them. The filter needs the files that
574/// a suppression comment removed from the report, and it keeps the findings
575/// that it removed, because a baseline entry for such a finding still
576/// describes the project and must not count as stale.
577#[derive(Debug, Default, Clone)]
578pub struct CascadeState {
579    /// Unused files whose finding an inline `fallow-ignore-file unused-file`
580    /// comment suppressed. The cascade filter treats them as reported, so a
581    /// suppression comment never makes a hidden finding visible again. An
582    /// issue-type selection without unused files clears this list.
583    pub suppressed_unused_files: Vec<PathBuf>,
584    /// The findings that the filter removed from the report.
585    pub hidden: CascadeHiddenFindings,
586}
587
588/// Findings that the unused-file cascade filter removed from the report.
589#[derive(Debug, Default, Clone)]
590pub struct CascadeHiddenFindings {
591    /// Hidden `unused_exports` findings.
592    pub unused_exports: Vec<UnusedExportFinding>,
593    /// Hidden `unused_types` findings.
594    pub unused_types: Vec<UnusedTypeFinding>,
595    /// Hidden `unused_enum_members` findings.
596    pub unused_enum_members: Vec<UnusedEnumMemberFinding>,
597    /// Hidden `unused_class_members` findings.
598    pub unused_class_members: Vec<UnusedClassMemberFinding>,
599}
600
601impl CascadeHiddenFindings {
602    /// Number of hidden findings.
603    #[must_use]
604    pub fn len(&self) -> usize {
605        self.unused_exports.len()
606            + self.unused_types.len()
607            + self.unused_enum_members.len()
608            + self.unused_class_members.len()
609    }
610
611    /// Whether the filter removed no finding.
612    #[must_use]
613    pub fn is_empty(&self) -> bool {
614        self.len() == 0
615    }
616
617    /// The hidden findings as a result set, for a baseline comparison.
618    #[must_use]
619    pub fn to_results(&self) -> AnalysisResults {
620        AnalysisResults {
621            unused_exports: self.unused_exports.clone(),
622            unused_types: self.unused_types.clone(),
623            unused_enum_members: self.unused_enum_members.clone(),
624            unused_class_members: self.unused_class_members.clone(),
625            ..AnalysisResults::default()
626        }
627    }
628
629    fn extend(&mut self, other: Self) {
630        self.unused_exports.extend(other.unused_exports);
631        self.unused_types.extend(other.unused_types);
632        self.unused_enum_members.extend(other.unused_enum_members);
633        self.unused_class_members.extend(other.unused_class_members);
634    }
635}
636
637struct AnalysisResultsCoreMergeParts {
638    unused_files: Vec<UnusedFileFinding>,
639    unused_exports: Vec<UnusedExportFinding>,
640    unused_types: Vec<UnusedTypeFinding>,
641    private_type_leaks: Vec<PrivateTypeLeakFinding>,
642    deprecated_exports_in_use: Vec<DeprecatedExportInUseFinding>,
643    unused_enum_members: Vec<UnusedEnumMemberFinding>,
644    unused_class_members: Vec<UnusedClassMemberFinding>,
645    unused_namespace_members: Vec<UnusedNamespaceMemberFinding>,
646    unused_protected_class_members: Vec<UnusedProtectedClassMemberFinding>,
647    namespace_escapes: Vec<NamespaceEscapeFinding>,
648    test_only_exports: Vec<TestOnlyExportFinding>,
649    unused_store_members: Vec<UnusedStoreMemberFinding>,
650    unresolved_imports: Vec<UnresolvedImportFinding>,
651    boundary_violations: Vec<BoundaryViolationFinding>,
652    boundary_coverage_violations: Vec<BoundaryCoverageViolationFinding>,
653    boundary_call_violations: Vec<BoundaryCallViolationFinding>,
654    policy_violations: Vec<PolicyViolationFinding>,
655    stale_suppressions: Vec<StaleSuppression>,
656}
657
658struct AnalysisResultsGraphMergeParts {
659    unused_dependencies: Vec<UnusedDependencyFinding>,
660    unused_dev_dependencies: Vec<UnusedDevDependencyFinding>,
661    unused_optional_dependencies: Vec<UnusedOptionalDependencyFinding>,
662    unlisted_dependencies: Vec<UnlistedDependencyFinding>,
663    unlisted_binaries: Vec<UnlistedBinaryFinding>,
664    duplicate_exports: Vec<DuplicateExportFinding>,
665    duplicate_export_aliases: Vec<DuplicateExportAliasFinding>,
666    type_only_dependencies: Vec<TypeOnlyDependencyFinding>,
667    test_only_dependencies: Vec<TestOnlyDependencyFinding>,
668    dev_dependencies_in_production: Vec<DevDependencyInProductionFinding>,
669    circular_dependencies: Vec<CircularDependencyFinding>,
670    re_export_cycles: Vec<ReExportCycleFinding>,
671    package_cycles: Vec<PackageCycleFinding>,
672}
673
674struct AnalysisResultsWorkspaceMergeParts {
675    unused_catalog_entries: Vec<UnusedCatalogEntryFinding>,
676    empty_catalog_groups: Vec<EmptyCatalogGroupFinding>,
677    unresolved_catalog_references: Vec<UnresolvedCatalogReferenceFinding>,
678    unused_dependency_overrides: Vec<UnusedDependencyOverrideFinding>,
679    misconfigured_dependency_overrides: Vec<MisconfiguredDependencyOverrideFinding>,
680}
681
682struct AnalysisResultsFrameworkMergeParts {
683    invalid_client_exports: Vec<InvalidClientExportFinding>,
684    mixed_client_server_barrels: Vec<MixedClientServerBarrelFinding>,
685    misplaced_directives: Vec<MisplacedDirectiveFinding>,
686    unprovided_injects: Vec<UnprovidedInjectFinding>,
687    unrendered_components: Vec<UnrenderedComponentFinding>,
688    route_collisions: Vec<RouteCollisionFinding>,
689    dynamic_segment_name_conflicts: Vec<DynamicSegmentNameConflictFinding>,
690    unused_component_props: Vec<UnusedComponentPropFinding>,
691    absent_component_props: Vec<AbsentComponentPropFinding>,
692    constant_parameters: Vec<ConstantParameterFinding>,
693    unused_component_emits: Vec<UnusedComponentEmitFinding>,
694    unused_component_inputs: Vec<UnusedComponentInputFinding>,
695    unused_component_outputs: Vec<UnusedComponentOutputFinding>,
696    unused_svelte_events: Vec<UnusedSvelteEventFinding>,
697    unused_effect_layers: Vec<UnusedEffectLayerFinding>,
698    unused_tagged_errors: Vec<UnusedTaggedErrorFinding>,
699    unproduced_catch_tags: Vec<UnproducedCatchTagFinding>,
700    unused_server_actions: Vec<UnusedServerActionFinding>,
701    unused_load_data_keys: Vec<UnusedLoadDataKeyFinding>,
702    unused_load_data_keys_global_abstain: bool,
703    prop_drilling_chains: Vec<PropDrillingChainFinding>,
704    thin_wrappers: Vec<ThinWrapperFinding>,
705    duplicate_prop_shapes: Vec<DuplicatePropShapeFinding>,
706}
707
708struct AnalysisResultsMetadataMergeParts {
709    shared_state: Option<crate::shared_state::SharedStateInventory>,
710    cascade_hidden: usize,
711    cascade: CascadeState,
712    suppression_count: usize,
713    unused_component_props_exempted: usize,
714    active_suppressions: Vec<ActiveSuppression>,
715    feature_flags: Vec<FeatureFlag>,
716    security_findings: Vec<SecurityFinding>,
717    suppressed_security_findings: Vec<SecurityFinding>,
718    security_unresolved_edge_files: usize,
719    security_unresolved_callee_sites: usize,
720    security_unresolved_callee_diagnostics: Vec<SecurityUnresolvedCalleeDiagnostic>,
721    export_usages: Vec<ExportUsage>,
722    signature_backed_types: Vec<crate::trace::SignatureBackedType>,
723    entry_point_summary: Option<EntryPointSummary>,
724    render_fan_in: Option<RenderFanInMetric>,
725    react_component_intel: Vec<ReactComponentIntel>,
726    semantic_reachable_files: rustc_hash::FxHashSet<PathBuf>,
727    semantic_framework_contracts: Vec<crate::semantic::SemanticFrameworkContract>,
728    constant_parameter_candidates: ConstantParameterCandidates,
729}
730
731macro_rules! counted_analysis_result_fields {
732    ($callback:ident $(, $arg:expr)? ) => {
733        $callback! {
734            $($arg,)?
735            unused_files => "unused_files",
736            unused_exports => "unused_exports",
737            unused_types => "unused_types",
738            private_type_leaks => "private_type_leaks",
739            deprecated_exports_in_use => "deprecated_exports_in_use",
740            unused_dependencies => "unused_dependencies",
741            unused_dev_dependencies => "unused_dev_dependencies",
742            unused_optional_dependencies => "unused_optional_dependencies",
743            unused_enum_members => "unused_enum_members",
744            unused_class_members => "unused_class_members",
745            unused_namespace_members => "unused_namespace_members",
746            unused_protected_class_members => "unused_protected_class_members",
747            namespace_escapes => "namespace_escapes",
748            test_only_exports => "test_only_exports",
749            unused_store_members => "unused_store_members",
750            unresolved_imports => "unresolved_imports",
751            unlisted_dependencies => "unlisted_dependencies",
752            unlisted_binaries => "unlisted_binaries",
753            duplicate_exports => "duplicate_exports",
754            duplicate_export_aliases => "duplicate_export_aliases",
755            type_only_dependencies => "type_only_dependencies",
756            test_only_dependencies => "test_only_dependencies",
757            dev_dependencies_in_production => "dev_dependencies_in_production",
758            circular_dependencies => "circular_dependencies",
759            re_export_cycles => "re_export_cycles",
760            package_cycles => "package_cycles",
761            boundary_violations => "boundary_violations",
762            boundary_coverage_violations => "boundary_coverage_violations",
763            boundary_call_violations => "boundary_call_violations",
764            policy_violations => "policy_violations",
765            stale_suppressions => "stale_suppressions",
766            unused_catalog_entries => "unused_catalog_entries",
767            empty_catalog_groups => "empty_catalog_groups",
768            unresolved_catalog_references => "unresolved_catalog_references",
769            unused_dependency_overrides => "unused_dependency_overrides",
770            misconfigured_dependency_overrides => "misconfigured_dependency_overrides",
771            invalid_client_exports => "invalid_client_exports",
772            mixed_client_server_barrels => "mixed_client_server_barrels",
773            misplaced_directives => "misplaced_directives",
774            unprovided_injects => "unprovided_injects",
775            unrendered_components => "unrendered_components",
776            route_collisions => "route_collisions",
777            dynamic_segment_name_conflicts => "dynamic_segment_name_conflicts",
778            unused_component_props => "unused_component_props",
779            absent_component_props => "absent_component_props",
780            constant_parameters => "constant_parameters",
781            unused_component_emits => "unused_component_emits",
782            unused_component_inputs => "unused_component_inputs",
783            unused_component_outputs => "unused_component_outputs",
784            unused_svelte_events => "unused_svelte_events",
785            unused_effect_layers => "unused_effect_layers",
786            unused_tagged_errors => "unused_tagged_errors",
787            unproduced_catch_tags => "unproduced_catch_tags",
788            unused_server_actions => "unused_server_actions",
789            unused_load_data_keys => "unused_load_data_keys",
790        }
791    };
792}
793
794trait FindingIgnorePolicy {
795    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool;
796}
797
798macro_rules! impl_single_source_dead_code {
799    ($($finding:ty => $($field:ident).+),+ $(,)?) => {
800        $(
801            impl FindingIgnorePolicy for $finding {
802                fn should_ignore(
803                    &self,
804                    predicate: &mut impl FnMut(&Path) -> bool,
805                ) -> bool {
806                    predicate(&self.$($field).+)
807                }
808            }
809        )+
810    };
811}
812
813impl_single_source_dead_code! {
814    UnusedFileFinding => file.path,
815    UnusedExportFinding => export.path,
816    UnusedTypeFinding => export.path,
817    PrivateTypeLeakFinding => leak.path,
818    DeprecatedExportInUseFinding => export.path,
819    UnusedEnumMemberFinding => member.path,
820    UnusedClassMemberFinding => member.path,
821    UnusedNamespaceMemberFinding => member.path,
822    UnusedProtectedClassMemberFinding => member.path,
823    NamespaceEscapeFinding => escape.path,
824    TestOnlyExportFinding => export.path,
825    UnusedStoreMemberFinding => member.path,
826    UnresolvedImportFinding => import.path,
827    UnprovidedInjectFinding => inject.path,
828    UnrenderedComponentFinding => component.path,
829    UnusedComponentPropFinding => prop.path,
830    AbsentComponentPropFinding => prop.path,
831    ConstantParameterFinding => parameter.path,
832    UnusedComponentEmitFinding => emit.path,
833    UnusedComponentInputFinding => input.path,
834    UnusedComponentOutputFinding => output.path,
835    UnusedSvelteEventFinding => event.path,
836    UnusedEffectLayerFinding => layer.path,
837    DuplicateExportAliasFinding => alias.path,
838    UnusedTaggedErrorFinding => error.path,
839    UnproducedCatchTagFinding => catch_tag.path,
840    UnusedServerActionFinding => action.path,
841    UnusedLoadDataKeyFinding => key.path,
842    ThinWrapperFinding => wrapper.file,
843    DuplicatePropShapeFinding => shape.file,
844}
845
846macro_rules! impl_never_ignored_finding {
847    ($($finding:ty),+ $(,)?) => {
848        $(
849            impl FindingIgnorePolicy for $finding {
850                fn should_ignore(
851                    &self,
852                    _predicate: &mut impl FnMut(&Path) -> bool,
853                ) -> bool {
854                    false
855                }
856            }
857        )+
858    };
859}
860
861impl_never_ignored_finding! {
862    UnusedDependencyFinding,
863    UnusedDevDependencyFinding,
864    UnusedOptionalDependencyFinding,
865    TypeOnlyDependencyFinding,
866    TestOnlyDependencyFinding,
867    DevDependencyInProductionFinding,
868    UnusedCatalogEntryFinding,
869    EmptyCatalogGroupFinding,
870    UnresolvedCatalogReferenceFinding,
871    UnusedDependencyOverrideFinding,
872    MisconfiguredDependencyOverrideFinding,
873    BoundaryViolationFinding,
874    BoundaryCoverageViolationFinding,
875    BoundaryCallViolationFinding,
876    PolicyViolationFinding,
877    StaleSuppression,
878    InvalidClientExportFinding,
879    MixedClientServerBarrelFinding,
880    MisplacedDirectiveFinding,
881    RouteCollisionFinding,
882    DynamicSegmentNameConflictFinding,
883}
884
885impl FindingIgnorePolicy for UnlistedDependencyFinding {
886    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
887        all_nonempty_paths_match(
888            self.dep.imported_from.iter().map(|site| &site.path),
889            predicate,
890        )
891    }
892}
893
894impl FindingIgnorePolicy for UnlistedBinaryFinding {
895    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
896        all_nonempty_paths_match(self.binary.used_in.iter().map(|site| &site.path), predicate)
897    }
898}
899
900impl FindingIgnorePolicy for DuplicateExportFinding {
901    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
902        all_nonempty_paths_match(
903            self.export.locations.iter().map(|location| &location.path),
904            predicate,
905        )
906    }
907}
908
909impl FindingIgnorePolicy for CircularDependencyFinding {
910    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
911        all_nonempty_paths_match(self.cycle.files.iter(), predicate)
912    }
913}
914
915impl FindingIgnorePolicy for ReExportCycleFinding {
916    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
917        all_nonempty_paths_match(self.cycle.files.iter(), predicate)
918    }
919}
920
921impl FindingIgnorePolicy for PackageCycleFinding {
922    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
923        all_nonempty_paths_match(self.cycle.edges.iter().map(|edge| &edge.path), predicate)
924    }
925}
926
927impl FindingIgnorePolicy for PropDrillingChainFinding {
928    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
929        all_nonempty_paths_match(self.chain.hops.iter().map(|hop| &hop.file), predicate)
930    }
931}
932
933/// Source-owned health families hidden by `ignoreFindings`.
934///
935/// These live outside the unconditional counted table: only explicit error
936/// findings contribute to `total_issues`; warnings remain advisory.
937macro_rules! uncounted_source_owned_result_fields {
938    ($callback:ident $(, $arg:expr)? ) => {
939        $callback! {
940            $($arg,)?
941            prop_drilling_chains => "prop_drilling_chains",
942            thin_wrappers => "thin_wrappers",
943            duplicate_prop_shapes => "duplicate_prop_shapes",
944        }
945    };
946}
947
948macro_rules! remove_configured_ignored_findings {
949    ($state:expr, $($field:ident => $key:literal,)+) => {{
950        let (results, predicate) = $state;
951        $(
952            results.$field.retain(|issue| {
953                !issue.should_ignore(&mut *predicate)
954            });
955        )+
956    }};
957}
958
959macro_rules! counted_result_key_slice {
960    ($($field:ident => $key:literal,)+) => {
961        &[$($key),+, "prop_drilling_chains", "thin_wrappers", "duplicate_prop_shapes"]
962    };
963}
964
965macro_rules! counted_result_field_sum {
966    ($results:expr, $($field:ident => $key:literal,)+) => {
967        0 $(+ ($results).$field.len())+
968    };
969}
970#[path = "results_key_findings.rs"]
971mod result_key_findings;
972
973/// Serialized `AnalysisResults` arrays that contribute to [`AnalysisResults::total_issues`].
974pub const TOTAL_ISSUE_RESULT_KEYS: &[&str] =
975    counted_analysis_result_fields!(counted_result_key_slice);
976
977impl AnalysisResults {
978    /// Remove the export and member findings whose file `covered` selects.
979    ///
980    /// Only `unused_exports`, `unused_types`, `unused_enum_members` and
981    /// `unused_class_members` change. A removed finding moves to
982    /// [`CascadeState::hidden`] and [`Self::cascade_hidden`] counts it. A second
983    /// call removes only findings that a later stage added, so the pass is
984    /// idempotent.
985    pub fn hide_cascade_findings(&mut self, covered: &dyn Fn(&Path) -> bool) {
986        let mut hidden = CascadeHiddenFindings::default();
987        move_covered(
988            &mut self.unused_exports,
989            &mut hidden.unused_exports,
990            |finding| finding.export.path.as_path(),
991            covered,
992        );
993        move_covered(
994            &mut self.unused_types,
995            &mut hidden.unused_types,
996            |finding| finding.export.path.as_path(),
997            covered,
998        );
999        move_covered(
1000            &mut self.unused_enum_members,
1001            &mut hidden.unused_enum_members,
1002            |finding| finding.member.path.as_path(),
1003            covered,
1004        );
1005        move_covered(
1006            &mut self.unused_class_members,
1007            &mut hidden.unused_class_members,
1008            |finding| finding.member.path.as_path(),
1009            covered,
1010        );
1011        self.cascade_hidden += hidden.len();
1012        self.cascade.hidden.extend(hidden);
1013    }
1014
1015    /// Move the findings that [`Self::hide_cascade_findings`] removed back
1016    /// into the report and reset [`Self::cascade_hidden`].
1017    ///
1018    /// Metrics that measure the code, such as the vital signs, read the
1019    /// result set after this call, so their value does not depend on
1020    /// `showCascade`.
1021    pub fn restore_cascade_findings(&mut self) {
1022        let hidden = std::mem::take(&mut self.cascade.hidden);
1023        self.unused_exports.extend(hidden.unused_exports);
1024        self.unused_types.extend(hidden.unused_types);
1025        self.unused_enum_members.extend(hidden.unused_enum_members);
1026        self.unused_class_members
1027            .extend(hidden.unused_class_members);
1028        self.cascade_hidden = 0;
1029    }
1030
1031    /// Remove dead-code findings whose complete, non-empty source-owner set
1032    /// matches `is_ignored`.
1033    ///
1034    /// Architecture, policy, suppression-hygiene, framework-correctness,
1035    /// security, and package/project findings are retained. Context paths
1036    /// embedded in a dead-code finding are not owners.
1037    #[doc(hidden)]
1038    pub fn remove_ignored_dead_code_findings(&mut self, mut is_ignored: impl FnMut(&Path) -> bool) {
1039        classify_ignore_findings_fields(self);
1040        counted_analysis_result_fields!(
1041            remove_configured_ignored_findings,
1042            (&mut *self, &mut is_ignored)
1043        );
1044        uncounted_source_owned_result_fields!(
1045            remove_configured_ignored_findings,
1046            (&mut *self, &mut is_ignored)
1047        );
1048    }
1049
1050    /// Total number of issues found.
1051    ///
1052    /// Sums across all issue categories (unused files, exports, types,
1053    /// dependencies, members, unresolved imports, unlisted deps, duplicates,
1054    /// type-only deps, circular deps, and boundary violations).
1055    ///
1056    /// # Examples
1057    ///
1058    /// ```
1059    /// use fallow_types::output_dead_code::{UnresolvedImportFinding, UnusedFileFinding};
1060    /// use fallow_types::results::{AnalysisResults, UnresolvedImport, UnusedFile};
1061    /// use std::path::PathBuf;
1062    ///
1063    /// let mut results = AnalysisResults::default();
1064    /// results
1065    ///     .unused_files
1066    ///     .push(UnusedFileFinding::with_actions(UnusedFile {
1067    ///         path: PathBuf::from("a.ts"),
1068    ///     }));
1069    /// results
1070    ///     .unresolved_imports
1071    ///     .push(UnresolvedImportFinding::with_actions(UnresolvedImport {
1072    ///         path: PathBuf::from("b.ts"),
1073    ///         specifier: "./missing".to_string(),
1074    ///         line: 1,
1075    ///         col: 0,
1076    ///         specifier_col: 0,
1077    ///     }));
1078    /// assert_eq!(results.total_issues(), 2);
1079    /// ```
1080    #[must_use]
1081    pub const fn total_issues(&self) -> usize {
1082        counted_analysis_result_fields!(counted_result_field_sum, self)
1083            + self.enforced_prop_drilling_count()
1084            + self.enforced_thin_wrapper_count()
1085            + self.enforced_duplicate_prop_shape_count()
1086    }
1087
1088    /// Whether any issues were found.
1089    #[must_use]
1090    pub const fn has_issues(&self) -> bool {
1091        self.total_issues() > 0
1092    }
1093
1094    /// Merge `other` into `self`, taking the union of every field.
1095    ///
1096    /// This is the single canonical way to combine two [`AnalysisResults`]
1097    /// (the LSP merges per-project-root results through it). The method
1098    /// exhaustively destructures `Self`, so adding a field to the struct
1099    /// becomes a compile error here instead of a silently-dropped field. See
1100    /// issue #444.
1101    ///
1102    /// Every `Vec` field is appended (callers dedup downstream where needed,
1103    /// e.g. the LSP's identity-keyed `dedup_results`). `suppression_count`
1104    /// sums; `entry_point_summary` keeps `self`'s value when present and
1105    /// otherwise adopts `other`'s.
1106    pub fn merge_into(&mut self, other: Self) {
1107        let (core, graph, workspace, framework, metadata) = split_merge_parts(other);
1108        self.merge_core_findings(core);
1109        self.merge_dependency_and_graph_findings(graph);
1110        self.merge_workspace_findings(workspace);
1111        self.merge_framework_findings(framework);
1112        self.merge_metadata_and_security(metadata);
1113    }
1114
1115    fn merge_core_findings(&mut self, parts: AnalysisResultsCoreMergeParts) {
1116        self.unused_files.extend(parts.unused_files);
1117        self.unused_exports.extend(parts.unused_exports);
1118        self.unused_types.extend(parts.unused_types);
1119        self.private_type_leaks.extend(parts.private_type_leaks);
1120        self.deprecated_exports_in_use
1121            .extend(parts.deprecated_exports_in_use);
1122        self.unused_enum_members.extend(parts.unused_enum_members);
1123        self.unused_class_members.extend(parts.unused_class_members);
1124        self.unused_namespace_members
1125            .extend(parts.unused_namespace_members);
1126        self.unused_protected_class_members
1127            .extend(parts.unused_protected_class_members);
1128        self.namespace_escapes.extend(parts.namespace_escapes);
1129        self.test_only_exports.extend(parts.test_only_exports);
1130        self.unused_store_members.extend(parts.unused_store_members);
1131        self.unresolved_imports.extend(parts.unresolved_imports);
1132        self.boundary_violations.extend(parts.boundary_violations);
1133        self.boundary_coverage_violations
1134            .extend(parts.boundary_coverage_violations);
1135        self.boundary_call_violations
1136            .extend(parts.boundary_call_violations);
1137        self.policy_violations.extend(parts.policy_violations);
1138        self.stale_suppressions.extend(parts.stale_suppressions);
1139    }
1140
1141    fn merge_dependency_and_graph_findings(&mut self, parts: AnalysisResultsGraphMergeParts) {
1142        self.unused_dependencies.extend(parts.unused_dependencies);
1143        self.unused_dev_dependencies
1144            .extend(parts.unused_dev_dependencies);
1145        self.unused_optional_dependencies
1146            .extend(parts.unused_optional_dependencies);
1147        self.unlisted_dependencies
1148            .extend(parts.unlisted_dependencies);
1149        self.unlisted_binaries.extend(parts.unlisted_binaries);
1150        self.duplicate_exports.extend(parts.duplicate_exports);
1151        self.duplicate_export_aliases
1152            .extend(parts.duplicate_export_aliases);
1153        self.type_only_dependencies
1154            .extend(parts.type_only_dependencies);
1155        self.test_only_dependencies
1156            .extend(parts.test_only_dependencies);
1157        self.dev_dependencies_in_production
1158            .extend(parts.dev_dependencies_in_production);
1159        self.circular_dependencies
1160            .extend(parts.circular_dependencies);
1161        self.re_export_cycles.extend(parts.re_export_cycles);
1162        self.package_cycles.extend(parts.package_cycles);
1163    }
1164
1165    fn merge_workspace_findings(&mut self, parts: AnalysisResultsWorkspaceMergeParts) {
1166        self.unused_catalog_entries
1167            .extend(parts.unused_catalog_entries);
1168        self.empty_catalog_groups.extend(parts.empty_catalog_groups);
1169        self.unresolved_catalog_references
1170            .extend(parts.unresolved_catalog_references);
1171        self.unused_dependency_overrides
1172            .extend(parts.unused_dependency_overrides);
1173        self.misconfigured_dependency_overrides
1174            .extend(parts.misconfigured_dependency_overrides);
1175    }
1176
1177    fn merge_framework_findings(&mut self, parts: AnalysisResultsFrameworkMergeParts) {
1178        self.invalid_client_exports
1179            .extend(parts.invalid_client_exports);
1180        self.mixed_client_server_barrels
1181            .extend(parts.mixed_client_server_barrels);
1182        self.misplaced_directives.extend(parts.misplaced_directives);
1183        self.unprovided_injects.extend(parts.unprovided_injects);
1184        self.unrendered_components
1185            .extend(parts.unrendered_components);
1186        self.route_collisions.extend(parts.route_collisions);
1187        self.dynamic_segment_name_conflicts
1188            .extend(parts.dynamic_segment_name_conflicts);
1189        self.unused_component_props
1190            .extend(parts.unused_component_props);
1191        self.absent_component_props
1192            .extend(parts.absent_component_props);
1193        self.constant_parameters.extend(parts.constant_parameters);
1194        self.unused_component_emits
1195            .extend(parts.unused_component_emits);
1196        self.unused_component_inputs
1197            .extend(parts.unused_component_inputs);
1198        self.unused_component_outputs
1199            .extend(parts.unused_component_outputs);
1200        self.unused_svelte_events.extend(parts.unused_svelte_events);
1201        self.unused_effect_layers.extend(parts.unused_effect_layers);
1202        self.unused_tagged_errors.extend(parts.unused_tagged_errors);
1203        self.unproduced_catch_tags
1204            .extend(parts.unproduced_catch_tags);
1205        self.unused_server_actions
1206            .extend(parts.unused_server_actions);
1207        self.unused_load_data_keys
1208            .extend(parts.unused_load_data_keys);
1209        self.unused_load_data_keys_global_abstain |= parts.unused_load_data_keys_global_abstain;
1210        self.prop_drilling_chains.extend(parts.prop_drilling_chains);
1211        self.thin_wrappers.extend(parts.thin_wrappers);
1212        self.duplicate_prop_shapes
1213            .extend(parts.duplicate_prop_shapes);
1214    }
1215
1216    /// Sort all result arrays for deterministic output ordering.
1217    ///
1218    /// Parallel collection (rayon, `FxHashMap` iteration) does not guarantee
1219    /// insertion order, so the same project can produce different orderings
1220    /// across runs. This method canonicalises every result list by sorting on
1221    /// (path, line, col, name) so that JSON/SARIF/human output is stable.
1222    pub fn sort(&mut self) {
1223        self.semantic_framework_contracts.sort();
1224        self.sort_core_findings();
1225        self.sort_dependency_findings();
1226        self.sort_graph_findings();
1227        self.sort_catalog_findings();
1228        self.sort_metadata_findings();
1229        self.sort_export_usages();
1230    }
1231
1232    fn sort_core_findings(&mut self) {
1233        self.sort_core_declaration_findings();
1234        self.sort_core_member_findings();
1235        self.sort_core_framework_findings();
1236        self.sort_core_route_and_load_findings();
1237    }
1238
1239    fn sort_core_declaration_findings(&mut self) {
1240        self.unused_files
1241            .sort_by(|a, b| a.file.path.cmp(&b.file.path));
1242
1243        self.unused_exports.sort_by(|a, b| {
1244            a.export
1245                .path
1246                .cmp(&b.export.path)
1247                .then(a.export.line.cmp(&b.export.line))
1248                .then(a.export.export_name.cmp(&b.export.export_name))
1249        });
1250
1251        self.unused_types.sort_by(|a, b| {
1252            a.export
1253                .path
1254                .cmp(&b.export.path)
1255                .then(a.export.line.cmp(&b.export.line))
1256                .then(a.export.export_name.cmp(&b.export.export_name))
1257        });
1258
1259        self.private_type_leaks.sort_by(|a, b| {
1260            a.leak
1261                .path
1262                .cmp(&b.leak.path)
1263                .then(a.leak.line.cmp(&b.leak.line))
1264                .then(a.leak.export_name.cmp(&b.leak.export_name))
1265                .then(a.leak.type_name.cmp(&b.leak.type_name))
1266        });
1267
1268        self.deprecated_exports_in_use.sort_by(|a, b| {
1269            a.export
1270                .path
1271                .cmp(&b.export.path)
1272                .then(a.export.line.cmp(&b.export.line))
1273                .then(a.export.export_name.cmp(&b.export.export_name))
1274        });
1275
1276        self.unused_dependencies.sort_by(|a, b| {
1277            a.dep
1278                .path
1279                .cmp(&b.dep.path)
1280                .then(a.dep.line.cmp(&b.dep.line))
1281                .then(a.dep.package_name.cmp(&b.dep.package_name))
1282        });
1283
1284        self.unused_dev_dependencies.sort_by(|a, b| {
1285            a.dep
1286                .path
1287                .cmp(&b.dep.path)
1288                .then(a.dep.line.cmp(&b.dep.line))
1289                .then(a.dep.package_name.cmp(&b.dep.package_name))
1290        });
1291
1292        self.unused_optional_dependencies.sort_by(|a, b| {
1293            a.dep
1294                .path
1295                .cmp(&b.dep.path)
1296                .then(a.dep.line.cmp(&b.dep.line))
1297                .then(a.dep.package_name.cmp(&b.dep.package_name))
1298        });
1299    }
1300
1301    fn sort_core_member_findings(&mut self) {
1302        self.unused_enum_members.sort_by(|a, b| {
1303            a.member
1304                .path
1305                .cmp(&b.member.path)
1306                .then(a.member.line.cmp(&b.member.line))
1307                .then(a.member.parent_name.cmp(&b.member.parent_name))
1308                .then(a.member.member_name.cmp(&b.member.member_name))
1309        });
1310
1311        self.unused_class_members.sort_by(|a, b| {
1312            a.member
1313                .path
1314                .cmp(&b.member.path)
1315                .then(a.member.line.cmp(&b.member.line))
1316                .then(a.member.parent_name.cmp(&b.member.parent_name))
1317                .then(a.member.member_name.cmp(&b.member.member_name))
1318        });
1319
1320        self.namespace_escapes.sort_by(|a, b| {
1321            (
1322                &a.escape.path,
1323                a.escape.line,
1324                a.escape.col,
1325                &a.escape.local_name,
1326            )
1327                .cmp(&(
1328                    &b.escape.path,
1329                    b.escape.line,
1330                    b.escape.col,
1331                    &b.escape.local_name,
1332                ))
1333        });
1334
1335        self.test_only_exports.sort_by(|a, b| {
1336            (
1337                &a.export.path,
1338                a.export.line,
1339                a.export.col,
1340                &a.export.export_name,
1341            )
1342                .cmp(&(
1343                    &b.export.path,
1344                    b.export.line,
1345                    b.export.col,
1346                    &b.export.export_name,
1347                ))
1348        });
1349
1350        self.unused_protected_class_members.sort_by(|a, b| {
1351            a.member
1352                .path
1353                .cmp(&b.member.path)
1354                .then(a.member.line.cmp(&b.member.line))
1355                .then(a.member.parent_name.cmp(&b.member.parent_name))
1356                .then(a.member.member_name.cmp(&b.member.member_name))
1357        });
1358
1359        self.unused_namespace_members.sort_by(|a, b| {
1360            a.member
1361                .path
1362                .cmp(&b.member.path)
1363                .then(a.member.line.cmp(&b.member.line))
1364                .then(a.member.parent_name.cmp(&b.member.parent_name))
1365                .then(a.member.member_name.cmp(&b.member.member_name))
1366        });
1367
1368        self.unused_store_members.sort_by(|a, b| {
1369            a.member
1370                .path
1371                .cmp(&b.member.path)
1372                .then(a.member.line.cmp(&b.member.line))
1373                .then(a.member.parent_name.cmp(&b.member.parent_name))
1374                .then(a.member.member_name.cmp(&b.member.member_name))
1375        });
1376
1377        self.unresolved_imports.sort_by(|a, b| {
1378            a.import
1379                .path
1380                .cmp(&b.import.path)
1381                .then(a.import.line.cmp(&b.import.line))
1382                .then(a.import.col.cmp(&b.import.col))
1383                .then(a.import.specifier.cmp(&b.import.specifier))
1384        });
1385    }
1386
1387    fn sort_core_framework_findings(&mut self) {
1388        self.invalid_client_exports.sort_by(|a, b| {
1389            a.export
1390                .path
1391                .cmp(&b.export.path)
1392                .then(a.export.line.cmp(&b.export.line))
1393                .then(a.export.export_name.cmp(&b.export.export_name))
1394        });
1395
1396        self.mixed_client_server_barrels.sort_by(|a, b| {
1397            a.barrel
1398                .path
1399                .cmp(&b.barrel.path)
1400                .then(a.barrel.line.cmp(&b.barrel.line))
1401                .then(a.barrel.client_origin.cmp(&b.barrel.client_origin))
1402                .then(a.barrel.server_origin.cmp(&b.barrel.server_origin))
1403        });
1404
1405        self.misplaced_directives.sort_by(|a, b| {
1406            a.directive_site
1407                .path
1408                .cmp(&b.directive_site.path)
1409                .then(a.directive_site.line.cmp(&b.directive_site.line))
1410                .then(a.directive_site.col.cmp(&b.directive_site.col))
1411                .then(a.directive_site.directive.cmp(&b.directive_site.directive))
1412        });
1413
1414        self.unprovided_injects.sort_by(|a, b| {
1415            a.inject
1416                .path
1417                .cmp(&b.inject.path)
1418                .then(a.inject.line.cmp(&b.inject.line))
1419                .then(a.inject.col.cmp(&b.inject.col))
1420                .then(a.inject.key_name.cmp(&b.inject.key_name))
1421        });
1422
1423        self.unrendered_components.sort_by(|a, b| {
1424            a.component
1425                .path
1426                .cmp(&b.component.path)
1427                .then(a.component.line.cmp(&b.component.line))
1428                .then(a.component.col.cmp(&b.component.col))
1429                .then(a.component.component_name.cmp(&b.component.component_name))
1430        });
1431    }
1432
1433    fn sort_core_route_and_load_findings(&mut self) {
1434        self.sort_core_route_findings();
1435        self.sort_core_component_prop_and_emit_findings();
1436        self.sort_core_component_io_findings();
1437        self.sort_core_server_load_findings();
1438    }
1439
1440    fn sort_core_route_findings(&mut self) {
1441        self.route_collisions.sort_by(|a, b| {
1442            a.collision
1443                .path
1444                .cmp(&b.collision.path)
1445                .then(a.collision.url.cmp(&b.collision.url))
1446        });
1447
1448        self.dynamic_segment_name_conflicts.sort_by(|a, b| {
1449            a.conflict
1450                .path
1451                .cmp(&b.conflict.path)
1452                .then(a.conflict.position.cmp(&b.conflict.position))
1453        });
1454    }
1455
1456    fn sort_core_component_prop_and_emit_findings(&mut self) {
1457        sort_constant_parameters(&mut self.constant_parameters);
1458        self.absent_component_props.sort_by(|a, b| {
1459            a.prop
1460                .path
1461                .cmp(&b.prop.path)
1462                .then(a.prop.line.cmp(&b.prop.line))
1463                .then(a.prop.prop_name.cmp(&b.prop.prop_name))
1464        });
1465        self.unused_component_props.sort_by(|a, b| {
1466            a.prop
1467                .path
1468                .cmp(&b.prop.path)
1469                .then(a.prop.line.cmp(&b.prop.line))
1470                .then(a.prop.prop_name.cmp(&b.prop.prop_name))
1471        });
1472
1473        self.unused_component_emits.sort_by(|a, b| {
1474            a.emit
1475                .path
1476                .cmp(&b.emit.path)
1477                .then(a.emit.line.cmp(&b.emit.line))
1478                .then(a.emit.emit_name.cmp(&b.emit.emit_name))
1479        });
1480
1481        self.unused_svelte_events.sort_by(|a, b| {
1482            a.event
1483                .path
1484                .cmp(&b.event.path)
1485                .then(a.event.line.cmp(&b.event.line))
1486                .then(a.event.event_name.cmp(&b.event.event_name))
1487        });
1488        self.sort_effect_findings();
1489    }
1490
1491    fn sort_effect_findings(&mut self) {
1492        self.unused_effect_layers.sort_by(|a, b| {
1493            a.layer
1494                .path
1495                .cmp(&b.layer.path)
1496                .then(a.layer.line.cmp(&b.layer.line))
1497                .then(a.layer.name.cmp(&b.layer.name))
1498        });
1499        self.unused_tagged_errors.sort_by(|a, b| {
1500            a.error
1501                .path
1502                .cmp(&b.error.path)
1503                .then(a.error.line.cmp(&b.error.line))
1504                .then(a.error.name.cmp(&b.error.name))
1505        });
1506        self.unproduced_catch_tags.sort_by(|a, b| {
1507            a.catch_tag
1508                .path
1509                .cmp(&b.catch_tag.path)
1510                .then(a.catch_tag.line.cmp(&b.catch_tag.line))
1511                .then(a.catch_tag.col.cmp(&b.catch_tag.col))
1512                .then(a.catch_tag.tag.cmp(&b.catch_tag.tag))
1513        });
1514    }
1515
1516    fn sort_core_component_io_findings(&mut self) {
1517        self.unused_component_inputs.sort_by(|a, b| {
1518            a.input
1519                .path
1520                .cmp(&b.input.path)
1521                .then(a.input.line.cmp(&b.input.line))
1522                .then(a.input.input_name.cmp(&b.input.input_name))
1523        });
1524
1525        self.unused_component_outputs.sort_by(|a, b| {
1526            a.output
1527                .path
1528                .cmp(&b.output.path)
1529                .then(a.output.line.cmp(&b.output.line))
1530                .then(a.output.output_name.cmp(&b.output.output_name))
1531        });
1532    }
1533
1534    fn sort_core_server_load_findings(&mut self) {
1535        self.unused_server_actions.sort_by(|a, b| {
1536            a.action
1537                .path
1538                .cmp(&b.action.path)
1539                .then(a.action.line.cmp(&b.action.line))
1540                .then(a.action.col.cmp(&b.action.col))
1541                .then(a.action.action_name.cmp(&b.action.action_name))
1542        });
1543
1544        self.unused_load_data_keys.sort_by(|a, b| {
1545            a.key
1546                .path
1547                .cmp(&b.key.path)
1548                .then(a.key.line.cmp(&b.key.line))
1549                .then(a.key.col.cmp(&b.key.col))
1550                .then(a.key.key_name.cmp(&b.key.key_name))
1551        });
1552    }
1553
1554    /// Sort prop-drilling chains by their source hop (first hop): file, line,
1555    /// prop, depth, for deterministic output. Split out of `sort_core_findings`
1556    /// to keep that function under the unit-size ceiling.
1557    fn sort_prop_drilling_chains(&mut self) {
1558        self.prop_drilling_chains.sort_by(|a, b| {
1559            let a_src = a.chain.hops.first();
1560            let b_src = b.chain.hops.first();
1561            let a_file = a_src.map(|h| &h.file);
1562            let b_file = b_src.map(|h| &h.file);
1563            a_file
1564                .cmp(&b_file)
1565                .then_with(|| a_src.map(|h| h.line).cmp(&b_src.map(|h| h.line)))
1566                .then(a.chain.prop.cmp(&b.chain.prop))
1567                .then(a.chain.depth.cmp(&b.chain.depth))
1568        });
1569    }
1570
1571    /// Sort thin-wrapper findings by file, line, then component for
1572    /// deterministic output.
1573    fn sort_thin_wrappers(&mut self) {
1574        self.thin_wrappers.sort_by(|a, b| {
1575            a.wrapper
1576                .file
1577                .cmp(&b.wrapper.file)
1578                .then(a.wrapper.line.cmp(&b.wrapper.line))
1579                .then(a.wrapper.component.cmp(&b.wrapper.component))
1580        });
1581    }
1582
1583    /// Sort duplicate-prop-shape findings by the shared shape first (so a
1584    /// group's members stay adjacent), then file, line, and component, for
1585    /// deterministic output.
1586    fn sort_duplicate_prop_shapes(&mut self) {
1587        self.duplicate_prop_shapes.sort_by(|a, b| {
1588            a.shape
1589                .shape
1590                .cmp(&b.shape.shape)
1591                .then(a.shape.file.cmp(&b.shape.file))
1592                .then(a.shape.line.cmp(&b.shape.line))
1593                .then(a.shape.component.cmp(&b.shape.component))
1594        });
1595    }
1596
1597    fn sort_dependency_findings(&mut self) {
1598        self.unlisted_dependencies
1599            .sort_by(|a, b| a.dep.package_name.cmp(&b.dep.package_name));
1600        for dep in &mut self.unlisted_dependencies {
1601            dep.dep
1602                .imported_from
1603                .sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
1604        }
1605
1606        self.unlisted_binaries
1607            .sort_by(|a, b| a.binary.binary_name.cmp(&b.binary.binary_name));
1608        for binary in &mut self.unlisted_binaries {
1609            binary.binary.used_in.sort_by(|a, b| {
1610                a.path
1611                    .cmp(&b.path)
1612                    .then(a.line.cmp(&b.line))
1613                    .then(a.col.cmp(&b.col))
1614            });
1615        }
1616
1617        self.duplicate_exports
1618            .sort_by(|a, b| a.export.export_name.cmp(&b.export.export_name));
1619        for dup in &mut self.duplicate_exports {
1620            dup.export
1621                .locations
1622                .sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
1623        }
1624        self.duplicate_export_aliases.sort_by(|a, b| {
1625            a.alias
1626                .path
1627                .cmp(&b.alias.path)
1628                .then(a.alias.line.cmp(&b.alias.line))
1629                .then(a.alias.col.cmp(&b.alias.col))
1630                .then_with(|| a.alias.export_names.cmp(&b.alias.export_names))
1631        });
1632
1633        self.type_only_dependencies.sort_by(|a, b| {
1634            a.dep
1635                .path
1636                .cmp(&b.dep.path)
1637                .then(a.dep.line.cmp(&b.dep.line))
1638                .then(a.dep.package_name.cmp(&b.dep.package_name))
1639        });
1640
1641        self.test_only_dependencies.sort_by(|a, b| {
1642            a.dep
1643                .path
1644                .cmp(&b.dep.path)
1645                .then(a.dep.line.cmp(&b.dep.line))
1646                .then(a.dep.package_name.cmp(&b.dep.package_name))
1647        });
1648
1649        self.dev_dependencies_in_production.sort_by(|a, b| {
1650            a.dep
1651                .path
1652                .cmp(&b.dep.path)
1653                .then(a.dep.line.cmp(&b.dep.line))
1654                .then(a.dep.package_name.cmp(&b.dep.package_name))
1655        });
1656    }
1657
1658    fn sort_graph_findings(&mut self) {
1659        self.circular_dependencies.sort_by(|a, b| {
1660            a.cycle
1661                .files
1662                .cmp(&b.cycle.files)
1663                .then(a.cycle.length.cmp(&b.cycle.length))
1664        });
1665
1666        self.re_export_cycles
1667            .sort_by(|a, b| a.cycle.files.cmp(&b.cycle.files));
1668
1669        self.package_cycles.sort_by(|a, b| {
1670            a.cycle
1671                .length
1672                .cmp(&b.cycle.length)
1673                .then_with(|| a.cycle.packages.cmp(&b.cycle.packages))
1674        });
1675
1676        self.boundary_violations.sort_by(|a, b| {
1677            a.violation
1678                .from_path
1679                .cmp(&b.violation.from_path)
1680                .then(a.violation.line.cmp(&b.violation.line))
1681                .then(a.violation.col.cmp(&b.violation.col))
1682                .then(a.violation.to_path.cmp(&b.violation.to_path))
1683        });
1684
1685        self.boundary_coverage_violations.sort_by(|a, b| {
1686            a.violation
1687                .path
1688                .cmp(&b.violation.path)
1689                .then(a.violation.line.cmp(&b.violation.line))
1690                .then(a.violation.col.cmp(&b.violation.col))
1691        });
1692
1693        self.boundary_call_violations.sort_by(|a, b| {
1694            a.violation
1695                .path
1696                .cmp(&b.violation.path)
1697                .then(a.violation.line.cmp(&b.violation.line))
1698                .then(a.violation.col.cmp(&b.violation.col))
1699                .then(a.violation.callee.cmp(&b.violation.callee))
1700        });
1701
1702        self.policy_violations.sort_by(|a, b| {
1703            a.violation
1704                .path
1705                .cmp(&b.violation.path)
1706                .then(a.violation.line.cmp(&b.violation.line))
1707                .then(a.violation.col.cmp(&b.violation.col))
1708                .then(a.violation.rule_id.cmp(&b.violation.rule_id))
1709        });
1710    }
1711
1712    fn sort_catalog_findings(&mut self) {
1713        self.sort_stale_suppressions();
1714        self.sort_unused_catalog_entries();
1715        self.sort_empty_catalog_groups();
1716        self.sort_unresolved_catalog_references();
1717        self.sort_unused_dependency_overrides();
1718    }
1719
1720    fn sort_stale_suppressions(&mut self) {
1721        self.stale_suppressions.sort_by(|a, b| {
1722            a.path
1723                .cmp(&b.path)
1724                .then(a.line.cmp(&b.line))
1725                .then(a.col.cmp(&b.col))
1726        });
1727    }
1728
1729    fn sort_unused_catalog_entries(&mut self) {
1730        self.unused_catalog_entries.sort_by(|a, b| {
1731            a.entry
1732                .path
1733                .cmp(&b.entry.path)
1734                .then_with(|| {
1735                    catalog_sort_key(&a.entry.catalog_name)
1736                        .cmp(&catalog_sort_key(&b.entry.catalog_name))
1737                })
1738                .then(a.entry.catalog_name.cmp(&b.entry.catalog_name))
1739                .then(a.entry.entry_name.cmp(&b.entry.entry_name))
1740        });
1741        for finding in &mut self.unused_catalog_entries {
1742            finding.entry.hardcoded_consumers.sort();
1743            finding.entry.hardcoded_consumers.dedup();
1744        }
1745    }
1746
1747    fn sort_empty_catalog_groups(&mut self) {
1748        self.empty_catalog_groups.sort_by(|a, b| {
1749            a.group
1750                .path
1751                .cmp(&b.group.path)
1752                .then_with(|| {
1753                    catalog_sort_key(&a.group.catalog_name)
1754                        .cmp(&catalog_sort_key(&b.group.catalog_name))
1755                })
1756                .then(a.group.catalog_name.cmp(&b.group.catalog_name))
1757                .then(a.group.line.cmp(&b.group.line))
1758        });
1759    }
1760
1761    fn sort_unresolved_catalog_references(&mut self) {
1762        self.unresolved_catalog_references.sort_by(|a, b| {
1763            a.reference
1764                .path
1765                .cmp(&b.reference.path)
1766                .then(a.reference.line.cmp(&b.reference.line))
1767                .then_with(|| {
1768                    catalog_sort_key(&a.reference.catalog_name)
1769                        .cmp(&catalog_sort_key(&b.reference.catalog_name))
1770                })
1771                .then(a.reference.catalog_name.cmp(&b.reference.catalog_name))
1772                .then(a.reference.entry_name.cmp(&b.reference.entry_name))
1773        });
1774        for finding in &mut self.unresolved_catalog_references {
1775            finding.reference.available_in_catalogs.sort();
1776            finding.reference.available_in_catalogs.dedup();
1777        }
1778    }
1779
1780    fn sort_unused_dependency_overrides(&mut self) {
1781        self.unused_dependency_overrides.sort_by(|a, b| {
1782            a.entry
1783                .path
1784                .cmp(&b.entry.path)
1785                .then(a.entry.line.cmp(&b.entry.line))
1786                .then(a.entry.raw_key.cmp(&b.entry.raw_key))
1787        });
1788    }
1789
1790    fn sort_metadata_findings(&mut self) {
1791        self.sort_prop_drilling_chains();
1792        self.sort_thin_wrappers();
1793        self.sort_duplicate_prop_shapes();
1794
1795        self.misconfigured_dependency_overrides.sort_by(|a, b| {
1796            a.entry
1797                .path
1798                .cmp(&b.entry.path)
1799                .then(a.entry.line.cmp(&b.entry.line))
1800                .then(a.entry.raw_key.cmp(&b.entry.raw_key))
1801        });
1802
1803        self.feature_flags.sort_by(|a, b| {
1804            a.path
1805                .cmp(&b.path)
1806                .then(a.line.cmp(&b.line))
1807                .then(a.flag_name.cmp(&b.flag_name))
1808        });
1809
1810        self.security_unresolved_callee_diagnostics.sort_by(|a, b| {
1811            a.path
1812                .cmp(&b.path)
1813                .then(a.line.cmp(&b.line))
1814                .then(a.col.cmp(&b.col))
1815                .then(a.reason.cmp(&b.reason))
1816                .then(a.expression_kind.cmp(&b.expression_kind))
1817        });
1818    }
1819
1820    fn sort_export_usages(&mut self) {
1821        for usage in &mut self.export_usages {
1822            usage.reference_locations.sort_by(|a, b| {
1823                a.path
1824                    .cmp(&b.path)
1825                    .then(a.line.cmp(&b.line))
1826                    .then(a.col.cmp(&b.col))
1827            });
1828        }
1829        self.export_usages.sort_by(|a, b| {
1830            a.path
1831                .cmp(&b.path)
1832                .then(a.line.cmp(&b.line))
1833                .then(a.export_name.cmp(&b.export_name))
1834        });
1835    }
1836}
1837
1838#[path = "results_export_findings.rs"]
1839mod export_findings;
1840pub use export_findings::*;
1841
1842#[path = "results_framework_findings.rs"]
1843mod framework_findings;
1844pub use framework_findings::*;
1845
1846#[path = "results_dependency_findings.rs"]
1847mod dependency_findings;
1848pub use dependency_findings::*;
1849
1850#[path = "results_security_types.rs"]
1851mod security_types;
1852pub use security_types::*;
1853
1854#[path = "results_catalog_findings.rs"]
1855mod catalog_findings;
1856pub use catalog_findings::*;
1857
1858#[path = "results_policy_findings.rs"]
1859mod policy_findings;
1860pub use policy_findings::*;
1861
1862#[path = "results_stale_suppression.rs"]
1863mod stale_suppression;
1864pub use stale_suppression::*;
1865
1866const _: () = assert!(std::mem::size_of::<FeatureFlag>() <= 160);
1867#[path = "results_feature_flags.rs"]
1868mod feature_flags;
1869pub use feature_flags::*;
1870
1871#[path = "results_helpers.rs"]
1872mod results_helpers;
1873use results_helpers::{all_nonempty_paths_match, catalog_sort_key, move_covered};
1874
1875#[cfg(test)]
1876#[path = "results_tests.rs"]
1877mod tests;