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,
210        UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
211        UnusedSvelteEventFinding, UnusedTypeFinding,
212    };
213    pub use fallow_types::output_dead_code::{
214        UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
215    };
216    pub use fallow_types::results::{
217        AbsentComponentProp, ActiveSuppression, AnalysisResults, BoundaryCallViolation,
218        BoundaryCoverageViolation, BoundaryViolation, CircularDependency, CircularDependencyEdge,
219        ComponentPropCallSite, DependencyLocation, DependencyOverrideMisconfigReason,
220        DependencyOverrideSource, DeprecatedConsumerKind, DeprecatedExportConsumer,
221        DeprecatedExportInUse, DevDependencyInProduction, DuplicateExport, DuplicateLocation,
222        DuplicatePropShape, DuplicatePropShapeMember, DynamicSegmentNameConflict,
223        EmptyCatalogGroup, EntryPointSummary, ExportUsage, FeatureFlag, FlagConfidence, FlagKind,
224        ImportSite, InvalidClientExport, MisconfiguredDependencyOverride, MisplacedDirective,
225        MixedClientServerBarrel, PackageCycle, PackageCycleEdge, PolicyRuleKind, PolicyViolation,
226        PolicyViolationSeverity, PrivateTypeLeak, PropDrillHop, PropDrillingChain, ReExportCycle,
227        ReExportCycleKind, ReactComponentIntel, ReactHookSummary, ReactPropDrill, ReactPropIntel,
228        ReferenceLocation, RenderFanInComponent, RenderFanInMetric, RouteCollision,
229        SecurityAttackSurfaceEntry, SecurityCandidate, SecurityCandidateBoundary,
230        SecurityCandidateSink, SecurityDeadCodeContext, SecurityDeadCodeKind,
231        SecurityDefensiveBoundary, SecurityDefensiveControl, SecurityFinding, SecurityFindingKind,
232        SecurityNetworkContext, SecurityReachability, SecurityRuntimeContext, SecurityRuntimeState,
233        SecuritySeverity, SecurityTaintFlow, SecurityUnresolvedCalleeDiagnostic,
234        SecurityZoneCrossing, StaleSuppression, SuppressionOrigin, TaintConfidence, TaintEndpoint,
235        TaintPath, TestOnlyDependency, ThinWrapper, TraceHop, TraceHopRole, TypeOnlyDependency,
236        UnlistedDependency, UnprovidedInject, UnrenderedComponent, UnresolvedCatalogReference,
237        UnresolvedImport, UnusedCatalogEntry, UnusedComponentEmit, UnusedComponentInput,
238        UnusedComponentOutput, UnusedComponentProp, UnusedDependency, UnusedDependencyOverride,
239        UnusedExport, UnusedFile, UnusedLoadDataKey, UnusedMember, UnusedServerAction,
240        UnusedSvelteEvent,
241    };
242    pub use fallow_types::results::{
243        ConstantParameter, ConstantParameterCallSite, ConstantParameterFinding,
244        ConstantParameterReason, ConstantParameterValue, ConstantParameterValueKind,
245    };
246    pub use fallow_types::results::{DuplicateExportAlias, DuplicateExportAliasLocation};
247    pub use fallow_types::results::{
248        EffectCatchSite, EffectLayerKind, UnproducedCatchTag, UnusedEffectLayer, UnusedTaggedError,
249    };
250}
251
252/// Security catalogue lookups exposed at the editor boundary.
253pub mod editor_security {
254    /// Return the human-readable security catalogue title for a finding kind.
255    #[must_use]
256    pub fn security_catalogue_title(kind: &str) -> Option<&'static str> {
257        fallow_engine::dead_code::security_catalogue_title(kind)
258    }
259}
260
261/// Inline-suppression contracts re-exported for editor adapters.
262pub mod editor_suppress {
263    pub use fallow_types::suppress::{IssueKind, is_suppressed};
264}
265
266/// Editor-boundary alias for the typed dead-code analysis results.
267pub type EditorAnalysisResults = fallow_types::results::AnalysisResults;
268
269/// Dead-code output retained for editor integrations.
270///
271/// The engine produces the data, but the editor API owns this public contract
272/// so LSP and future editor adapters do not depend on engine result structs.
273#[derive(Debug)]
274pub struct EditorDeadCodeAnalysisOutput {
275    /// Typed dead-code findings from the analysis.
276    pub results: EditorAnalysisResults,
277    /// Retained per-module parse artifacts; `None` unless the run was asked
278    /// to keep them for follow-up editor features.
279    pub modules: Option<Vec<ModuleInfo>>,
280    /// Retained discovered-file records matching `modules`.
281    pub files: Option<Vec<DiscoveredFile>>,
282}
283
284impl EditorDeadCodeAnalysisOutput {
285    fn from_engine(output: fallow_engine::dead_code::DeadCodeAnalysisOutput) -> Self {
286        Self {
287            results: output.results,
288            modules: output.modules,
289            files: output.files,
290        }
291    }
292}
293
294/// Editor-facing inline complexity signal for code lens and similar surfaces.
295///
296/// The finding is derived from retained typed engine parse artifacts, but the
297/// editor API owns the stable shape so LSP and future editor adapters do not
298/// need to inspect raw modules directly.
299#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct EditorInlineComplexityFinding {
301    /// Absolute path of the file declaring the function.
302    pub path: PathBuf,
303    /// Function name as extracted from the source.
304    pub name: String,
305    /// One-based line of the function declaration.
306    pub line: u32,
307    /// Zero-based column of the function declaration.
308    pub col: u32,
309    /// Measured cyclomatic complexity.
310    pub cyclomatic: u16,
311    /// Measured cognitive complexity.
312    pub cognitive: u16,
313    /// Which configured threshold(s) the function exceeded.
314    pub exceeded: EditorInlineComplexityExceeded,
315}
316
317/// Which health complexity threshold(s) a function exceeded.
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319pub enum EditorInlineComplexityExceeded {
320    /// Only the cyclomatic threshold was exceeded.
321    Cyclomatic,
322    /// Only the cognitive threshold was exceeded.
323    Cognitive,
324    /// Both thresholds were exceeded.
325    CyclomaticAndCognitive,
326}
327
328/// Collect inline complexity findings from retained editor analysis artifacts.
329///
330/// The rule is `fallow_engine::health::inline_complexity`, the one that the
331/// health findings use, so the code lens and `fallow health` flag the same
332/// functions, also under `health.thresholdOverrides`.
333#[must_use]
334pub fn collect_inline_complexity(
335    config: &fallow_config::ResolvedConfig,
336    output: &EditorDeadCodeAnalysisOutput,
337) -> Vec<EditorInlineComplexityFinding> {
338    let (Some(modules), Some(files)) = (output.modules.as_ref(), output.files.as_ref()) else {
339        return Vec::new();
340    };
341    fallow_engine::health::inline_complexity(config, modules, files)
342        .into_iter()
343        .map(|finding| EditorInlineComplexityFinding {
344            exceeded: match (finding.exceeds_cyclomatic, finding.exceeds_cognitive) {
345                (true, true) => EditorInlineComplexityExceeded::CyclomaticAndCognitive,
346                (true, false) => EditorInlineComplexityExceeded::Cyclomatic,
347                (false, _) => EditorInlineComplexityExceeded::Cognitive,
348            },
349            path: finding.path,
350            name: finding.name,
351            line: finding.line,
352            col: finding.col,
353            cyclomatic: finding.cyclomatic,
354            cognitive: finding.cognitive,
355        })
356        .collect()
357}
358
359/// Filter inline complexity findings to the changed-file set.
360#[expect(
361    clippy::implicit_hasher,
362    reason = "editor analysis changed-file sets use the workspace FxHashSet convention"
363)]
364pub fn filter_inline_complexity_by_changed_files(
365    findings: &mut Vec<EditorInlineComplexityFinding>,
366    changed_files: &FxHashSet<PathBuf>,
367) {
368    findings.retain(|finding| changed_files.contains(&finding.path));
369}
370
371/// Retain the inline complexity findings in a resolved change scope.
372pub fn filter_inline_complexity_by_change_scope(
373    findings: &mut Vec<EditorInlineComplexityFinding>,
374    scope: &ChangeScope,
375) {
376    findings.retain(|finding| scope.contains(&finding.path));
377}
378
379/// The parse work of an editor session. See
380/// [`fallow_engine::session::SessionParseCounts`].
381pub type EditorSessionParseCounts = fallow_engine::session::SessionParseCounts;
382
383/// Reusable editor analysis session owned by the API boundary.
384#[derive(Debug)]
385pub struct EditorAnalysisSession {
386    inner: fallow_engine::session::AnalysisSession,
387    /// Whether a project analysis of the session runs duplication.
388    runs_duplication: bool,
389}
390
391impl EditorAnalysisSession {
392    /// Open the session of the dead-code analysis of a resolved run. The
393    /// project analyses of the session run duplication only when the run
394    /// plans it.
395    ///
396    /// # Errors
397    ///
398    /// Returns an error when the run skips the dead-code analysis.
399    pub fn open(run: &crate::run::ResolvedRun) -> Result<Self, crate::ProgrammaticError> {
400        use crate::run::AnalysisSlot;
401        use fallow_config::PlannedAnalysis;
402        let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
403            return Err(crate::ProgrammaticError::new(
404                "an editor session needs a run that plans the dead-code analysis",
405                2,
406            ));
407        };
408        Ok(Self {
409            inner: dead_code.open_session(),
410            runs_duplication: matches!(
411                run.analysis(PlannedAnalysis::Duplication),
412                AnalysisSlot::Runs(_)
413            ),
414        })
415    }
416
417    /// Load config and discover files for an editor project root.
418    ///
419    /// # Errors
420    ///
421    /// Returns an engine error when project config loading fails.
422    #[cfg(any(test, feature = "testing"))]
423    pub fn load(root: &Path, config_path: Option<&Path>) -> fallow_engine::EngineResult<Self> {
424        fallow_engine::session::AnalysisSession::load(root, config_path).map(Self::from_engine)
425    }
426
427    /// Load config, apply one editor-specific adjustment, then discover files.
428    ///
429    /// # Errors
430    ///
431    /// Returns an engine error when project config loading fails.
432    #[cfg(any(test, feature = "testing"))]
433    pub fn load_with_config(
434        root: &Path,
435        config_path: Option<&Path>,
436        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
437    ) -> fallow_engine::EngineResult<Self> {
438        fallow_engine::session::AnalysisSession::load_with_config(root, config_path, configure)
439            .map(Self::from_engine)
440    }
441
442    /// Load config with an explicit inheritance trust policy, apply one
443    /// editor-specific adjustment, then discover files.
444    ///
445    /// # Errors
446    ///
447    /// Returns an engine error when project config loading fails.
448    #[cfg(any(test, feature = "testing"))]
449    pub fn load_with_config_options(
450        root: &Path,
451        config_path: Option<&Path>,
452        load_options: fallow_config::ConfigLoadOptions,
453        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
454    ) -> fallow_engine::EngineResult<Self> {
455        fallow_engine::session::AnalysisSession::load_with_config_options(
456            root,
457            config_path,
458            load_options,
459            configure,
460        )
461        .map(Self::from_engine)
462    }
463
464    /// Load config with an explicit inheritance trust policy and the editor
465    /// production override, apply one editor-specific adjustment, then
466    /// discover files. The override decides the production mode before
467    /// resolution, so the rules of production mode match the CLI
468    /// `--production` flag. `None` leaves the project config in force.
469    ///
470    /// # Errors
471    ///
472    /// Returns an engine error when project config loading fails.
473    #[cfg(any(test, feature = "testing"))]
474    pub fn load_with_production(
475        root: &Path,
476        config_path: Option<&Path>,
477        load_options: fallow_config::ConfigLoadOptions,
478        production_override: Option<bool>,
479        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
480    ) -> fallow_engine::EngineResult<Self> {
481        let mut project = fallow_engine::project_config::config_for_project_with_production(
482            root,
483            config_path,
484            load_options,
485            fallow_engine::project_config::ProductionFlags {
486                global: production_override,
487                ..fallow_engine::project_config::ProductionFlags::default()
488            },
489        )?;
490        configure(&mut project.config);
491        Ok(Self::from_engine(
492            fallow_engine::session::AnalysisSession::from_config(
493                project.without_workspace_metadata(),
494            ),
495        ))
496    }
497
498    /// Build a session from built-in defaults, ignoring project config files.
499    #[cfg(any(test, feature = "testing"))]
500    #[must_use]
501    pub fn load_default(root: &Path) -> Self {
502        Self::from_engine(fallow_engine::session::AnalysisSession::load_default(root))
503    }
504
505    /// Build a session from built-in defaults, apply one editor-specific
506    /// adjustment, then discover files.
507    #[cfg(any(test, feature = "testing"))]
508    #[must_use]
509    pub fn load_default_with_config(
510        root: &Path,
511        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
512    ) -> Self {
513        Self::from_engine(
514            fallow_engine::session::AnalysisSession::load_default_with_config(root, configure),
515        )
516    }
517
518    /// Attach a caller-owned cancellation token to this session.
519    ///
520    /// The analyses of the session check the token at each pipeline stage
521    /// boundary and in the per-file parse loop. Once the token is set, they
522    /// return an engine error whose `is_cancelled()` is true, never a partial
523    /// result. See
524    /// [`fallow_engine::session::AnalysisSession::with_cancellation`] for the
525    /// limits of the cooperative stop.
526    #[must_use]
527    pub fn with_cancellation(
528        self,
529        cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
530    ) -> Self {
531        Self {
532            inner: self.inner.with_cancellation(cancellation),
533            runs_duplication: self.runs_duplication,
534        }
535    }
536
537    /// Replace the cancellation token of a session that serves several runs.
538    pub fn set_cancellation(
539        &mut self,
540        cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
541    ) {
542        self.inner.set_cancellation(cancellation);
543    }
544
545    /// Walk the project again before a run of a long-lived session. The
546    /// parsed modules stay when the file set did not change. Returns whether
547    /// the file set changed. See
548    /// [`fallow_engine::session::AnalysisSession::refresh_discovery`].
549    pub fn refresh_discovery(&mut self) -> bool {
550        self.inner.refresh_discovery()
551    }
552
553    /// The plugin files, rule packs and `autoDiscover` directories that
554    /// config resolution read for this session. A long-lived caller compares
555    /// two snapshots of them to see that the config is out of date.
556    #[must_use]
557    pub fn config_inputs(&self) -> &fallow_config::ConfigInputs {
558        self.inner.config_inputs()
559    }
560
561    /// The content of [`Self::config_inputs`] just before config resolution
562    /// read them.
563    #[must_use]
564    pub fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
565        self.inner.config_inputs_before_resolve()
566    }
567
568    /// The estimated heap memory of the parsed modules that the session
569    /// keeps between runs. Zero before the first parse.
570    #[must_use]
571    pub fn retained_bytes_estimate(&self) -> u64 {
572        self.inner.retained_bytes_estimate()
573    }
574
575    /// Write the modules of incremental parses to the persisted parse cache.
576    /// Call it before the session is dropped.
577    pub fn flush_parse_cache(&self) {
578        self.inner.flush_parse_cache();
579    }
580
581    /// Parse the project files into the session without analysis, so the
582    /// first run starts from warm modules.
583    ///
584    /// # Errors
585    ///
586    /// Returns a cancelled engine error when the token of the session is set.
587    pub fn prewarm(&self, retain_complexity_artifacts: bool) -> fallow_engine::EngineResult<()> {
588        self.inner
589            .prewarm_parsed_modules(retain_complexity_artifacts)
590    }
591
592    /// The parse work of this session since it was created.
593    #[must_use]
594    pub fn parse_counts(&self) -> EditorSessionParseCounts {
595        self.inner.parse_counts()
596    }
597
598    /// Resolved project config.
599    #[must_use]
600    pub fn config(&self) -> &fallow_config::ResolvedConfig {
601        self.inner.config()
602    }
603
604    /// Resolve the change scope of this project with the engine rule that
605    /// the CLI and the programmatic API use.
606    ///
607    /// # Errors
608    ///
609    /// Returns a typed error when the package map names an invalid or unknown
610    /// workspace root, or a Git ref that does not resolve.
611    pub fn change_scope(
612        &self,
613        request: ChangeScopeRequest<'_>,
614    ) -> Result<ChangeScope, PackageBaselineError> {
615        ChangeScope::resolve(request, self.inner.config(), self.inner.workspaces())
616    }
617
618    /// `workspace_diagnostics[]` entries for the config patterns
619    /// (`ignoreFindings`, `ignoreDependencies`) that matched nothing in the
620    /// latest analysis of this session. The CLI and the programmatic API
621    /// build the same entries with the same engine function.
622    #[must_use]
623    pub fn unmatched_config_patterns(&self) -> Vec<fallow_config::WorkspaceDiagnostic> {
624        fallow_engine::dead_code::config_pattern_diagnostics(self.inner.config(), true)
625    }
626
627    /// Config file path when one was loaded.
628    #[must_use]
629    pub fn config_path(&self) -> Option<&Path> {
630        self.inner.config_path()
631    }
632
633    /// Refine this editor session's dead-code findings with exact TypeScript
634    /// symbol evidence.
635    ///
636    /// # Errors
637    ///
638    /// Returns a programmatic error when the semantic companion cannot provide
639    /// the requested analysis contract.
640    pub fn refine_type_aware_dead_code(
641        &self,
642        options: &crate::TypeAwareOptions,
643        filters: &crate::DeadCodeFilters,
644        output: &mut EditorDeadCodeAnalysisOutput,
645    ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
646        let meta = crate::type_aware::refine_programmatic_dead_code(
647            options,
648            filters,
649            &self.inner,
650            &mut output.results,
651        )?;
652        // Reconciliation can add findings, so rule severities are resolved
653        // again over the refined set. The pass removes findings and writes
654        // each gate severity again, so repeating it is idempotent.
655        fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
656        Ok(meta)
657    }
658
659    /// Refine editor findings through a root-bound persistent semantic session.
660    pub fn refine_type_aware_dead_code_in_session(
661        &self,
662        semantic_session: &mut crate::TypeAwareSession,
663        changes: Option<&crate::TypeAwareFileChanges>,
664        options: &crate::TypeAwareOptions,
665        filters: &crate::DeadCodeFilters,
666        output: &mut EditorDeadCodeAnalysisOutput,
667    ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
668        let meta = crate::type_aware::refine_programmatic_dead_code_in_session(
669            semantic_session,
670            changes,
671            options,
672            filters,
673            &self.inner,
674            &mut output.results,
675        )?;
676        fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
677        Ok(meta)
678    }
679
680    /// Run dead-code and duplication analysis for this editor session.
681    ///
682    /// # Errors
683    ///
684    /// Returns an engine error when dead-code parsing or analysis fails.
685    pub fn analyze_project_with(
686        &self,
687        duplicates_config: &fallow_config::DuplicatesConfig,
688        retain_complexity_artifacts: bool,
689    ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
690        self.inner
691            .analyze_project_with(duplicates_config, retain_complexity_artifacts)
692            .map(EditorProjectAnalysisOutput::from_engine)
693            .map(|output| self.with_resolved_rule_severities(output))
694    }
695
696    /// Run dead-code and duplication analysis, optionally focusing duplication
697    /// to files the editor already resolved as changed.
698    ///
699    /// Dead-code retains full graph context and semantic evidence scope.
700    /// After type-aware refinement, call [`Self::apply_change_scope`] to narrow
701    /// the findings and clone groups of this project.
702    ///
703    /// # Errors
704    ///
705    /// Returns an engine error when dead-code parsing or analysis fails.
706    pub fn analyze_project_with_changed_files(
707        &self,
708        duplicates_config: &fallow_config::DuplicatesConfig,
709        retain_complexity_artifacts: bool,
710        changed_files: Option<&FxHashSet<PathBuf>>,
711    ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
712        let artifacts = if self.runs_duplication {
713            self.inner.analyze_project_with_artifacts(
714                duplicates_config,
715                fallow_engine::project_analysis::ProjectAnalysisArtifactOptions {
716                    retain_complexity_artifacts,
717                    changed_files: changed_files.cloned(),
718                    ..fallow_engine::project_analysis::ProjectAnalysisArtifactOptions::default()
719                },
720            )?
721        } else {
722            fallow_engine::project_analysis::ProjectAnalysisArtifacts {
723                dead_code: self
724                    .inner
725                    .analyze_dead_code_with_artifacts(retain_complexity_artifacts, false)?,
726                duplication: fallow_types::duplicates::DuplicationReport::default(),
727                changed_files: changed_files.cloned(),
728                source_fingerprints: None,
729            }
730        };
731        Ok(
732            self.with_resolved_rule_severities(EditorProjectAnalysisOutput::from_engine(
733                artifacts.into_output(),
734            )),
735        )
736    }
737
738    /// Narrow the dead-code findings and clone groups of this project to a
739    /// resolved change scope, with the engine functions that the CLI, MCP and
740    /// Node API use.
741    ///
742    /// Apply scope after type-aware refinement so added findings are scoped
743    /// too. Each project in a multi-root editor session has its own
744    /// `ignoreFindings`, so apply scope per project before merging.
745    pub fn apply_change_scope(
746        &self,
747        output: &mut EditorProjectAnalysisOutput,
748        scope: &ChangeScope,
749    ) {
750        fallow_engine::dead_code::apply_scope(
751            &mut output.dead_code.results,
752            &fallow_engine::dead_code::DeadCodeScope {
753                workspace_roots: None,
754                changes: Some(scope),
755                diff: None,
756                files: None,
757            },
758            self.inner.config(),
759        );
760        fallow_engine::duplicates::apply_scope(
761            &mut output.duplication,
762            &fallow_engine::duplicates::DuplicationScope {
763                changes: Some(scope),
764                diff: None,
765                workspace_roots: None,
766            },
767            &self.inner.config().root,
768        );
769    }
770
771    /// Resolve configured rule severities, including per-path
772    /// `overrides[].rules`, against a freshly analyzed project slice.
773    ///
774    /// Each project root is filtered with its own config before a multi-root
775    /// editor session merges the outputs, so an override only ever applies to
776    /// the project that declares it.
777    fn with_resolved_rule_severities(
778        &self,
779        mut output: EditorProjectAnalysisOutput,
780    ) -> EditorProjectAnalysisOutput {
781        fallow_engine::dead_code::apply_rule_severities(
782            &mut output.dead_code.results,
783            self.inner.config(),
784        );
785        output
786    }
787
788    /// A session of a constructor without a resolved run. No editor action
789    /// names the duplication analysis, so `duplicates.enabled: false` leaves
790    /// the editor without clone groups, as it leaves the bare `fallow` run.
791    #[cfg(any(test, feature = "testing"))]
792    fn from_engine(inner: fallow_engine::session::AnalysisSession) -> Self {
793        Self {
794            runs_duplication: inner.config().duplicates.runs_by_default(),
795            inner,
796        }
797    }
798}
799
800/// Dead-code and duplication project output owned by the editor API boundary.
801#[derive(Debug)]
802pub struct EditorProjectAnalysisOutput {
803    /// Dead-code findings plus optionally retained parse artifacts.
804    pub dead_code: EditorDeadCodeAnalysisOutput,
805    /// Duplication report for the analyzed project slice.
806    pub duplication: EditorDuplicationReport,
807}
808
809impl EditorProjectAnalysisOutput {
810    fn from_engine(output: fallow_engine::project_analysis::ProjectAnalysisOutput) -> Self {
811        Self {
812            dead_code: EditorDeadCodeAnalysisOutput::from_engine(output.dead_code),
813            duplication: output.duplication,
814        }
815    }
816}
817
818/// Dead-code and duplication output shaped for editor integrations.
819#[derive(Debug, Default)]
820pub struct EditorAnalysisOutput {
821    /// Typed dead-code findings.
822    pub results: EditorAnalysisResults,
823    /// Duplication report.
824    pub duplication: EditorDuplicationReport,
825}
826
827impl EditorAnalysisOutput {
828    /// Pair dead-code results with a duplication report.
829    #[must_use]
830    pub const fn new(results: EditorAnalysisResults, duplication: EditorDuplicationReport) -> Self {
831        Self {
832            results,
833            duplication,
834        }
835    }
836
837    /// Merge another project analysis output into this accumulated output.
838    pub fn merge_project_output(&mut self, output: EditorProjectAnalysisOutput) {
839        self.merge_results(output.dead_code.results);
840        self.merge_duplication(output.duplication);
841    }
842
843    /// Merge another dead-code results set into this one.
844    pub fn merge_results(&mut self, source: EditorAnalysisResults) {
845        self.results.merge_into(source);
846    }
847
848    /// Merge another duplication report into this one, summing the aggregate
849    /// stats and recomputing the duplication percentage over the union.
850    pub fn merge_duplication(&mut self, source: EditorDuplicationReport) {
851        self.duplication.clone_groups.extend(source.clone_groups);
852        self.duplication
853            .clone_families
854            .extend(source.clone_families);
855        self.duplication
856            .mirrored_directories
857            .extend(source.mirrored_directories);
858        self.duplication.stats.clone_groups += source.stats.clone_groups;
859        self.duplication.stats.clone_families += source.stats.clone_families;
860        self.duplication.stats.clone_instances += source.stats.clone_instances;
861        self.duplication.stats.total_files += source.stats.total_files;
862        self.duplication.stats.files_with_clones += source.stats.files_with_clones;
863        self.duplication.stats.total_lines += source.stats.total_lines;
864        self.duplication.stats.duplicated_lines += source.stats.duplicated_lines;
865        self.duplication.stats.total_tokens += source.stats.total_tokens;
866        self.duplication.stats.duplicated_tokens += source.stats.duplicated_tokens;
867        self.duplication.stats.clone_groups_below_min_occurrences +=
868            source.stats.clone_groups_below_min_occurrences;
869        self.duplication.stats.clone_groups_ignored += source.stats.clone_groups_ignored;
870        self.duplication.stats.near_candidates_skipped += source.stats.near_candidates_skipped;
871        self.duplication.stats.duplication_percentage = if self.duplication.stats.total_lines > 0 {
872            (self.duplication.stats.duplicated_lines as f64
873                / self.duplication.stats.total_lines as f64)
874                * 100.0
875        } else {
876            0.0
877        };
878    }
879
880    /// Drop findings and clone groups that do not touch any changed file.
881    ///
882    /// Each project scopes dead-code findings with its own config in
883    /// [`EditorAnalysisSession::apply_change_scope`]. This merged-output filter
884    /// narrows clone groups and preserves the already scoped findings.
885    pub fn filter_by_changed_files(&mut self, changed_files: &FxHashSet<PathBuf>, root: &Path) {
886        fallow_engine::changed_files::filter_results_by_changed_files(
887            &mut self.results,
888            changed_files,
889        );
890        fallow_engine::changed_files::filter_duplication_by_changed_files(
891            &mut self.duplication,
892            changed_files,
893            root,
894        );
895    }
896}
897
898#[cfg(test)]
899#[path = "editor_tests.rs"]
900pub(crate) mod tests;