Skip to main content

fallow_api/
editor.rs

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