Skip to content
18 changes: 18 additions & 0 deletions src/decoder/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::BTreeMap;
use std::io;
use std::io::{BufReader, Read};

Expand All @@ -12,6 +13,8 @@ use crate::jsontypes::RawSourceMap;
use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection};
use crate::vlq::parse_vlq_segment_into;

mod scope;

#[derive(PartialEq, Eq)]
enum HeaderState {
Undecided,
Expand Down Expand Up @@ -263,6 +266,17 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result<SourceMap> {
.sources_content
.map(|x| x.into_iter().map(|v| v.map(Into::into)).collect::<Vec<_>>());

let mut scopes = BTreeMap::new();

for (idx, items) in rsm.scopes.iter().flatten().enumerate() {
match items.as_ref() {
None => continue,
Some(items) => {
scopes.insert(idx, scope::decode_scopes(items)?);
}
}
}

let mut sm = SourceMap::new(file, tokens, names, sources, source_content);
sm.set_source_root(rsm.source_root);
sm.set_debug_id(rsm.debug_id.into());
Expand All @@ -272,6 +286,8 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result<SourceMap> {
}
}

sm.scopes = scopes;

Ok(sm)
}

Expand Down Expand Up @@ -422,6 +438,7 @@ mod tests {
range_mappings: None,
mappings: None,
ignore_list: None,
scopes: None,
x_facebook_offsets: None,
x_metro_module_paths: None,
x_facebook_sources: None,
Expand Down Expand Up @@ -450,6 +467,7 @@ mod tests {
range_mappings: None,
mappings: None,
ignore_list: None,
scopes: None,
x_facebook_offsets: None,
x_metro_module_paths: None,
x_facebook_sources: None,
Expand Down
243 changes: 243 additions & 0 deletions src/decoder/scope.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
use crate::types::{OriginalScopes, RawOriginalScope};
use crate::{vlq, Error, Result};

#[derive(Debug, Clone, Default)]
struct PositionAccumulator {
line: u32,
column: u32,
}

impl PositionAccumulator {
fn advance(&mut self, line_incr: u32, col_incr: u32) -> (u32, u32) {
if line_incr == 0 {
self.column = self.column.saturating_add(col_incr);
} else {
self.line = self.line.saturating_add(line_incr);
self.column = col_incr;
}

(self.line, self.column)
}
}

#[derive(Debug, Clone, Default)]
struct IndexAccumulator(u32);

impl IndexAccumulator {
fn add(&mut self, incr: i32) -> u32 {
self.0 = self.0.saturating_add_signed(incr);
self.0
}
}

#[derive(Debug, Clone, Default)]
struct VlqBuffer(Vec<i64>);

impl VlqBuffer {
fn inner_mut(&mut self) -> &mut Vec<i64> {
self.0.clear();
&mut self.0
}

fn get(&self, index: usize) -> Result<i32> {
let n = self
.0
.get(index)
.ok_or(Error::BadSegmentSize(self.0.len() as u32))?;
Ok(*n as i32)
}
}

/// Running state for decoding the scopes for a source.
#[derive(Debug, Clone, Default)]
struct DecodeScopeState {
/// The running position, used for the start and end of scopes.
position: PositionAccumulator,
/// The running name index.
name_idx: IndexAccumulator,
/// The running kind index.
kind_idx: IndexAccumulator,
/// Buffer for decoding VLQs.
vlq_buffer: VlqBuffer,
}

impl DecodeScopeState {
fn decode_vlq(&mut self, segment: &str) -> Result<&VlqBuffer> {
vlq::parse_vlq_segment_into(segment, self.vlq_buffer.inner_mut())?;
Ok(&self.vlq_buffer)
}
}

/// Scope start entries are of the form
/// `B <flags> <line> <column> <name_or_kind>? <kind>?`.
///
/// This function assumes that the leading `B` has already been stripped, only the
/// numbers remain. `<line>` and `<column>` are relative offsets used to advance
/// the current position, `<name>` and `<kind>` are relative offsets used to advance
/// the respective indices in the decoding state.
///
/// This returns a partial `RawOriginalScope` in which the children and end position
/// aren't filled in yet. They are backfilled when the scope is closed by `decode_scope_end`.
fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result<RawOriginalScope> {
// Indicates that `<name_or_kind>` is present and contains a name index.
const NAME_FLAG: u32 = 0x1;
// Indicates that either `<name_or_kind>` or `<kind>` is present and contains
// a kind index, depending on whether `NAME_FLAG` is also set.
const KIND_FLAG: u32 = 0x2;
// Indicates that this scope creates a stack frame.
const STACKFRAME_FLAG: u32 = 0x4;

let nums = state.decode_vlq(item)?;

let flags = unsigned(nums.get(0)?);
let line = unsigned(nums.get(1)?);
let column = unsigned(nums.get(2)?);

let has_name = (flags & NAME_FLAG) > 0;
let has_kind = (flags & KIND_FLAG) > 0;
let is_stack_frame = (flags & STACKFRAME_FLAG) > 0;

let (name_id, kind_id) = match (has_name, has_kind) {
(false, false) => (None, None),
(true, false) => (Some(nums.get(3)?), None),
(false, true) => (None, Some(nums.get(3)?)),
(true, true) => (Some(nums.get(3)?), Some(nums.get(4)?)),
};

let (start_line, start_col) = state.position.advance(line, column);
let name_id = name_id.map_or(u32::MAX, |name_incr| state.name_idx.add(name_incr));
let kind_id = kind_id.map_or(u32::MAX, |kind_incr| state.kind_idx.add(kind_incr));

Ok(RawOriginalScope {
start_line,
start_col,
end_line: start_line,
end_col: start_col,
name_id,
kind_id,
is_stack_frame,
parent: None,
children: Vec::new(),
})
}

/// Scope start entries are of the form `C <line> <column>`.
///
/// This function assumes that the leading `C` has already been stripped, only the
/// numbers remain. `<line>` and `<column>` are relative offsets used to advance
/// the current position.
///
/// This returns a `line` and `column` that are used to fill in the end position
/// of the scope closed by this record.
fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u32)> {
let nums = state.decode_vlq(item)?;
let line = unsigned(nums.get(0)?);
let column = unsigned(nums.get(1)?);

Ok(state.position.advance(line, column))
}

/// Decodes one entry in a sourcemap's `scopes` array, containing
/// scope information corresponding to one particular source file.
///
/// The textual format is a comma-separated list of records. Each record
/// must start with `B`, in which case it starts a scope, or `C`, in which
/// case it ends a previously started scope, or `D`, in which case it
/// contains variable information for the current scope. Variables aren't
/// currently handled.
///
/// Scope trees are encoded by simply nesting `B` and `C` records appropriately.
///
/// The returned struct contains the parsed scopes in post-order in the `all_scopes`
/// field. Each scope's `children` list contains the indices of its children
/// (which precede it) in `all_scopes`. Furthermore, the `roots` field contains
/// the indices of the elements of `all_scopes` which are root scopes.
pub fn decode_scopes(items: &str) -> Result<OriginalScopes> {
if items.is_empty() {
return Ok(Default::default());
}

// A stack of nested in-progress scopes.
let mut in_progress = vec![];
let mut state = DecodeScopeState::default();
let mut out = OriginalScopes::default();

for item in items.split(',') {
match item.split_at_checked(1) {
Some(("B", start)) => {
in_progress.push(decode_scope_start(start, &mut state)?);
}
Some(("C", end)) => {
// If there's no scope in progress, we have unbalanced start and end records.
let mut current = match in_progress.pop() {
Some(current) => current,
None => return Err(Error::InvalidScopes),
};

let (end_line, end_col) = decode_scope_end(end, &mut state)?;
current.end_line = end_line;
current.end_col = end_col;

// The index the current scope will have in the output list.
let current_idx = out.all_scopes.len();

// If there's a scope in progress before the current one,
// we add the current one to its children.
if let Some(parent) = in_progress.last_mut() {
parent.children.push(current_idx);
}

// We can now go back over the current scope's children (previously
// written) and set the parent.
for &child_idx in &current.children {
out.all_scopes[child_idx].parent = Some(current_idx);
}

out.all_scopes.push(current);

// If there's nothing left on the stack, then this was a
// root scope.
if in_progress.is_empty() {
out.roots.push(current_idx);
}
}
Some(("D", _vars)) => {
// variables would be handled here
}
_ => return Err(Error::InvalidScopes),
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// If the `in_progress` stack isn't empty at the point
// where we run out of records, we have unbalanced
// start and end records.
if !in_progress.is_empty() {
return Err(Error::InvalidScopes);
}

Ok(out)
}

/// Reinterprets a signed VLQ as an unsigned number.
///
/// This reverts the operation described in
/// <https://tc39.es/ecma426/branch/proposal-scopes/#sec-VLQSignedValue>.
fn unsigned(mut vlq: i32) -> u32 {
if vlq == i32::MIN {
return 1;
}

let neg = vlq < 0;

if neg {
vlq = -vlq;
}

vlq <<= 1;

if neg {
vlq |= 1;
}

vlq as u32
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
4 changes: 4 additions & 0 deletions src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ impl Encodable for SourceMap {
} else {
Some(self.ignore_list.iter().cloned().collect())
},
scopes: None,
x_facebook_offsets: None,
x_metro_module_paths: None,
x_facebook_sources: None,
Expand Down Expand Up @@ -209,6 +210,7 @@ impl Encodable for SourceMapIndex {
range_mappings: None,
mappings: None,
ignore_list: None,
scopes: None,
x_facebook_offsets: None,
x_metro_module_paths: None,
x_facebook_sources: None,
Expand Down Expand Up @@ -272,6 +274,7 @@ mod tests {
range_mappings: None,
mappings: None,
ignore_list: None,
scopes: None,
x_facebook_offsets: None,
x_metro_module_paths: None,
x_facebook_sources: None,
Expand Down Expand Up @@ -301,6 +304,7 @@ mod tests {
range_mappings: None,
mappings: None,
ignore_list: None,
scopes: None,
x_facebook_offsets: None,
x_metro_module_paths: None,
x_facebook_sources: None,
Expand Down
3 changes: 3 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub enum Error {
InvalidRangeMappingIndex(data_encoding::DecodeError),

InvalidBase64(char),
/// Invalid scope data
InvalidScopes,
}

impl From<io::Error> for Error {
Expand Down Expand Up @@ -126,6 +128,7 @@ impl fmt::Display for Error {
Error::NotARamBundle => write!(f, "not a ram bundle"),
Error::InvalidRangeMappingIndex(err) => write!(f, "invalid range mapping index: {err}"),
Error::InvalidBase64(c) => write!(f, "invalid base64 character: {c}"),
Error::InvalidScopes => write!(f, "invalid scope data in sourcemap"),
}
}
}
2 changes: 2 additions & 0 deletions src/jsontypes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ pub struct RawSourceMap {
#[serde(rename = "ignoreList", skip_serializing_if = "Option::is_none")]
pub ignore_list: Option<Vec<u32>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scopes: Option<Vec<Option<String>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub x_facebook_offsets: Option<Vec<Option<u32>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub x_metro_module_paths: Option<Vec<String>>,
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ pub use crate::errors::{Error, Result};
pub use crate::hermes::SourceMapHermes;
pub use crate::sourceview::SourceView;
pub use crate::types::{
DecodedMap, NameIter, RawToken, RewriteOptions, SourceContentsIter, SourceIter, SourceMap,
SourceMapIndex, SourceMapSection, SourceMapSectionIter, Token, TokenIter,
DecodedMap, NameIter, OriginalScope, OriginalScopeIter, RawToken, RewriteOptions,
SourceContentsIter, SourceIter, SourceMap, SourceMapIndex, SourceMapSection,
SourceMapSectionIter, Token, TokenIter,
};
pub use crate::utils::make_relative_path;

Expand Down
Loading
Loading