Skip to main content

fallow_api/
editor.rs

1//! Editor-facing analysis contracts shared by LSP and future editor adapters.
2
3use std::path::{Path, PathBuf};
4
5use rustc_hash::FxHashSet;
6
7use fallow_types::{discover::DiscoveredFile, extract::ModuleInfo};
8
9use crate::{ChangeScope, ChangeScopeRequest, PackageBaselineError};
10
11/// Editor-boundary alias for the clone-family payload.
12pub type EditorCloneFamily = fallow_types::duplicates::CloneFamily;
13/// Editor-boundary alias for the clone-group payload.
14pub type EditorCloneGroup = fallow_types::duplicates::CloneGroup;
15/// Editor-boundary alias for one clone occurrence within a group.
16pub type EditorCloneInstance = fallow_types::duplicates::CloneInstance;
17/// Editor-boundary alias for the full duplication report.
18pub type EditorDuplicationReport = fallow_types::duplicates::DuplicationReport;
19/// Editor-boundary alias for aggregate duplication statistics.
20pub type EditorDuplicationStats = fallow_types::duplicates::DuplicationStats;
21/// Editor-boundary alias for a mirrored-directory finding.
22pub type EditorMirroredDirectory = fallow_types::duplicates::MirroredDirectory;
23/// Editor-boundary alias for the refactoring-suggestion kind.
24pub type EditorRefactoringKind = fallow_types::duplicates::RefactoringKind;
25/// Editor-boundary alias for a refactoring suggestion.
26pub type EditorRefactoringSuggestion = fallow_types::duplicates::RefactoringSuggestion;
27
28/// Report-scoped clone fingerprint assignment for editor-facing duplication output.
29#[derive(Debug, Clone)]
30pub struct EditorCloneFingerprintSet {
31    inner: fallow_engine::duplicates::CloneFingerprintSet,
32}
33
34impl EditorCloneFingerprintSet {
35    /// Assign collision-free fingerprints for clone groups in one report.
36    #[must_use]
37    pub fn from_groups(groups: &[EditorCloneGroup]) -> Self {
38        Self {
39            inner: fallow_engine::duplicates::CloneFingerprintSet::from_groups(groups),
40        }
41    }
42
43    /// Return the assigned fingerprint for a clone group.
44    #[must_use]
45    pub fn fingerprint_for_group(&self, group: &EditorCloneGroup) -> String {
46        self.inner.fingerprint_for_group(group)
47    }
48
49    /// Return the assigned fingerprint for clone-group parts.
50    #[must_use]
51    pub fn fingerprint_for_parts(
52        &self,
53        instances: &[EditorCloneInstance],
54        token_count: usize,
55        line_count: usize,
56    ) -> String {
57        self.inner
58            .fingerprint_for_parts(instances, token_count, line_count)
59    }
60
61    /// Find the group addressed by an assigned fingerprint.
62    #[must_use]
63    pub fn find_group<'a>(
64        &self,
65        groups: &'a [EditorCloneGroup],
66        fingerprint: &str,
67    ) -> Option<&'a EditorCloneGroup> {
68        self.inner.find_group(groups, fingerprint)
69    }
70}
71
72/// Duplication contracts re-exported under their unprefixed names so editor
73/// adapters can import them as a module namespace.
74pub mod editor_duplicates {
75    pub use crate::editor::{
76        EditorCloneFamily as CloneFamily, EditorCloneFingerprintSet as CloneFingerprintSet,
77        EditorCloneGroup as CloneGroup, EditorCloneInstance as CloneInstance,
78        EditorDuplicationReport as DuplicationReport, EditorDuplicationStats as DuplicationStats,
79        EditorMirroredDirectory as MirroredDirectory, EditorRefactoringKind as RefactoringKind,
80        EditorRefactoringSuggestion as RefactoringSuggestion,
81    };
82}
83
84/// Classification of a changed-file git failure for editor integrations.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum ChangedFilesError {
87    /// Git ref failed validation before invoking `git`.
88    InvalidRef(String),
89    /// `git` binary not found or not executable.
90    GitMissing(String),
91    /// Command ran but the directory is not a git repository.
92    NotARepository,
93    /// Command ran but the ref is invalid or another git error occurred.
94    GitFailed(String),
95}
96
97impl ChangedFilesError {
98    /// Human-readable clause suitable for embedding in an error message.
99    #[must_use]
100    pub fn describe(&self) -> String {
101        match self {
102            Self::InvalidRef(err) => format!("invalid git ref: {err}"),
103            Self::GitMissing(err) => format!("failed to run git: {err}"),
104            Self::NotARepository => "not a git repository".to_owned(),
105            Self::GitFailed(stderr) => {
106                let lower = stderr.to_ascii_lowercase();
107                if lower.contains("not a valid object name")
108                    || lower.contains("unknown revision")
109                    || lower.contains("ambiguous argument")
110                {
111                    format!(
112                        "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
113                    )
114                } else {
115                    stderr.clone()
116                }
117            }
118        }
119    }
120}
121
122impl From<fallow_engine::changed_files::ChangedFilesError> for ChangedFilesError {
123    fn from(error: fallow_engine::changed_files::ChangedFilesError) -> Self {
124        match error {
125            fallow_engine::changed_files::ChangedFilesError::InvalidRef(err) => {
126                Self::InvalidRef(err)
127            }
128            fallow_engine::changed_files::ChangedFilesError::GitMissing(err) => {
129                Self::GitMissing(err)
130            }
131            fallow_engine::changed_files::ChangedFilesError::NotARepository => Self::NotARepository,
132            fallow_engine::changed_files::ChangedFilesError::GitFailed(stderr) => {
133                Self::GitFailed(stderr)
134            }
135        }
136    }
137}
138
139/// Resolve the canonical git toplevel for `cwd`.
140///
141/// # Errors
142///
143/// Returns an API-owned changed-file error when git cannot inspect the
144/// repository.
145pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
146    fallow_engine::changed_files::resolve_git_toplevel(cwd).map_err(ChangedFilesError::from)
147}
148
149/// Get changed files and the git toplevel used to resolve them.
150///
151/// # Errors
152///
153/// Returns an API-owned changed-file error when git cannot resolve the ref or
154/// repository state.
155pub fn try_get_changed_files_with_toplevel(
156    cwd: &Path,
157    toplevel: &Path,
158    git_ref: &str,
159) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
160    fallow_engine::changed_files::try_get_changed_files_with_toplevel(cwd, toplevel, git_ref)
161        .map_err(ChangedFilesError::from)
162}
163
164/// Per-module extraction facts re-exported for editor adapters that inspect
165/// retained parse artifacts.
166pub mod editor_extract {
167    pub use fallow_types::extract::{
168        AngularComponentSelector, AngularInputMember, AngularOutputMember,
169        AngularTemplateMemberAccessFact, AngularThisSpreadFact, CalleeUse, ClassHeritageInfo,
170        ComplexityContribution, ComplexityContributionKind, ComplexityMetric, ComponentEmit,
171        ComponentFunction, ComponentFunctionKind, ComponentProp, CssAnalytics, CssDeclarationBlock,
172        CssRuleMetric, DiFramework, DiKeySite, DiRole, DispatchedEvent,
173        DynamicCustomElementRenderFact, DynamicImportInfo, DynamicImportPattern, ExportInfo,
174        ExportName, FactoryCallMemberAccessFact, FactoryFnMemberAccessFact, FactoryReturnExport,
175        FlagUse, FlagUseKind, FluentChainMemberAccessFact, FluentChainNewMemberAccessFact,
176        ForwardAttr, FunctionComplexity, HookUse, HookUseKind, ImportInfo, ImportedName,
177        InstanceExportBindingFact, LoadReturnKey, LocalTypeDeclaration, MemberAccess, MemberInfo,
178        MemberKind, MisplacedDirectiveSite, ModuleInfo, NamespaceObjectAlias, PUBLIC_ENV_EXACT,
179        PUBLIC_ENV_METADATA_TOKENS, PUBLIC_ENV_PREFIXES, ParseResult, PlaywrightFixtureAliasFact,
180        PlaywrightFixtureDefinitionFact, PlaywrightFixtureTypeFact, PlaywrightFixtureUseFact,
181        PublicSignatureTypeReference, ReExportInfo, RegisteredCustomElement, RenderEdge,
182        RequireCallInfo, SECRET_ENV_TOKENS, SanitizedSinkArg, SanitizerScope, SecurityControlKind,
183        SecurityControlSite, SecurityUrlShape, SemanticFact, SemanticFactView, SinkArgKind,
184        SinkLiteralValue, SinkObjectProperty, SinkShape, SinkSite,
185        SkippedSecurityCalleeExpressionKind, SkippedSecurityCalleeReason,
186        SkippedSecurityCalleeSite, TaintedBinding, VisibilityTag,
187    };
188}
189
190/// Typed analysis-result and finding contracts re-exported for editor
191/// adapters.
192pub mod editor_results {
193    pub use fallow_types::output_dead_code::DuplicateExportAliasFinding;
194    pub use fallow_types::output_dead_code::{
195        AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
196        BoundaryViolationFinding, CircularDependencyFinding, DeprecatedExportInUseFinding,
197        DevDependencyInProductionFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
198        DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding, InvalidClientExportFinding,
199        MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
200        MixedClientServerBarrelFinding, PackageCycleFinding, PolicyViolationFinding,
201        PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding,
202        RouteCollisionFinding, TestOnlyDependencyFinding, ThinWrapperFinding,
203        TypeOnlyDependencyFinding, UnlistedDependencyFinding, UnprovidedInjectFinding,
204        UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding, UnresolvedImportFinding,
205        UnusedCatalogEntryFinding, UnusedClassMemberFinding, UnusedComponentEmitFinding,
206        UnusedComponentInputFinding, UnusedComponentOutputFinding, UnusedComponentPropFinding,
207        UnusedDependencyFinding, UnusedDependencyOverrideFinding, UnusedDevDependencyFinding,
208        UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
209        UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding, UnusedServerActionFinding,
210        UnusedStoreMemberFinding, UnusedSvelteEventFinding, UnusedTypeFinding,
211    };
212    pub use fallow_types::output_dead_code::{
213        UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
214    };
215    pub use fallow_types::results::{
216        AbsentComponentProp, ActiveSuppression, AnalysisResults, BoundaryCallViolation,
217        BoundaryCoverageViolation, BoundaryViolation, CircularDependency, CircularDependencyEdge,
218        ComponentPropCallSite, DependencyLocation, DependencyOverrideMisconfigReason,
219        DependencyOverrideSource, DeprecatedConsumerKind, DeprecatedExportConsumer,
220        DeprecatedExportInUse, DevDependencyInProduction, DuplicateExport, DuplicateLocation,
221        DuplicatePropShape, DuplicatePropShapeMember, DynamicSegmentNameConflict,
222        EmptyCatalogGroup, EntryPointSummary, ExportUsage, FeatureFlag, FlagConfidence, FlagKind,
223        ImportSite, InvalidClientExport, MisconfiguredDependencyOverride, MisplacedDirective,
224        MixedClientServerBarrel, PackageCycle, PackageCycleEdge, PolicyRuleKind, PolicyViolation,
225        PolicyViolationSeverity, PrivateTypeLeak, PropDrillHop, PropDrillingChain, ReExportCycle,
226        ReExportCycleKind, ReactComponentIntel, ReactHookSummary, ReactPropDrill, ReactPropIntel,
227        ReferenceLocation, RenderFanInComponent, RenderFanInMetric, RouteCollision,
228        SecurityAttackSurfaceEntry, SecurityCandidate, SecurityCandidateBoundary,
229        SecurityCandidateSink, SecurityDeadCodeContext, SecurityDeadCodeKind,
230        SecurityDefensiveBoundary, SecurityDefensiveControl, SecurityFinding, SecurityFindingKind,
231        SecurityNetworkContext, SecurityReachability, SecurityRuntimeContext, SecurityRuntimeState,
232        SecuritySeverity, SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic,
233        SecurityZoneCrossing, StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint,
234        TaintPath, TestOnlyDependency, ThinWrapper, TraceHop, TraceHopRole, TypeOnlyDependency,
235        UnlistedDependency, UnprovidedInject, UnrenderedComponent, UnresolvedCatalogReference,
236        UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit, UnusedComponentInput,
237        UnusedComponentOutput, UnusedComponentProp, UnusedDependency, UnusedDependencyOverride,
238        UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember, UnusedServerAction,
239        UnusedSvelteEvent,
240    };
241    pub use fallow_types::results::{
242        ConstantParameter, ConstantParameterCallSite, ConstantParameterFinding,
243        ConstantParameterReason, ConstantParameterValue, ConstantParameterValueKind,
244    };
245    pub use fallow_types::results::{DuplicateExportAlias, DuplicateExportAliasLocation};
246    pub use fallow_types::results::{
247        EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
248    };
249}
250
251/// Security catalogue lookups exposed at the editor boundary.
252pub mod editor_security {
253    /// Return the human-readable security catalogue title for a finding kind.
254    #[must_use]
255    pub fn security_catalogue_title(kind: &str) -> Option<&'static str> {
256        fallow_engine::dead_code::security_catalogue_title(kind)
257    }
258}
259
260/// Inline-suppression contracts re-exported for editor adapters.
261pub mod editor_suppress {
262    pub use fallow_types::suppress::{IssueKind, is_suppressed};
263}
264
265/// Editor-boundary alias for the typed dead-code analysis results.
266pub type EditorAnalysisResults = fallow_types::results::AnalysisResults;
267
268/// Dead-code output retained for editor integrations.
269///
270/// The engine produces the data, but the editor API owns this public contract
271/// so LSP and future editor adapters do not depend on engine result structs.
272#[derive(Debug)]
273pub struct EditorDeadCodeAnalysisOutput {
274    /// Typed dead-code findings from the analysis.
275    pub results: EditorAnalysisResults,
276    /// Retained per-module parse artifacts; `None` unless the run was asked
277    /// to keep them for follow-up editor features.
278    pub modules: Option<Vec<ModuleInfo>>,
279    /// Retained discovered-file records matching `modules`.
280    pub files: Option<Vec<DiscoveredFile>>,
281}
282
283impl EditorDeadCodeAnalysisOutput {
284    fn from_engine(output: fallow_engine::dead_code::DeadCodeAnalysisOutput) -> Self {
285        Self {
286            results: output.results,
287            modules: output.modules,
288            files: output.files,
289        }
290    }
291}
292
293/// Editor-facing inline complexity signal for code lens and similar surfaces.
294///
295/// The finding is derived from retained typed engine parse artifacts, but the
296/// editor API owns the stable shape so LSP and future editor adapters do not
297/// need to inspect raw modules directly.
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct EditorInlineComplexityFinding {
300    /// Absolute path of the file declaring the function.
301    pub path: PathBuf,
302    /// Function name as extracted from the source.
303    pub name: String,
304    /// One-based line of the function declaration.
305    pub line: u32,
306    /// Zero-based column of the function declaration.
307    pub col: u32,
308    /// Measured cyclomatic complexity.
309    pub cyclomatic: u16,
310    /// Measured cognitive complexity.
311    pub cognitive: u16,
312    /// Which configured threshold(s) the function exceeded.
313    pub exceeded: EditorInlineComplexityExceeded,
314}
315
316/// Which health complexity threshold(s) a function exceeded.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum EditorInlineComplexityExceeded {
319    /// Only the cyclomatic threshold was exceeded.
320    Cyclomatic,
321    /// Only the cognitive threshold was exceeded.
322    Cognitive,
323    /// Both thresholds were exceeded.
324    CyclomaticAndCognitive,
325}
326
327/// Collect inline complexity findings from retained editor analysis artifacts.
328///
329/// The rule is `fallow_engine::health::inline_complexity`, the one that the
330/// health findings use, so the code lens and `fallow health` flag the same
331/// functions, also under `health.thresholdOverrides`.
332#[must_use]
333pub fn collect_inline_complexity(
334    config: &fallow_config::ResolvedConfig,
335    output: &EditorDeadCodeAnalysisOutput,
336) -> Vec<EditorInlineComplexityFinding> {
337    let (Some(modules), Some(files)) = (output.modules.as_ref(), output.files.as_ref()) else {
338        return Vec::new();
339    };
340    fallow_engine::health::inline_complexity(config, modules, files)
341        .into_iter()
342        .map(|finding| EditorInlineComplexityFinding {
343            exceeded: match (finding.exceeds_cyclomatic, finding.exceeds_cognitive) {
344                (true, true) => EditorInlineComplexityExceeded::CyclomaticAndCognitive,
345                (true, false) => EditorInlineComplexityExceeded::Cyclomatic,
346                (false, _) => EditorInlineComplexityExceeded::Cognitive,
347            },
348            path: finding.path,
349            name: finding.name,
350            line: finding.line,
351            col: finding.col,
352            cyclomatic: finding.cyclomatic,
353            cognitive: finding.cognitive,
354        })
355        .collect()
356}
357
358/// Filter inline complexity findings to the changed-file set.
359#[expect(
360    clippy::implicit_hasher,
361    reason = "editor analysis changed-file sets use the workspace FxHashSet convention"
362)]
363pub fn filter_inline_complexity_by_changed_files(
364    findings: &mut Vec<EditorInlineComplexityFinding>,
365    changed_files: &FxHashSet<PathBuf>,
366) {
367    findings.retain(|finding| changed_files.contains(&finding.path));
368}
369
370/// Retain the inline complexity findings in a resolved change scope.
371pub fn filter_inline_complexity_by_change_scope(
372    findings: &mut Vec<EditorInlineComplexityFinding>,
373    scope: &ChangeScope,
374) {
375    findings.retain(|finding| scope.contains(&finding.path));
376}
377
378/// The parse work of an editor session. See
379/// [`fallow_engine::session::SessionParseCounts`].
380pub type EditorSessionParseCounts = fallow_engine::session::SessionParseCounts;
381
382/// Reusable editor analysis session owned by the API boundary.
383#[derive(Debug)]
384pub struct EditorAnalysisSession {
385    inner: fallow_engine::session::AnalysisSession,
386}
387
388impl EditorAnalysisSession {
389    /// Load config and discover files for an editor project root.
390    ///
391    /// # Errors
392    ///
393    /// Returns an engine error when project config loading fails.
394    pub fn load(root: &Path, config_path: Option<&Path>) -> fallow_engine::EngineResult<Self> {
395        fallow_engine::session::AnalysisSession::load(root, config_path).map(Self::from_engine)
396    }
397
398    /// Load config, apply one editor-specific adjustment, then discover files.
399    ///
400    /// # Errors
401    ///
402    /// Returns an engine error when project config loading fails.
403    pub fn load_with_config(
404        root: &Path,
405        config_path: Option<&Path>,
406        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
407    ) -> fallow_engine::EngineResult<Self> {
408        fallow_engine::session::AnalysisSession::load_with_config(root, config_path, configure)
409            .map(Self::from_engine)
410    }
411
412    /// Load config with an explicit inheritance trust policy, apply one
413    /// editor-specific adjustment, then discover files.
414    ///
415    /// # Errors
416    ///
417    /// Returns an engine error when project config loading fails.
418    pub fn load_with_config_options(
419        root: &Path,
420        config_path: Option<&Path>,
421        load_options: fallow_config::ConfigLoadOptions,
422        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
423    ) -> fallow_engine::EngineResult<Self> {
424        fallow_engine::session::AnalysisSession::load_with_config_options(
425            root,
426            config_path,
427            load_options,
428            configure,
429        )
430        .map(Self::from_engine)
431    }
432
433    /// Build a session from built-in defaults, ignoring project config files.
434    #[must_use]
435    pub fn load_default(root: &Path) -> Self {
436        Self::from_engine(fallow_engine::session::AnalysisSession::load_default(root))
437    }
438
439    /// Build a session from built-in defaults, apply one editor-specific
440    /// adjustment, then discover files.
441    #[must_use]
442    pub fn load_default_with_config(
443        root: &Path,
444        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
445    ) -> Self {
446        Self::from_engine(
447            fallow_engine::session::AnalysisSession::load_default_with_config(root, configure),
448        )
449    }
450
451    /// Attach a caller-owned cancellation token to this session.
452    ///
453    /// The analyses of the session check the token at each pipeline stage
454    /// boundary and in the per-file parse loop. Once the token is set, they
455    /// return an engine error whose `is_cancelled()` is true, never a partial
456    /// result. See
457    /// [`fallow_engine::session::AnalysisSession::with_cancellation`] for the
458    /// limits of the cooperative stop.
459    #[must_use]
460    pub fn with_cancellation(
461        self,
462        cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
463    ) -> Self {
464        Self::from_engine(self.inner.with_cancellation(cancellation))
465    }
466
467    /// Replace the cancellation token of a session that serves several runs.
468    pub fn set_cancellation(
469        &mut self,
470        cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
471    ) {
472        self.inner.set_cancellation(cancellation);
473    }
474
475    /// Walk the project again before a run of a long-lived session. The
476    /// parsed modules stay when the file set did not change. Returns whether
477    /// the file set changed. See
478    /// [`fallow_engine::session::AnalysisSession::refresh_discovery`].
479    pub fn refresh_discovery(&mut self) -> bool {
480        self.inner.refresh_discovery()
481    }
482
483    /// The plugin files, rule packs and `autoDiscover` directories that
484    /// config resolution read for this session. A long-lived caller compares
485    /// two snapshots of them to see that the config is out of date.
486    #[must_use]
487    pub fn config_inputs(&self) -> &fallow_config::ConfigInputs {
488        self.inner.config_inputs()
489    }
490
491    /// The content of [`Self::config_inputs`] just before config resolution
492    /// read them.
493    #[must_use]
494    pub fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
495        self.inner.config_inputs_before_resolve()
496    }
497
498    /// The estimated heap memory of the parsed modules that the session
499    /// keeps between runs. Zero before the first parse.
500    #[must_use]
501    pub fn retained_bytes_estimate(&self) -> u64 {
502        self.inner.retained_bytes_estimate()
503    }
504
505    /// Write the modules of incremental parses to the persisted parse cache.
506    /// Call it before the session is dropped.
507    pub fn flush_parse_cache(&self) {
508        self.inner.flush_parse_cache();
509    }
510
511    /// Parse the project files into the session without analysis, so the
512    /// first run starts from warm modules.
513    ///
514    /// # Errors
515    ///
516    /// Returns a cancelled engine error when the token of the session is set.
517    pub fn prewarm(&self, retain_complexity_artifacts: bool) -> fallow_engine::EngineResult<()> {
518        self.inner
519            .prewarm_parsed_modules(retain_complexity_artifacts)
520    }
521
522    /// The parse work of this session since it was created.
523    #[must_use]
524    pub fn parse_counts(&self) -> EditorSessionParseCounts {
525        self.inner.parse_counts()
526    }
527
528    /// Resolved project config.
529    #[must_use]
530    pub fn config(&self) -> &fallow_config::ResolvedConfig {
531        self.inner.config()
532    }
533
534    /// Resolve the change scope of this project with the engine rule that
535    /// the CLI and the programmatic API use.
536    ///
537    /// # Errors
538    ///
539    /// Returns a typed error when the package map names an invalid or unknown
540    /// workspace root, or a Git ref that does not resolve.
541    pub fn change_scope(
542        &self,
543        request: ChangeScopeRequest<'_>,
544    ) -> Result<ChangeScope, PackageBaselineError> {
545        ChangeScope::resolve(request, self.inner.config(), self.inner.workspaces())
546    }
547
548    /// `workspace_diagnostics[]` entries for the config patterns
549    /// (`ignoreFindings`, `ignoreDependencies`) that matched nothing in the
550    /// latest analysis of this session. The CLI and the programmatic API
551    /// build the same entries with the same engine function.
552    #[must_use]
553    pub fn unmatched_config_patterns(&self) -> Vec<fallow_config::WorkspaceDiagnostic> {
554        fallow_engine::dead_code::config_pattern_diagnostics(self.inner.config(), true)
555    }
556
557    /// Config file path when one was loaded.
558    #[must_use]
559    pub fn config_path(&self) -> Option<&Path> {
560        self.inner.config_path()
561    }
562
563    /// Refine this editor session's dead-code findings with exact TypeScript
564    /// symbol evidence.
565    ///
566    /// # Errors
567    ///
568    /// Returns a programmatic error when the semantic companion cannot provide
569    /// the requested analysis contract.
570    pub fn refine_type_aware_dead_code(
571        &self,
572        options: &crate::TypeAwareOptions,
573        filters: &crate::DeadCodeFilters,
574        output: &mut EditorDeadCodeAnalysisOutput,
575    ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
576        let meta = crate::type_aware::refine_programmatic_dead_code(
577            options,
578            filters,
579            &self.inner,
580            &mut output.results,
581        )?;
582        // Reconciliation can add findings, so rule severities are resolved
583        // again over the refined set. The pass removes findings and writes
584        // each gate severity again, so repeating it is idempotent.
585        fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
586        Ok(meta)
587    }
588
589    /// Refine editor findings through a root-bound persistent semantic session.
590    pub fn refine_type_aware_dead_code_in_session(
591        &self,
592        semantic_session: &mut crate::TypeAwareSession,
593        changes: Option<&crate::TypeAwareFileChanges>,
594        options: &crate::TypeAwareOptions,
595        filters: &crate::DeadCodeFilters,
596        output: &mut EditorDeadCodeAnalysisOutput,
597    ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
598        let meta = crate::type_aware::refine_programmatic_dead_code_in_session(
599            semantic_session,
600            changes,
601            options,
602            filters,
603            &self.inner,
604            &mut output.results,
605        )?;
606        fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
607        Ok(meta)
608    }
609
610    /// Run dead-code and duplication analysis for this editor session.
611    ///
612    /// # Errors
613    ///
614    /// Returns an engine error when dead-code parsing or analysis fails.
615    pub fn analyze_project_with(
616        &self,
617        duplicates_config: &fallow_config::DuplicatesConfig,
618        retain_complexity_artifacts: bool,
619    ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
620        self.inner
621            .analyze_project_with(duplicates_config, retain_complexity_artifacts)
622            .map(EditorProjectAnalysisOutput::from_engine)
623            .map(|output| self.with_resolved_rule_severities(output))
624    }
625
626    /// Run dead-code and duplication analysis, optionally focusing duplication
627    /// to files the editor already resolved as changed.
628    ///
629    /// Dead-code retains full graph context and semantic evidence scope.
630    /// After type-aware refinement, call [`Self::apply_change_scope`] to narrow
631    /// the findings and clone groups of this project.
632    ///
633    /// # Errors
634    ///
635    /// Returns an engine error when dead-code parsing or analysis fails.
636    pub fn analyze_project_with_changed_files(
637        &self,
638        duplicates_config: &fallow_config::DuplicatesConfig,
639        retain_complexity_artifacts: bool,
640        changed_files: Option<&FxHashSet<PathBuf>>,
641    ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
642        self.inner
643            .analyze_project_with_artifacts(
644                duplicates_config,
645                fallow_engine::project_analysis::ProjectAnalysisArtifactOptions {
646                    retain_complexity_artifacts,
647                    changed_files: changed_files.cloned(),
648                    ..fallow_engine::project_analysis::ProjectAnalysisArtifactOptions::default()
649                },
650            )
651            .map(fallow_engine::project_analysis::ProjectAnalysisArtifacts::into_output)
652            .map(EditorProjectAnalysisOutput::from_engine)
653            .map(|output| self.with_resolved_rule_severities(output))
654    }
655
656    /// Narrow the dead-code findings and clone groups of this project to a
657    /// resolved change scope, with the engine functions that the CLI, MCP and
658    /// Node API use.
659    ///
660    /// Apply scope after type-aware refinement so added findings are scoped
661    /// too. Each project in a multi-root editor session has its own
662    /// `ignoreFindings`, so apply scope per project before merging.
663    pub fn apply_change_scope(
664        &self,
665        output: &mut EditorProjectAnalysisOutput,
666        scope: &ChangeScope,
667    ) {
668        fallow_engine::dead_code::apply_scope(
669            &mut output.dead_code.results,
670            &fallow_engine::dead_code::DeadCodeScope {
671                workspace_roots: None,
672                changes: Some(scope),
673                diff: None,
674                files: None,
675            },
676            self.inner.config(),
677        );
678        fallow_engine::duplicates::apply_scope(
679            &mut output.duplication,
680            &fallow_engine::duplicates::DuplicationScope {
681                changes: Some(scope),
682                diff: None,
683                workspace_roots: None,
684            },
685            &self.inner.config().root,
686        );
687    }
688
689    /// Resolve configured rule severities, including per-path
690    /// `overrides[].rules`, against a freshly analyzed project slice.
691    ///
692    /// Each project root is filtered with its own config before a multi-root
693    /// editor session merges the outputs, so an override only ever applies to
694    /// the project that declares it.
695    fn with_resolved_rule_severities(
696        &self,
697        mut output: EditorProjectAnalysisOutput,
698    ) -> EditorProjectAnalysisOutput {
699        fallow_engine::dead_code::apply_rule_severities(
700            &mut output.dead_code.results,
701            self.inner.config(),
702        );
703        output
704    }
705
706    const fn from_engine(inner: fallow_engine::session::AnalysisSession) -> Self {
707        Self { inner }
708    }
709}
710
711/// Dead-code and duplication project output owned by the editor API boundary.
712#[derive(Debug)]
713pub struct EditorProjectAnalysisOutput {
714    /// Dead-code findings plus optionally retained parse artifacts.
715    pub dead_code: EditorDeadCodeAnalysisOutput,
716    /// Duplication report for the analyzed project slice.
717    pub duplication: EditorDuplicationReport,
718}
719
720impl EditorProjectAnalysisOutput {
721    fn from_engine(output: fallow_engine::project_analysis::ProjectAnalysisOutput) -> Self {
722        Self {
723            dead_code: EditorDeadCodeAnalysisOutput::from_engine(output.dead_code),
724            duplication: output.duplication,
725        }
726    }
727}
728
729/// Dead-code and duplication output shaped for editor integrations.
730#[derive(Debug, Default)]
731pub struct EditorAnalysisOutput {
732    /// Typed dead-code findings.
733    pub results: EditorAnalysisResults,
734    /// Duplication report.
735    pub duplication: EditorDuplicationReport,
736}
737
738impl EditorAnalysisOutput {
739    /// Pair dead-code results with a duplication report.
740    #[must_use]
741    pub const fn new(results: EditorAnalysisResults, duplication: EditorDuplicationReport) -> Self {
742        Self {
743            results,
744            duplication,
745        }
746    }
747
748    /// Merge another project analysis output into this accumulated output.
749    pub fn merge_project_output(&mut self, output: EditorProjectAnalysisOutput) {
750        self.merge_results(output.dead_code.results);
751        self.merge_duplication(output.duplication);
752    }
753
754    /// Merge another dead-code results set into this one.
755    pub fn merge_results(&mut self, source: EditorAnalysisResults) {
756        self.results.merge_into(source);
757    }
758
759    /// Merge another duplication report into this one, summing the aggregate
760    /// stats and recomputing the duplication percentage over the union.
761    pub fn merge_duplication(&mut self, source: EditorDuplicationReport) {
762        self.duplication.clone_groups.extend(source.clone_groups);
763        self.duplication
764            .clone_families
765            .extend(source.clone_families);
766        self.duplication
767            .mirrored_directories
768            .extend(source.mirrored_directories);
769        self.duplication.stats.clone_groups += source.stats.clone_groups;
770        self.duplication.stats.clone_families += source.stats.clone_families;
771        self.duplication.stats.clone_instances += source.stats.clone_instances;
772        self.duplication.stats.total_files += source.stats.total_files;
773        self.duplication.stats.files_with_clones += source.stats.files_with_clones;
774        self.duplication.stats.total_lines += source.stats.total_lines;
775        self.duplication.stats.duplicated_lines += source.stats.duplicated_lines;
776        self.duplication.stats.total_tokens += source.stats.total_tokens;
777        self.duplication.stats.duplicated_tokens += source.stats.duplicated_tokens;
778        self.duplication.stats.clone_groups_below_min_occurrences +=
779            source.stats.clone_groups_below_min_occurrences;
780        self.duplication.stats.clone_groups_ignored += source.stats.clone_groups_ignored;
781        self.duplication.stats.near_candidates_skipped += source.stats.near_candidates_skipped;
782        self.duplication.stats.duplication_percentage = if self.duplication.stats.total_lines > 0 {
783            (self.duplication.stats.duplicated_lines as f64
784                / self.duplication.stats.total_lines as f64)
785                * 100.0
786        } else {
787            0.0
788        };
789    }
790
791    /// Drop findings and clone groups that do not touch any changed file.
792    ///
793    /// Each project scopes dead-code findings with its own config in
794    /// [`EditorAnalysisSession::apply_change_scope`]. This merged-output filter
795    /// narrows clone groups and preserves the already scoped findings.
796    pub fn filter_by_changed_files(&mut self, changed_files: &FxHashSet<PathBuf>, root: &Path) {
797        fallow_engine::changed_files::filter_results_by_changed_files(
798            &mut self.results,
799            changed_files,
800        );
801        fallow_engine::changed_files::filter_duplication_by_changed_files(
802            &mut self.duplication,
803            changed_files,
804            root,
805        );
806    }
807}
808
809#[cfg(test)]
810#[path = "editor_tests.rs"]
811pub(crate) mod tests;