oxc_sourcemap 7.0.0

Basic sourcemap handling for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::borrow::Cow;

use crate::{
    SourceViewToken,
    decode::{JSONSourceMap, decode, decode_from_string},
    encode::{encode, encode_to_string},
    error::Result,
    token::{Token, TokenChunk},
};

/// A parsed source map.
///
/// `SourceMap` is parameterized by a lifetime `'a` because its string fields
/// borrow directly from the source they were built from when possible. For a
/// map parsed via [`SourceMap::from_json_string`], `'a` is the lifetime of the
/// input JSON buffer — most strings (those without JSON escapes) are zero-copy
/// views into that buffer; only escaped strings allocate. For maps built
/// programmatically via the builder, the lifetime is `'static`.
#[derive(Debug, Clone, Default)]
pub struct SourceMap<'a> {
    pub(crate) file: Option<Cow<'a, str>>,
    pub(crate) names: Vec<Cow<'a, str>>,
    pub(crate) source_root: Option<Cow<'a, str>>,
    pub(crate) sources: Vec<Cow<'a, str>>,
    pub(crate) source_contents: Vec<Option<Cow<'a, str>>>,
    pub(crate) tokens: Box<[Token]>,
    pub(crate) token_chunks: Option<Vec<TokenChunk>>,
    /// Identifies third-party sources (such as framework code or bundler-generated code), allowing developers to avoid code that they don't want to see or step through, without having to configure this beforehand.
    /// The `x_google_ignoreList` field refers to the `sources` array, and lists the indices of all the known third-party sources in that source map.
    /// When parsing the source map, developer tools can use this to determine sections of the code that the browser loads and runs that could be automatically ignore-listed.
    pub(crate) x_google_ignore_list: Option<Vec<u32>>,
    pub(crate) debug_id: Option<Cow<'a, str>>,
}

impl<'a> SourceMap<'a> {
    pub fn new(
        file: Option<Cow<'a, str>>,
        names: Vec<Cow<'a, str>>,
        source_root: Option<Cow<'a, str>>,
        sources: Vec<Cow<'a, str>>,
        source_contents: Vec<Option<Cow<'a, str>>>,
        tokens: Box<[Token]>,
        token_chunks: Option<Vec<TokenChunk>>,
    ) -> Self {
        Self {
            file,
            names,
            source_root,
            sources,
            source_contents,
            tokens,
            token_chunks,
            x_google_ignore_list: None,
            debug_id: None,
        }
    }

    /// Convert the vlq sourcemap to to `SourceMap`.
    /// # Errors
    ///
    /// The `serde_json` deserialize Error.
    pub fn from_json(value: JSONSourceMap) -> Result<SourceMap<'static>> {
        decode(value)
    }

    /// Convert the vlq sourcemap string to `SourceMap`.
    ///
    /// The returned `SourceMap` borrows string data from `value` for any
    /// fields that have no JSON escape sequences; everything else is owned.
    ///
    /// # Errors
    ///
    /// The `serde_json` deserialize Error.
    pub fn from_json_string(value: &'a str) -> Result<SourceMap<'a>> {
        decode_from_string(value)
    }

    /// Convert `SourceMap` to vlq sourcemap.
    pub fn to_json(&self) -> JSONSourceMap {
        encode(self)
    }

    /// Convert `SourceMap` to vlq sourcemap string.
    pub fn to_json_string(&self) -> String {
        encode_to_string(self)
    }

    /// Convert `SourceMap` to vlq sourcemap data url.
    pub fn to_data_url(&self) -> String {
        let base_64_str = base64_simd::STANDARD.encode_to_string(self.to_json_string().as_bytes());
        format!("data:application/json;charset=utf-8;base64,{base_64_str}")
    }

    /// Detach this `SourceMap` from its input buffer by allocating owned
    /// copies of any borrowed strings. Use this when the resulting map
    /// needs to outlive the JSON input it was parsed from, or when the
    /// borrow lifetime from a concat builder is shorter than where you
    /// want to use the result.
    ///
    /// `Cow::Owned` entries are moved without copying; `Cow::Borrowed`
    /// entries allocate.
    pub fn into_owned(self) -> SourceMap<'static> {
        SourceMap {
            file: self.file.map(|c| Cow::Owned(c.into_owned())),
            names: self.names.into_iter().map(|c| Cow::Owned(c.into_owned())).collect(),
            source_root: self.source_root.map(|c| Cow::Owned(c.into_owned())),
            sources: self.sources.into_iter().map(|c| Cow::Owned(c.into_owned())).collect(),
            source_contents: self
                .source_contents
                .into_iter()
                .map(|opt| opt.map(|c| Cow::Owned(c.into_owned())))
                .collect(),
            tokens: self.tokens,
            token_chunks: self.token_chunks,
            x_google_ignore_list: self.x_google_ignore_list,
            debug_id: self.debug_id.map(|c| Cow::Owned(c.into_owned())),
        }
    }

    /// Decompose this `SourceMap` into its constituent owned parts.
    ///
    /// Useful for downstream code that wants to consume the map (e.g.
    /// transform tokens, swap in a different `file` field) without
    /// re-cloning every name/source string via accessors. Pair with
    /// [`SourceMap::from_parts`] (or `From`) to reassemble.
    pub fn into_parts(self) -> SourceMapParts<'a> {
        SourceMapParts {
            file: self.file,
            names: self.names,
            source_root: self.source_root,
            sources: self.sources,
            source_contents: self.source_contents,
            tokens: self.tokens,
            token_chunks: self.token_chunks,
            x_google_ignore_list: self.x_google_ignore_list,
            debug_id: self.debug_id,
        }
    }

    /// Reassemble a `SourceMap` from its parts. See [`SourceMap::into_parts`].
    pub fn from_parts(parts: SourceMapParts<'a>) -> Self {
        Self {
            file: parts.file,
            names: parts.names,
            source_root: parts.source_root,
            sources: parts.sources,
            source_contents: parts.source_contents,
            tokens: parts.tokens,
            token_chunks: parts.token_chunks,
            x_google_ignore_list: parts.x_google_ignore_list,
            debug_id: parts.debug_id,
        }
    }

    pub fn get_file(&self) -> Option<&str> {
        self.file.as_deref()
    }

    pub fn set_file(&mut self, file: &str) {
        self.file = Some(Cow::Owned(file.to_owned()));
    }

    pub fn get_source_root(&self) -> Option<&str> {
        self.source_root.as_deref()
    }

    pub fn get_x_google_ignore_list(&self) -> Option<&[u32]> {
        self.x_google_ignore_list.as_deref()
    }

    /// Set `x_google_ignoreList`.
    pub fn set_x_google_ignore_list(&mut self, x_google_ignore_list: Vec<u32>) {
        self.x_google_ignore_list = Some(x_google_ignore_list);
    }

    pub fn set_debug_id(&mut self, debug_id: &str) {
        self.debug_id = Some(Cow::Owned(debug_id.to_owned()));
    }

    pub fn get_debug_id(&self) -> Option<&str> {
        self.debug_id.as_deref()
    }

    pub fn get_names(&self) -> impl Iterator<Item = &str> {
        self.names.iter().map(AsRef::as_ref)
    }

    /// Adjust `sources`.
    pub fn set_sources<S: AsRef<str>, I: IntoIterator<Item = S>>(&mut self, sources: I) {
        self.sources = sources.into_iter().map(|s| Cow::Owned(s.as_ref().to_owned())).collect();
    }

    pub fn get_sources(&self) -> impl Iterator<Item = &str> {
        self.sources.iter().map(AsRef::as_ref)
    }

    /// Adjust `source_content`.
    pub fn set_source_contents(&mut self, source_contents: Vec<Option<&str>>) {
        self.source_contents =
            source_contents.into_iter().map(|v| v.map(|s| Cow::Owned(s.to_owned()))).collect();
    }

    pub fn get_source_contents(&self) -> impl Iterator<Item = Option<&str>> {
        self.source_contents.iter().map(|item| item.as_deref())
    }

    pub fn get_token(&self, index: u32) -> Option<Token> {
        self.tokens.get(index as usize).copied()
    }

    pub fn get_source_view_token(&self, index: u32) -> Option<SourceViewToken<'_, 'a>> {
        self.tokens.get(index as usize).copied().map(|token| SourceViewToken::new(token, self))
    }

    /// Get raw tokens.
    pub fn get_tokens(&self) -> impl Iterator<Item = Token> {
        self.tokens.iter().copied()
    }

    /// Get source view tokens. See [`SourceViewToken`] for more information.
    pub fn get_source_view_tokens(&self) -> impl Iterator<Item = SourceViewToken<'_, 'a>> {
        self.tokens.iter().map(|&token| SourceViewToken::new(token, self))
    }

    pub fn get_name(&self, id: u32) -> Option<&str> {
        self.names.get(id as usize).map(AsRef::as_ref)
    }

    pub fn get_source(&self, id: u32) -> Option<&str> {
        self.sources.get(id as usize).map(AsRef::as_ref)
    }

    pub fn get_source_content(&self, id: u32) -> Option<&str> {
        self.source_contents.get(id as usize).and_then(|item| item.as_deref())
    }

    pub fn get_source_and_content(&self, id: u32) -> Option<(&str, &str)> {
        let source = self.get_source(id)?;
        let content = self.get_source_content(id)?;
        Some((source, content))
    }

    /// Generate a lookup table, it will be used at `lookup_token` or `lookup_source_view_token`.
    pub fn generate_lookup_table(&self) -> Vec<LineLookupTable<'_>> {
        // The dst line/dst col always has increasing order.
        if let Some(last_token) = self.tokens.last() {
            let mut table = vec![&self.tokens[..0]; last_token.dst_line as usize + 1];
            let mut prev_start_idx = 0u32;
            let mut prev_dst_line = 0u32;
            for (idx, token) in self.tokens.iter().enumerate() {
                if token.dst_line != prev_dst_line {
                    table[prev_dst_line as usize] = &self.tokens[prev_start_idx as usize..idx];
                    prev_start_idx = idx as u32;
                    prev_dst_line = token.dst_line;
                }
            }
            table[prev_dst_line as usize] = &self.tokens[prev_start_idx as usize..];
            table
        } else {
            vec![]
        }
    }

    /// Lookup a token by line and column, it will used at remapping.
    pub fn lookup_token(
        &self,
        lookup_table: &[LineLookupTable],
        line: u32,
        col: u32,
    ) -> Option<Token> {
        // If the line is greater than the number of lines in the lookup table, it hasn't corresponding origin token.
        if line >= lookup_table.len() as u32 {
            return None;
        }
        let token = greatest_lower_bound(lookup_table[line as usize], &(line, col), |token| {
            (token.dst_line, token.dst_col)
        })?;
        Some(*token)
    }

    /// Lookup a token by line and column, it will used at remapping. See `SourceViewToken`.
    pub fn lookup_source_view_token(
        &self,
        lookup_table: &[LineLookupTable],
        line: u32,
        col: u32,
    ) -> Option<SourceViewToken<'_, 'a>> {
        self.lookup_token(lookup_table, line, col).map(|token| SourceViewToken::new(token, self))
    }
}

/// Owned destructured parts of a [`SourceMap`].
///
/// Returned by [`SourceMap::into_parts`] for downstream code that wants to
/// take ownership of the internal `Vec<Cow<'_, str>>` storage without going
/// through accessors (which only return `&str` and force a clone to take
/// ownership).
#[derive(Debug, Clone, Default)]
pub struct SourceMapParts<'a> {
    pub file: Option<Cow<'a, str>>,
    pub names: Vec<Cow<'a, str>>,
    pub source_root: Option<Cow<'a, str>>,
    pub sources: Vec<Cow<'a, str>>,
    pub source_contents: Vec<Option<Cow<'a, str>>>,
    pub tokens: Box<[Token]>,
    pub token_chunks: Option<Vec<TokenChunk>>,
    pub x_google_ignore_list: Option<Vec<u32>>,
    pub debug_id: Option<Cow<'a, str>>,
}

impl<'a> From<SourceMapParts<'a>> for SourceMap<'a> {
    fn from(parts: SourceMapParts<'a>) -> Self {
        SourceMap::from_parts(parts)
    }
}

type LineLookupTable<'a> = &'a [Token];

fn greatest_lower_bound<'a, T, K: Ord, F: Fn(&'a T) -> K>(
    slice: &'a [T],
    key: &K,
    map: F,
) -> Option<&'a T> {
    let mut idx = match slice.binary_search_by_key(key, &map) {
        Ok(index) => index,
        Err(index) => {
            // If there is no match, then we know for certain that the index is where we should
            // insert a new token, and that the token directly before is the greatest lower bound.
            return slice.get(index.checked_sub(1)?);
        }
    };

    // If we get an exact match, then we need to continue looking at previous tokens to see if
    // they also match. We use a linear search because the number of exact matches is generally
    // very small, and almost certainly smaller than the number of tokens before the index.
    for i in (0..idx).rev() {
        if map(&slice[i]) == *key {
            idx = i;
        } else {
            break;
        }
    }
    slice.get(idx)
}

#[test]
fn test_sourcemap_lookup_token() {
    let input = r#"{
        "version": 3,
        "sources": ["coolstuff.js"],
        "sourceRoot": "x",
        "names": ["x","alert"],
        "mappings": "AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM"
    }"#;
    let sm = SourceMap::from_json_string(input).unwrap();
    let lookup_table = sm.generate_lookup_table();
    assert_eq!(
        sm.lookup_source_view_token(&lookup_table, 0, 0).unwrap().to_tuple(),
        (Some("coolstuff.js"), 0, 0, None)
    );
    assert_eq!(
        sm.lookup_source_view_token(&lookup_table, 0, 3).unwrap().to_tuple(),
        (Some("coolstuff.js"), 0, 4, Some("x"))
    );
    assert_eq!(
        sm.lookup_source_view_token(&lookup_table, 0, 24).unwrap().to_tuple(),
        (Some("coolstuff.js"), 2, 8, None)
    );

    // Lines continue out to infinity
    assert_eq!(
        sm.lookup_source_view_token(&lookup_table, 0, 1000).unwrap().to_tuple(),
        (Some("coolstuff.js"), 2, 8, None)
    );

    assert!(sm.lookup_source_view_token(&lookup_table, 1000, 0).is_none());
}

#[test]
fn test_sourcemap_source_view_token() {
    let sm = SourceMap::new(
        None,
        vec![Cow::Borrowed("foo")],
        None,
        vec![Cow::Borrowed("foo.js")],
        vec![],
        vec![Token::new(1, 1, 1, 1, Some(0), Some(0))].into_boxed_slice(),
        None,
    );
    let mut source_view_tokens = sm.get_source_view_tokens();
    assert_eq!(source_view_tokens.next().unwrap().to_tuple(), (Some("foo.js"), 1, 1, Some("foo")));
}

#[test]
fn test_mut_sourcemap() {
    let mut sm = SourceMap::default();
    sm.set_file("index.js");
    sm.set_sources(vec!["foo.js"]);
    sm.set_source_contents(vec![Some("foo")]);

    assert_eq!(sm.get_file(), Some("index.js"));
    assert_eq!(sm.get_source(0), Some("foo.js"));
    assert_eq!(sm.get_source_content(0), Some("foo"));
}