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    /// The session config holds the type-aware decision of the run (the
399    /// given input, then the variables that the surface reads, then
400    /// `typeAware.enabled`) and the rule defaults of a type-aware run, as the
401    /// CLI applies them. [`Self::type_aware_options`] gives the options of
402    /// the refinement.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error when the run skips the dead-code analysis, or when a
407    /// type-aware variable that the surface reads has a value that the run
408    /// cannot use.
409    pub fn open(run: &crate::run::ResolvedRun) -> Result<Self, crate::ProgrammaticError> {
410        use crate::run::AnalysisSlot;
411        use fallow_config::PlannedAnalysis;
412        let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
413            return Err(crate::ProgrammaticError::new(
414                "an editor session needs a run that plans the dead-code analysis",
415                2,
416            ));
417        };
418        let type_aware = run
419            .type_aware()
420            .map_err(|err| crate::ProgrammaticError::new(err.message(), 2))?
421            .clone();
422        let inner = dead_code
423            .open_session_adjusted(|config| {
424                config.type_aware.enabled = *type_aware.enabled.value();
425                config.type_aware.projects = type_aware
426                    .projects
427                    .value()
428                    .iter()
429                    .map(|path| path.to_string_lossy().into_owned())
430                    .collect();
431                config.type_aware.require = *type_aware.require.value();
432                config.apply_type_aware_rule_defaults(false);
433            })
434            .map_err(|err| crate::ProgrammaticError::new(err.to_string(), 2))?;
435        Ok(Self {
436            inner,
437            runs_duplication: matches!(
438                run.analysis(PlannedAnalysis::Duplication),
439                AnalysisSlot::Runs(_)
440            ),
441        })
442    }
443
444    /// The options of the type-aware refinement of the session, or `None`
445    /// when the session runs no type-aware analysis.
446    #[must_use]
447    pub fn type_aware_options(&self) -> Option<crate::TypeAwareOptions> {
448        let section = &self.inner.config().type_aware;
449        section.enabled.then(|| crate::TypeAwareOptions {
450            enabled: Some(true),
451            projects: section.projects.iter().map(PathBuf::from).collect(),
452            require: section.require,
453        })
454    }
455
456    /// Load config and discover files for an editor project root.
457    ///
458    /// # Errors
459    ///
460    /// Returns an engine error when project config loading fails.
461    #[cfg(any(test, feature = "testing"))]
462    pub fn load(root: &Path, config_path: Option<&Path>) -> fallow_engine::EngineResult<Self> {
463        fallow_engine::session::AnalysisSession::load(root, config_path).map(Self::from_engine)
464    }
465
466    /// Load config, apply one editor-specific adjustment, then discover files.
467    ///
468    /// # Errors
469    ///
470    /// Returns an engine error when project config loading fails.
471    #[cfg(any(test, feature = "testing"))]
472    pub fn load_with_config(
473        root: &Path,
474        config_path: Option<&Path>,
475        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
476    ) -> fallow_engine::EngineResult<Self> {
477        fallow_engine::session::AnalysisSession::load_with_config(root, config_path, configure)
478            .map(Self::from_engine)
479    }
480
481    /// Load config with an explicit inheritance trust policy, apply one
482    /// editor-specific adjustment, then discover files.
483    ///
484    /// # Errors
485    ///
486    /// Returns an engine error when project config loading fails.
487    #[cfg(any(test, feature = "testing"))]
488    pub fn load_with_config_options(
489        root: &Path,
490        config_path: Option<&Path>,
491        load_options: fallow_config::ConfigLoadOptions,
492        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
493    ) -> fallow_engine::EngineResult<Self> {
494        fallow_engine::session::AnalysisSession::load_with_config_options(
495            root,
496            config_path,
497            load_options,
498            configure,
499        )
500        .map(Self::from_engine)
501    }
502
503    /// Load config with an explicit inheritance trust policy and the editor
504    /// production override, apply one editor-specific adjustment, then
505    /// discover files. The override decides the production mode before
506    /// resolution, so the rules of production mode match the CLI
507    /// `--production` flag. `None` leaves the project config in force.
508    ///
509    /// # Errors
510    ///
511    /// Returns an engine error when project config loading fails.
512    #[cfg(any(test, feature = "testing"))]
513    pub fn load_with_production(
514        root: &Path,
515        config_path: Option<&Path>,
516        load_options: fallow_config::ConfigLoadOptions,
517        production_override: Option<bool>,
518        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
519    ) -> fallow_engine::EngineResult<Self> {
520        let mut project = fallow_engine::project_config::config_for_project_with_production(
521            root,
522            config_path,
523            load_options,
524            fallow_engine::project_config::ProductionFlags {
525                global: production_override,
526                ..fallow_engine::project_config::ProductionFlags::default()
527            },
528        )?;
529        configure(&mut project.config);
530        Ok(Self::from_engine(
531            fallow_engine::session::AnalysisSession::from_config(
532                project.without_workspace_metadata(),
533            ),
534        ))
535    }
536
537    /// Build a session from built-in defaults, ignoring project config files.
538    #[cfg(any(test, feature = "testing"))]
539    #[must_use]
540    pub fn load_default(root: &Path) -> Self {
541        Self::from_engine(fallow_engine::session::AnalysisSession::load_default(root))
542    }
543
544    /// Build a session from built-in defaults, apply one editor-specific
545    /// adjustment, then discover files.
546    #[cfg(any(test, feature = "testing"))]
547    #[must_use]
548    pub fn load_default_with_config(
549        root: &Path,
550        configure: impl FnOnce(&mut fallow_config::ResolvedConfig),
551    ) -> Self {
552        Self::from_engine(
553            fallow_engine::session::AnalysisSession::load_default_with_config(root, configure),
554        )
555    }
556
557    /// Attach a caller-owned cancellation token to this session.
558    ///
559    /// The analyses of the session check the token at each pipeline stage
560    /// boundary and in the per-file parse loop. Once the token is set, they
561    /// return an engine error whose `is_cancelled()` is true, never a partial
562    /// result. See
563    /// [`fallow_engine::session::AnalysisSession::with_cancellation`] for the
564    /// limits of the cooperative stop.
565    #[must_use]
566    pub fn with_cancellation(
567        self,
568        cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
569    ) -> Self {
570        Self {
571            inner: self.inner.with_cancellation(cancellation),
572            runs_duplication: self.runs_duplication,
573        }
574    }
575
576    /// Replace the cancellation token of a session that serves several runs.
577    pub fn set_cancellation(
578        &mut self,
579        cancellation: std::sync::Arc<std::sync::atomic::AtomicBool>,
580    ) {
581        self.inner.set_cancellation(cancellation);
582    }
583
584    /// Walk the project again before a run of a long-lived session. The
585    /// parsed modules stay when the file set did not change. Returns whether
586    /// the file set changed. See
587    /// [`fallow_engine::session::AnalysisSession::refresh_discovery`].
588    pub fn refresh_discovery(&mut self) -> bool {
589        self.inner.refresh_discovery()
590    }
591
592    /// The plugin files, rule packs and `autoDiscover` directories that
593    /// config resolution read for this session. A long-lived caller compares
594    /// two snapshots of them to see that the config is out of date.
595    #[must_use]
596    pub fn config_inputs(&self) -> &fallow_config::ConfigInputs {
597        self.inner.config_inputs()
598    }
599
600    /// The content of [`Self::config_inputs`] just before config resolution
601    /// read them.
602    #[must_use]
603    pub fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
604        self.inner.config_inputs_before_resolve()
605    }
606
607    /// The estimated heap memory of the parsed modules that the session
608    /// keeps between runs. Zero before the first parse.
609    #[must_use]
610    pub fn retained_bytes_estimate(&self) -> u64 {
611        self.inner.retained_bytes_estimate()
612    }
613
614    /// Write the modules of incremental parses to the persisted parse cache.
615    /// Call it before the session is dropped.
616    pub fn flush_parse_cache(&self) {
617        self.inner.flush_parse_cache();
618    }
619
620    /// Parse the project files into the session without analysis, so the
621    /// first run starts from warm modules.
622    ///
623    /// # Errors
624    ///
625    /// Returns a cancelled engine error when the token of the session is set.
626    pub fn prewarm(&self, retain_complexity_artifacts: bool) -> fallow_engine::EngineResult<()> {
627        self.inner
628            .prewarm_parsed_modules(retain_complexity_artifacts)
629    }
630
631    /// The parse work of this session since it was created.
632    #[must_use]
633    pub fn parse_counts(&self) -> EditorSessionParseCounts {
634        self.inner.parse_counts()
635    }
636
637    /// Resolved project config.
638    #[must_use]
639    pub fn config(&self) -> &fallow_config::ResolvedConfig {
640        self.inner.config()
641    }
642
643    /// Resolve the change scope of this project with the engine rule that
644    /// the CLI and the programmatic API use.
645    ///
646    /// # Errors
647    ///
648    /// Returns a typed error when the package map names an invalid or unknown
649    /// workspace root, or a Git ref that does not resolve.
650    pub fn change_scope(
651        &self,
652        request: ChangeScopeRequest<'_>,
653    ) -> Result<ChangeScope, PackageBaselineError> {
654        ChangeScope::resolve(request, self.inner.config(), self.inner.workspaces())
655    }
656
657    /// `workspace_diagnostics[]` entries for the config patterns
658    /// (`ignoreFindings`, `ignoreDependencies`) that matched nothing in the
659    /// latest analysis of this session. The CLI and the programmatic API
660    /// build the same entries with the same engine function.
661    #[must_use]
662    pub fn unmatched_config_patterns(&self) -> Vec<fallow_config::WorkspaceDiagnostic> {
663        fallow_engine::dead_code::config_pattern_diagnostics(self.inner.config(), true)
664    }
665
666    /// Config file path when one was loaded.
667    #[must_use]
668    pub fn config_path(&self) -> Option<&Path> {
669        self.inner.config_path()
670    }
671
672    /// Refine this editor session's dead-code findings with exact TypeScript
673    /// symbol evidence.
674    ///
675    /// # Errors
676    ///
677    /// Returns a programmatic error when the semantic companion cannot provide
678    /// the requested analysis contract.
679    pub fn refine_type_aware_dead_code(
680        &self,
681        options: &crate::TypeAwareOptions,
682        filters: &crate::DeadCodeFilters,
683        output: &mut EditorDeadCodeAnalysisOutput,
684    ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
685        let meta = crate::type_aware::refine_programmatic_dead_code(
686            options,
687            filters,
688            &self.inner,
689            &mut output.results,
690        )?;
691        // Reconciliation can add findings, so rule severities are resolved
692        // again over the refined set. The pass removes findings and writes
693        // each gate severity again, so repeating it is idempotent.
694        fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
695        Ok(meta)
696    }
697
698    /// Refine editor findings through a root-bound persistent semantic session.
699    pub fn refine_type_aware_dead_code_in_session(
700        &self,
701        semantic_session: &mut crate::TypeAwareSession,
702        changes: Option<&crate::TypeAwareFileChanges>,
703        options: &crate::TypeAwareOptions,
704        filters: &crate::DeadCodeFilters,
705        output: &mut EditorDeadCodeAnalysisOutput,
706    ) -> Result<Option<fallow_types::envelope::TypeAwareMeta>, crate::ProgrammaticError> {
707        let meta = crate::type_aware::refine_programmatic_dead_code_in_session(
708            semantic_session,
709            changes,
710            options,
711            filters,
712            &self.inner,
713            &mut output.results,
714        )?;
715        fallow_engine::dead_code::apply_rule_severities(&mut output.results, self.inner.config());
716        Ok(meta)
717    }
718
719    /// Run dead-code and duplication analysis for this editor session.
720    ///
721    /// # Errors
722    ///
723    /// Returns an engine error when dead-code parsing or analysis fails.
724    pub fn analyze_project_with(
725        &self,
726        duplicates_config: &fallow_config::DuplicatesConfig,
727        retain_complexity_artifacts: bool,
728    ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
729        self.inner
730            .analyze_project_with(duplicates_config, retain_complexity_artifacts)
731            .map(EditorProjectAnalysisOutput::from_engine)
732            .map(|output| self.with_resolved_rule_severities(output))
733    }
734
735    /// Run dead-code and duplication analysis, optionally focusing duplication
736    /// to files the editor already resolved as changed.
737    ///
738    /// Dead-code retains full graph context and semantic evidence scope.
739    /// After type-aware refinement, call [`Self::apply_change_scope`] to narrow
740    /// the findings and clone groups of this project.
741    ///
742    /// # Errors
743    ///
744    /// Returns an engine error when dead-code parsing or analysis fails.
745    pub fn analyze_project_with_changed_files(
746        &self,
747        duplicates_config: &fallow_config::DuplicatesConfig,
748        retain_complexity_artifacts: bool,
749        changed_files: Option<&FxHashSet<PathBuf>>,
750    ) -> fallow_engine::EngineResult<EditorProjectAnalysisOutput> {
751        let artifacts = if self.runs_duplication {
752            self.inner.analyze_project_with_artifacts(
753                duplicates_config,
754                fallow_engine::project_analysis::ProjectAnalysisArtifactOptions {
755                    retain_complexity_artifacts,
756                    changed_files: changed_files.cloned(),
757                    ..fallow_engine::project_analysis::ProjectAnalysisArtifactOptions::default()
758                },
759            )?
760        } else {
761            fallow_engine::project_analysis::ProjectAnalysisArtifacts {
762                dead_code: self
763                    .inner
764                    .analyze_dead_code_with_artifacts(retain_complexity_artifacts, false)?,
765                duplication: fallow_types::duplicates::DuplicationReport::default(),
766                ignored_clone_groups: Vec::new(),
767                changed_files: changed_files.cloned(),
768                source_fingerprints: None,
769            }
770        };
771        Ok(
772            self.with_resolved_rule_severities(EditorProjectAnalysisOutput::from_engine(
773                artifacts.into_output(),
774            )),
775        )
776    }
777
778    /// Narrow the dead-code findings and clone groups of this project to a
779    /// resolved change scope, with the engine functions that the CLI, MCP and
780    /// Node API use.
781    ///
782    /// Apply scope after type-aware refinement so added findings are scoped
783    /// too. Each project in a multi-root editor session has its own
784    /// `ignoreFindings`, so apply scope per project before merging.
785    pub fn apply_change_scope(
786        &self,
787        output: &mut EditorProjectAnalysisOutput,
788        scope: &ChangeScope,
789    ) {
790        fallow_engine::dead_code::apply_scope(
791            &mut output.dead_code.results,
792            &fallow_engine::dead_code::DeadCodeScope {
793                workspace_roots: None,
794                changes: Some(scope),
795                diff: None,
796                files: None,
797            },
798            self.inner.config(),
799        );
800        fallow_engine::duplicates::apply_scope(
801            &mut output.duplication,
802            &fallow_engine::duplicates::DuplicationScope {
803                changes: Some(scope),
804                diff: None,
805                workspace_roots: None,
806            },
807            &self.inner.config().root,
808        );
809    }
810
811    /// Resolve configured rule severities, including per-path
812    /// `overrides[].rules`, against a freshly analyzed project slice.
813    ///
814    /// Each project root is filtered with its own config before a multi-root
815    /// editor session merges the outputs, so an override only ever applies to
816    /// the project that declares it.
817    fn with_resolved_rule_severities(
818        &self,
819        mut output: EditorProjectAnalysisOutput,
820    ) -> EditorProjectAnalysisOutput {
821        fallow_engine::dead_code::apply_rule_severities(
822            &mut output.dead_code.results,
823            self.inner.config(),
824        );
825        output
826    }
827
828    /// A session of a constructor without a resolved run. No editor action
829    /// names the duplication analysis, so `duplicates.enabled: false` leaves
830    /// the editor without clone groups, as it leaves the bare `fallow` run.
831    #[cfg(any(test, feature = "testing"))]
832    fn from_engine(inner: fallow_engine::session::AnalysisSession) -> Self {
833        Self {
834            runs_duplication: inner.config().duplicates.runs_by_default(),
835            inner,
836        }
837    }
838}
839
840/// Dead-code and duplication project output owned by the editor API boundary.
841#[derive(Debug)]
842pub struct EditorProjectAnalysisOutput {
843    /// Dead-code findings plus optionally retained parse artifacts.
844    pub dead_code: EditorDeadCodeAnalysisOutput,
845    /// Duplication report for the analyzed project slice.
846    pub duplication: EditorDuplicationReport,
847}
848
849impl EditorProjectAnalysisOutput {
850    fn from_engine(output: fallow_engine::project_analysis::ProjectAnalysisOutput) -> Self {
851        Self {
852            dead_code: EditorDeadCodeAnalysisOutput::from_engine(output.dead_code),
853            duplication: output.duplication,
854        }
855    }
856}
857
858/// Dead-code and duplication output shaped for editor integrations.
859#[derive(Debug, Default)]
860pub struct EditorAnalysisOutput {
861    /// Typed dead-code findings.
862    pub results: EditorAnalysisResults,
863    /// Duplication report.
864    pub duplication: EditorDuplicationReport,
865}
866
867impl EditorAnalysisOutput {
868    /// Pair dead-code results with a duplication report.
869    #[must_use]
870    pub const fn new(results: EditorAnalysisResults, duplication: EditorDuplicationReport) -> Self {
871        Self {
872            results,
873            duplication,
874        }
875    }
876
877    /// Merge another project analysis output into this accumulated output.
878    pub fn merge_project_output(&mut self, output: EditorProjectAnalysisOutput) {
879        self.merge_results(output.dead_code.results);
880        self.merge_duplication(output.duplication);
881    }
882
883    /// Merge another dead-code results set into this one.
884    pub fn merge_results(&mut self, source: EditorAnalysisResults) {
885        self.results.merge_into(source);
886    }
887
888    /// Merge another duplication report into this one, summing the aggregate
889    /// stats and recomputing the duplication percentage over the union.
890    pub fn merge_duplication(&mut self, source: EditorDuplicationReport) {
891        self.duplication.clone_groups.extend(source.clone_groups);
892        self.duplication
893            .clone_families
894            .extend(source.clone_families);
895        self.duplication
896            .mirrored_directories
897            .extend(source.mirrored_directories);
898        self.duplication.stats.clone_groups += source.stats.clone_groups;
899        self.duplication.stats.clone_families += source.stats.clone_families;
900        self.duplication.stats.clone_instances += source.stats.clone_instances;
901        self.duplication.stats.total_files += source.stats.total_files;
902        self.duplication.stats.files_with_clones += source.stats.files_with_clones;
903        self.duplication.stats.total_lines += source.stats.total_lines;
904        self.duplication.stats.duplicated_lines += source.stats.duplicated_lines;
905        self.duplication.stats.total_tokens += source.stats.total_tokens;
906        self.duplication.stats.duplicated_tokens += source.stats.duplicated_tokens;
907        self.duplication.stats.clone_groups_below_min_occurrences +=
908            source.stats.clone_groups_below_min_occurrences;
909        self.duplication.stats.clone_groups_ignored += source.stats.clone_groups_ignored;
910        self.duplication.stats.near_candidates_skipped += source.stats.near_candidates_skipped;
911        self.duplication.stats.duplication_percentage = if self.duplication.stats.total_lines > 0 {
912            (self.duplication.stats.duplicated_lines as f64
913                / self.duplication.stats.total_lines as f64)
914                * 100.0
915        } else {
916            0.0
917        };
918    }
919
920    /// Drop findings and clone groups that do not touch any changed file.
921    ///
922    /// Each project scopes dead-code findings with its own config in
923    /// [`EditorAnalysisSession::apply_change_scope`]. This merged-output filter
924    /// narrows clone groups and preserves the already scoped findings.
925    pub fn filter_by_changed_files(&mut self, changed_files: &FxHashSet<PathBuf>, root: &Path) {
926        fallow_engine::changed_files::filter_results_by_changed_files(
927            &mut self.results,
928            changed_files,
929        );
930        fallow_engine::changed_files::filter_duplication_by_changed_files(
931            &mut self.duplication,
932            changed_files,
933            root,
934        );
935    }
936}
937
938#[cfg(test)]
939#[path = "editor_tests.rs"]
940pub(crate) mod tests;