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 std::fmt::Display for ExportName {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 match self {
163 Self::Named(n) => write!(f, "{n}"),
164 Self::Default => write!(f, "default"),
165 }
166 }
167}
168
169/// An import declaration.
170#[derive(Debug, Clone)]
171pub struct ImportInfo {
172 /// The import specifier (e.g., `./utils` or `react`).
173 pub source: String,
174 /// How the symbol is imported (named, default, namespace, or side-effect).
175 pub imported_name: ImportedName,
176 /// The local binding name in the importing module.
177 pub local_name: String,
178 /// Whether this is a type-only import (`import type`).
179 pub is_type_only: bool,
180 /// Source span of the import declaration.
181 pub span: Span,
182}
183
184/// How a symbol is imported.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub enum ImportedName {
187 /// A named import (e.g., `import { foo }`).
188 Named(String),
189 /// A default import (e.g., `import React`).
190 Default,
191 /// A namespace import (e.g., `import * as utils`).
192 Namespace,
193 /// A side-effect import (e.g., `import './styles.css'`).
194 SideEffect,
195}
196
197// Size assertions to prevent memory regressions in hot-path types.
198// These types are stored in Vecs inside `ModuleInfo` (one per file) and are
199// iterated during graph construction and analysis. Keeping them compact
200// improves cache locality on large projects with thousands of files.
201#[cfg(target_pointer_width = "64")]
202const _: () = assert!(std::mem::size_of::<ExportInfo>() == 88);
203#[cfg(target_pointer_width = "64")]
204const _: () = assert!(std::mem::size_of::<ImportInfo>() == 88);
205#[cfg(target_pointer_width = "64")]
206const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
207#[cfg(target_pointer_width = "64")]
208const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
209#[cfg(target_pointer_width = "64")]
210const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
211// `ModuleInfo` is the per-file extraction result — stored in a Vec during parallel parsing.
212#[cfg(target_pointer_width = "64")]
213const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 280);
214
215/// A re-export declaration.
216#[derive(Debug, Clone)]
217pub struct ReExportInfo {
218 /// The module being re-exported from.
219 pub source: String,
220 /// The name imported from the source module (or `*` for star re-exports).
221 pub imported_name: String,
222 /// The name exported from this module.
223 pub exported_name: String,
224 /// Whether this is a type-only re-export.
225 pub is_type_only: bool,
226}
227
228/// A dynamic `import()` call.
229#[derive(Debug, Clone)]
230pub struct DynamicImportInfo {
231 /// The import specifier.
232 pub source: String,
233 /// Source span of the `import()` expression.
234 pub span: Span,
235 /// Names destructured from the dynamic import result.
236 /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
237 /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
238 pub destructured_names: Vec<String>,
239 /// The local variable name for `const x = await import(...)`.
240 /// Used for namespace import narrowing via member access tracking.
241 pub local_name: Option<String>,
242}
243
244/// A `require()` call.
245#[derive(Debug, Clone)]
246pub struct RequireCallInfo {
247 /// The require specifier.
248 pub source: String,
249 /// Source span of the `require()` call.
250 pub span: Span,
251 /// Names destructured from the `require()` result.
252 /// Non-empty means `const { a, b } = require(...)` -> Named imports.
253 /// Empty means simple `require(...)` or `const x = require(...)` -> Namespace.
254 pub destructured_names: Vec<String>,
255 /// The local variable name for `const x = require(...)`.
256 /// Used for namespace import narrowing via member access tracking.
257 pub local_name: Option<String>,
258}
259
260/// Result of parsing all files, including incremental cache statistics.
261pub struct ParseResult {
262 /// Extracted module information for all successfully parsed files.
263 pub modules: Vec<ModuleInfo>,
264 /// Number of files whose parse results were loaded from cache (unchanged).
265 pub cache_hits: usize,
266 /// Number of files that required a full parse (new or changed).
267 pub cache_misses: usize,
268}