rhaiper-map 0.1.0

Resolve Source Map v3 positions without std, for tracing Rhai runtime errors on-device
Documentation
//! Resolving positions through a Source Map v3 `mappings` string, without `std`.
//!
//! Only the `mappings` field is needed to map a generated position back to a source position, so a
//! device can embed that one string rather than a whole JSON document. Parsing the JSON envelope is
//! the host's job.
//!
//! Columns are in whatever unit the producer used. The `rhaiper` crate writes UTF-16 code units, as
//! the Source Map v3 specification requires; that differs from rhai's own character-counted columns
//! only on lines containing astral-plane characters such as emoji.

#![no_std]

extern crate alloc;

pub mod vlq;

/// A source position recovered from a mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Resolved {
    /// Index into the map's `sources` array.
    pub source: u32,
    /// 0-based line in that source.
    pub line: u32,
    /// 0-based column in that source.
    pub col: u32,
    /// Index into the map's `names` array, for segments that carried one.
    pub name: Option<u32>,
}

/// Maps a generated position back to its source position.
///
/// `gen_line` and `gen_col` are 0-based. Returns the mapping covering `gen_col` — the one with the
/// greatest generated column not exceeding it — or `None` if the line has no mapping at or before
/// that column, or if that region is explicitly unmapped.
///
/// Segments hold deltas, and only the generated column resets per line: source index, line, column
/// and name index accumulate across the whole map. So this decodes from the start each time, which
/// is a single linear pass and allocates nothing.
pub fn resolve(mappings: &str, gen_line: u32, gen_col: u32) -> Option<Resolved> {
    let (mut source, mut line, mut col, mut name_total) = (0u32, 0u32, 0u32, 0u32);
    let mut best: Option<Resolved> = None;

    for (line_no, line_text) in mappings.split(';').enumerate() {
        let mut segment_col: i64 = 0;
        let on_target_line = line_no as u32 == gen_line;
        let covers = |c: i64| on_target_line && c <= i64::from(gen_col);

        for segment in line_text.split(',') {
            if segment.is_empty() {
                continue;
            }
            let mut d = vlq::Decoder::new(segment);
            segment_col += d.next_value()?;

            let Some(source_delta) = d.next_value() else {
                // A one-field segment marks generated code that deliberately has no source
                // position, so it ends the reach of any earlier mapping on this line.
                if covers(segment_col) {
                    best = None;
                }
                continue;
            };

            source = add(source, source_delta)?;
            line = add(line, d.next_value()?)?;
            col = add(col, d.next_value()?)?;

            // The name field is optional per segment. Its delta feeds a running total shared across
            // the map, but a segment without the field simply has no name.
            let name = match d.next_value() {
                Some(delta) => {
                    name_total = add(name_total, delta)?;
                    Some(name_total)
                }
                None => None,
            };

            // Segments are ordered by generated column, so the last one that fits is the closest.
            if covers(segment_col) {
                best = Some(Resolved {
                    source,
                    line,
                    col,
                    name,
                });
            }
        }

        if on_target_line {
            return best;
        }
    }
    None
}

fn add(base: u32, delta: i64) -> Option<u32> {
    let sum = i64::from(base) + delta;
    (0..=i64::from(u32::MAX))
        .contains(&sum)
        .then_some(sum as u32)
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::String;

    /// Builds a `mappings` string from `(gen_line, gen_col, src_line, src_col)` tuples.
    fn build(entries: &[(u32, u32, u32, u32)]) -> String {
        let mut out = String::new();
        let (mut prev_line, mut prev_col, mut prev_src_line, mut prev_src_col) =
            (0, 0i64, 0i64, 0i64);
        for &(gen_line, gen_col, src_line, src_col) in entries {
            while prev_line < gen_line {
                out.push(';');
                prev_line += 1;
                prev_col = 0;
            }
            if !out.is_empty() && !out.ends_with(';') {
                out.push(',');
            }
            vlq::encode(i64::from(gen_col) - prev_col, &mut out);
            vlq::encode(0, &mut out);
            vlq::encode(i64::from(src_line) - prev_src_line, &mut out);
            vlq::encode(i64::from(src_col) - prev_src_col, &mut out);
            prev_col = i64::from(gen_col);
            prev_src_line = i64::from(src_line);
            prev_src_col = i64::from(src_col);
        }
        out
    }

    #[test]
    fn resolves_exact_and_interior_positions() {
        let map = build(&[(0, 0, 0, 0), (0, 4, 0, 8), (1, 0, 3, 2)]);

        assert_eq!(resolve(&map, 0, 0).unwrap().col, 0);
        // Interior of the first mapping still resolves to it.
        assert_eq!(resolve(&map, 0, 3).unwrap().col, 0);
        assert_eq!(resolve(&map, 0, 4).unwrap().col, 8);
        assert_eq!(resolve(&map, 0, 99).unwrap().col, 8);

        let second = resolve(&map, 1, 0).unwrap();
        assert_eq!((second.line, second.col), (3, 2));
    }

    #[test]
    fn unmapped_before_first_segment_and_past_last_line() {
        let map = build(&[(0, 4, 0, 8)]);
        assert_eq!(resolve(&map, 0, 0), None);
        assert_eq!(resolve(&map, 7, 0), None);
    }

    #[test]
    fn deltas_accumulate_across_lines() {
        // Source columns must keep accumulating even though generated columns reset per line.
        let map = build(&[(0, 0, 0, 0), (1, 0, 1, 10), (2, 0, 2, 4)]);
        assert_eq!(
            (
                resolve(&map, 1, 0).unwrap().line,
                resolve(&map, 1, 0).unwrap().col
            ),
            (1, 10)
        );
        assert_eq!(
            (
                resolve(&map, 2, 0).unwrap().line,
                resolve(&map, 2, 0).unwrap().col
            ),
            (2, 4)
        );
    }

    #[test]
    fn one_field_segment_unmaps_the_region() {
        let mut map = build(&[(0, 0, 0, 0)]);
        map.push(',');
        vlq::encode(4, &mut map); // generated column 4, no source fields
        assert_eq!(resolve(&map, 0, 0).unwrap().col, 0);
        assert_eq!(resolve(&map, 0, 4), None);
    }

    #[test]
    fn rejects_malformed_input() {
        assert_eq!(resolve("!!!", 0, 0), None);
    }
}