Skip to main content

js2zig_core/
sourcemap.rs

1//! Source map: tracks JS source locations → generated Zig line numbers.
2//!
3//! Two output formats:
4//! - Inline comments: `// @src(file.js:42)` embedded in generated Zig
5//! - JSON mapping file: `{ "mappings": [...] }` for tooling
6
7use serde::Serialize;
8
9/// Pre-computed line-start byte offsets for O(log n) byte→line lookup.
10pub struct LineIndex {
11    /// Byte offset of the start of each line (0-indexed).
12    /// line_starts[0] = 0, line_starts[1] = offset after first '\n', etc.
13    line_starts: Vec<u32>,
14}
15
16impl LineIndex {
17    /// Build a LineIndex from source text.
18    pub fn new(source: &str) -> Self {
19        let mut starts = vec![0u32];
20        for (i, ch) in source.char_indices() {
21            if ch == '\n' {
22                starts.push((i + 1) as u32);
23            }
24        }
25        Self {
26            line_starts: starts,
27        }
28    }
29
30    /// Convert a byte offset to (line, col), both 1-based.
31    pub fn offset_to_line_col(&self, offset: u32) -> (u32, u32) {
32        let line_0 = match self.line_starts.binary_search(&offset) {
33            Ok(exact) => exact,
34            Err(insert) => insert.saturating_sub(1),
35        };
36        let col_0 = offset.saturating_sub(self.line_starts[line_0]);
37        (line_0 as u32 + 1, col_0 + 1)
38    }
39}
40
41/// A single mapping entry: one Zig output line ↔ one JS source location.
42#[derive(Debug, Clone, Serialize)]
43pub struct SourceMapping {
44    /// 1-based line number in generated Zig code
45    pub zig_line: u32,
46    /// Original JS file name (relative)
47    pub js_file: String,
48    /// 1-based line in JS source
49    pub js_line: u32,
50    /// 1-based column in JS source
51    pub js_col: u32,
52    /// Human-readable description (e.g. "function add", "class Person")
53    pub kind: String,
54}
55
56/// Accumulated source map for a single JS→Zig translation.
57#[derive(Debug, Clone, Serialize)]
58pub struct SourceMap {
59    /// The source file name
60    pub source_file: String,
61    /// All collected mappings, sorted by zig_line
62    pub mappings: Vec<SourceMapping>,
63}
64
65impl SourceMap {
66    pub fn new(source_file: &str) -> Self {
67        Self {
68            source_file: source_file.to_string(),
69            mappings: Vec::new(),
70        }
71    }
72
73    /// Record a mapping. `zig_line` is 1-based.
74    pub fn add(&mut self, zig_line: u32, js_line: u32, js_col: u32, kind: &str) {
75        self.mappings.push(SourceMapping {
76            zig_line,
77            js_file: self.source_file.clone(),
78            js_line,
79            js_col,
80            kind: kind.to_string(),
81        });
82    }
83
84    /// Serialize to JSON.
85    pub fn to_json(&self) -> String {
86        serde_json::to_string_pretty(self).unwrap_or_default()
87    }
88}
89
90/// Count newlines in a string to determine the current 1-based line number.
91/// The line *after* the last newline is the current line being written.
92pub fn count_lines(s: &str) -> u32 {
93    s.bytes().filter(|&b| b == b'\n').count() as u32 + 1
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn test_line_index_single_line() {
102        let idx = LineIndex::new("hello world");
103        assert_eq!(idx.offset_to_line_col(0), (1, 1));
104        assert_eq!(idx.offset_to_line_col(5), (1, 6));
105    }
106
107    #[test]
108    fn test_line_index_multi_line() {
109        let idx = LineIndex::new("abc\ndef\nghi");
110        assert_eq!(idx.offset_to_line_col(0), (1, 1)); // 'a'
111        assert_eq!(idx.offset_to_line_col(4), (2, 1)); // 'd'
112        assert_eq!(idx.offset_to_line_col(8), (3, 1)); // 'g'
113        assert_eq!(idx.offset_to_line_col(10), (3, 3)); // 'i'
114    }
115
116    #[test]
117    fn test_count_lines() {
118        assert_eq!(count_lines(""), 1);
119        assert_eq!(count_lines("a"), 1);
120        assert_eq!(count_lines("a\nb"), 2);
121        assert_eq!(count_lines("a\nb\nc\n"), 4);
122    }
123
124    #[test]
125    fn test_source_map_json() {
126        let mut sm = SourceMap::new("test.js");
127        sm.add(1, 1, 1, "function add");
128        let json = sm.to_json();
129        assert!(json.contains("function add"));
130        assert!(json.contains("test.js"));
131    }
132}