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