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 /// Source span of the re-export declaration on this module.
398 /// Used for line-number reporting when an unused re-export is detected.
399 /// Defaults to `Span::default()` (0, 0) for re-exports without a meaningful
400 /// source location (e.g., synthesized in the graph layer).
401 pub span: oxc_span::Span,
402}
403
404/// A dynamic `import()` call.
405#[derive(Debug, Clone)]
406pub struct DynamicImportInfo {
407 /// The import specifier.
408 pub source: String,
409 /// Source span of the `import()` expression.
410 pub span: Span,
411 /// Names destructured from the dynamic import result.
412 /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
413 /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
414 pub destructured_names: Vec<String>,
415 /// The local variable name for `const x = await import(...)`.
416 /// Used for namespace import narrowing via member access tracking.
417 pub local_name: Option<String>,
418}
419
420/// A `require()` call.
421#[derive(Debug, Clone)]
422pub struct RequireCallInfo {
423 /// The require specifier.
424 pub source: String,
425 /// Source span of the `require()` call.
426 pub span: Span,
427 /// Names destructured from the `require()` result.
428 /// Non-empty means `const { a, b } = require(...)` -> Named imports.
429 /// Empty means simple `require(...)` or `const x = require(...)` -> Namespace.
430 pub destructured_names: Vec<String>,
431 /// The local variable name for `const x = require(...)`.
432 /// Used for namespace import narrowing via member access tracking.
433 pub local_name: Option<String>,
434}
435
436/// Result of parsing all files, including incremental cache statistics.
437pub struct ParseResult {
438 /// Extracted module information for all successfully parsed files.
439 pub modules: Vec<ModuleInfo>,
440 /// Number of files whose parse results were loaded from cache (unchanged).
441 pub cache_hits: usize,
442 /// Number of files that required a full parse (new or changed).
443 pub cache_misses: usize,
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 // ── compute_line_offsets ──────────────────────────────────────────
451
452 #[test]
453 fn line_offsets_empty_string() {
454 assert_eq!(compute_line_offsets(""), vec![0]);
455 }
456
457 #[test]
458 fn line_offsets_single_line_no_newline() {
459 assert_eq!(compute_line_offsets("hello"), vec![0]);
460 }
461
462 #[test]
463 fn line_offsets_single_line_with_newline() {
464 // "hello\n" => line 0 starts at 0, line 1 starts at 6
465 assert_eq!(compute_line_offsets("hello\n"), vec![0, 6]);
466 }
467
468 #[test]
469 fn line_offsets_multiple_lines() {
470 // "abc\ndef\nghi"
471 // line 0: offset 0 ("abc")
472 // line 1: offset 4 ("def")
473 // line 2: offset 8 ("ghi")
474 assert_eq!(compute_line_offsets("abc\ndef\nghi"), vec![0, 4, 8]);
475 }
476
477 #[test]
478 fn line_offsets_trailing_newline() {
479 // "abc\ndef\n"
480 // line 0: offset 0, line 1: offset 4, line 2: offset 8 (empty line after trailing \n)
481 assert_eq!(compute_line_offsets("abc\ndef\n"), vec![0, 4, 8]);
482 }
483
484 #[test]
485 fn line_offsets_consecutive_newlines() {
486 // "\n\n\n" = 3 newlines => 4 lines
487 assert_eq!(compute_line_offsets("\n\n\n"), vec![0, 1, 2, 3]);
488 }
489
490 #[test]
491 fn line_offsets_multibyte_utf8() {
492 // "á\n" => 'á' is 2 bytes (0xC3 0xA1), '\n' at byte 2 => next line at byte 3
493 assert_eq!(compute_line_offsets("á\n"), vec![0, 3]);
494 }
495
496 // ── byte_offset_to_line_col ──────────────────────────────────────
497
498 #[test]
499 fn line_col_offset_zero() {
500 let offsets = compute_line_offsets("abc\ndef\nghi");
501 let (line, col) = byte_offset_to_line_col(&offsets, 0);
502 assert_eq!((line, col), (1, 0)); // line 1, col 0
503 }
504
505 #[test]
506 fn line_col_middle_of_first_line() {
507 let offsets = compute_line_offsets("abc\ndef\nghi");
508 let (line, col) = byte_offset_to_line_col(&offsets, 2);
509 assert_eq!((line, col), (1, 2)); // 'c' in "abc"
510 }
511
512 #[test]
513 fn line_col_start_of_second_line() {
514 let offsets = compute_line_offsets("abc\ndef\nghi");
515 // byte 4 = start of "def"
516 let (line, col) = byte_offset_to_line_col(&offsets, 4);
517 assert_eq!((line, col), (2, 0));
518 }
519
520 #[test]
521 fn line_col_middle_of_second_line() {
522 let offsets = compute_line_offsets("abc\ndef\nghi");
523 // byte 5 = 'e' in "def"
524 let (line, col) = byte_offset_to_line_col(&offsets, 5);
525 assert_eq!((line, col), (2, 1));
526 }
527
528 #[test]
529 fn line_col_start_of_third_line() {
530 let offsets = compute_line_offsets("abc\ndef\nghi");
531 // byte 8 = start of "ghi"
532 let (line, col) = byte_offset_to_line_col(&offsets, 8);
533 assert_eq!((line, col), (3, 0));
534 }
535
536 #[test]
537 fn line_col_end_of_file() {
538 let offsets = compute_line_offsets("abc\ndef\nghi");
539 // byte 10 = 'i' (last char)
540 let (line, col) = byte_offset_to_line_col(&offsets, 10);
541 assert_eq!((line, col), (3, 2));
542 }
543
544 #[test]
545 fn line_col_single_line() {
546 let offsets = compute_line_offsets("hello");
547 let (line, col) = byte_offset_to_line_col(&offsets, 3);
548 assert_eq!((line, col), (1, 3));
549 }
550
551 #[test]
552 fn line_col_at_newline_byte() {
553 let offsets = compute_line_offsets("abc\ndef");
554 // byte 3 = the '\n' character itself, still part of line 1
555 let (line, col) = byte_offset_to_line_col(&offsets, 3);
556 assert_eq!((line, col), (1, 3));
557 }
558
559 // ── ExportName ───────────────────────────────────────────────────
560
561 #[test]
562 fn export_name_matches_str_named() {
563 let name = ExportName::Named("foo".to_string());
564 assert!(name.matches_str("foo"));
565 assert!(!name.matches_str("bar"));
566 assert!(!name.matches_str("default"));
567 }
568
569 #[test]
570 fn export_name_matches_str_default() {
571 let name = ExportName::Default;
572 assert!(name.matches_str("default"));
573 assert!(!name.matches_str("foo"));
574 }
575
576 #[test]
577 fn export_name_display_named() {
578 let name = ExportName::Named("myExport".to_string());
579 assert_eq!(name.to_string(), "myExport");
580 }
581
582 #[test]
583 fn export_name_display_default() {
584 let name = ExportName::Default;
585 assert_eq!(name.to_string(), "default");
586 }
587
588 // ── ExportName equality & hashing ────────────────────────────
589
590 #[test]
591 fn export_name_equality_named() {
592 let a = ExportName::Named("foo".to_string());
593 let b = ExportName::Named("foo".to_string());
594 let c = ExportName::Named("bar".to_string());
595 assert_eq!(a, b);
596 assert_ne!(a, c);
597 }
598
599 #[test]
600 fn export_name_equality_default() {
601 let a = ExportName::Default;
602 let b = ExportName::Default;
603 assert_eq!(a, b);
604 }
605
606 #[test]
607 fn export_name_named_not_equal_to_default() {
608 let named = ExportName::Named("default".to_string());
609 let default = ExportName::Default;
610 assert_ne!(named, default);
611 }
612
613 #[test]
614 fn export_name_hash_consistency() {
615 use std::collections::hash_map::DefaultHasher;
616 use std::hash::{Hash, Hasher};
617
618 let mut h1 = DefaultHasher::new();
619 let mut h2 = DefaultHasher::new();
620 ExportName::Named("foo".to_string()).hash(&mut h1);
621 ExportName::Named("foo".to_string()).hash(&mut h2);
622 assert_eq!(h1.finish(), h2.finish());
623 }
624
625 // ── ExportName::matches_str edge cases ───────────────────────
626
627 #[test]
628 fn export_name_matches_str_empty_string() {
629 let name = ExportName::Named(String::new());
630 assert!(name.matches_str(""));
631 assert!(!name.matches_str("foo"));
632 }
633
634 #[test]
635 fn export_name_default_does_not_match_empty() {
636 let name = ExportName::Default;
637 assert!(!name.matches_str(""));
638 }
639
640 // ── ImportedName equality ────────────────────────────────────
641
642 #[test]
643 fn imported_name_equality() {
644 assert_eq!(
645 ImportedName::Named("foo".to_string()),
646 ImportedName::Named("foo".to_string())
647 );
648 assert_ne!(
649 ImportedName::Named("foo".to_string()),
650 ImportedName::Named("bar".to_string())
651 );
652 assert_eq!(ImportedName::Default, ImportedName::Default);
653 assert_eq!(ImportedName::Namespace, ImportedName::Namespace);
654 assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
655 assert_ne!(ImportedName::Default, ImportedName::Namespace);
656 assert_ne!(
657 ImportedName::Named("default".to_string()),
658 ImportedName::Default
659 );
660 }
661
662 // ── MemberKind equality ────────────────────────────────────
663
664 #[test]
665 fn member_kind_equality() {
666 assert_eq!(MemberKind::EnumMember, MemberKind::EnumMember);
667 assert_eq!(MemberKind::ClassMethod, MemberKind::ClassMethod);
668 assert_eq!(MemberKind::ClassProperty, MemberKind::ClassProperty);
669 assert_eq!(MemberKind::NamespaceMember, MemberKind::NamespaceMember);
670 assert_ne!(MemberKind::EnumMember, MemberKind::ClassMethod);
671 assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
672 assert_ne!(MemberKind::NamespaceMember, MemberKind::EnumMember);
673 }
674
675 // ── MemberKind bitcode roundtrip ─────────────────────────────
676
677 #[test]
678 fn member_kind_bitcode_roundtrip() {
679 let kinds = [
680 MemberKind::EnumMember,
681 MemberKind::ClassMethod,
682 MemberKind::ClassProperty,
683 MemberKind::NamespaceMember,
684 ];
685 for kind in &kinds {
686 let bytes = bitcode::encode(kind);
687 let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
688 assert_eq!(&decoded, kind);
689 }
690 }
691
692 // ── MemberAccess bitcode roundtrip ─────────────────────────
693
694 #[test]
695 fn member_access_bitcode_roundtrip() {
696 let access = MemberAccess {
697 object: "Status".to_string(),
698 member: "Active".to_string(),
699 };
700 let bytes = bitcode::encode(&access);
701 let decoded: MemberAccess = bitcode::decode(&bytes).unwrap();
702 assert_eq!(decoded.object, "Status");
703 assert_eq!(decoded.member, "Active");
704 }
705
706 // ── compute_line_offsets with Windows line endings ───────────
707
708 #[test]
709 fn line_offsets_crlf_only_counts_lf() {
710 // \r\n should produce offsets at the \n boundary
711 // "ab\r\ncd" => bytes: a(0) b(1) \r(2) \n(3) c(4) d(5)
712 // Line 0: offset 0, line 1: offset 4
713 let offsets = compute_line_offsets("ab\r\ncd");
714 assert_eq!(offsets, vec![0, 4]);
715 }
716
717 // ── byte_offset_to_line_col edge cases ──────────────────────
718
719 #[test]
720 fn line_col_empty_file_offset_zero() {
721 let offsets = compute_line_offsets("");
722 let (line, col) = byte_offset_to_line_col(&offsets, 0);
723 assert_eq!((line, col), (1, 0));
724 }
725
726 // ── FunctionComplexity bitcode roundtrip ──────────────────────
727
728 #[test]
729 fn function_complexity_bitcode_roundtrip() {
730 let fc = FunctionComplexity {
731 name: "processData".to_string(),
732 line: 42,
733 col: 4,
734 cyclomatic: 15,
735 cognitive: 25,
736 line_count: 80,
737 param_count: 3,
738 };
739 let bytes = bitcode::encode(&fc);
740 let decoded: FunctionComplexity = bitcode::decode(&bytes).unwrap();
741 assert_eq!(decoded.name, "processData");
742 assert_eq!(decoded.line, 42);
743 assert_eq!(decoded.col, 4);
744 assert_eq!(decoded.cyclomatic, 15);
745 assert_eq!(decoded.cognitive, 25);
746 assert_eq!(decoded.line_count, 80);
747 }
748}