From 096abb871fc0d8b601276e34f64a4a25f7e5e4f2 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 10:38:36 +0100 Subject: [PATCH 01/13] WIP --- src/decoder/mod.rs | 18 ++++ src/decoder/scopes.rs | 229 ++++++++++++++++++++++++++++++++++++++++++ src/encoder.rs | 4 + src/errors.rs | 3 + src/jsontypes.rs | 2 + src/types/mod.rs | 45 ++++++++- 6 files changed, 298 insertions(+), 3 deletions(-) create mode 100644 src/decoder/scopes.rs diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index be652ce..00b398f 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 scopes; + #[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().enumerate() { + match items.as_ref() { + None => continue, + Some(items) => { + scopes.insert(idx, scopes::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: vec![], 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: vec![], x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, diff --git a/src/decoder/scopes.rs b/src/decoder/scopes.rs new file mode 100644 index 0000000..baf8d99 --- /dev/null +++ b/src/decoder/scopes.rs @@ -0,0 +1,229 @@ +use crate::types::RawOriginalScope; +use crate::Error::BadSegmentSize; +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 + } +} + +/// 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, +} + +/// 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 = vlq::parse_vlq_segment(item)?; + if nums.len() < 3 { + return Err(BadSegmentSize(nums.len() as u32)); + } + + let flags = unsigned(nums[0] as i32); + let line = unsigned(nums[1] as i32); + let column = unsigned(nums[2] as i32); + + 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) => { + if nums.len() < 4 { + return Err(BadSegmentSize(nums.len() as u32)); + } + + (Some(nums[3] as i32), None) + } + (false, true) => { + if nums.len() < 4 { + return Err(BadSegmentSize(nums.len() as u32)); + } + + (None, Some(nums[3] as i32)) + } + (true, true) => { + if nums.len() < 5 { + return Err(BadSegmentSize(nums.len() as u32)); + } + + (Some(nums[3] as i32), Some(nums[4] as i32)) + } + }; + + 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, + 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 = vlq::parse_vlq_segment(item)?; + if nums.len() < 2 { + return Err(BadSegmentSize(nums.len() as u32)); + } + + let line = unsigned(nums[0] as i32); + let column = unsigned(nums[1] as i32); + + 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 entries. Each entry +/// 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` entries appropriately. +/// The returned list of scopes contains the top-level scopes, which in turn +/// contain their children. +pub fn decode_scopes(items: &str) -> Result> { + // List of in-progress scopes, organized by nesting level. + // + // All scopes in `in_progress[j+1]` are children of the last scope in + // `in_progress[j]`. Scopes in `in_progress[0]` are top-level scopes + // which will be returned. + let mut in_progress = vec![vec![]]; + let mut state = DecodeScopeState::default(); + + for item in items.split(',') { + match item.split_at_checked(1) { + Some(("B", start)) => { + in_progress + .last_mut() + .expect("in_progress is never empty") + .push(decode_scope_start(start, &mut state)?); + + // Push a new layer for this scope's children. + in_progress.push(Vec::new()); + } + Some(("C", end)) => { + // Pop the children of the scope that's being ended. + // The layer for the children was added when the scope was started, + // so if this fails, the scope data is malformed. + let children = match in_progress.pop() { + Some(children) => children, + None => return Err(Error::InvalidScopes), + }; + + // The last scope in the last layer (after popping the children) is the scope which is being closed by this end record. + // If it doesn't exist, the end record has no corresponding start record, so the scope data is malformed. + let current = match in_progress.last_mut().and_then(|level| level.last_mut()) { + 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; + current.children = children; + } + Some(("D", _vars)) => { + // variables would be handled here + } + _ => return Err(Error::InvalidScopes), + } + } + + // When we run out of items, exactly one layer of scopes (the top-level ones) should remain. + // Anything else indicates malfored data. + if in_progress.len() != 1 { + return Err(Error::InvalidScopes); + } + + Ok(in_progress.remove(0)) +} + +/// 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..2244959 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: vec![], 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: vec![], 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: vec![], 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: vec![], 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..931c8b9 100644 --- a/src/jsontypes.rs +++ b/src/jsontypes.rs @@ -49,6 +49,8 @@ pub struct RawSourceMap { pub mappings: Option, #[serde(rename = "ignoreList", skip_serializing_if = "Option::is_none")] pub ignore_list: Option>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub scopes: Vec>, #[serde(skip_serializing_if = "Option::is_none")] pub x_facebook_offsets: Option>>, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/src/types/mod.rs b/src/types/mod.rs index aa011cb..9514103 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; @@ -244,6 +244,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 +371,7 @@ impl SourceMap { .map(|opt| opt.map(SourceView::new)) .collect(), ignore_list: BTreeSet::default(), + scopes: BTreeMap::new(), debug_id: None, } } @@ -715,7 +717,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), @@ -812,9 +813,45 @@ impl 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, +} + +#[derive(Debug, Clone)] +pub struct OriginalScope<'a> { + sm: &'a SourceMap, + raw: RawOriginalScope, +} + +impl<'a> OriginalScope<'a> { + pub fn get_name(&self) -> Option<&'a str> { + if self.raw.name_id == !0 { + None + } else { + self.sm.get_name(self.raw.name_id) + } + } + + pub fn get_kind(&self) -> Option<&'a str> { + if self.raw.kind_id == !0 { + None + } else { + self.sm.get_name(self.raw.kind_id) + } + } +} + #[cfg(test)] mod tests { - use std::collections::BTreeSet; + use std::collections::{BTreeMap, BTreeSet}; use super::{DecodedMap, RewriteOptions, SourceMap}; use debugid::DebugId; @@ -939,6 +976,7 @@ mod tests { sources_prefixed: None, sources_content: vec![], ignore_list: BTreeSet::new(), + scopes: BTreeMap::new(), debug_id: None, }); @@ -957,6 +995,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")), }) ); From eb99e4f2e4133d8b197ed8861d3c56309bf06f95 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 13:29:46 +0100 Subject: [PATCH 02/13] nonrecursive --- src/decoder/scopes.rs | 53 +++++++++++++++++++++++++++++++++++++------ src/types/mod.rs | 20 +++++++++++++++- 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/src/decoder/scopes.rs b/src/decoder/scopes.rs index baf8d99..1d5251a 100644 --- a/src/decoder/scopes.rs +++ b/src/decoder/scopes.rs @@ -40,6 +40,16 @@ struct DecodeScopeState { name_idx: IndexAccumulator, /// The running kind index. kind_idx: IndexAccumulator, + /// Buffer for decoding VLQs. + vlq_buffer: Vec, +} + +impl DecodeScopeState { + fn decode_vlq(&mut self, segment: &str) -> Result<&[i64]> { + self.vlq_buffer.clear(); + vlq::parse_vlq_segment_into(segment, &mut self.vlq_buffer)?; + Ok(&self.vlq_buffer[..]) + } } /// Scope start entries are of the form @@ -61,7 +71,7 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result Result Result Result<(u32, u32)> { - let nums = vlq::parse_vlq_segment(item)?; + let nums = state.decode_vlq(item)?; if nums.len() < 2 { return Err(BadSegmentSize(nums.len() as u32)); } @@ -145,8 +156,10 @@ fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u3 /// currently handled. /// /// Scope trees are encoded by simply nesting `B` and `C` entries appropriately. -/// The returned list of scopes contains the top-level scopes, which in turn -/// contain their children. +/// +/// The returned list contains the parsed scopes in post-order. Each scope's +/// `children` list contains the indices of its children (which precede it +/// in the list). pub fn decode_scopes(items: &str) -> Result> { // List of in-progress scopes, organized by nesting level. // @@ -155,6 +168,7 @@ pub fn decode_scopes(items: &str) -> Result> { // which will be returned. let mut in_progress = vec![vec![]]; let mut state = DecodeScopeState::default(); + let mut out: Vec = Vec::new(); for item in items.split(',') { match item.split_at_checked(1) { @@ -186,7 +200,16 @@ pub fn decode_scopes(items: &str) -> Result> { let (end_line, end_col) = decode_scope_end(end, &mut state)?; current.end_line = end_line; current.end_col = end_col; - current.children = children; + + // Append the current scope's children to the output list and + // record their indices in the current scope. + for child in children { + for &grandchild_idx in &child.children { + out[grandchild_idx].parent = Some(out.len()); + } + current.children.push(out.len()); + out.push(child); + } } Some(("D", _vars)) => { // variables would be handled here @@ -196,12 +219,19 @@ pub fn decode_scopes(items: &str) -> Result> { } // When we run out of items, exactly one layer of scopes (the top-level ones) should remain. - // Anything else indicates malfored data. + // Anything else indicates malformed data. if in_progress.len() != 1 { return Err(Error::InvalidScopes); } - Ok(in_progress.remove(0)) + for scope in in_progress.remove(0) { + for &child_idx in &scope.children { + out[child_idx].parent = Some(out.len()); + } + out.push(scope); + } + + Ok(out) } /// Reinterprets a signed VLQ as an unsigned number. @@ -227,3 +257,12 @@ fn unsigned(mut vlq: i32) -> u32 { vlq as u32 } + +#[test] +fn test_decode_scopes() { + let input = "BCCAQ,BHAAAC,BCCaC,CDC,CCA,CCY"; + + let scopes = decode_scopes(input).unwrap(); + dbg!(scopes); + panic!(); +} diff --git a/src/types/mod.rs b/src/types/mod.rs index 9514103..875926f 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -822,7 +822,8 @@ pub(crate) struct RawOriginalScope { pub(crate) name_id: u32, pub(crate) kind_id: u32, pub(crate) is_stack_frame: bool, - pub(crate) children: Vec, + pub(crate) children: Vec, + pub(crate) parent: Option, } #[derive(Debug, Clone)] @@ -832,6 +833,7 @@ pub struct OriginalScope<'a> { } 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 @@ -840,6 +842,7 @@ impl<'a> OriginalScope<'a> { } } + /// Get this scope's kind. pub fn get_kind(&self) -> Option<&'a str> { if self.raw.kind_id == !0 { None @@ -847,6 +850,21 @@ impl<'a> OriginalScope<'a> { 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 + } } #[cfg(test)] From 4ac62a2f1daebe6ae048b9ab0900f13e9d1acfc1 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 14:35:08 +0100 Subject: [PATCH 03/13] docs, cleanup --- src/decoder/mod.rs | 14 ++- src/decoder/{scopes.rs => scope.rs} | 76 +++++----------- src/types/mod.rs | 58 +------------ src/types/scope.rs | 130 ++++++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 111 deletions(-) rename src/decoder/{scopes.rs => scope.rs} (73%) create mode 100644 src/types/scope.rs diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index 00b398f..dc9f892 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -10,10 +10,12 @@ use serde_json::Value; use crate::errors::{Error, Result}; use crate::hermes::decode_hermes; use crate::jsontypes::RawSourceMap; -use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection}; +use crate::types::{ + DecodedMap, OriginalScopes, RawToken, SourceMap, SourceMapIndex, SourceMapSection, +}; use crate::vlq::parse_vlq_segment_into; -mod scopes; +mod scope; #[derive(PartialEq, Eq)] enum HeaderState { @@ -272,7 +274,13 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { match items.as_ref() { None => continue, Some(items) => { - scopes.insert(idx, scopes::decode_scopes(items)?); + let all_scopes = scope::decode_scopes(items)?; + let roots = (0..all_scopes.len()) + .into_iter() + .filter(|idx| all_scopes[*idx].parent.is_none()) + .collect(); + + scopes.insert(idx, OriginalScopes { all_scopes, roots }); } } } diff --git a/src/decoder/scopes.rs b/src/decoder/scope.rs similarity index 73% rename from src/decoder/scopes.rs rename to src/decoder/scope.rs index 1d5251a..d760191 100644 --- a/src/decoder/scopes.rs +++ b/src/decoder/scope.rs @@ -149,50 +149,31 @@ fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u3 /// 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 entries. Each entry +/// 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` entries appropriately. +/// Scope trees are encoded by simply nesting `B` and `C` records appropriately. /// /// The returned list contains the parsed scopes in post-order. Each scope's /// `children` list contains the indices of its children (which precede it /// in the list). pub fn decode_scopes(items: &str) -> Result> { - // List of in-progress scopes, organized by nesting level. - // - // All scopes in `in_progress[j+1]` are children of the last scope in - // `in_progress[j]`. Scopes in `in_progress[0]` are top-level scopes - // which will be returned. - let mut in_progress = vec![vec![]]; + // A stack of nested in-progress scopes. + let mut in_progress = vec![]; let mut state = DecodeScopeState::default(); let mut out: Vec = Vec::new(); for item in items.split(',') { match item.split_at_checked(1) { Some(("B", start)) => { - in_progress - .last_mut() - .expect("in_progress is never empty") - .push(decode_scope_start(start, &mut state)?); - - // Push a new layer for this scope's children. - in_progress.push(Vec::new()); + in_progress.push(decode_scope_start(start, &mut state)?); } Some(("C", end)) => { - // Pop the children of the scope that's being ended. - // The layer for the children was added when the scope was started, - // so if this fails, the scope data is malformed. - let children = match in_progress.pop() { - Some(children) => children, - None => return Err(Error::InvalidScopes), - }; - - // The last scope in the last layer (after popping the children) is the scope which is being closed by this end record. - // If it doesn't exist, the end record has no corresponding start record, so the scope data is malformed. - let current = match in_progress.last_mut().and_then(|level| level.last_mut()) { + // 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), }; @@ -201,15 +182,22 @@ pub fn decode_scopes(items: &str) -> Result> { current.end_line = end_line; current.end_col = end_col; - // Append the current scope's children to the output list and - // record their indices in the current scope. - for child in children { - for &grandchild_idx in &child.children { - out[grandchild_idx].parent = Some(out.len()); - } - current.children.push(out.len()); - out.push(child); + // The index the current scope will have in the output list. + let current_idx = out.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[child_idx].parent = Some(current_idx); } + + out.push(current) } Some(("D", _vars)) => { // variables would be handled here @@ -218,19 +206,10 @@ pub fn decode_scopes(items: &str) -> Result> { } } - // When we run out of items, exactly one layer of scopes (the top-level ones) should remain. - // Anything else indicates malformed data. - if in_progress.len() != 1 { + if !in_progress.is_empty() { return Err(Error::InvalidScopes); } - for scope in in_progress.remove(0) { - for &child_idx in &scope.children { - out[child_idx].parent = Some(out.len()); - } - out.push(scope); - } - Ok(out) } @@ -257,12 +236,3 @@ fn unsigned(mut vlq: i32) -> u32 { vlq as u32 } - -#[test] -fn test_decode_scopes() { - let input = "BCCAQ,BHAAAC,BCCaC,CDC,CCA,CCY"; - - let scopes = decode_scopes(input).unwrap(); - dbg!(scopes); - panic!(); -} diff --git a/src/types/mod.rs b/src/types/mod.rs index 875926f..3658348 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -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,7 +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) scopes: BTreeMap, pub(crate) debug_id: Option, } @@ -813,60 +815,6 @@ impl 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, -} - -#[derive(Debug, Clone)] -pub struct OriginalScope<'a> { - sm: &'a SourceMap, - raw: 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 - } -} - #[cfg(test)] mod tests { use std::collections::{BTreeMap, BTreeSet}; diff --git a/src/types/scope.rs b/src/types/scope.rs new file mode 100644 index 0000000..62c1d3a --- /dev/null +++ b/src/types/scope.rs @@ -0,0 +1,130 @@ +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, + raw: &'a RawOriginalScope, + source: usize, +} + +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, + source: self.source, + 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 scopes = self.sm.scopes.get(&self.source)?; + let raw = scopes.all_scopes.get(parent_idx)?; + + Some(Self { + sm: self.sm, + raw, + source: self.source, + }) + } +} + +pub struct OriginalScopeIter<'a> { + sm: &'a SourceMap, + indices: &'a [usize], + source: 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.sm.scopes.get(&self.source)?.all_scopes.get(*next)?; + Some(OriginalScope { + sm: self.sm, + raw, + source: self.source, + }) + } +} + +impl SourceMap { + /// Returns an iterator over the root scopes for a source. + pub fn scopes_for_source(&self, source_id: u32) -> OriginalScopeIter<'_> { + let indices = match self.scopes.get(&(source_id as usize)) { + Some(scopes) => &scopes.roots[..], + None => &[], + }; + + OriginalScopeIter { + sm: self, + indices, + source: source_id as usize, + } + } +} + +/// A collection of scopes for one source. +#[derive(Debug, Clone, 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, +} From 20529f33354e24cc72fec5bda35f2f772d853703 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 14:44:39 +0100 Subject: [PATCH 04/13] One more comment --- src/decoder/scope.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index d760191..f63f9fc 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -206,6 +206,9 @@ pub fn decode_scopes(items: &str) -> Result> { } } + // 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); } From 58b51a9abaa3fa72566a352842c085a56480fdaa Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 14:52:49 +0100 Subject: [PATCH 05/13] simplify --- src/types/scope.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/types/scope.rs b/src/types/scope.rs index 62c1d3a..89d7f57 100644 --- a/src/types/scope.rs +++ b/src/types/scope.rs @@ -17,8 +17,8 @@ pub(crate) struct RawOriginalScope { #[derive(Debug, Clone)] pub struct OriginalScope<'a> { sm: &'a SourceMap, + scopes: &'a [RawOriginalScope], raw: &'a RawOriginalScope, - source: usize, } impl<'a> OriginalScope<'a> { @@ -59,7 +59,7 @@ impl<'a> OriginalScope<'a> { pub fn children(&self) -> OriginalScopeIter<'a> { OriginalScopeIter { sm: self.sm, - source: self.source, + scopes: self.scopes, indices: &self.raw.children[..], } } @@ -67,21 +67,20 @@ impl<'a> OriginalScope<'a> { /// 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 scopes = self.sm.scopes.get(&self.source)?; - let raw = scopes.all_scopes.get(parent_idx)?; + let raw = self.scopes.get(parent_idx)?; Some(Self { sm: self.sm, + scopes: self.scopes, raw, - source: self.source, }) } } pub struct OriginalScopeIter<'a> { sm: &'a SourceMap, + scopes: &'a [RawOriginalScope], indices: &'a [usize], - source: usize, } impl<'a> Iterator for OriginalScopeIter<'a> { @@ -90,11 +89,11 @@ impl<'a> Iterator for OriginalScopeIter<'a> { fn next(&mut self) -> Option { let (next, rest) = self.indices.split_first()?; self.indices = rest; - let raw = self.sm.scopes.get(&self.source)?.all_scopes.get(*next)?; + let raw = self.scopes.get(*next)?; Some(OriginalScope { sm: self.sm, + scopes: self.scopes, raw, - source: self.source, }) } } @@ -102,15 +101,15 @@ impl<'a> Iterator for OriginalScopeIter<'a> { impl SourceMap { /// Returns an iterator over the root scopes for a source. pub fn scopes_for_source(&self, source_id: u32) -> OriginalScopeIter<'_> { - let indices = match self.scopes.get(&(source_id as usize)) { - Some(scopes) => &scopes.roots[..], - None => &[], + let (scopes, indices) = match self.scopes.get(&(source_id as usize)) { + Some(scopes) => (&scopes.all_scopes[..], &scopes.roots[..]), + None => (&[][..], &[][..]), }; OriginalScopeIter { sm: self, + scopes, indices, - source: source_id as usize, } } } From f093670a4a8d03faad06f2d9b98a8824633d7a1a Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 15:49:00 +0100 Subject: [PATCH 06/13] Handle empty strings in parsing --- src/decoder/scope.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index f63f9fc..a93d749 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -161,6 +161,10 @@ fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u3 /// `children` list contains the indices of its children (which precede it /// in the list). pub fn decode_scopes(items: &str) -> Result> { + if items.is_empty() { + return Ok(vec![]); + } + // A stack of nested in-progress scopes. let mut in_progress = vec![]; let mut state = DecodeScopeState::default(); From 82c3ab3bda7ae17f3ea315266f722023f4f0493c Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 15:53:20 +0100 Subject: [PATCH 07/13] Fix VLQ bug --- src/vlq.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/vlq.rs b/src/vlq.rs index cca51ca..4066b43 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -286,7 +286,12 @@ pub(crate) fn parse_vlq_segment_into(segment: &str, rv: &mut Vec) -> Result let sign = cur & 1; cur >>= 1; if sign != 0 { - cur = -cur; + // See , point 5. + if cur == 0 { + cur = i32::MIN as i64; + } else { + cur = -cur; + } } rv.push(cur); cur = 0; @@ -338,6 +343,8 @@ mod tests { assert_eq!(rv, vec![0, 0, 0, 0]); let rv = parse_vlq_segment("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); + let rv = parse_vlq_segment("B").unwrap(); + assert_eq!(rv, vec![i32::MIN as i64]); } #[test] From dc570c549595632aa0c25e7021fac9fc734340e6 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 15:56:58 +0100 Subject: [PATCH 08/13] Make scopes an Option --- src/decoder/mod.rs | 6 +++--- src/encoder.rs | 8 ++++---- src/jsontypes.rs | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index dc9f892..5258174 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -270,7 +270,7 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { let mut scopes = BTreeMap::new(); - for (idx, items) in rsm.scopes.iter().enumerate() { + for (idx, items) in rsm.scopes.iter().flatten().enumerate() { match items.as_ref() { None => continue, Some(items) => { @@ -446,7 +446,7 @@ mod tests { range_mappings: None, mappings: None, ignore_list: None, - scopes: vec![], + scopes: None, x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, @@ -475,7 +475,7 @@ mod tests { range_mappings: None, mappings: None, ignore_list: None, - scopes: vec![], + scopes: None, x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, diff --git a/src/encoder.rs b/src/encoder.rs index 2244959..52427f9 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -175,7 +175,7 @@ impl Encodable for SourceMap { } else { Some(self.ignore_list.iter().cloned().collect()) }, - scopes: vec![], + scopes: None, x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, @@ -210,7 +210,7 @@ impl Encodable for SourceMapIndex { range_mappings: None, mappings: None, ignore_list: None, - scopes: vec![], + scopes: None, x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, @@ -274,7 +274,7 @@ mod tests { range_mappings: None, mappings: None, ignore_list: None, - scopes: vec![], + scopes: None, x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, @@ -304,7 +304,7 @@ mod tests { range_mappings: None, mappings: None, ignore_list: None, - scopes: vec![], + scopes: None, x_facebook_offsets: None, x_metro_module_paths: None, x_facebook_sources: None, diff --git a/src/jsontypes.rs b/src/jsontypes.rs index 931c8b9..da4554a 100644 --- a/src/jsontypes.rs +++ b/src/jsontypes.rs @@ -49,8 +49,8 @@ pub struct RawSourceMap { pub mappings: Option, #[serde(rename = "ignoreList", skip_serializing_if = "Option::is_none")] pub ignore_list: Option>, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub scopes: Vec>, + #[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")] From c1f98b8de371a650c797e3109c2a62839539d0ee Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 15:57:57 +0100 Subject: [PATCH 09/13] Fix exports --- src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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; From 99c54133f7e6f4a45eaa12511fbdc88d480d5a0d Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 16:13:26 +0100 Subject: [PATCH 10/13] Revert "Fix VLQ bug" This reverts commit 82c3ab3bda7ae17f3ea315266f722023f4f0493c. This fix has been moved to its own PR. --- src/vlq.rs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/vlq.rs b/src/vlq.rs index 4066b43..cca51ca 100644 --- a/src/vlq.rs +++ b/src/vlq.rs @@ -286,12 +286,7 @@ pub(crate) fn parse_vlq_segment_into(segment: &str, rv: &mut Vec) -> Result let sign = cur & 1; cur >>= 1; if sign != 0 { - // See , point 5. - if cur == 0 { - cur = i32::MIN as i64; - } else { - cur = -cur; - } + cur = -cur; } rv.push(cur); cur = 0; @@ -343,8 +338,6 @@ mod tests { assert_eq!(rv, vec![0, 0, 0, 0]); let rv = parse_vlq_segment("GAAIA").unwrap(); assert_eq!(rv, vec![3, 0, 0, 4, 0]); - let rv = parse_vlq_segment("B").unwrap(); - assert_eq!(rv, vec![i32::MIN as i64]); } #[test] From ee7736e91a71441c326379d2a6e876e4d27ffeaf Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 17:01:15 +0100 Subject: [PATCH 11/13] Simplify VLQ checks --- src/decoder/scope.rs | 69 +++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 39 deletions(-) diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index a93d749..7113891 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -1,5 +1,4 @@ use crate::types::RawOriginalScope; -use crate::Error::BadSegmentSize; use crate::{vlq, Error, Result}; #[derive(Debug, Clone, Default)] @@ -31,6 +30,24 @@ impl IndexAccumulator { } } +#[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 { @@ -41,14 +58,13 @@ struct DecodeScopeState { /// The running kind index. kind_idx: IndexAccumulator, /// Buffer for decoding VLQs. - vlq_buffer: Vec, + vlq_buffer: VlqBuffer, } impl DecodeScopeState { - fn decode_vlq(&mut self, segment: &str) -> Result<&[i64]> { - self.vlq_buffer.clear(); - vlq::parse_vlq_segment_into(segment, &mut self.vlq_buffer)?; - Ok(&self.vlq_buffer[..]) + fn decode_vlq(&mut self, segment: &str) -> Result<&VlqBuffer> { + vlq::parse_vlq_segment_into(segment, self.vlq_buffer.inner_mut())?; + Ok(&self.vlq_buffer) } } @@ -72,13 +88,10 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result 0; let has_kind = (flags & KIND_FLAG) > 0; @@ -86,27 +99,9 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result (None, None), - (true, false) => { - if nums.len() < 4 { - return Err(BadSegmentSize(nums.len() as u32)); - } - - (Some(nums[3] as i32), None) - } - (false, true) => { - if nums.len() < 4 { - return Err(BadSegmentSize(nums.len() as u32)); - } - - (None, Some(nums[3] as i32)) - } - (true, true) => { - if nums.len() < 5 { - return Err(BadSegmentSize(nums.len() as u32)); - } - - (Some(nums[3] as i32), Some(nums[4] as i32)) - } + (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); @@ -136,12 +131,8 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result Result<(u32, u32)> { let nums = state.decode_vlq(item)?; - if nums.len() < 2 { - return Err(BadSegmentSize(nums.len() as u32)); - } - - let line = unsigned(nums[0] as i32); - let column = unsigned(nums[1] as i32); + let line = unsigned(nums.get(0)?); + let column = unsigned(nums.get(1)?); Ok(state.position.advance(line, column)) } From c5353dc8a7d2ecee46b901d818dd96cd85353d21 Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 17:25:06 +0100 Subject: [PATCH 12/13] Track root scopes at parse time --- src/decoder/mod.rs | 12 ++---------- src/decoder/scope.rs | 20 +++++++++++++------- src/types/scope.rs | 2 +- 3 files changed, 16 insertions(+), 18 deletions(-) diff --git a/src/decoder/mod.rs b/src/decoder/mod.rs index 5258174..e27ee17 100644 --- a/src/decoder/mod.rs +++ b/src/decoder/mod.rs @@ -10,9 +10,7 @@ use serde_json::Value; use crate::errors::{Error, Result}; use crate::hermes::decode_hermes; use crate::jsontypes::RawSourceMap; -use crate::types::{ - DecodedMap, OriginalScopes, RawToken, SourceMap, SourceMapIndex, SourceMapSection, -}; +use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection}; use crate::vlq::parse_vlq_segment_into; mod scope; @@ -274,13 +272,7 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result { match items.as_ref() { None => continue, Some(items) => { - let all_scopes = scope::decode_scopes(items)?; - let roots = (0..all_scopes.len()) - .into_iter() - .filter(|idx| all_scopes[*idx].parent.is_none()) - .collect(); - - scopes.insert(idx, OriginalScopes { all_scopes, roots }); + scopes.insert(idx, scope::decode_scopes(items)?); } } } diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index 7113891..237f1d9 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -1,4 +1,4 @@ -use crate::types::RawOriginalScope; +use crate::types::{OriginalScopes, RawOriginalScope}; use crate::{vlq, Error, Result}; #[derive(Debug, Clone, Default)] @@ -151,15 +151,15 @@ fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u3 /// The returned list contains the parsed scopes in post-order. Each scope's /// `children` list contains the indices of its children (which precede it /// in the list). -pub fn decode_scopes(items: &str) -> Result> { +pub fn decode_scopes(items: &str) -> Result { if items.is_empty() { - return Ok(vec![]); + return Ok(Default::default()); } // A stack of nested in-progress scopes. let mut in_progress = vec![]; let mut state = DecodeScopeState::default(); - let mut out: Vec = Vec::new(); + let mut out = OriginalScopes::default(); for item in items.split(',') { match item.split_at_checked(1) { @@ -178,7 +178,7 @@ pub fn decode_scopes(items: &str) -> Result> { current.end_col = end_col; // The index the current scope will have in the output list. - let current_idx = out.len(); + 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. @@ -189,10 +189,16 @@ pub fn decode_scopes(items: &str) -> Result> { // We can now go back over the current scope's children (previously // written) and set the parent. for &child_idx in ¤t.children { - out[child_idx].parent = Some(current_idx); + out.all_scopes[child_idx].parent = Some(current_idx); } - out.push(current) + 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 diff --git a/src/types/scope.rs b/src/types/scope.rs index 89d7f57..0add677 100644 --- a/src/types/scope.rs +++ b/src/types/scope.rs @@ -115,7 +115,7 @@ impl SourceMap { } /// A collection of scopes for one source. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub(crate) struct OriginalScopes { /// A forest of scopes. /// From e4171680961e9a245968d717bd177504ffc734ed Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Wed, 25 Nov 2026 17:27:18 +0100 Subject: [PATCH 13/13] Update docstring --- src/decoder/scope.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/decoder/scope.rs b/src/decoder/scope.rs index 237f1d9..21ea03a 100644 --- a/src/decoder/scope.rs +++ b/src/decoder/scope.rs @@ -148,9 +148,10 @@ fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u3 /// /// Scope trees are encoded by simply nesting `B` and `C` records appropriately. /// -/// The returned list contains the parsed scopes in post-order. Each scope's -/// `children` list contains the indices of its children (which precede it -/// in the list). +/// 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());