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    /// Per-function complexity metrics computed during AST traversal.
46    /// Used by the `fallow health` subcommand to report high-complexity functions.
47    pub complexity: Vec<FunctionComplexity>,
48    /// Feature flag use sites detected during AST traversal.
49    /// Used by the `fallow flags` subcommand to report feature flag patterns.
50    pub flag_uses: Vec<FlagUse>,
51}
52
53/// Compute a table of line-start byte offsets from source text.
54///
55/// The returned vec contains one entry per line: `line_offsets[i]` is the byte
56/// offset where line `i` starts (0-indexed). The first entry is always `0`.
57///
58/// # Examples
59///
60/// ```
61/// use fallow_types::extract::compute_line_offsets;
62///
63/// let offsets = compute_line_offsets("abc\ndef\nghi");
64/// assert_eq!(offsets, vec![0, 4, 8]);
65/// ```
66#[must_use]
67#[expect(
68    clippy::cast_possible_truncation,
69    reason = "source files are practically < 4GB"
70)]
71pub fn compute_line_offsets(source: &str) -> Vec<u32> {
72    let mut offsets = vec![0u32];
73    for (i, byte) in source.bytes().enumerate() {
74        if byte == b'\n' {
75            debug_assert!(
76                u32::try_from(i + 1).is_ok(),
77                "source file exceeds u32::MAX bytes — line offsets would overflow"
78            );
79            offsets.push((i + 1) as u32);
80        }
81    }
82    offsets
83}
84
85/// Convert a byte offset to a 1-based line number and 0-based byte column
86/// using a pre-computed line offset table (from [`compute_line_offsets`]).
87///
88/// Uses binary search for O(log L) lookup where L is the number of lines.
89///
90/// # Examples
91///
92/// ```
93/// use fallow_types::extract::{compute_line_offsets, byte_offset_to_line_col};
94///
95/// let offsets = compute_line_offsets("abc\ndef\nghi");
96/// assert_eq!(byte_offset_to_line_col(&offsets, 0), (1, 0)); // 'a' on line 1
97/// assert_eq!(byte_offset_to_line_col(&offsets, 4), (2, 0)); // 'd' on line 2
98/// assert_eq!(byte_offset_to_line_col(&offsets, 9), (3, 1)); // 'h' on line 3
99/// ```
100#[must_use]
101#[expect(
102    clippy::cast_possible_truncation,
103    reason = "line count is bounded by source size"
104)]
105pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
106    // Binary search: find the last line whose start is <= byte_offset
107    let line_idx = match line_offsets.binary_search(&byte_offset) {
108        Ok(idx) => idx,
109        Err(idx) => idx.saturating_sub(1),
110    };
111    let line = line_idx as u32 + 1; // 1-based
112    let col = byte_offset - line_offsets[line_idx];
113    (line, col)
114}
115
116/// Complexity metrics for a single function/method/arrow.
117#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
118pub struct FunctionComplexity {
119    /// Function name (or `"<anonymous>"` for unnamed functions/arrows).
120    pub name: String,
121    /// 1-based line number where the function starts.
122    pub line: u32,
123    /// 0-based byte column where the function starts.
124    pub col: u32,
125    /// `McCabe` cyclomatic complexity (1 + decision points).
126    pub cyclomatic: u16,
127    /// `SonarSource` cognitive complexity (structural + nesting penalty).
128    pub cognitive: u16,
129    /// Number of lines in the function body.
130    pub line_count: u32,
131    /// Number of parameters (excluding TypeScript's `this` parameter).
132    pub param_count: u8,
133}
134
135/// The kind of feature flag pattern detected.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
137pub enum FlagUseKind {
138    /// `process.env.FEATURE_X` pattern.
139    EnvVar,
140    /// SDK function call like `useFlag('name')`.
141    SdkCall,
142    /// Config object access like `config.features.x`.
143    ConfigObject,
144}
145
146/// A feature flag use site detected during AST traversal.
147#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
148pub struct FlagUse {
149    /// Name/identifier of the flag (e.g., `ENABLE_NEW_CHECKOUT`, `new-checkout`).
150    pub flag_name: String,
151    /// How the flag was detected.
152    pub kind: FlagUseKind,
153    /// 1-based line number.
154    pub line: u32,
155    /// 0-based byte column offset.
156    pub col: u32,
157    /// Start byte offset of the guarded code block (if-branch span), if detected.
158    pub guard_span_start: Option<u32>,
159    /// End byte offset of the guarded code block (if-branch span), if detected.
160    pub guard_span_end: Option<u32>,
161    /// SDK/provider name if detected from SDK call pattern (e.g., "LaunchDarkly").
162    pub sdk_name: Option<String>,
163}
164
165// Size assertion: FlagUse is stored in a Vec per file in the cache.
166const _: () = assert!(std::mem::size_of::<FlagUse>() <= 96);
167
168/// A dynamic import with a pattern that can be partially resolved (e.g., template literals).
169#[derive(Debug, Clone)]
170pub struct DynamicImportPattern {
171    /// Static prefix of the import path (e.g., "./locales/"). May contain glob characters.
172    pub prefix: String,
173    /// Static suffix of the import path (e.g., ".json"), if any.
174    pub suffix: Option<String>,
175    /// Source span in the original file.
176    pub span: Span,
177}
178
179/// Visibility tag from JSDoc/TSDoc comments.
180///
181/// Controls whether an export is reported as unused. All non-`None` variants
182/// suppress unused-export detection, but preserve the semantic distinction
183/// for API surface reporting and filtering.
184#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
185#[serde(rename_all = "lowercase")]
186#[repr(u8)]
187pub enum VisibilityTag {
188    /// No visibility tag present.
189    #[default]
190    None = 0,
191    /// `@public` or `@api public` -- part of the public API surface.
192    Public = 1,
193    /// `@internal` -- exported for internal use (sister packages, build tools).
194    Internal = 2,
195    /// `@beta` -- public but unstable, may change without notice.
196    Beta = 3,
197    /// `@alpha` -- early preview, may change drastically without notice.
198    Alpha = 4,
199}
200
201impl VisibilityTag {
202    /// Whether this tag suppresses unused-export detection.
203    pub const fn suppresses_unused(self) -> bool {
204        !matches!(self, Self::None)
205    }
206
207    /// For serde `skip_serializing_if`.
208    pub fn is_none(&self) -> bool {
209        matches!(self, Self::None)
210    }
211}
212
213/// An export declaration.
214#[derive(Debug, Clone, serde::Serialize)]
215pub struct ExportInfo {
216    /// The exported name (named or default).
217    pub name: ExportName,
218    /// The local binding name, if different from the exported name.
219    pub local_name: Option<String>,
220    /// Whether this is a type-only export (`export type`).
221    pub is_type_only: bool,
222    /// Visibility tag from JSDoc/TSDoc comment (`@public`, `@internal`, `@alpha`, `@beta`).
223    /// Exports with any visibility tag are never reported as unused.
224    #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
225    pub visibility: VisibilityTag,
226    /// Source span of the export declaration.
227    #[serde(serialize_with = "serialize_span")]
228    pub span: Span,
229    /// Members of this export (for enums, classes, and namespaces).
230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
231    pub members: Vec<MemberInfo>,
232    /// The local name of the parent class from `extends` clause, if any.
233    /// Used to build inheritance maps for unused class member detection.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub super_class: Option<String>,
236}
237
238/// A member of an enum, class, or namespace.
239#[derive(Debug, Clone, serde::Serialize)]
240pub struct MemberInfo {
241    /// Member name.
242    pub name: String,
243    /// The kind of member (enum, class method/property, or namespace member).
244    pub kind: MemberKind,
245    /// Source span of the member declaration.
246    #[serde(serialize_with = "serialize_span")]
247    pub span: Span,
248    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
249    /// Decorated members are used by frameworks at runtime and should not be
250    /// flagged as unused class members.
251    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
252    pub has_decorator: bool,
253}
254
255/// The kind of member.
256///
257/// # Examples
258///
259/// ```
260/// use fallow_types::extract::MemberKind;
261///
262/// let kind = MemberKind::EnumMember;
263/// assert_eq!(kind, MemberKind::EnumMember);
264/// assert_ne!(kind, MemberKind::ClassMethod);
265/// assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
266/// ```
267#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
268#[serde(rename_all = "snake_case")]
269pub enum MemberKind {
270    /// A TypeScript enum member.
271    EnumMember,
272    /// A class method.
273    ClassMethod,
274    /// A class property.
275    ClassProperty,
276    /// A member exported from a TypeScript namespace.
277    NamespaceMember,
278}
279
280/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
281///
282/// # Examples
283///
284/// ```
285/// use fallow_types::extract::MemberAccess;
286///
287/// let access = MemberAccess {
288///     object: "Status".to_string(),
289///     member: "Active".to_string(),
290/// };
291/// assert_eq!(access.object, "Status");
292/// assert_eq!(access.member, "Active");
293/// ```
294#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
295pub struct MemberAccess {
296    /// The identifier being accessed (the import name).
297    pub object: String,
298    /// The member being accessed.
299    pub member: String,
300}
301
302#[expect(
303    clippy::trivially_copy_pass_by_ref,
304    reason = "serde serialize_with requires &T"
305)]
306fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
307    use serde::ser::SerializeMap;
308    let mut map = serializer.serialize_map(Some(2))?;
309    map.serialize_entry("start", &span.start)?;
310    map.serialize_entry("end", &span.end)?;
311    map.end()
312}
313
314/// Export identifier.
315///
316/// # Examples
317///
318/// ```
319/// use fallow_types::extract::ExportName;
320///
321/// let named = ExportName::Named("foo".to_string());
322/// assert_eq!(named.to_string(), "foo");
323/// assert!(named.matches_str("foo"));
324///
325/// let default = ExportName::Default;
326/// assert_eq!(default.to_string(), "default");
327/// assert!(default.matches_str("default"));
328/// ```
329#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
330pub enum ExportName {
331    /// A named export (e.g., `export const foo`).
332    Named(String),
333    /// The default export.
334    Default,
335}
336
337impl ExportName {
338    /// Compare against a string without allocating (avoids `to_string()`).
339    #[must_use]
340    pub fn matches_str(&self, s: &str) -> bool {
341        match self {
342            Self::Named(n) => n == s,
343            Self::Default => s == "default",
344        }
345    }
346}
347
348impl std::fmt::Display for ExportName {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        match self {
351            Self::Named(n) => write!(f, "{n}"),
352            Self::Default => write!(f, "default"),
353        }
354    }
355}
356
357/// An import declaration.
358#[derive(Debug, Clone)]
359pub struct ImportInfo {
360    /// The import specifier (e.g., `./utils` or `react`).
361    pub source: String,
362    /// How the symbol is imported (named, default, namespace, or side-effect).
363    pub imported_name: ImportedName,
364    /// The local binding name in the importing module.
365    pub local_name: String,
366    /// Whether this is a type-only import (`import type`).
367    pub is_type_only: bool,
368    /// Source span of the import declaration.
369    pub span: Span,
370    /// Span of the source string literal (e.g., the `'./utils'` in `import { foo } from './utils'`).
371    /// Used by the LSP to highlight just the specifier in diagnostics.
372    pub source_span: Span,
373}
374
375/// How a symbol is imported.
376///
377/// # Examples
378///
379/// ```
380/// use fallow_types::extract::ImportedName;
381///
382/// let named = ImportedName::Named("useState".to_string());
383/// assert_eq!(named, ImportedName::Named("useState".to_string()));
384/// assert_ne!(named, ImportedName::Default);
385///
386/// // Side-effect imports have no binding
387/// assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
388/// ```
389#[derive(Debug, Clone, PartialEq, Eq)]
390pub enum ImportedName {
391    /// A named import (e.g., `import { foo }`).
392    Named(String),
393    /// A default import (e.g., `import React`).
394    Default,
395    /// A namespace import (e.g., `import * as utils`).
396    Namespace,
397    /// A side-effect import (e.g., `import './styles.css'`).
398    SideEffect,
399}
400
401// Size assertions to prevent memory regressions in hot-path types.
402// These types are stored in Vecs inside `ModuleInfo` (one per file) and are
403// iterated during graph construction and analysis. Keeping them compact
404// improves cache locality on large projects with thousands of files.
405#[cfg(target_pointer_width = "64")]
406const _: () = assert!(std::mem::size_of::<ExportInfo>() == 112);
407#[cfg(target_pointer_width = "64")]
408const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
409#[cfg(target_pointer_width = "64")]
410const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
411#[cfg(target_pointer_width = "64")]
412const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
413#[cfg(target_pointer_width = "64")]
414const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
415// `ModuleInfo` is the per-file extraction result — stored in a Vec during parallel parsing.
416#[cfg(target_pointer_width = "64")]
417const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 328);
418
419/// A re-export declaration.
420#[derive(Debug, Clone)]
421pub struct ReExportInfo {
422    /// The module being re-exported from.
423    pub source: String,
424    /// The name imported from the source module (or `*` for star re-exports).
425    pub imported_name: String,
426    /// The name exported from this module.
427    pub exported_name: String,
428    /// Whether this is a type-only re-export.
429    pub is_type_only: bool,
430    /// Source span of the re-export declaration on this module.
431    /// Used for line-number reporting when an unused re-export is detected.
432    /// Defaults to `Span::default()` (0, 0) for re-exports without a meaningful
433    /// source location (e.g., synthesized in the graph layer).
434    pub span: oxc_span::Span,
435}
436
437/// A dynamic `import()` call.
438#[derive(Debug, Clone)]
439pub struct DynamicImportInfo {
440    /// The import specifier.
441    pub source: String,
442    /// Source span of the `import()` expression.
443    pub span: Span,
444    /// Names destructured from the dynamic import result.
445    /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
446    /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
447    pub destructured_names: Vec<String>,
448    /// The local variable name for `const x = await import(...)`.
449    /// Used for namespace import narrowing via member access tracking.
450    pub local_name: Option<String>,
451}
452
453/// A `require()` call.
454#[derive(Debug, Clone)]
455pub struct RequireCallInfo {
456    /// The require specifier.
457    pub source: String,
458    /// Source span of the `require()` call.
459    pub span: Span,
460    /// Names destructured from the `require()` result.
461    /// Non-empty means `const { a, b } = require(...)` -> Named imports.
462    /// Empty means simple `require(...)` or `const x = require(...)` -> Namespace.
463    pub destructured_names: Vec<String>,
464    /// The local variable name for `const x = require(...)`.
465    /// Used for namespace import narrowing via member access tracking.
466    pub local_name: Option<String>,
467}
468
469/// Result of parsing all files, including incremental cache statistics.
470pub struct ParseResult {
471    /// Extracted module information for all successfully parsed files.
472    pub modules: Vec<ModuleInfo>,
473    /// Number of files whose parse results were loaded from cache (unchanged).
474    pub cache_hits: usize,
475    /// Number of files that required a full parse (new or changed).
476    pub cache_misses: usize,
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    // ── compute_line_offsets ──────────────────────────────────────────
484
485    #[test]
486    fn line_offsets_empty_string() {
487        assert_eq!(compute_line_offsets(""), vec![0]);
488    }
489
490    #[test]
491    fn line_offsets_single_line_no_newline() {
492        assert_eq!(compute_line_offsets("hello"), vec![0]);
493    }
494
495    #[test]
496    fn line_offsets_single_line_with_newline() {
497        // "hello\n" => line 0 starts at 0, line 1 starts at 6
498        assert_eq!(compute_line_offsets("hello\n"), vec![0, 6]);
499    }
500
501    #[test]
502    fn line_offsets_multiple_lines() {
503        // "abc\ndef\nghi"
504        // line 0: offset 0 ("abc")
505        // line 1: offset 4 ("def")
506        // line 2: offset 8 ("ghi")
507        assert_eq!(compute_line_offsets("abc\ndef\nghi"), vec![0, 4, 8]);
508    }
509
510    #[test]
511    fn line_offsets_trailing_newline() {
512        // "abc\ndef\n"
513        // line 0: offset 0, line 1: offset 4, line 2: offset 8 (empty line after trailing \n)
514        assert_eq!(compute_line_offsets("abc\ndef\n"), vec![0, 4, 8]);
515    }
516
517    #[test]
518    fn line_offsets_consecutive_newlines() {
519        // "\n\n\n" = 3 newlines => 4 lines
520        assert_eq!(compute_line_offsets("\n\n\n"), vec![0, 1, 2, 3]);
521    }
522
523    #[test]
524    fn line_offsets_multibyte_utf8() {
525        // "á\n" => 'á' is 2 bytes (0xC3 0xA1), '\n' at byte 2 => next line at byte 3
526        assert_eq!(compute_line_offsets("á\n"), vec![0, 3]);
527    }
528
529    // ── byte_offset_to_line_col ──────────────────────────────────────
530
531    #[test]
532    fn line_col_offset_zero() {
533        let offsets = compute_line_offsets("abc\ndef\nghi");
534        let (line, col) = byte_offset_to_line_col(&offsets, 0);
535        assert_eq!((line, col), (1, 0)); // line 1, col 0
536    }
537
538    #[test]
539    fn line_col_middle_of_first_line() {
540        let offsets = compute_line_offsets("abc\ndef\nghi");
541        let (line, col) = byte_offset_to_line_col(&offsets, 2);
542        assert_eq!((line, col), (1, 2)); // 'c' in "abc"
543    }
544
545    #[test]
546    fn line_col_start_of_second_line() {
547        let offsets = compute_line_offsets("abc\ndef\nghi");
548        // byte 4 = start of "def"
549        let (line, col) = byte_offset_to_line_col(&offsets, 4);
550        assert_eq!((line, col), (2, 0));
551    }
552
553    #[test]
554    fn line_col_middle_of_second_line() {
555        let offsets = compute_line_offsets("abc\ndef\nghi");
556        // byte 5 = 'e' in "def"
557        let (line, col) = byte_offset_to_line_col(&offsets, 5);
558        assert_eq!((line, col), (2, 1));
559    }
560
561    #[test]
562    fn line_col_start_of_third_line() {
563        let offsets = compute_line_offsets("abc\ndef\nghi");
564        // byte 8 = start of "ghi"
565        let (line, col) = byte_offset_to_line_col(&offsets, 8);
566        assert_eq!((line, col), (3, 0));
567    }
568
569    #[test]
570    fn line_col_end_of_file() {
571        let offsets = compute_line_offsets("abc\ndef\nghi");
572        // byte 10 = 'i' (last char)
573        let (line, col) = byte_offset_to_line_col(&offsets, 10);
574        assert_eq!((line, col), (3, 2));
575    }
576
577    #[test]
578    fn line_col_single_line() {
579        let offsets = compute_line_offsets("hello");
580        let (line, col) = byte_offset_to_line_col(&offsets, 3);
581        assert_eq!((line, col), (1, 3));
582    }
583
584    #[test]
585    fn line_col_at_newline_byte() {
586        let offsets = compute_line_offsets("abc\ndef");
587        // byte 3 = the '\n' character itself, still part of line 1
588        let (line, col) = byte_offset_to_line_col(&offsets, 3);
589        assert_eq!((line, col), (1, 3));
590    }
591
592    // ── ExportName ───────────────────────────────────────────────────
593
594    #[test]
595    fn export_name_matches_str_named() {
596        let name = ExportName::Named("foo".to_string());
597        assert!(name.matches_str("foo"));
598        assert!(!name.matches_str("bar"));
599        assert!(!name.matches_str("default"));
600    }
601
602    #[test]
603    fn export_name_matches_str_default() {
604        let name = ExportName::Default;
605        assert!(name.matches_str("default"));
606        assert!(!name.matches_str("foo"));
607    }
608
609    #[test]
610    fn export_name_display_named() {
611        let name = ExportName::Named("myExport".to_string());
612        assert_eq!(name.to_string(), "myExport");
613    }
614
615    #[test]
616    fn export_name_display_default() {
617        let name = ExportName::Default;
618        assert_eq!(name.to_string(), "default");
619    }
620
621    // ── ExportName equality & hashing ────────────────────────────
622
623    #[test]
624    fn export_name_equality_named() {
625        let a = ExportName::Named("foo".to_string());
626        let b = ExportName::Named("foo".to_string());
627        let c = ExportName::Named("bar".to_string());
628        assert_eq!(a, b);
629        assert_ne!(a, c);
630    }
631
632    #[test]
633    fn export_name_equality_default() {
634        let a = ExportName::Default;
635        let b = ExportName::Default;
636        assert_eq!(a, b);
637    }
638
639    #[test]
640    fn export_name_named_not_equal_to_default() {
641        let named = ExportName::Named("default".to_string());
642        let default = ExportName::Default;
643        assert_ne!(named, default);
644    }
645
646    #[test]
647    fn export_name_hash_consistency() {
648        use std::collections::hash_map::DefaultHasher;
649        use std::hash::{Hash, Hasher};
650
651        let mut h1 = DefaultHasher::new();
652        let mut h2 = DefaultHasher::new();
653        ExportName::Named("foo".to_string()).hash(&mut h1);
654        ExportName::Named("foo".to_string()).hash(&mut h2);
655        assert_eq!(h1.finish(), h2.finish());
656    }
657
658    // ── ExportName::matches_str edge cases ───────────────────────
659
660    #[test]
661    fn export_name_matches_str_empty_string() {
662        let name = ExportName::Named(String::new());
663        assert!(name.matches_str(""));
664        assert!(!name.matches_str("foo"));
665    }
666
667    #[test]
668    fn export_name_default_does_not_match_empty() {
669        let name = ExportName::Default;
670        assert!(!name.matches_str(""));
671    }
672
673    // ── ImportedName equality ────────────────────────────────────
674
675    #[test]
676    fn imported_name_equality() {
677        assert_eq!(
678            ImportedName::Named("foo".to_string()),
679            ImportedName::Named("foo".to_string())
680        );
681        assert_ne!(
682            ImportedName::Named("foo".to_string()),
683            ImportedName::Named("bar".to_string())
684        );
685        assert_eq!(ImportedName::Default, ImportedName::Default);
686        assert_eq!(ImportedName::Namespace, ImportedName::Namespace);
687        assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
688        assert_ne!(ImportedName::Default, ImportedName::Namespace);
689        assert_ne!(
690            ImportedName::Named("default".to_string()),
691            ImportedName::Default
692        );
693    }
694
695    // ── MemberKind equality ────────────────────────────────────
696
697    #[test]
698    fn member_kind_equality() {
699        assert_eq!(MemberKind::EnumMember, MemberKind::EnumMember);
700        assert_eq!(MemberKind::ClassMethod, MemberKind::ClassMethod);
701        assert_eq!(MemberKind::ClassProperty, MemberKind::ClassProperty);
702        assert_eq!(MemberKind::NamespaceMember, MemberKind::NamespaceMember);
703        assert_ne!(MemberKind::EnumMember, MemberKind::ClassMethod);
704        assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
705        assert_ne!(MemberKind::NamespaceMember, MemberKind::EnumMember);
706    }
707
708    // ── MemberKind bitcode roundtrip ─────────────────────────────
709
710    #[test]
711    fn member_kind_bitcode_roundtrip() {
712        let kinds = [
713            MemberKind::EnumMember,
714            MemberKind::ClassMethod,
715            MemberKind::ClassProperty,
716            MemberKind::NamespaceMember,
717        ];
718        for kind in &kinds {
719            let bytes = bitcode::encode(kind);
720            let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
721            assert_eq!(&decoded, kind);
722        }
723    }
724
725    // ── MemberAccess bitcode roundtrip ─────────────────────────
726
727    #[test]
728    fn member_access_bitcode_roundtrip() {
729        let access = MemberAccess {
730            object: "Status".to_string(),
731            member: "Active".to_string(),
732        };
733        let bytes = bitcode::encode(&access);
734        let decoded: MemberAccess = bitcode::decode(&bytes).unwrap();
735        assert_eq!(decoded.object, "Status");
736        assert_eq!(decoded.member, "Active");
737    }
738
739    // ── compute_line_offsets with Windows line endings ───────────
740
741    #[test]
742    fn line_offsets_crlf_only_counts_lf() {
743        // \r\n should produce offsets at the \n boundary
744        // "ab\r\ncd" => bytes: a(0) b(1) \r(2) \n(3) c(4) d(5)
745        // Line 0: offset 0, line 1: offset 4
746        let offsets = compute_line_offsets("ab\r\ncd");
747        assert_eq!(offsets, vec![0, 4]);
748    }
749
750    // ── byte_offset_to_line_col edge cases ──────────────────────
751
752    #[test]
753    fn line_col_empty_file_offset_zero() {
754        let offsets = compute_line_offsets("");
755        let (line, col) = byte_offset_to_line_col(&offsets, 0);
756        assert_eq!((line, col), (1, 0));
757    }
758
759    // ── FunctionComplexity bitcode roundtrip ──────────────────────
760
761    #[test]
762    fn function_complexity_bitcode_roundtrip() {
763        let fc = FunctionComplexity {
764            name: "processData".to_string(),
765            line: 42,
766            col: 4,
767            cyclomatic: 15,
768            cognitive: 25,
769            line_count: 80,
770            param_count: 3,
771        };
772        let bytes = bitcode::encode(&fc);
773        let decoded: FunctionComplexity = bitcode::decode(&bytes).unwrap();
774        assert_eq!(decoded.name, "processData");
775        assert_eq!(decoded.line, 42);
776        assert_eq!(decoded.col, 4);
777        assert_eq!(decoded.cyclomatic, 15);
778        assert_eq!(decoded.cognitive, 25);
779        assert_eq!(decoded.line_count, 80);
780    }
781}