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/// An export declaration.
180#[derive(Debug, Clone, serde::Serialize)]
181pub struct ExportInfo {
182    /// The exported name (named or default).
183    pub name: ExportName,
184    /// The local binding name, if different from the exported name.
185    pub local_name: Option<String>,
186    /// Whether this is a type-only export (`export type`).
187    pub is_type_only: bool,
188    /// Whether this export has a `@public` JSDoc/TSDoc tag.
189    /// Exports marked `@public` are never reported as unused — they are
190    /// assumed to be consumed by external consumers (library API surface).
191    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
192    pub is_public: bool,
193    /// Source span of the export declaration.
194    #[serde(serialize_with = "serialize_span")]
195    pub span: Span,
196    /// Members of this export (for enums, classes, and namespaces).
197    #[serde(default, skip_serializing_if = "Vec::is_empty")]
198    pub members: Vec<MemberInfo>,
199    /// The local name of the parent class from `extends` clause, if any.
200    /// Used to build inheritance maps for unused class member detection.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub super_class: Option<String>,
203}
204
205/// A member of an enum, class, or namespace.
206#[derive(Debug, Clone, serde::Serialize)]
207pub struct MemberInfo {
208    /// Member name.
209    pub name: String,
210    /// The kind of member (enum, class method/property, or namespace member).
211    pub kind: MemberKind,
212    /// Source span of the member declaration.
213    #[serde(serialize_with = "serialize_span")]
214    pub span: Span,
215    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
216    /// Decorated members are used by frameworks at runtime and should not be
217    /// flagged as unused class members.
218    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
219    pub has_decorator: bool,
220}
221
222/// The kind of member.
223///
224/// # Examples
225///
226/// ```
227/// use fallow_types::extract::MemberKind;
228///
229/// let kind = MemberKind::EnumMember;
230/// assert_eq!(kind, MemberKind::EnumMember);
231/// assert_ne!(kind, MemberKind::ClassMethod);
232/// assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
233/// ```
234#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
235#[serde(rename_all = "snake_case")]
236pub enum MemberKind {
237    /// A TypeScript enum member.
238    EnumMember,
239    /// A class method.
240    ClassMethod,
241    /// A class property.
242    ClassProperty,
243    /// A member exported from a TypeScript namespace.
244    NamespaceMember,
245}
246
247/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
248///
249/// # Examples
250///
251/// ```
252/// use fallow_types::extract::MemberAccess;
253///
254/// let access = MemberAccess {
255///     object: "Status".to_string(),
256///     member: "Active".to_string(),
257/// };
258/// assert_eq!(access.object, "Status");
259/// assert_eq!(access.member, "Active");
260/// ```
261#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
262pub struct MemberAccess {
263    /// The identifier being accessed (the import name).
264    pub object: String,
265    /// The member being accessed.
266    pub member: String,
267}
268
269#[expect(
270    clippy::trivially_copy_pass_by_ref,
271    reason = "serde serialize_with requires &T"
272)]
273fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
274    use serde::ser::SerializeMap;
275    let mut map = serializer.serialize_map(Some(2))?;
276    map.serialize_entry("start", &span.start)?;
277    map.serialize_entry("end", &span.end)?;
278    map.end()
279}
280
281/// Export identifier.
282///
283/// # Examples
284///
285/// ```
286/// use fallow_types::extract::ExportName;
287///
288/// let named = ExportName::Named("foo".to_string());
289/// assert_eq!(named.to_string(), "foo");
290/// assert!(named.matches_str("foo"));
291///
292/// let default = ExportName::Default;
293/// assert_eq!(default.to_string(), "default");
294/// assert!(default.matches_str("default"));
295/// ```
296#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
297pub enum ExportName {
298    /// A named export (e.g., `export const foo`).
299    Named(String),
300    /// The default export.
301    Default,
302}
303
304impl ExportName {
305    /// Compare against a string without allocating (avoids `to_string()`).
306    #[must_use]
307    pub fn matches_str(&self, s: &str) -> bool {
308        match self {
309            Self::Named(n) => n == s,
310            Self::Default => s == "default",
311        }
312    }
313}
314
315impl std::fmt::Display for ExportName {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        match self {
318            Self::Named(n) => write!(f, "{n}"),
319            Self::Default => write!(f, "default"),
320        }
321    }
322}
323
324/// An import declaration.
325#[derive(Debug, Clone)]
326pub struct ImportInfo {
327    /// The import specifier (e.g., `./utils` or `react`).
328    pub source: String,
329    /// How the symbol is imported (named, default, namespace, or side-effect).
330    pub imported_name: ImportedName,
331    /// The local binding name in the importing module.
332    pub local_name: String,
333    /// Whether this is a type-only import (`import type`).
334    pub is_type_only: bool,
335    /// Source span of the import declaration.
336    pub span: Span,
337    /// Span of the source string literal (e.g., the `'./utils'` in `import { foo } from './utils'`).
338    /// Used by the LSP to highlight just the specifier in diagnostics.
339    pub source_span: Span,
340}
341
342/// How a symbol is imported.
343///
344/// # Examples
345///
346/// ```
347/// use fallow_types::extract::ImportedName;
348///
349/// let named = ImportedName::Named("useState".to_string());
350/// assert_eq!(named, ImportedName::Named("useState".to_string()));
351/// assert_ne!(named, ImportedName::Default);
352///
353/// // Side-effect imports have no binding
354/// assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
355/// ```
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub enum ImportedName {
358    /// A named import (e.g., `import { foo }`).
359    Named(String),
360    /// A default import (e.g., `import React`).
361    Default,
362    /// A namespace import (e.g., `import * as utils`).
363    Namespace,
364    /// A side-effect import (e.g., `import './styles.css'`).
365    SideEffect,
366}
367
368// Size assertions to prevent memory regressions in hot-path types.
369// These types are stored in Vecs inside `ModuleInfo` (one per file) and are
370// iterated during graph construction and analysis. Keeping them compact
371// improves cache locality on large projects with thousands of files.
372#[cfg(target_pointer_width = "64")]
373const _: () = assert!(std::mem::size_of::<ExportInfo>() == 112);
374#[cfg(target_pointer_width = "64")]
375const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
376#[cfg(target_pointer_width = "64")]
377const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
378#[cfg(target_pointer_width = "64")]
379const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
380#[cfg(target_pointer_width = "64")]
381const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
382// `ModuleInfo` is the per-file extraction result — stored in a Vec during parallel parsing.
383#[cfg(target_pointer_width = "64")]
384const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 328);
385
386/// A re-export declaration.
387#[derive(Debug, Clone)]
388pub struct ReExportInfo {
389    /// The module being re-exported from.
390    pub source: String,
391    /// The name imported from the source module (or `*` for star re-exports).
392    pub imported_name: String,
393    /// The name exported from this module.
394    pub exported_name: String,
395    /// Whether this is a type-only re-export.
396    pub is_type_only: bool,
397}
398
399/// A dynamic `import()` call.
400#[derive(Debug, Clone)]
401pub struct DynamicImportInfo {
402    /// The import specifier.
403    pub source: String,
404    /// Source span of the `import()` expression.
405    pub span: Span,
406    /// Names destructured from the dynamic import result.
407    /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
408    /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
409    pub destructured_names: Vec<String>,
410    /// The local variable name for `const x = await import(...)`.
411    /// Used for namespace import narrowing via member access tracking.
412    pub local_name: Option<String>,
413}
414
415/// A `require()` call.
416#[derive(Debug, Clone)]
417pub struct RequireCallInfo {
418    /// The require specifier.
419    pub source: String,
420    /// Source span of the `require()` call.
421    pub span: Span,
422    /// Names destructured from the `require()` result.
423    /// Non-empty means `const { a, b } = require(...)` -> Named imports.
424    /// Empty means simple `require(...)` or `const x = require(...)` -> Namespace.
425    pub destructured_names: Vec<String>,
426    /// The local variable name for `const x = require(...)`.
427    /// Used for namespace import narrowing via member access tracking.
428    pub local_name: Option<String>,
429}
430
431/// Result of parsing all files, including incremental cache statistics.
432pub struct ParseResult {
433    /// Extracted module information for all successfully parsed files.
434    pub modules: Vec<ModuleInfo>,
435    /// Number of files whose parse results were loaded from cache (unchanged).
436    pub cache_hits: usize,
437    /// Number of files that required a full parse (new or changed).
438    pub cache_misses: usize,
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    // ── compute_line_offsets ──────────────────────────────────────────
446
447    #[test]
448    fn line_offsets_empty_string() {
449        assert_eq!(compute_line_offsets(""), vec![0]);
450    }
451
452    #[test]
453    fn line_offsets_single_line_no_newline() {
454        assert_eq!(compute_line_offsets("hello"), vec![0]);
455    }
456
457    #[test]
458    fn line_offsets_single_line_with_newline() {
459        // "hello\n" => line 0 starts at 0, line 1 starts at 6
460        assert_eq!(compute_line_offsets("hello\n"), vec![0, 6]);
461    }
462
463    #[test]
464    fn line_offsets_multiple_lines() {
465        // "abc\ndef\nghi"
466        // line 0: offset 0 ("abc")
467        // line 1: offset 4 ("def")
468        // line 2: offset 8 ("ghi")
469        assert_eq!(compute_line_offsets("abc\ndef\nghi"), vec![0, 4, 8]);
470    }
471
472    #[test]
473    fn line_offsets_trailing_newline() {
474        // "abc\ndef\n"
475        // line 0: offset 0, line 1: offset 4, line 2: offset 8 (empty line after trailing \n)
476        assert_eq!(compute_line_offsets("abc\ndef\n"), vec![0, 4, 8]);
477    }
478
479    #[test]
480    fn line_offsets_consecutive_newlines() {
481        // "\n\n\n" = 3 newlines => 4 lines
482        assert_eq!(compute_line_offsets("\n\n\n"), vec![0, 1, 2, 3]);
483    }
484
485    #[test]
486    fn line_offsets_multibyte_utf8() {
487        // "á\n" => 'á' is 2 bytes (0xC3 0xA1), '\n' at byte 2 => next line at byte 3
488        assert_eq!(compute_line_offsets("á\n"), vec![0, 3]);
489    }
490
491    // ── byte_offset_to_line_col ──────────────────────────────────────
492
493    #[test]
494    fn line_col_offset_zero() {
495        let offsets = compute_line_offsets("abc\ndef\nghi");
496        let (line, col) = byte_offset_to_line_col(&offsets, 0);
497        assert_eq!((line, col), (1, 0)); // line 1, col 0
498    }
499
500    #[test]
501    fn line_col_middle_of_first_line() {
502        let offsets = compute_line_offsets("abc\ndef\nghi");
503        let (line, col) = byte_offset_to_line_col(&offsets, 2);
504        assert_eq!((line, col), (1, 2)); // 'c' in "abc"
505    }
506
507    #[test]
508    fn line_col_start_of_second_line() {
509        let offsets = compute_line_offsets("abc\ndef\nghi");
510        // byte 4 = start of "def"
511        let (line, col) = byte_offset_to_line_col(&offsets, 4);
512        assert_eq!((line, col), (2, 0));
513    }
514
515    #[test]
516    fn line_col_middle_of_second_line() {
517        let offsets = compute_line_offsets("abc\ndef\nghi");
518        // byte 5 = 'e' in "def"
519        let (line, col) = byte_offset_to_line_col(&offsets, 5);
520        assert_eq!((line, col), (2, 1));
521    }
522
523    #[test]
524    fn line_col_start_of_third_line() {
525        let offsets = compute_line_offsets("abc\ndef\nghi");
526        // byte 8 = start of "ghi"
527        let (line, col) = byte_offset_to_line_col(&offsets, 8);
528        assert_eq!((line, col), (3, 0));
529    }
530
531    #[test]
532    fn line_col_end_of_file() {
533        let offsets = compute_line_offsets("abc\ndef\nghi");
534        // byte 10 = 'i' (last char)
535        let (line, col) = byte_offset_to_line_col(&offsets, 10);
536        assert_eq!((line, col), (3, 2));
537    }
538
539    #[test]
540    fn line_col_single_line() {
541        let offsets = compute_line_offsets("hello");
542        let (line, col) = byte_offset_to_line_col(&offsets, 3);
543        assert_eq!((line, col), (1, 3));
544    }
545
546    #[test]
547    fn line_col_at_newline_byte() {
548        let offsets = compute_line_offsets("abc\ndef");
549        // byte 3 = the '\n' character itself, still part of line 1
550        let (line, col) = byte_offset_to_line_col(&offsets, 3);
551        assert_eq!((line, col), (1, 3));
552    }
553
554    // ── ExportName ───────────────────────────────────────────────────
555
556    #[test]
557    fn export_name_matches_str_named() {
558        let name = ExportName::Named("foo".to_string());
559        assert!(name.matches_str("foo"));
560        assert!(!name.matches_str("bar"));
561        assert!(!name.matches_str("default"));
562    }
563
564    #[test]
565    fn export_name_matches_str_default() {
566        let name = ExportName::Default;
567        assert!(name.matches_str("default"));
568        assert!(!name.matches_str("foo"));
569    }
570
571    #[test]
572    fn export_name_display_named() {
573        let name = ExportName::Named("myExport".to_string());
574        assert_eq!(name.to_string(), "myExport");
575    }
576
577    #[test]
578    fn export_name_display_default() {
579        let name = ExportName::Default;
580        assert_eq!(name.to_string(), "default");
581    }
582
583    // ── ExportName equality & hashing ────────────────────────────
584
585    #[test]
586    fn export_name_equality_named() {
587        let a = ExportName::Named("foo".to_string());
588        let b = ExportName::Named("foo".to_string());
589        let c = ExportName::Named("bar".to_string());
590        assert_eq!(a, b);
591        assert_ne!(a, c);
592    }
593
594    #[test]
595    fn export_name_equality_default() {
596        let a = ExportName::Default;
597        let b = ExportName::Default;
598        assert_eq!(a, b);
599    }
600
601    #[test]
602    fn export_name_named_not_equal_to_default() {
603        let named = ExportName::Named("default".to_string());
604        let default = ExportName::Default;
605        assert_ne!(named, default);
606    }
607
608    #[test]
609    fn export_name_hash_consistency() {
610        use std::collections::hash_map::DefaultHasher;
611        use std::hash::{Hash, Hasher};
612
613        let mut h1 = DefaultHasher::new();
614        let mut h2 = DefaultHasher::new();
615        ExportName::Named("foo".to_string()).hash(&mut h1);
616        ExportName::Named("foo".to_string()).hash(&mut h2);
617        assert_eq!(h1.finish(), h2.finish());
618    }
619
620    // ── ExportName::matches_str edge cases ───────────────────────
621
622    #[test]
623    fn export_name_matches_str_empty_string() {
624        let name = ExportName::Named(String::new());
625        assert!(name.matches_str(""));
626        assert!(!name.matches_str("foo"));
627    }
628
629    #[test]
630    fn export_name_default_does_not_match_empty() {
631        let name = ExportName::Default;
632        assert!(!name.matches_str(""));
633    }
634
635    // ── ImportedName equality ────────────────────────────────────
636
637    #[test]
638    fn imported_name_equality() {
639        assert_eq!(
640            ImportedName::Named("foo".to_string()),
641            ImportedName::Named("foo".to_string())
642        );
643        assert_ne!(
644            ImportedName::Named("foo".to_string()),
645            ImportedName::Named("bar".to_string())
646        );
647        assert_eq!(ImportedName::Default, ImportedName::Default);
648        assert_eq!(ImportedName::Namespace, ImportedName::Namespace);
649        assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
650        assert_ne!(ImportedName::Default, ImportedName::Namespace);
651        assert_ne!(
652            ImportedName::Named("default".to_string()),
653            ImportedName::Default
654        );
655    }
656
657    // ── MemberKind equality ────────────────────────────────────
658
659    #[test]
660    fn member_kind_equality() {
661        assert_eq!(MemberKind::EnumMember, MemberKind::EnumMember);
662        assert_eq!(MemberKind::ClassMethod, MemberKind::ClassMethod);
663        assert_eq!(MemberKind::ClassProperty, MemberKind::ClassProperty);
664        assert_eq!(MemberKind::NamespaceMember, MemberKind::NamespaceMember);
665        assert_ne!(MemberKind::EnumMember, MemberKind::ClassMethod);
666        assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
667        assert_ne!(MemberKind::NamespaceMember, MemberKind::EnumMember);
668    }
669
670    // ── MemberKind bitcode roundtrip ─────────────────────────────
671
672    #[test]
673    fn member_kind_bitcode_roundtrip() {
674        let kinds = [
675            MemberKind::EnumMember,
676            MemberKind::ClassMethod,
677            MemberKind::ClassProperty,
678            MemberKind::NamespaceMember,
679        ];
680        for kind in &kinds {
681            let bytes = bitcode::encode(kind);
682            let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
683            assert_eq!(&decoded, kind);
684        }
685    }
686
687    // ── MemberAccess bitcode roundtrip ─────────────────────────
688
689    #[test]
690    fn member_access_bitcode_roundtrip() {
691        let access = MemberAccess {
692            object: "Status".to_string(),
693            member: "Active".to_string(),
694        };
695        let bytes = bitcode::encode(&access);
696        let decoded: MemberAccess = bitcode::decode(&bytes).unwrap();
697        assert_eq!(decoded.object, "Status");
698        assert_eq!(decoded.member, "Active");
699    }
700
701    // ── compute_line_offsets with Windows line endings ───────────
702
703    #[test]
704    fn line_offsets_crlf_only_counts_lf() {
705        // \r\n should produce offsets at the \n boundary
706        // "ab\r\ncd" => bytes: a(0) b(1) \r(2) \n(3) c(4) d(5)
707        // Line 0: offset 0, line 1: offset 4
708        let offsets = compute_line_offsets("ab\r\ncd");
709        assert_eq!(offsets, vec![0, 4]);
710    }
711
712    // ── byte_offset_to_line_col edge cases ──────────────────────
713
714    #[test]
715    fn line_col_empty_file_offset_zero() {
716        let offsets = compute_line_offsets("");
717        let (line, col) = byte_offset_to_line_col(&offsets, 0);
718        assert_eq!((line, col), (1, 0));
719    }
720
721    // ── FunctionComplexity bitcode roundtrip ──────────────────────
722
723    #[test]
724    fn function_complexity_bitcode_roundtrip() {
725        let fc = FunctionComplexity {
726            name: "processData".to_string(),
727            line: 42,
728            col: 4,
729            cyclomatic: 15,
730            cognitive: 25,
731            line_count: 80,
732            param_count: 3,
733        };
734        let bytes = bitcode::encode(&fc);
735        let decoded: FunctionComplexity = bitcode::decode(&bytes).unwrap();
736        assert_eq!(decoded.name, "processData");
737        assert_eq!(decoded.line, 42);
738        assert_eq!(decoded.col, 4);
739        assert_eq!(decoded.cyclomatic, 15);
740        assert_eq!(decoded.cognitive, 25);
741        assert_eq!(decoded.line_count, 80);
742    }
743}