Skip to main content

fallow_engine/
results.rs

1//! Internal analysis result contracts re-exported through typed engine modules.
2
3#![allow(
4    unused_imports,
5    reason = "private result contract aggregation re-exports types consumed through typed engine modules"
6)]
7
8use std::path::PathBuf;
9use std::sync::Arc;
10use std::time::Duration;
11
12use fallow_config::ResolvedConfig;
13use fallow_output::{HealthGrouping, HealthReport, HealthTimings};
14use fallow_types::discover::DiscoveredFile;
15use fallow_types::extract::ModuleInfo;
16use fallow_types::source_fingerprint::SourceFingerprint;
17use fallow_types::workspace::WorkspaceDiagnostic;
18use rustc_hash::{FxHashMap, FxHashSet};
19
20use crate::{duplicates, module_graph, trace};
21
22pub use crate::security::{
23    derive_security_severity, enable_security_rules, resolve_security_finding_severity,
24    security_catalogue_title, security_rule_id, security_rules_can_error,
25};
26pub use fallow_types::output_dead_code::{
27    AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
28    BoundaryViolationFinding, CircularDependencyFinding, DuplicateExportFinding,
29    DuplicatePropShapeFinding, DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding,
30    InvalidClientExportFinding, MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
31    MixedClientServerBarrelFinding, NamespaceEscapeFinding, PackageCycleFinding,
32    PolicyViolationFinding, PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding,
33    RouteCollisionFinding, TestOnlyDependencyFinding, ThinWrapperFinding,
34    TypeOnlyDependencyFinding, UnlistedDependencyFinding, UnprovidedInjectFinding,
35    UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding, UnresolvedImportFinding,
36    UnusedCatalogEntryFinding, UnusedClassMemberFinding, UnusedComponentEmitFinding,
37    UnusedComponentInputFinding, UnusedComponentOutputFinding, UnusedComponentPropFinding,
38    UnusedDependencyFinding, UnusedDependencyOverrideFinding, UnusedDevDependencyFinding,
39    UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
40    UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding,
41    UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
42    UnusedSvelteEventFinding, UnusedTypeFinding,
43};
44pub use fallow_types::output_dead_code::{
45    UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
46};
47pub use fallow_types::results::{
48    AbsentComponentProp, ActiveSuppression, AnalysisResults, BoundaryCallViolation,
49    BoundaryCoverageViolation, BoundaryViolation, CircularDependency, CircularDependencyEdge,
50    ComponentPropCallSite, DependencyLocation, DependencyOverrideMisconfigReason,
51    DependencyOverrideSource, DuplicateExport, DuplicateLocation, DuplicatePropShape,
52    DuplicatePropShapeMember, DynamicSegmentNameConflict, EmptyCatalogGroup, EntryPointSummary,
53    ExportUsage, FeatureFlag, FlagConfidence, FlagKind, ImportSite, InvalidClientExport,
54    MisconfiguredDependencyOverride, MisplacedDirective, MixedClientServerBarrel, PackageCycle,
55    PackageCycleEdge, PolicyRuleKind, PolicyViolation, PolicyViolationSeverity, PrivateTypeLeak,
56    PropDrillHop, PropDrillingChain, ReExportCycle, ReExportCycleKind, ReactComponentIntel,
57    ReactHookSummary, ReactPropDrill, ReactPropIntel, ReferenceLocation, RenderFanInComponent,
58    RenderFanInMetric, RouteCollision, SecurityAttackSurfaceEntry, SecurityCandidate,
59    SecurityCandidateBoundary, SecurityCandidateSink, SecurityDeadCodeContext,
60    SecurityDeadCodeKind, SecurityDefensiveBoundary, SecurityDefensiveControl, SecurityFinding,
61    SecurityFindingKind, SecurityNetworkContext, SecurityReachability, SecurityRuntimeContext,
62    SecurityRuntimeState, SecuritySeverity, SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic,
63    SecurityZoneCrossing, StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint,
64    TaintPath, TestOnlyDependency, ThinWrapper, TraceHop, TraceHopRole, TypeOnlyDependency,
65    UnlistedDependency, UnprovidedInject, UnrenderedComponent, UnresolvedCatalogReference,
66    UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit, UnusedComponentInput,
67    UnusedComponentOutput, UnusedComponentProp, UnusedDependency, UnusedDependencyOverride,
68    UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember, UnusedServerAction,
69    UnusedSvelteEvent,
70};
71pub use fallow_types::results::{
72    CandidateArgument, ConstantParameter, ConstantParameterCallSite, ConstantParameterCandidates,
73    ConstantParameterEvidence, ConstantParameterFinding, ConstantParameterReason,
74    ConstantParameterValue, ConstantParameterValueKind, MethodClassCandidate,
75    UnusedDefaultCandidate, constant_parameter_explanation,
76};
77pub use fallow_types::results::{
78    EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
79};
80
81/// Typed dead-code analysis result.
82#[derive(Debug)]
83pub struct DeadCodeAnalysis {
84    /// Findings across all dead-code categories.
85    pub results: AnalysisResults,
86}
87
88/// Typed dead-code analysis result with per-file source hashes.
89#[derive(Debug)]
90pub struct DeadCodeAnalysisWithHashes {
91    /// Findings across all dead-code categories.
92    pub results: AnalysisResults,
93    /// Per-file source content hashes for cache invalidation.
94    pub file_hashes: FxHashMap<PathBuf, u64>,
95}
96
97/// Typed dead-code analysis result with retained parser artifacts.
98#[derive(Debug)]
99pub struct DeadCodeAnalysisOutput {
100    /// Findings across all dead-code categories.
101    pub results: AnalysisResults,
102    /// Parsed modules retained for reuse, when the caller asked for them.
103    pub modules: Option<Vec<ModuleInfo>>,
104    /// Discovered files retained for reuse, when the caller asked for them.
105    pub files: Option<Vec<DiscoveredFile>>,
106}
107
108/// Typed dead-code analysis result with all reusable pipeline artifacts.
109#[derive(Debug)]
110pub struct DeadCodeAnalysisArtifacts {
111    /// Findings across all dead-code categories.
112    pub results: AnalysisResults,
113    /// Per-phase pipeline timings, when the run measured them.
114    pub timings: Option<trace::PipelineTimings>,
115    /// Retained module graph for downstream passes (health, trace, impact).
116    pub graph: Option<module_graph::RetainedModuleGraph>,
117    /// Parsed modules retained for reuse, when the caller asked for them.
118    pub modules: Option<Vec<ModuleInfo>>,
119    /// Discovered files retained for reuse, when the caller asked for them.
120    pub files: Option<Vec<DiscoveredFile>>,
121    /// Package names referenced from package.json scripts, which keeps those
122    /// dependencies from being reported unused.
123    pub script_used_packages: FxHashSet<String>,
124    /// Which configs name which files and dependency names, for the trace
125    /// output.
126    pub trace_provenance: trace::TraceProvenance,
127    /// Per-file source content hashes for cache invalidation.
128    pub file_hashes: FxHashMap<PathBuf, u64>,
129}
130
131/// Shared parser artifacts for workspace-internal session consumers.
132///
133/// This additive contract lets internal callers retain immutable parsed
134/// modules without deep-cloning the session cache. Stable owned APIs continue
135/// to return [`DeadCodeAnalysisArtifacts`].
136#[doc(hidden)]
137#[derive(Debug)]
138pub struct SharedDeadCodeAnalysisArtifacts {
139    pub results: AnalysisResults,
140    pub timings: Option<trace::PipelineTimings>,
141    pub graph: Option<module_graph::RetainedModuleGraph>,
142    pub modules: Option<Arc<[ModuleInfo]>>,
143    pub files: Option<Vec<DiscoveredFile>>,
144    pub script_used_packages: FxHashSet<String>,
145    pub trace_provenance: trace::TraceProvenance,
146    pub file_hashes: FxHashMap<PathBuf, u64>,
147}
148
149impl SharedDeadCodeAnalysisArtifacts {
150    /// Convert shared parser artifacts to the stable owned result contract.
151    #[must_use]
152    pub fn into_owned(self) -> DeadCodeAnalysisArtifacts {
153        let modules = self.modules.map(|modules| {
154            let mut owned = modules.to_vec();
155            for module in &mut owned {
156                module.release_resolution_payload();
157            }
158            owned
159        });
160        DeadCodeAnalysisArtifacts {
161            results: self.results,
162            timings: self.timings,
163            graph: self.graph,
164            modules,
165            files: self.files,
166            script_used_packages: self.script_used_packages,
167            trace_provenance: self.trace_provenance,
168            file_hashes: self.file_hashes,
169        }
170    }
171}
172
173/// Typed project analysis result combining dead-code and duplication outputs.
174#[derive(Debug)]
175pub struct ProjectAnalysisOutput {
176    /// Dead-code findings with optionally retained parser artifacts.
177    pub dead_code: DeadCodeAnalysisOutput,
178    /// Duplication report for the same file set.
179    pub duplication: duplicates::DuplicationReport,
180}
181
182/// Typed project analysis result with reusable session artifacts.
183#[derive(Debug)]
184pub struct ProjectAnalysisArtifacts {
185    /// Dead-code findings with all reusable pipeline artifacts.
186    pub dead_code: DeadCodeAnalysisArtifacts,
187    /// Duplication report for the same file set.
188    pub duplication: duplicates::DuplicationReport,
189    /// The clone groups that `duplicates.ignoredClones` hid from
190    /// `duplication`.
191    pub ignored_clone_groups: Vec<duplicates::IgnoredCloneGroup>,
192    /// Diff scope the run was limited to, when one was resolved.
193    pub changed_files: Option<FxHashSet<PathBuf>>,
194    /// Per-file source fingerprints for downstream cache invalidation.
195    pub source_fingerprints: Option<FxHashMap<PathBuf, SourceFingerprint>>,
196}
197
198impl ProjectAnalysisArtifacts {
199    /// Drop retained reuse-only artifacts and return the stable project output.
200    #[must_use]
201    pub fn into_output(self) -> ProjectAnalysisOutput {
202        ProjectAnalysisOutput {
203            dead_code: DeadCodeAnalysisOutput {
204                results: self.dead_code.results,
205                modules: self.dead_code.modules,
206                files: self.dead_code.files,
207            },
208            duplication: self.duplication,
209        }
210    }
211}
212
213/// Typed duplication analysis result.
214#[derive(Debug)]
215pub struct DuplicationAnalysis {
216    /// The clone groups after every filter, with statistics.
217    pub report: duplicates::DuplicationReport,
218    /// Files that the built-in duplication ignores skipped, per pattern.
219    pub default_ignore_skips: duplicates::DefaultIgnoreSkips,
220    /// The clone groups that `duplicates.ignoredClones` hid from `report`.
221    pub ignored_clone_groups: Vec<duplicates::IgnoredCloneGroup>,
222}
223
224/// Typed health analysis result shared by CLI, API, NAPI, and future embedders.
225///
226/// The result contract belongs at the engine boundary so downstream callers can
227/// depend on a command-neutral shape.
228#[derive(Debug)]
229pub struct HealthAnalysisResult<GroupResolver = ()> {
230    /// The assembled health report for the active run scope.
231    pub report: HealthReport,
232    /// Optional TypeScript semantic metadata for advisory health overlays.
233    pub type_aware_meta: Option<fallow_types::envelope::TypeAwareMeta>,
234    /// Per-file branching totals, keyed by absolute path.
235    ///
236    /// Threshold-blind and suppression-blind, unlike `report`, which holds only
237    /// units that breached a threshold. The audit compares this map across the
238    /// base and head revisions; nothing else reads it, and it is not
239    /// serialized, so it carries no schema version.
240    pub branching_by_file: crate::health::BranchingByFile,
241    /// Per-group health output when grouping is active.
242    ///
243    /// `None` for the default run; `Some` for any grouped invocation. The
244    /// top-level report reflects the active run scope; consumers that want
245    /// per-group metrics read from `grouping.groups`.
246    pub grouping: Option<HealthGrouping>,
247    /// Optional grouping resolver retained by callers that need to tag findings
248    /// after analysis without rediscovering ownership or package metadata.
249    pub group_resolver: Option<GroupResolver>,
250    /// Resolved config the run executed under.
251    pub config: ResolvedConfig,
252    /// Diagnostics from workspace discovery (undeclared or invalid members).
253    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
254    /// Total wall time of the health run.
255    pub elapsed: Duration,
256    /// Per-phase timings, when the run measured them.
257    pub timings: Option<HealthTimings>,
258    /// True when the coverage gaps section produced findings.
259    pub coverage_gaps_has_findings: bool,
260    /// True when coverage gap findings should fail the run (the gate is
261    /// enforced rather than advisory).
262    pub should_fail_on_coverage_gaps: bool,
263    /// The changed files the run analyzed, when a changed-file set narrowed
264    /// it: the files of that set that discovery kept. `None` when the run was
265    /// not narrowed by changed files. Callers size a `changed-since` scope
266    /// from it.
267    pub changed_files_analyzed: Option<Vec<std::path::PathBuf>>,
268}
269
270impl<GroupResolver> HealthAnalysisResult<GroupResolver> {
271    /// Drop presentation-only grouping resolver state while preserving the
272    /// command-neutral health analysis payload.
273    #[must_use]
274    pub fn without_group_resolver(self) -> HealthAnalysisResult<()> {
275        HealthAnalysisResult {
276            report: self.report,
277            type_aware_meta: self.type_aware_meta,
278            branching_by_file: self.branching_by_file,
279            grouping: self.grouping,
280            group_resolver: None,
281            config: self.config,
282            workspace_diagnostics: self.workspace_diagnostics,
283            elapsed: self.elapsed,
284            timings: self.timings,
285            coverage_gaps_has_findings: self.coverage_gaps_has_findings,
286            should_fail_on_coverage_gaps: self.should_fail_on_coverage_gaps,
287            changed_files_analyzed: self.changed_files_analyzed,
288        }
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use crate::project_config::{ProjectConfigOptions, config_for_project_analysis};
295    use fallow_config::ProductionAnalysis;
296    use fallow_types::output_format::OutputFormat;
297
298    use super::*;
299
300    #[test]
301    fn health_analysis_result_drops_presentation_resolver() {
302        let project = tempfile::tempdir().expect("temp dir");
303        let project_config = config_for_project_analysis(
304            project.path(),
305            None,
306            ProjectConfigOptions {
307                output: OutputFormat::Json,
308                no_cache: true,
309                threads: 1,
310                production_override: None,
311                quiet: true,
312                analysis: ProductionAnalysis::Health,
313                allow_remote_extends: false,
314            },
315        )
316        .expect("project config loads");
317        let result = HealthAnalysisResult {
318            report: HealthReport::default(),
319            branching_by_file: crate::health::BranchingByFile::default(),
320            grouping: None,
321            group_resolver: Some("resolver"),
322            config: project_config.config,
323            workspace_diagnostics: Vec::new(),
324            elapsed: Duration::from_millis(7),
325            timings: None,
326            coverage_gaps_has_findings: true,
327            should_fail_on_coverage_gaps: true,
328            type_aware_meta: None,
329            changed_files_analyzed: None,
330        };
331
332        let neutral = result.without_group_resolver();
333
334        assert!(neutral.group_resolver.is_none());
335        assert_eq!(neutral.elapsed, Duration::from_millis(7));
336        assert!(neutral.coverage_gaps_has_findings);
337        assert!(neutral.should_fail_on_coverage_gaps);
338    }
339
340    #[test]
341    fn engine_result_surface_uses_explicit_reexports() {
342        let source = include_str!("results.rs");
343        let output_dead_code_wildcard = concat!("pub use fallow_types::output_dead_code::", "*");
344        let results_wildcard = concat!("pub use fallow_types::results::", "*");
345
346        assert!(!source.contains(output_dead_code_wildcard));
347        assert!(!source.contains(results_wildcard));
348    }
349}