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