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;
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    /// xxh3 hash of the file content for incremental caching.
33    pub content_hash: u64,
34    /// Inline suppression directives parsed from comments.
35    pub suppressions: Vec<Suppression>,
36    /// Local names of import bindings that are never referenced in this file.
37    /// Populated via `oxc_semantic` scope analysis. Used at graph-build time
38    /// to skip adding references for imports whose binding is never read,
39    /// improving unused-export detection precision.
40    pub unused_import_bindings: Vec<String>,
41    /// Pre-computed byte offsets where each line starts, for O(log N) byte-to-line/col conversion.
42    /// Entry `i` is the byte offset of the start of line `i` (0-indexed).
43    /// Example: for "abc\ndef\n", `line_offsets` = \[0, 4\].
44    pub line_offsets: Vec<u32>,
45}
46
47/// Compute a table of line-start byte offsets from source text.
48///
49/// The returned vec contains one entry per line: `line_offsets[i]` is the byte
50/// offset where line `i` starts (0-indexed). The first entry is always `0`.
51pub fn compute_line_offsets(source: &str) -> Vec<u32> {
52    let mut offsets = vec![0u32];
53    for (i, byte) in source.bytes().enumerate() {
54        if byte == b'\n' {
55            offsets.push((i + 1) as u32);
56        }
57    }
58    offsets
59}
60
61/// Convert a byte offset to a 1-based line number and 0-based byte column
62/// using a pre-computed line offset table (from [`compute_line_offsets`]).
63///
64/// Uses binary search for O(log L) lookup where L is the number of lines.
65pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
66    // Binary search: find the last line whose start is <= byte_offset
67    let line_idx = match line_offsets.binary_search(&byte_offset) {
68        Ok(idx) => idx,
69        Err(idx) => idx.saturating_sub(1),
70    };
71    let line = line_idx as u32 + 1; // 1-based
72    let col = byte_offset - line_offsets[line_idx];
73    (line, col)
74}
75
76/// A dynamic import with a pattern that can be partially resolved (e.g., template literals).
77#[derive(Debug, Clone)]
78pub struct DynamicImportPattern {
79    /// Static prefix of the import path (e.g., "./locales/"). May contain glob characters.
80    pub prefix: String,
81    /// Static suffix of the import path (e.g., ".json"), if any.
82    pub suffix: Option<String>,
83    /// Source span in the original file.
84    pub span: Span,
85}
86
87/// An export declaration.
88#[derive(Debug, Clone, serde::Serialize)]
89pub struct ExportInfo {
90    /// The exported name (named or default).
91    pub name: ExportName,
92    /// The local binding name, if different from the exported name.
93    pub local_name: Option<String>,
94    /// Whether this is a type-only export (`export type`).
95    pub is_type_only: bool,
96    /// Source span of the export declaration.
97    #[serde(serialize_with = "serialize_span")]
98    pub span: Span,
99    /// Members of this export (for enums and classes).
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub members: Vec<MemberInfo>,
102}
103
104/// A member of an enum or class.
105#[derive(Debug, Clone, serde::Serialize)]
106pub struct MemberInfo {
107    /// Member name.
108    pub name: String,
109    /// Whether this is an enum member, class method, or class property.
110    pub kind: MemberKind,
111    /// Source span of the member declaration.
112    #[serde(serialize_with = "serialize_span")]
113    pub span: Span,
114    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
115    /// Decorated members are used by frameworks at runtime and should not be
116    /// flagged as unused class members.
117    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
118    pub has_decorator: bool,
119}
120
121/// The kind of member.
122#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bincode::Encode, bincode::Decode)]
123#[serde(rename_all = "snake_case")]
124pub enum MemberKind {
125    /// A TypeScript enum member.
126    EnumMember,
127    /// A class method.
128    ClassMethod,
129    /// A class property.
130    ClassProperty,
131}
132
133/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
134#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bincode::Encode, bincode::Decode)]
135pub struct MemberAccess {
136    /// The identifier being accessed (the import name).
137    pub object: String,
138    /// The member being accessed.
139    pub member: String,
140}
141
142#[expect(clippy::trivially_copy_pass_by_ref)] // serde serialize_with requires &T
143fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
144    use serde::ser::SerializeMap;
145    let mut map = serializer.serialize_map(Some(2))?;
146    map.serialize_entry("start", &span.start)?;
147    map.serialize_entry("end", &span.end)?;
148    map.end()
149}
150
151/// Export identifier.
152#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
153pub enum ExportName {
154    /// A named export (e.g., `export const foo`).
155    Named(String),
156    /// The default export.
157    Default,
158}
159
160impl ExportName {
161    /// Compare against a string without allocating (avoids `to_string()`).
162    pub fn matches_str(&self, s: &str) -> bool {
163        match self {
164            Self::Named(n) => n == s,
165            Self::Default => s == "default",
166        }
167    }
168}
169
170impl std::fmt::Display for ExportName {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        match self {
173            Self::Named(n) => write!(f, "{n}"),
174            Self::Default => write!(f, "default"),
175        }
176    }
177}
178
179/// An import declaration.
180#[derive(Debug, Clone)]
181pub struct ImportInfo {
182    /// The import specifier (e.g., `./utils` or `react`).
183    pub source: String,
184    /// How the symbol is imported (named, default, namespace, or side-effect).
185    pub imported_name: ImportedName,
186    /// The local binding name in the importing module.
187    pub local_name: String,
188    /// Whether this is a type-only import (`import type`).
189    pub is_type_only: bool,
190    /// Source span of the import declaration.
191    pub span: Span,
192}
193
194/// How a symbol is imported.
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub enum ImportedName {
197    /// A named import (e.g., `import { foo }`).
198    Named(String),
199    /// A default import (e.g., `import React`).
200    Default,
201    /// A namespace import (e.g., `import * as utils`).
202    Namespace,
203    /// A side-effect import (e.g., `import './styles.css'`).
204    SideEffect,
205}
206
207// Size assertions to prevent memory regressions in hot-path types.
208// These types are stored in Vecs inside `ModuleInfo` (one per file) and are
209// iterated during graph construction and analysis. Keeping them compact
210// improves cache locality on large projects with thousands of files.
211#[cfg(target_pointer_width = "64")]
212const _: () = assert!(std::mem::size_of::<ExportInfo>() == 88);
213#[cfg(target_pointer_width = "64")]
214const _: () = assert!(std::mem::size_of::<ImportInfo>() == 88);
215#[cfg(target_pointer_width = "64")]
216const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
217#[cfg(target_pointer_width = "64")]
218const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
219#[cfg(target_pointer_width = "64")]
220const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
221// `ModuleInfo` is the per-file extraction result — stored in a Vec during parallel parsing.
222#[cfg(target_pointer_width = "64")]
223const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 280);
224
225/// A re-export declaration.
226#[derive(Debug, Clone)]
227pub struct ReExportInfo {
228    /// The module being re-exported from.
229    pub source: String,
230    /// The name imported from the source module (or `*` for star re-exports).
231    pub imported_name: String,
232    /// The name exported from this module.
233    pub exported_name: String,
234    /// Whether this is a type-only re-export.
235    pub is_type_only: bool,
236}
237
238/// A dynamic `import()` call.
239#[derive(Debug, Clone)]
240pub struct DynamicImportInfo {
241    /// The import specifier.
242    pub source: String,
243    /// Source span of the `import()` expression.
244    pub span: Span,
245    /// Names destructured from the dynamic import result.
246    /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
247    /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
248    pub destructured_names: Vec<String>,
249    /// The local variable name for `const x = await import(...)`.
250    /// Used for namespace import narrowing via member access tracking.
251    pub local_name: Option<String>,
252}
253
254/// A `require()` call.
255#[derive(Debug, Clone)]
256pub struct RequireCallInfo {
257    /// The require specifier.
258    pub source: String,
259    /// Source span of the `require()` call.
260    pub span: Span,
261    /// Names destructured from the `require()` result.
262    /// Non-empty means `const { a, b } = require(...)` -> Named imports.
263    /// Empty means simple `require(...)` or `const x = require(...)` -> Namespace.
264    pub destructured_names: Vec<String>,
265    /// The local variable name for `const x = require(...)`.
266    /// Used for namespace import narrowing via member access tracking.
267    pub local_name: Option<String>,
268}
269
270/// Result of parsing all files, including incremental cache statistics.
271pub struct ParseResult {
272    /// Extracted module information for all successfully parsed files.
273    pub modules: Vec<ModuleInfo>,
274    /// Number of files whose parse results were loaded from cache (unchanged).
275    pub cache_hits: usize,
276    /// Number of files that required a full parse (new or changed).
277    pub cache_misses: usize,
278}