diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index be652ce..e27ee17 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeMap; use std::io; use std::io::{BufReader, Read}; @@ -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, @@ -263,6 +266,17 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { .sources_content .map(|x| x.into_iter().map(|v| v.map(Into::into)).collect::>()); + 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()); @@ -272,6 +286,8 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { } } + sm.scopes = scopes; + Ok(sm) } @@ -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, @@ -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, diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs new file mode 100644 index 0000000..21ea03a --- /dev/null +++ b/src/decoder/scope.rs @@ -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); + +impl VlqBuffer { + fn inner_mut(&mut self) -> &mut Vec { + self.0.clear(); + &mut self.0 + } + + fn get(&self, index: usize) -> Result { + 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 ? ?`. +/// +/// This function assumes that the leading `B` has already been stripped, only the +/// numbers remain. `` and `` are relative offsets used to advance +/// the current position, `` and `` 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 { + // Indicates that `` is present and contains a name index. + const NAME_FLAG: u32 = 0x1; + // Indicates that either `` or `` 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 `. +/// +/// This function assumes that the leading `C` has already been stripped, only the +/// numbers remain. `` and `` 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 { + 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 ¤t.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), + } + } + + // 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 +/// . +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 +} diff --git a/src/encoder.rs b/src/encoder.rs index c4e5c8c..52427f9 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -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, @@ -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, @@ -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, @@ -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, diff --git a/src/errors.rs b/src/errors.rs index 01342f9..7a42afc 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -49,6 +49,8 @@ pub enum Error { InvalidRangeMappingIndex(data_encoding::DecodeError), InvalidBase64(char), + /// Invalid scope data + InvalidScopes, } impl From for Error { @@ -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"), } } } diff --git a/src/jsontypes.rs b/src/jsontypes.rs index 9185bf5..da4554a 100644 --- a/src/jsontypes.rs +++ b/src/jsontypes.rs @@ -50,6 +50,8 @@ pub struct RawSourceMap { #[serde(rename = "ignoreList", skip_serializing_if = "Option::is_none")] pub ignore_list: Option>, #[serde(skip_serializing_if = "Option::is_none")] + pub scopes: Option>>, + #[serde(skip_serializing_if = "Option::is_none")] pub x_facebook_offsets: Option>>, #[serde(skip_serializing_if = "Option::is_none")] pub x_metro_module_paths: Option>, diff --git a/src/lib.rs b/src/lib.rs index 7aeccd7..ea0fabc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/types/mod.rs b/src/types/mod.rs index aa011cb..3658348 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::io::{Read, Write}; use std::path::Path; use std::sync::Arc; @@ -14,9 +14,11 @@ use crate::utils::{find_common_prefix, greatest_lower_bound}; use debugid::DebugId; mod index; +mod scope; mod token; pub use index::*; +pub use scope::*; pub use token::*; /// Controls the `SourceMap::rewrite` behavior @@ -244,6 +246,7 @@ pub struct SourceMap { pub(crate) sources_prefixed: Option>>, pub(crate) sources_content: Vec>, pub(crate) ignore_list: BTreeSet, + pub(crate) scopes: BTreeMap, pub(crate) debug_id: Option, } @@ -370,6 +373,7 @@ impl SourceMap { .map(|opt| opt.map(SourceView::new)) .collect(), ignore_list: BTreeSet::default(), + scopes: BTreeMap::new(), debug_id: None, } } @@ -715,7 +719,6 @@ impl SourceMap { } /// Turns a list of tokens into a list of ranges, using the provided `key` function to determine the order of the tokens. - #[allow(clippy::ptr_arg)] fn create_ranges( tokens: &mut [RawToken], key: fn(&RawToken) -> (u32, u32), @@ -814,7 +817,7 @@ impl SourceMap { #[cfg(test)] mod tests { - use std::collections::BTreeSet; + use std::collections::{BTreeMap, BTreeSet}; use super::{DecodedMap, RewriteOptions, SourceMap}; use debugid::DebugId; @@ -939,6 +942,7 @@ mod tests { sources_prefixed: None, sources_content: vec![], ignore_list: BTreeSet::new(), + scopes: BTreeMap::new(), debug_id: None, }); @@ -957,6 +961,7 @@ mod tests { sources_prefixed: None, sources_content: vec![], ignore_list: BTreeSet::new(), + scopes: BTreeMap::new(), debug_id: Some(DEBUG_ID.parse().expect("valid debug id")), }) ); diff --git a/src/types/scope.rs b/src/types/scope.rs new file mode 100644 index 0000000..0add677 --- /dev/null +++ b/src/types/scope.rs @@ -0,0 +1,129 @@ +use crate::SourceMap; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct RawOriginalScope { + pub(crate) start_line: u32, + pub(crate) start_col: u32, + pub(crate) end_line: u32, + pub(crate) end_col: u32, + pub(crate) name_id: u32, + pub(crate) kind_id: u32, + pub(crate) is_stack_frame: bool, + pub(crate) children: Vec, + pub(crate) parent: Option, +} + +/// A lexical scope in an original source file. +#[derive(Debug, Clone)] +pub struct OriginalScope<'a> { + sm: &'a SourceMap, + scopes: &'a [RawOriginalScope], + raw: &'a RawOriginalScope, +} + +impl<'a> OriginalScope<'a> { + /// The original name of this scope (e.g. the class or function name). + pub fn get_name(&self) -> Option<&'a str> { + if self.raw.name_id == !0 { + None + } else { + self.sm.get_name(self.raw.name_id) + } + } + + /// Get this scope's kind. + pub fn get_kind(&self) -> Option<&'a str> { + if self.raw.kind_id == !0 { + None + } else { + self.sm.get_name(self.raw.kind_id) + } + } + + /// Get the scope's (inclusive) start position. + pub fn get_start(&self) -> (u32, u32) { + (self.raw.start_line, self.raw.start_col) + } + + /// Get the scope's (exclusive) end position. + pub fn get_end(&self) -> (u32, u32) { + (self.raw.end_line, self.raw.end_col) + } + + /// Whether this scope would introduce a stack frame when run. + pub fn is_stack_frame(&self) -> bool { + self.raw.is_stack_frame + } + + /// Returns an iterator over this scope's children. + pub fn children(&self) -> OriginalScopeIter<'a> { + OriginalScopeIter { + sm: self.sm, + scopes: self.scopes, + indices: &self.raw.children[..], + } + } + + /// Returns this scope's parent, or `None` if it is a root scope. + pub fn parent(&self) -> Option { + let parent_idx = self.raw.parent?; + let raw = self.scopes.get(parent_idx)?; + + Some(Self { + sm: self.sm, + scopes: self.scopes, + raw, + }) + } +} + +pub struct OriginalScopeIter<'a> { + sm: &'a SourceMap, + scopes: &'a [RawOriginalScope], + indices: &'a [usize], +} + +impl<'a> Iterator for OriginalScopeIter<'a> { + type Item = OriginalScope<'a>; + + fn next(&mut self) -> Option { + let (next, rest) = self.indices.split_first()?; + self.indices = rest; + let raw = self.scopes.get(*next)?; + Some(OriginalScope { + sm: self.sm, + scopes: self.scopes, + raw, + }) + } +} + +impl SourceMap { + /// Returns an iterator over the root scopes for a source. + pub fn scopes_for_source(&self, source_id: u32) -> OriginalScopeIter<'_> { + let (scopes, indices) = match self.scopes.get(&(source_id as usize)) { + Some(scopes) => (&scopes.all_scopes[..], &scopes.roots[..]), + None => (&[][..], &[][..]), + }; + + OriginalScopeIter { + sm: self, + scopes, + indices, + } + } +} + +/// A collection of scopes for one source. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct OriginalScopes { + /// A forest of scopes. + /// + /// Scopes without a parent are root scopes. + /// A scope's parent index as well as its children indices + /// are the indices of its parent and children in this list, + /// respectively. + pub(crate) all_scopes: Vec, + /// The list of indices of root scopes in this collection. + pub(crate) roots: Vec, +}