Skip to main content

fallow_types/
extract.rs

1//! Module extraction types: exports, imports, re-exports, members, and parse results.
2
3use oxc_span::Span;
4
5use crate::discover::FileId;
6use crate::suppress::{Suppression, UnknownSuppressionKind};
7
8/// Extracted module information from a single file.
9#[derive(Debug, Clone)]
10pub struct ModuleInfo {
11    /// Unique identifier for this file.
12    pub file_id: FileId,
13    /// All export declarations in this module.
14    pub exports: Vec<ExportInfo>,
15    /// All import declarations in this module.
16    pub imports: Vec<ImportInfo>,
17    /// All re-export declarations (e.g., `export { foo } from './bar'`).
18    pub re_exports: Vec<ReExportInfo>,
19    /// All dynamic `import()` calls with string literal sources.
20    pub dynamic_imports: Vec<DynamicImportInfo>,
21    /// Dynamic import patterns from template literals, string concat, or `import.meta.glob`.
22    pub dynamic_import_patterns: Vec<DynamicImportPattern>,
23    /// All `require()` calls.
24    pub require_calls: Vec<RequireCallInfo>,
25    /// Static member access expressions (e.g., `Status.Active`).
26    pub member_accesses: Vec<MemberAccess>,
27    /// Identifiers used in "all members consumed" patterns
28    /// (Object.values, Object.keys, Object.entries, Object.getOwnPropertyNames, for..in, spread, computed dynamic access).
29    pub whole_object_uses: Vec<String>,
30    /// Whether this module uses `CommonJS` exports (`module.exports` or `exports.*`).
31    pub has_cjs_exports: bool,
32    /// True when this module declares at least one Angular `@Component({
33    /// templateUrl: ... })` (the visitor emits a SideEffect import for each
34    /// such templateUrl, and this flag is set in the same branch). Used by
35    /// the CRAP-inherit walker (`crates/cli/src/health/scoring.rs::build_template_inherit_contexts`)
36    /// to gate the discriminator `coverage_source == "estimated_component_inherited"`:
37    /// a `.ts` file that imports an `.html` via plain `import './x.html'` is
38    /// NOT a component owner and must not trigger the inherit path. Without
39    /// this gate, the contract documented on `ComplexityViolation.inherited_from`
40    /// (Angular component `.ts` reached via the inverse `templateUrl` edge)
41    /// is silently violated for any non-Angular file importing an `.html`.
42    pub has_angular_component_template_url: bool,
43    /// xxh3 hash of the file content for incremental caching.
44    pub content_hash: u64,
45    /// Inline suppression directives parsed from comments.
46    pub suppressions: Vec<Suppression>,
47    /// Suppression tokens that did not parse to any known `IssueKind`.
48    /// Surfaced as `StaleSuppression` findings via `find_stale` so users see
49    /// typos or obsolete kind names instead of having the entire marker
50    /// silently discarded. See issue #449.
51    pub unknown_suppression_kinds: Vec<UnknownSuppressionKind>,
52    /// Local names of import bindings that are never referenced in this file.
53    /// Populated via `oxc_semantic` scope analysis. Used at graph-build time
54    /// to skip adding references for imports whose binding is never read,
55    /// improving unused-export detection precision.
56    pub unused_import_bindings: Vec<String>,
57    /// Local import bindings that are referenced from TypeScript type positions.
58    /// Used to distinguish value-namespace and type-namespace references when a
59    /// module exports both `const X` and `type X`.
60    pub type_referenced_import_bindings: Vec<String>,
61    /// Local import bindings that are referenced from runtime/value positions.
62    /// Used alongside `type_referenced_import_bindings` for TS namespace-split
63    /// exports that share the same name.
64    pub value_referenced_import_bindings: Vec<String>,
65    /// Pre-computed byte offsets where each line starts, for O(log N) byte-to-line/col conversion.
66    /// Entry `i` is the byte offset of the start of line `i` (0-indexed).
67    /// Example: for "abc\ndef\n", `line_offsets` = \[0, 4\].
68    pub line_offsets: Vec<u32>,
69    /// Per-function complexity metrics computed during AST traversal.
70    /// Used by the `fallow health` subcommand to report high-complexity functions.
71    pub complexity: Vec<FunctionComplexity>,
72    /// Feature flag use sites detected during AST traversal.
73    /// Used by the `fallow flags` subcommand to report feature flag patterns.
74    pub flag_uses: Vec<FlagUse>,
75    /// Heritage metadata for exported classes that declare `implements`.
76    /// Used to scope `usedClassMembers` rules during analysis.
77    pub class_heritage: Vec<ClassHeritageInfo>,
78    /// Local type-capable declarations in this module.
79    /// Used to detect exported signatures that expose a same-file private type.
80    pub local_type_declarations: Vec<LocalTypeDeclaration>,
81    /// Type references that appear in exported symbols' public signatures.
82    /// The analysis layer checks these against `local_type_declarations`.
83    pub public_signature_type_references: Vec<PublicSignatureTypeReference>,
84    /// Aliases of namespace imports re-exported through an object literal
85    /// (`import * as foo from './bar'; export const API = { foo }`).
86    ///
87    /// Each entry says: "downstream consumer accessing `<my-export>.<suffix>.<X>`
88    /// is really accessing `<X>` on the namespace whose local name is
89    /// `namespace_local`". The graph layer uses these to propagate references
90    /// from cross-package consumers to the namespace's source module so that
91    /// `<X>` is not falsely reported as `unused-export`. See issue #303.
92    pub namespace_object_aliases: Vec<NamespaceObjectAlias>,
93}
94
95/// One alias entry tying an exported object's dotted property path to a
96/// namespace import on the same module.
97///
98/// Produced when the visitor sees `export const API = { foo }` (or any deeper
99/// nesting) and detects that the property's source identifier is a namespace
100/// import (`import * as foo from './bar'`). The graph layer reads these to
101/// resolve cross-package consumer accesses like `API.foo.bar` so that `bar`
102/// is credited as referenced on `./bar.ts`.
103#[derive(Debug, Clone)]
104pub struct NamespaceObjectAlias {
105    /// Canonical export name on this module (the `API` in `export const API = { foo }`).
106    pub via_export_name: String,
107    /// Dotted suffix of the property path relative to the export
108    /// (e.g. `"foo"` for `API.foo`, `"motionNet.adEngine"` for `API.motionNet.adEngine`).
109    pub suffix: String,
110    /// Local name of the namespace import on this module
111    /// (the `foo` in `import * as foo from './bar'`).
112    pub namespace_local: String,
113}
114
115/// Compute a table of line-start byte offsets from source text.
116///
117/// The returned vec contains one entry per line: `line_offsets[i]` is the byte
118/// offset where line `i` starts (0-indexed). The first entry is always `0`.
119///
120/// # Examples
121///
122/// ```
123/// use fallow_types::extract::compute_line_offsets;
124///
125/// let offsets = compute_line_offsets("abc\ndef\nghi");
126/// assert_eq!(offsets, vec![0, 4, 8]);
127/// ```
128#[must_use]
129#[expect(
130    clippy::cast_possible_truncation,
131    reason = "source files are practically < 4GB"
132)]
133pub fn compute_line_offsets(source: &str) -> Vec<u32> {
134    let mut offsets = vec![0u32];
135    for (i, byte) in source.bytes().enumerate() {
136        if byte == b'\n' {
137            debug_assert!(
138                u32::try_from(i + 1).is_ok(),
139                "source file exceeds u32::MAX bytes — line offsets would overflow"
140            );
141            offsets.push((i + 1) as u32);
142        }
143    }
144    offsets
145}
146
147/// Convert a byte offset to a 1-based line number and 0-based byte column
148/// using a pre-computed line offset table (from [`compute_line_offsets`]).
149///
150/// Uses binary search for O(log L) lookup where L is the number of lines.
151///
152/// # Examples
153///
154/// ```
155/// use fallow_types::extract::{compute_line_offsets, byte_offset_to_line_col};
156///
157/// let offsets = compute_line_offsets("abc\ndef\nghi");
158/// assert_eq!(byte_offset_to_line_col(&offsets, 0), (1, 0)); // 'a' on line 1
159/// assert_eq!(byte_offset_to_line_col(&offsets, 4), (2, 0)); // 'd' on line 2
160/// assert_eq!(byte_offset_to_line_col(&offsets, 9), (3, 1)); // 'h' on line 3
161/// ```
162#[must_use]
163#[expect(
164    clippy::cast_possible_truncation,
165    reason = "line count is bounded by source size"
166)]
167pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
168    // Binary search: find the last line whose start is <= byte_offset
169    let line_idx = match line_offsets.binary_search(&byte_offset) {
170        Ok(idx) => idx,
171        Err(idx) => idx.saturating_sub(1),
172    };
173    let line = line_idx as u32 + 1; // 1-based
174    let col = byte_offset - line_offsets[line_idx];
175    (line, col)
176}
177
178/// Complexity metrics for a single function/method/arrow.
179#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
180pub struct FunctionComplexity {
181    /// Function name (or `"<anonymous>"` for unnamed functions/arrows).
182    pub name: String,
183    /// 1-based line number where the function starts.
184    pub line: u32,
185    /// 0-based byte column where the function starts.
186    pub col: u32,
187    /// `McCabe` cyclomatic complexity (1 + decision points).
188    pub cyclomatic: u16,
189    /// `SonarSource` cognitive complexity (structural + nesting penalty).
190    pub cognitive: u16,
191    /// Number of lines in the function body.
192    pub line_count: u32,
193    /// Number of parameters (excluding TypeScript's `this` parameter).
194    pub param_count: u8,
195}
196
197/// The kind of feature flag pattern detected.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
199pub enum FlagUseKind {
200    /// `process.env.FEATURE_X` pattern.
201    EnvVar,
202    /// SDK function call like `useFlag('name')`.
203    SdkCall,
204    /// Config object access like `config.features.x`.
205    ConfigObject,
206}
207
208/// A feature flag use site detected during AST traversal.
209#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
210pub struct FlagUse {
211    /// Name/identifier of the flag (e.g., `ENABLE_NEW_CHECKOUT`, `new-checkout`).
212    pub flag_name: String,
213    /// How the flag was detected.
214    pub kind: FlagUseKind,
215    /// 1-based line number.
216    pub line: u32,
217    /// 0-based byte column offset.
218    pub col: u32,
219    /// Start byte offset of the guarded code block (if-branch span), if detected.
220    pub guard_span_start: Option<u32>,
221    /// End byte offset of the guarded code block (if-branch span), if detected.
222    pub guard_span_end: Option<u32>,
223    /// SDK/provider name if detected from SDK call pattern (e.g., "LaunchDarkly").
224    pub sdk_name: Option<String>,
225}
226
227// Size assertion: FlagUse is stored in a Vec per file in the cache.
228const _: () = assert!(std::mem::size_of::<FlagUse>() <= 96);
229
230/// A dynamic import with a pattern that can be partially resolved (e.g., template literals).
231#[derive(Debug, Clone)]
232pub struct DynamicImportPattern {
233    /// Static prefix of the import path (e.g., "./locales/"). May contain glob characters.
234    pub prefix: String,
235    /// Static suffix of the import path (e.g., ".json"), if any.
236    pub suffix: Option<String>,
237    /// Source span in the original file.
238    pub span: Span,
239}
240
241/// Visibility tag from JSDoc/TSDoc comments.
242///
243/// Controls whether an export is reported as unused. All non-`None` variants
244/// suppress unused-export detection, but preserve the semantic distinction
245/// for API surface reporting and filtering.
246#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
247#[serde(rename_all = "lowercase")]
248#[repr(u8)]
249pub enum VisibilityTag {
250    /// No visibility tag present.
251    #[default]
252    None = 0,
253    /// `@public` or `@api public` -- part of the public API surface.
254    Public = 1,
255    /// `@internal` -- exported for internal use (sister packages, build tools).
256    Internal = 2,
257    /// `@beta` -- public but unstable, may change without notice.
258    Beta = 3,
259    /// `@alpha` -- early preview, may change drastically without notice.
260    Alpha = 4,
261    /// `@expected-unused` -- intentionally unused, should warn when it becomes used.
262    ExpectedUnused = 5,
263}
264
265impl VisibilityTag {
266    /// Whether this tag permanently suppresses unused-export detection.
267    /// `ExpectedUnused` is handled separately (conditionally suppresses,
268    /// reports stale when the export becomes used).
269    pub const fn suppresses_unused(self) -> bool {
270        matches!(
271            self,
272            Self::Public | Self::Internal | Self::Beta | Self::Alpha
273        )
274    }
275
276    /// For serde `skip_serializing_if`.
277    pub fn is_none(&self) -> bool {
278        matches!(self, Self::None)
279    }
280}
281
282/// An export declaration.
283#[derive(Debug, Clone, serde::Serialize)]
284pub struct ExportInfo {
285    /// The exported name (named or default).
286    pub name: ExportName,
287    /// The local binding name, if different from the exported name.
288    pub local_name: Option<String>,
289    /// Whether this is a type-only export (`export type`).
290    pub is_type_only: bool,
291    /// Whether this export is registered through a runtime side effect at module
292    /// load time (e.g. a Lit `@customElement('tag')` class decorator or a
293    /// `customElements.define('tag', ClassRef)` call). Such classes are
294    /// referenced by their registered tag string, not by their identifier, so
295    /// no other file imports them by name. The unused-export detector treats
296    /// this flag as an effective reference.
297    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
298    pub is_side_effect_used: bool,
299    /// Visibility tag from JSDoc/TSDoc comment (`@public`, `@internal`, `@alpha`, `@beta`).
300    /// Exports with any visibility tag are never reported as unused.
301    #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
302    pub visibility: VisibilityTag,
303    /// Source span of the export declaration.
304    #[serde(serialize_with = "serialize_span")]
305    pub span: Span,
306    /// Members of this export (for enums, classes, and namespaces).
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub members: Vec<MemberInfo>,
309    /// The local name of the parent class from `extends` clause, if any.
310    /// Used to build inheritance maps for unused class member detection.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub super_class: Option<String>,
313}
314
315/// Additional heritage metadata for an exported class.
316#[derive(
317    Debug,
318    Clone,
319    serde::Serialize,
320    serde::Deserialize,
321    bitcode::Encode,
322    bitcode::Decode,
323    PartialEq,
324    Eq,
325)]
326pub struct ClassHeritageInfo {
327    /// Export name (`default` for default-exported classes).
328    pub export_name: String,
329    /// Parent class name from the `extends` clause, if any.
330    pub super_class: Option<String>,
331    /// Interface names from the class `implements` clause.
332    pub implements: Vec<String>,
333    /// Typed instance bindings on this class: pairs of `(local_name, type_name)`
334    /// from typed constructor parameters with accessibility modifiers
335    /// (`constructor(public svc: Svc)`), non-private typed property
336    /// declarations (`svc: Svc`), and non-private typed getters
337    /// (`get svc(): Svc`).
338    ///
339    /// Used by the analysis layer to resolve typed member-access chains
340    /// (`factory.service.getTotal()`) and Angular template member-access chains
341    /// on external templates (`templateUrl`), where the HTML file is parsed
342    /// independently and cannot see the component's constructor types.
343    /// For `constructor(public dataService: DataService)` in a component that
344    /// uses an external template with `{{ dataService.getTotal() }}`, this
345    /// field carries `("dataService", "DataService")` so the bridge can credit
346    /// `DataService.getTotal` as used.
347    #[serde(default, skip_serializing_if = "Vec::is_empty")]
348    pub instance_bindings: Vec<(String, String)>,
349}
350
351/// A module-scope declaration that can be used as a TypeScript type.
352#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
353pub struct LocalTypeDeclaration {
354    /// Local declaration name.
355    pub name: String,
356    /// Declaration identifier span.
357    #[serde(serialize_with = "serialize_span")]
358    pub span: Span,
359}
360
361/// A reference from an exported symbol's public signature to a type name.
362#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
363pub struct PublicSignatureTypeReference {
364    /// Exported symbol whose signature contains the reference.
365    pub export_name: String,
366    /// Referenced type name. Qualified names are reduced to their root identifier.
367    pub type_name: String,
368    /// Reference span.
369    #[serde(serialize_with = "serialize_span")]
370    pub span: Span,
371}
372
373/// A member of an enum, class, or namespace.
374#[derive(Debug, Clone, serde::Serialize)]
375pub struct MemberInfo {
376    /// Member name.
377    pub name: String,
378    /// The kind of member (enum, class method/property, or namespace member).
379    pub kind: MemberKind,
380    /// Source span of the member declaration.
381    #[serde(serialize_with = "serialize_span")]
382    pub span: Span,
383    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
384    /// Decorated members are used by frameworks at runtime and should not be
385    /// flagged as unused class members, unless every decorator on the member
386    /// is opted out via `FallowConfig.ignore_decorators`.
387    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
388    pub has_decorator: bool,
389    /// Full dotted path of each decorator on this member, in source order.
390    /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
391    /// undecorated members, Angular signal-initializer properties (which set
392    /// `has_decorator` without a literal decorator AST node), and decorators
393    /// whose expression is not an identifier ladder (the entry is the empty
394    /// string in that case, treated as never-matching by the predicate).
395    #[serde(default, skip_serializing_if = "Vec::is_empty")]
396    pub decorator_names: Vec<String>,
397    /// True when this is a static class method that returns a fresh instance
398    /// of the same class: either via `return new this()` / `return new
399    /// <SameClassName>()` in the body's last statement, or via a declared
400    /// return type matching the class name. Consumers calling such a static
401    /// method receive an instance, so the call result's member accesses are
402    /// credited against the class. See issues #346, #387.
403    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
404    pub is_instance_returning_static: bool,
405    /// True when this is an instance class method whose call result is an
406    /// instance of the same class. Qualifies when the declared return type
407    /// matches the class name (`setX(): EventBuilder { ... }`) or when the
408    /// body's last statement is `return this`. The analyze layer walks fluent
409    /// chains (`Class.factory().setX().setY()`) only through methods carrying
410    /// this flag, so the chain stops at a non-self-returning method like
411    /// `.build()`. See issue #387.
412    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
413    pub is_self_returning: bool,
414}
415
416/// The kind of member.
417///
418/// # Examples
419///
420/// ```
421/// use fallow_types::extract::MemberKind;
422///
423/// let kind = MemberKind::EnumMember;
424/// assert_eq!(kind, MemberKind::EnumMember);
425/// assert_ne!(kind, MemberKind::ClassMethod);
426/// assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
427/// ```
428#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
429#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
430#[serde(rename_all = "snake_case")]
431pub enum MemberKind {
432    /// A TypeScript enum member.
433    EnumMember,
434    /// A class method.
435    ClassMethod,
436    /// A class property.
437    ClassProperty,
438    /// A member exported from a TypeScript namespace.
439    NamespaceMember,
440}
441
442/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
443///
444/// # Examples
445///
446/// ```
447/// use fallow_types::extract::MemberAccess;
448///
449/// let access = MemberAccess {
450///     object: "Status".to_string(),
451///     member: "Active".to_string(),
452/// };
453/// assert_eq!(access.object, "Status");
454/// assert_eq!(access.member, "Active");
455/// ```
456#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
457pub struct MemberAccess {
458    /// The identifier being accessed (the import name).
459    pub object: String,
460    /// The member being accessed.
461    pub member: String,
462}
463
464#[expect(
465    clippy::trivially_copy_pass_by_ref,
466    reason = "serde serialize_with requires &T"
467)]
468fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
469    use serde::ser::SerializeMap;
470    let mut map = serializer.serialize_map(Some(2))?;
471    map.serialize_entry("start", &span.start)?;
472    map.serialize_entry("end", &span.end)?;
473    map.end()
474}
475
476/// Export identifier.
477///
478/// # Examples
479///
480/// ```
481/// use fallow_types::extract::ExportName;
482///
483/// let named = ExportName::Named("foo".to_string());
484/// assert_eq!(named.to_string(), "foo");
485/// assert!(named.matches_str("foo"));
486///
487/// let default = ExportName::Default;
488/// assert_eq!(default.to_string(), "default");
489/// assert!(default.matches_str("default"));
490/// ```
491#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
492pub enum ExportName {
493    /// A named export (e.g., `export const foo`).
494    Named(String),
495    /// The default export.
496    Default,
497}
498
499impl ExportName {
500    /// Compare against a string without allocating (avoids `to_string()`).
501    #[must_use]
502    pub fn matches_str(&self, s: &str) -> bool {
503        match self {
504            Self::Named(n) => n == s,
505            Self::Default => s == "default",
506        }
507    }
508}
509
510impl std::fmt::Display for ExportName {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        match self {
513            Self::Named(n) => write!(f, "{n}"),
514            Self::Default => write!(f, "default"),
515        }
516    }
517}
518
519/// An import declaration.
520#[derive(Debug, Clone)]
521pub struct ImportInfo {
522    /// The import specifier (e.g., `./utils` or `react`).
523    pub source: String,
524    /// How the symbol is imported (named, default, namespace, or side-effect).
525    pub imported_name: ImportedName,
526    /// The local binding name in the importing module.
527    pub local_name: String,
528    /// Whether this is a type-only import (`import type`).
529    pub is_type_only: bool,
530    /// Whether this import originated from a CSS-context (an SFC `<style lang="scss">` block,
531    /// `<style src="...">` reference, or other style-section parser). The resolver uses this
532    /// to enable SCSS partial / include-path / node_modules fallbacks for SFC importers
533    /// without applying them to JS-context imports from the same file.
534    pub from_style: bool,
535    /// Source span of the import declaration.
536    pub span: Span,
537    /// Span of the source string literal (e.g., the `'./utils'` in `import { foo } from './utils'`).
538    /// Used by the LSP to highlight just the specifier in diagnostics.
539    pub source_span: Span,
540}
541
542/// How a symbol is imported.
543///
544/// # Examples
545///
546/// ```
547/// use fallow_types::extract::ImportedName;
548///
549/// let named = ImportedName::Named("useState".to_string());
550/// assert_eq!(named, ImportedName::Named("useState".to_string()));
551/// assert_ne!(named, ImportedName::Default);
552///
553/// // Side-effect imports have no binding
554/// assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
555/// ```
556#[derive(Debug, Clone, PartialEq, Eq)]
557pub enum ImportedName {
558    /// A named import (e.g., `import { foo }`).
559    Named(String),
560    /// A default import (e.g., `import React`).
561    Default,
562    /// A namespace import (e.g., `import * as utils`).
563    Namespace,
564    /// A side-effect import (e.g., `import './styles.css'`).
565    SideEffect,
566}
567
568// Size assertions to prevent memory regressions in hot-path types.
569// These types are stored in Vecs inside `ModuleInfo` (one per file) and are
570// iterated during graph construction and analysis. Keeping them compact
571// improves cache locality on large projects with thousands of files.
572#[cfg(target_pointer_width = "64")]
573const _: () = assert!(std::mem::size_of::<ExportInfo>() == 112);
574#[cfg(target_pointer_width = "64")]
575const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
576#[cfg(target_pointer_width = "64")]
577const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
578#[cfg(target_pointer_width = "64")]
579const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
580#[cfg(target_pointer_width = "64")]
581const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
582// `ModuleInfo` is the per-file extraction result, stored in a Vec during parallel parsing.
583#[cfg(target_pointer_width = "64")]
584const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 496);
585
586/// A re-export declaration.
587#[derive(Debug, Clone)]
588pub struct ReExportInfo {
589    /// The module being re-exported from.
590    pub source: String,
591    /// The name imported from the source module (or `*` for star re-exports).
592    pub imported_name: String,
593    /// The name exported from this module.
594    pub exported_name: String,
595    /// Whether this is a type-only re-export.
596    pub is_type_only: bool,
597    /// Source span of the re-export declaration on this module.
598    /// Used for line-number reporting when an unused re-export is detected.
599    /// Defaults to `Span::default()` (0, 0) for re-exports without a meaningful
600    /// source location (e.g., synthesized in the graph layer).
601    pub span: oxc_span::Span,
602}
603
604/// A dynamic `import()` call.
605#[derive(Debug, Clone)]
606pub struct DynamicImportInfo {
607    /// The import specifier.
608    pub source: String,
609    /// Source span of the `import()` expression.
610    pub span: Span,
611    /// Names destructured from the dynamic import result.
612    /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
613    /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
614    pub destructured_names: Vec<String>,
615    /// The local variable name for `const x = await import(...)`.
616    /// Used for namespace import narrowing via member access tracking.
617    pub local_name: Option<String>,
618    /// True when this dynamic import was synthesised by fallow rather than
619    /// appearing in user source (e.g. the Vitest `__mocks__/<file>` auto-mock
620    /// sibling that pairs with a `vi.mock('./foo')` call). When the resolver
621    /// cannot find the synthesised target, the entry is dropped silently
622    /// instead of surfacing as an `unresolved-import` finding pointing at a
623    /// path the user never wrote.
624    pub is_speculative: bool,
625}
626
627/// A `require()` call.
628#[derive(Debug, Clone)]
629pub struct RequireCallInfo {
630    /// The require specifier.
631    pub source: String,
632    /// Source span of the `require()` call.
633    pub span: Span,
634    /// Names destructured from the `require()` result.
635    /// Non-empty means `const { a, b } = require(...)` -> Named imports.
636    /// Empty means simple `require(...)` or `const x = require(...)` -> Namespace.
637    pub destructured_names: Vec<String>,
638    /// The local variable name for `const x = require(...)`.
639    /// Used for namespace import narrowing via member access tracking.
640    pub local_name: Option<String>,
641}
642
643/// Result of parsing all files, including incremental cache statistics.
644pub struct ParseResult {
645    /// Extracted module information for all successfully parsed files.
646    pub modules: Vec<ModuleInfo>,
647    /// Number of files whose parse results were loaded from cache (unchanged).
648    pub cache_hits: usize,
649    /// Number of files that required a full parse (new or changed).
650    pub cache_misses: usize,
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656
657    // ── compute_line_offsets ──────────────────────────────────────────
658
659    #[test]
660    fn line_offsets_empty_string() {
661        assert_eq!(compute_line_offsets(""), vec![0]);
662    }
663
664    #[test]
665    fn line_offsets_single_line_no_newline() {
666        assert_eq!(compute_line_offsets("hello"), vec![0]);
667    }
668
669    #[test]
670    fn line_offsets_single_line_with_newline() {
671        // "hello\n" => line 0 starts at 0, line 1 starts at 6
672        assert_eq!(compute_line_offsets("hello\n"), vec![0, 6]);
673    }
674
675    #[test]
676    fn line_offsets_multiple_lines() {
677        // "abc\ndef\nghi"
678        // line 0: offset 0 ("abc")
679        // line 1: offset 4 ("def")
680        // line 2: offset 8 ("ghi")
681        assert_eq!(compute_line_offsets("abc\ndef\nghi"), vec![0, 4, 8]);
682    }
683
684    #[test]
685    fn line_offsets_trailing_newline() {
686        // "abc\ndef\n"
687        // line 0: offset 0, line 1: offset 4, line 2: offset 8 (empty line after trailing \n)
688        assert_eq!(compute_line_offsets("abc\ndef\n"), vec![0, 4, 8]);
689    }
690
691    #[test]
692    fn line_offsets_consecutive_newlines() {
693        // "\n\n\n" = 3 newlines => 4 lines
694        assert_eq!(compute_line_offsets("\n\n\n"), vec![0, 1, 2, 3]);
695    }
696
697    #[test]
698    fn line_offsets_multibyte_utf8() {
699        // "á\n" => 'á' is 2 bytes (0xC3 0xA1), '\n' at byte 2 => next line at byte 3
700        assert_eq!(compute_line_offsets("á\n"), vec![0, 3]);
701    }
702
703    // ── byte_offset_to_line_col ──────────────────────────────────────
704
705    #[test]
706    fn line_col_offset_zero() {
707        let offsets = compute_line_offsets("abc\ndef\nghi");
708        let (line, col) = byte_offset_to_line_col(&offsets, 0);
709        assert_eq!((line, col), (1, 0)); // line 1, col 0
710    }
711
712    #[test]
713    fn line_col_middle_of_first_line() {
714        let offsets = compute_line_offsets("abc\ndef\nghi");
715        let (line, col) = byte_offset_to_line_col(&offsets, 2);
716        assert_eq!((line, col), (1, 2)); // 'c' in "abc"
717    }
718
719    #[test]
720    fn line_col_start_of_second_line() {
721        let offsets = compute_line_offsets("abc\ndef\nghi");
722        // byte 4 = start of "def"
723        let (line, col) = byte_offset_to_line_col(&offsets, 4);
724        assert_eq!((line, col), (2, 0));
725    }
726
727    #[test]
728    fn line_col_middle_of_second_line() {
729        let offsets = compute_line_offsets("abc\ndef\nghi");
730        // byte 5 = 'e' in "def"
731        let (line, col) = byte_offset_to_line_col(&offsets, 5);
732        assert_eq!((line, col), (2, 1));
733    }
734
735    #[test]
736    fn line_col_start_of_third_line() {
737        let offsets = compute_line_offsets("abc\ndef\nghi");
738        // byte 8 = start of "ghi"
739        let (line, col) = byte_offset_to_line_col(&offsets, 8);
740        assert_eq!((line, col), (3, 0));
741    }
742
743    #[test]
744    fn line_col_end_of_file() {
745        let offsets = compute_line_offsets("abc\ndef\nghi");
746        // byte 10 = 'i' (last char)
747        let (line, col) = byte_offset_to_line_col(&offsets, 10);
748        assert_eq!((line, col), (3, 2));
749    }
750
751    #[test]
752    fn line_col_single_line() {
753        let offsets = compute_line_offsets("hello");
754        let (line, col) = byte_offset_to_line_col(&offsets, 3);
755        assert_eq!((line, col), (1, 3));
756    }
757
758    #[test]
759    fn line_col_at_newline_byte() {
760        let offsets = compute_line_offsets("abc\ndef");
761        // byte 3 = the '\n' character itself, still part of line 1
762        let (line, col) = byte_offset_to_line_col(&offsets, 3);
763        assert_eq!((line, col), (1, 3));
764    }
765
766    // ── ExportName ───────────────────────────────────────────────────
767
768    #[test]
769    fn export_name_matches_str_named() {
770        let name = ExportName::Named("foo".to_string());
771        assert!(name.matches_str("foo"));
772        assert!(!name.matches_str("bar"));
773        assert!(!name.matches_str("default"));
774    }
775
776    #[test]
777    fn export_name_matches_str_default() {
778        let name = ExportName::Default;
779        assert!(name.matches_str("default"));
780        assert!(!name.matches_str("foo"));
781    }
782
783    #[test]
784    fn export_name_display_named() {
785        let name = ExportName::Named("myExport".to_string());
786        assert_eq!(name.to_string(), "myExport");
787    }
788
789    #[test]
790    fn export_name_display_default() {
791        let name = ExportName::Default;
792        assert_eq!(name.to_string(), "default");
793    }
794
795    // ── ExportName equality & hashing ────────────────────────────
796
797    #[test]
798    fn export_name_equality_named() {
799        let a = ExportName::Named("foo".to_string());
800        let b = ExportName::Named("foo".to_string());
801        let c = ExportName::Named("bar".to_string());
802        assert_eq!(a, b);
803        assert_ne!(a, c);
804    }
805
806    #[test]
807    fn export_name_equality_default() {
808        let a = ExportName::Default;
809        let b = ExportName::Default;
810        assert_eq!(a, b);
811    }
812
813    #[test]
814    fn export_name_named_not_equal_to_default() {
815        let named = ExportName::Named("default".to_string());
816        let default = ExportName::Default;
817        assert_ne!(named, default);
818    }
819
820    #[test]
821    fn export_name_hash_consistency() {
822        use std::collections::hash_map::DefaultHasher;
823        use std::hash::{Hash, Hasher};
824
825        let mut h1 = DefaultHasher::new();
826        let mut h2 = DefaultHasher::new();
827        ExportName::Named("foo".to_string()).hash(&mut h1);
828        ExportName::Named("foo".to_string()).hash(&mut h2);
829        assert_eq!(h1.finish(), h2.finish());
830    }
831
832    // ── ExportName::matches_str edge cases ───────────────────────
833
834    #[test]
835    fn export_name_matches_str_empty_string() {
836        let name = ExportName::Named(String::new());
837        assert!(name.matches_str(""));
838        assert!(!name.matches_str("foo"));
839    }
840
841    #[test]
842    fn export_name_default_does_not_match_empty() {
843        let name = ExportName::Default;
844        assert!(!name.matches_str(""));
845    }
846
847    // ── ImportedName equality ────────────────────────────────────
848
849    #[test]
850    fn imported_name_equality() {
851        assert_eq!(
852            ImportedName::Named("foo".to_string()),
853            ImportedName::Named("foo".to_string())
854        );
855        assert_ne!(
856            ImportedName::Named("foo".to_string()),
857            ImportedName::Named("bar".to_string())
858        );
859        assert_eq!(ImportedName::Default, ImportedName::Default);
860        assert_eq!(ImportedName::Namespace, ImportedName::Namespace);
861        assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
862        assert_ne!(ImportedName::Default, ImportedName::Namespace);
863        assert_ne!(
864            ImportedName::Named("default".to_string()),
865            ImportedName::Default
866        );
867    }
868
869    // ── MemberKind equality ────────────────────────────────────
870
871    #[test]
872    fn member_kind_equality() {
873        assert_eq!(MemberKind::EnumMember, MemberKind::EnumMember);
874        assert_eq!(MemberKind::ClassMethod, MemberKind::ClassMethod);
875        assert_eq!(MemberKind::ClassProperty, MemberKind::ClassProperty);
876        assert_eq!(MemberKind::NamespaceMember, MemberKind::NamespaceMember);
877        assert_ne!(MemberKind::EnumMember, MemberKind::ClassMethod);
878        assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
879        assert_ne!(MemberKind::NamespaceMember, MemberKind::EnumMember);
880    }
881
882    // ── MemberKind bitcode roundtrip ─────────────────────────────
883
884    #[test]
885    fn member_kind_bitcode_roundtrip() {
886        let kinds = [
887            MemberKind::EnumMember,
888            MemberKind::ClassMethod,
889            MemberKind::ClassProperty,
890            MemberKind::NamespaceMember,
891        ];
892        for kind in &kinds {
893            let bytes = bitcode::encode(kind);
894            let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
895            assert_eq!(&decoded, kind);
896        }
897    }
898
899    // ── MemberAccess bitcode roundtrip ─────────────────────────
900
901    #[test]
902    fn member_access_bitcode_roundtrip() {
903        let access = MemberAccess {
904            object: "Status".to_string(),
905            member: "Active".to_string(),
906        };
907        let bytes = bitcode::encode(&access);
908        let decoded: MemberAccess = bitcode::decode(&bytes).unwrap();
909        assert_eq!(decoded.object, "Status");
910        assert_eq!(decoded.member, "Active");
911    }
912
913    // ── compute_line_offsets with Windows line endings ───────────
914
915    #[test]
916    fn line_offsets_crlf_only_counts_lf() {
917        // \r\n should produce offsets at the \n boundary
918        // "ab\r\ncd" => bytes: a(0) b(1) \r(2) \n(3) c(4) d(5)
919        // Line 0: offset 0, line 1: offset 4
920        let offsets = compute_line_offsets("ab\r\ncd");
921        assert_eq!(offsets, vec![0, 4]);
922    }
923
924    // ── byte_offset_to_line_col edge cases ──────────────────────
925
926    #[test]
927    fn line_col_empty_file_offset_zero() {
928        let offsets = compute_line_offsets("");
929        let (line, col) = byte_offset_to_line_col(&offsets, 0);
930        assert_eq!((line, col), (1, 0));
931    }
932
933    // ── FunctionComplexity bitcode roundtrip ──────────────────────
934
935    #[test]
936    fn function_complexity_bitcode_roundtrip() {
937        let fc = FunctionComplexity {
938            name: "processData".to_string(),
939            line: 42,
940            col: 4,
941            cyclomatic: 15,
942            cognitive: 25,
943            line_count: 80,
944            param_count: 3,
945        };
946        let bytes = bitcode::encode(&fc);
947        let decoded: FunctionComplexity = bitcode::decode(&bytes).unwrap();
948        assert_eq!(decoded.name, "processData");
949        assert_eq!(decoded.line, 42);
950        assert_eq!(decoded.col, 4);
951        assert_eq!(decoded.cyclomatic, 15);
952        assert_eq!(decoded.cognitive, 25);
953        assert_eq!(decoded.line_count, 80);
954    }
955}