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