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