Skip to main content

rhaiper_map/
lib.rs

1//! Resolving positions through a Source Map v3 `mappings` string, without `std`.
2//!
3//! Only the `mappings` field is needed to map a generated position back to a source position, so a
4//! device can embed that one string rather than a whole JSON document. Parsing the JSON envelope is
5//! the host's job.
6//!
7//! Columns are in whatever unit the producer used. The `rhaiper` crate writes UTF-16 code units, as
8//! the Source Map v3 specification requires; that differs from rhai's own character-counted columns
9//! only on lines containing astral-plane characters such as emoji.
10
11#![no_std]
12
13extern crate alloc;
14
15pub mod vlq;
16
17/// A source position recovered from a mapping.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Resolved {
20    /// Index into the map's `sources` array.
21    pub source: u32,
22    /// 0-based line in that source.
23    pub line: u32,
24    /// 0-based column in that source.
25    pub col: u32,
26    /// Index into the map's `names` array, for segments that carried one.
27    pub name: Option<u32>,
28}
29
30/// Maps a generated position back to its source position.
31///
32/// `gen_line` and `gen_col` are 0-based. Returns the mapping covering `gen_col` — the one with the
33/// greatest generated column not exceeding it — or `None` if the line has no mapping at or before
34/// that column, or if that region is explicitly unmapped.
35///
36/// Segments hold deltas, and only the generated column resets per line: source index, line, column
37/// and name index accumulate across the whole map. So this decodes from the start each time, which
38/// is a single linear pass and allocates nothing.
39pub fn resolve(mappings: &str, gen_line: u32, gen_col: u32) -> Option<Resolved> {
40    let (mut source, mut line, mut col, mut name_total) = (0u32, 0u32, 0u32, 0u32);
41    let mut best: Option<Resolved> = None;
42
43    for (line_no, line_text) in mappings.split(';').enumerate() {
44        let mut segment_col: i64 = 0;
45        let on_target_line = line_no as u32 == gen_line;
46        let covers = |c: i64| on_target_line && c <= i64::from(gen_col);
47
48        for segment in line_text.split(',') {
49            if segment.is_empty() {
50                continue;
51            }
52            let mut d = vlq::Decoder::new(segment);
53            segment_col += d.next_value()?;
54
55            let Some(source_delta) = d.next_value() else {
56                // A one-field segment marks generated code that deliberately has no source
57                // position, so it ends the reach of any earlier mapping on this line.
58                if covers(segment_col) {
59                    best = None;
60                }
61                continue;
62            };
63
64            source = add(source, source_delta)?;
65            line = add(line, d.next_value()?)?;
66            col = add(col, d.next_value()?)?;
67
68            // The name field is optional per segment. Its delta feeds a running total shared across
69            // the map, but a segment without the field simply has no name.
70            let name = match d.next_value() {
71                Some(delta) => {
72                    name_total = add(name_total, delta)?;
73                    Some(name_total)
74                }
75                None => None,
76            };
77
78            // Segments are ordered by generated column, so the last one that fits is the closest.
79            if covers(segment_col) {
80                best = Some(Resolved {
81                    source,
82                    line,
83                    col,
84                    name,
85                });
86            }
87        }
88
89        if on_target_line {
90            return best;
91        }
92    }
93    None
94}
95
96fn add(base: u32, delta: i64) -> Option<u32> {
97    let sum = i64::from(base) + delta;
98    (0..=i64::from(u32::MAX))
99        .contains(&sum)
100        .then_some(sum as u32)
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use alloc::string::String;
107
108    /// Builds a `mappings` string from `(gen_line, gen_col, src_line, src_col)` tuples.
109    fn build(entries: &[(u32, u32, u32, u32)]) -> String {
110        let mut out = String::new();
111        let (mut prev_line, mut prev_col, mut prev_src_line, mut prev_src_col) =
112            (0, 0i64, 0i64, 0i64);
113        for &(gen_line, gen_col, src_line, src_col) in entries {
114            while prev_line < gen_line {
115                out.push(';');
116                prev_line += 1;
117                prev_col = 0;
118            }
119            if !out.is_empty() && !out.ends_with(';') {
120                out.push(',');
121            }
122            vlq::encode(i64::from(gen_col) - prev_col, &mut out);
123            vlq::encode(0, &mut out);
124            vlq::encode(i64::from(src_line) - prev_src_line, &mut out);
125            vlq::encode(i64::from(src_col) - prev_src_col, &mut out);
126            prev_col = i64::from(gen_col);
127            prev_src_line = i64::from(src_line);
128            prev_src_col = i64::from(src_col);
129        }
130        out
131    }
132
133    #[test]
134    fn resolves_exact_and_interior_positions() {
135        let map = build(&[(0, 0, 0, 0), (0, 4, 0, 8), (1, 0, 3, 2)]);
136
137        assert_eq!(resolve(&map, 0, 0).unwrap().col, 0);
138        // Interior of the first mapping still resolves to it.
139        assert_eq!(resolve(&map, 0, 3).unwrap().col, 0);
140        assert_eq!(resolve(&map, 0, 4).unwrap().col, 8);
141        assert_eq!(resolve(&map, 0, 99).unwrap().col, 8);
142
143        let second = resolve(&map, 1, 0).unwrap();
144        assert_eq!((second.line, second.col), (3, 2));
145    }
146
147    #[test]
148    fn unmapped_before_first_segment_and_past_last_line() {
149        let map = build(&[(0, 4, 0, 8)]);
150        assert_eq!(resolve(&map, 0, 0), None);
151        assert_eq!(resolve(&map, 7, 0), None);
152    }
153
154    #[test]
155    fn deltas_accumulate_across_lines() {
156        // Source columns must keep accumulating even though generated columns reset per line.
157        let map = build(&[(0, 0, 0, 0), (1, 0, 1, 10), (2, 0, 2, 4)]);
158        assert_eq!(
159            (
160                resolve(&map, 1, 0).unwrap().line,
161                resolve(&map, 1, 0).unwrap().col
162            ),
163            (1, 10)
164        );
165        assert_eq!(
166            (
167                resolve(&map, 2, 0).unwrap().line,
168                resolve(&map, 2, 0).unwrap().col
169            ),
170            (2, 4)
171        );
172    }
173
174    #[test]
175    fn one_field_segment_unmaps_the_region() {
176        let mut map = build(&[(0, 0, 0, 0)]);
177        map.push(',');
178        vlq::encode(4, &mut map); // generated column 4, no source fields
179        assert_eq!(resolve(&map, 0, 0).unwrap().col, 0);
180        assert_eq!(resolve(&map, 0, 4), None);
181    }
182
183    #[test]
184    fn rejects_malformed_input() {
185        assert_eq!(resolve("!!!", 0, 0), None);
186    }
187}