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