sourcemap 9.3.2

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
405
406
407
408
409
410
411
412
413
use std::fmt;
use std::str;
use std::sync::Arc;
use std::sync::Mutex;

use if_chain::if_chain;

use crate::detector::{locate_sourcemap_reference_slice, SourceMapRef};
use crate::errors::Result;
use crate::js_identifiers::{get_javascript_token, is_valid_javascript_identifier};
use crate::types::Token;

/// An iterator that iterates over tokens in reverse.
pub struct RevTokenIter<'view, 'map> {
    sv: &'view SourceView,
    token: Option<Token<'map>>,
    source_line: Option<(&'view str, usize, usize, usize)>,
}

impl<'view, 'map> Iterator for RevTokenIter<'view, 'map> {
    type Item = (Token<'map>, Option<&'view str>);

    fn next(&mut self) -> Option<(Token<'map>, Option<&'view str>)> {
        let token = self.token.take()?;
        let idx = token.idx;

        if idx > 0 {
            self.token = token.sm.get_token(idx - 1);
        }

        // if we are going to the same line as we did last iteration, we don't have to scan
        // up to it again.  For normal sourcemaps this should mean we only ever go to the
        // line once.
        let (source_line, last_char_offset, last_byte_offset) = if_chain! {
            if let Some((source_line, dst_line, last_char_offset,
                         last_byte_offset)) = self.source_line;

            if dst_line == token.get_dst_line() as usize;
            then {
                (source_line, last_char_offset, last_byte_offset)
            } else {
                if let Some(source_line) = self.sv.get_line(token.get_dst_line()) {
                    (source_line, !0, !0)
                } else {
                    // if we can't find the line, return am empty one
                    ("", !0, !0)
                }
            }
        };

        // find the byte offset where our token starts
        let byte_offset = if last_byte_offset == !0 {
            let mut off = 0;
            let mut idx = 0;
            for c in source_line.chars() {
                if idx >= token.get_dst_col() as usize {
                    break;
                }
                off += c.len_utf8();
                idx += c.len_utf16();
            }
            off
        } else {
            let chars_to_move = last_char_offset - token.get_dst_col() as usize;
            let mut new_offset = last_byte_offset;
            let mut idx = 0;
            for c in source_line
                .get(..last_byte_offset)
                .unwrap_or("")
                .chars()
                .rev()
            {
                if idx >= chars_to_move {
                    break;
                }
                new_offset -= c.len_utf8();
                idx += c.len_utf16();
            }
            new_offset
        };

        // remember where we were
        self.source_line = Some((
            source_line,
            token.get_dst_line() as usize,
            token.get_dst_col() as usize,
            byte_offset,
        ));

        // in case we run out of bounds here we reset the cache
        if byte_offset >= source_line.len() {
            self.source_line = None;
            Some((token, None))
        } else {
            Some((
                token,
                source_line
                    .get(byte_offset..)
                    .and_then(get_javascript_token),
            ))
        }
    }
}

pub struct Lines<'a> {
    sv: &'a SourceView,
    idx: u32,
}

impl<'a> Iterator for Lines<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if let Some(line) = self.sv.get_line(self.idx) {
            self.idx += 1;
            Some(line)
        } else {
            None
        }
    }
}

/// Provides efficient access to minified sources.
///
/// This type is used to implement fairly efficient source mapping
/// operations.
pub struct SourceView {
    source: Arc<str>,
    line_end_offsets: Mutex<Vec<LineEndOffset>>,
}

impl Clone for SourceView {
    fn clone(&self) -> SourceView {
        SourceView {
            source: self.source.clone(),
            line_end_offsets: Mutex::new(vec![]),
        }
    }
}

impl fmt::Debug for SourceView {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("SourceView")
            .field("source", &self.source())
            .finish()
    }
}

impl PartialEq for SourceView {
    fn eq(&self, other: &Self) -> bool {
        self.source == other.source
    }
}

impl SourceView {
    /// Creates an optimized view of a given source.
    pub fn new(source: Arc<str>) -> SourceView {
        SourceView {
            source,
            line_end_offsets: Mutex::new(vec![]),
        }
    }

    /// Creates an optimized view from a given source string
    pub fn from_string(source: String) -> SourceView {
        SourceView {
            source: source.into(),
            line_end_offsets: Mutex::new(vec![]),
        }
    }

    /// Returns a requested minified line.
    pub fn get_line(&self, idx: u32) -> Option<&str> {
        let idx = idx as usize;

        let get_from_line_ends = |line_ends: &[LineEndOffset]| {
            let end = line_ends.get(idx)?.to_end_index();
            let start = if idx == 0 {
                0
            } else {
                line_ends[idx - 1].to_start_index()
            };
            Some(&self.source[start..end])
        };

        let mut line_ends = self
            .line_end_offsets
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        if let Some(line) = get_from_line_ends(&line_ends) {
            return Some(line);
        }

        // check whether we've processed the entire string - the end of the
        // last-processed line would be the same as the end of the string
        if line_ends
            .last()
            .is_some_and(|i| i.to_end_index() == self.source.len())
        {
            return None;
        }

        let mut rest_offset = line_ends.last().map_or(0, |i| i.to_start_index());
        let mut rest = &self.source[rest_offset..];
        let mut done = false;

        while !done {
            let line_term = if let Some(idx) = rest.find(['\n', '\r']) {
                rest_offset += idx;
                rest = &rest[idx..];
                if rest.starts_with("\r\n") {
                    LineTerminator::CrLf
                } else {
                    LineTerminator::LfOrCr
                }
            } else {
                rest_offset += rest.len();
                rest = &rest[rest.len()..];
                done = true;
                LineTerminator::Eof
            };

            line_ends.push(LineEndOffset::new(rest_offset, line_term));
            rest_offset += line_term as usize;
            rest = &rest[line_term as usize..];
            if let Some(line) = get_from_line_ends(&line_ends) {
                return Some(line);
            }
        }

        None
    }

    /// Returns a line slice.
    ///
    /// Note that columns are indexed as JavaScript WTF-16 columns.
    pub fn get_line_slice(&self, line: u32, col: u32, span: u32) -> Option<&str> {
        self.get_line(line).and_then(|line| {
            let mut off = 0;
            let mut idx = 0;
            let mut char_iter = line.chars().peekable();

            while let Some(&c) = char_iter.peek() {
                if idx >= col as usize {
                    break;
                }
                char_iter.next();
                off += c.len_utf8();
                idx += c.len_utf16();
            }

            let mut off_end = off;
            for c in char_iter {
                if idx >= (col + span) as usize {
                    break;
                }
                off_end += c.len_utf8();
                idx += c.len_utf16();
            }

            if idx < ((col + span) as usize) {
                None
            } else {
                line.get(off..off_end)
            }
        })
    }

    /// Returns an iterator over all lines.
    pub fn lines(&self) -> Lines<'_> {
        Lines { sv: self, idx: 0 }
    }

    /// Returns the source.
    pub fn source(&self) -> &str {
        &self.source
    }

    fn rev_token_iter<'this, 'map>(&'this self, token: Token<'map>) -> RevTokenIter<'this, 'map> {
        RevTokenIter {
            sv: self,
            token: Some(token),
            source_line: None,
        }
    }

    /// Given a token and minified function name this attemps to resolve the
    /// name to an original function name.
    ///
    /// This invokes some guesswork and requires access to the original minified
    /// source.  This will not yield proper results for anonymous functions or
    /// functions that do not have clear function names.  (For instance it's
    /// recommended that dotted function names are not passed to this
    /// function).
    pub fn get_original_function_name<'map>(
        &self,
        token: Token<'map>,
        minified_name: &str,
    ) -> Option<&'map str> {
        if !is_valid_javascript_identifier(minified_name) {
            return None;
        }

        let mut iter = self.rev_token_iter(token).take(128).peekable();

        while let Some((token, original_identifier)) = iter.next() {
            if_chain! {
                if original_identifier == Some(minified_name);
                if let Some(item) = iter.peek();
                if item.1 == Some("function");
                then {
                    return token.get_name();
                }
            }
        }

        None
    }

    /// Returns the number of lines.
    pub fn line_count(&self) -> usize {
        self.get_line(!0);
        self.line_end_offsets.lock().unwrap().len()
    }

    /// Returns the source map reference in the source view.
    pub fn sourcemap_reference(&self) -> Result<Option<SourceMapRef>> {
        locate_sourcemap_reference_slice(self.source.as_bytes())
    }
}

/// A wrapper around an index that stores a [`LineTerminator`] in its 2 lowest bits.
// We use `u64` instead of `usize` in order to not lose data when bit-packing
// on 32-bit targets.
#[derive(Clone, Copy)]
struct LineEndOffset(u64);

#[derive(Clone, Copy)]
enum LineTerminator {
    Eof = 0,
    LfOrCr = 1,
    CrLf = 2,
}

impl LineEndOffset {
    fn new(index: usize, line_end: LineTerminator) -> Self {
        let shifted = (index as u64) << 2;

        Self(shifted | line_end as u64)
    }

    /// Return the index of the end of this line.
    fn to_end_index(self) -> usize {
        (self.0 >> 2) as usize
    }

    /// Return the index of the start of the next line.
    fn to_start_index(self) -> usize {
        self.to_end_index() + (self.0 & 0b11) as usize
    }
}

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

    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn test_minified_source_view() {
        let view = SourceView::new("a\nb\nc".into());
        assert_eq!(view.get_line(0), Some("a"));
        assert_eq!(view.get_line(0), Some("a"));
        assert_eq!(view.get_line(2), Some("c"));
        assert_eq!(view.get_line(1), Some("b"));
        assert_eq!(view.get_line(3), None);

        assert_eq!(view.line_count(), 3);

        let view = SourceView::new("a\r\nb\r\nc".into());
        assert_eq!(view.get_line(0), Some("a"));
        assert_eq!(view.get_line(0), Some("a"));
        assert_eq!(view.get_line(2), Some("c"));
        assert_eq!(view.get_line(1), Some("b"));
        assert_eq!(view.get_line(3), None);

        assert_eq!(view.line_count(), 3);

        let view = SourceView::new("abc👌def\nblah".into());
        assert_eq!(view.get_line_slice(0, 0, 3), Some("abc"));
        assert_eq!(view.get_line_slice(0, 3, 1), Some("👌"));
        assert_eq!(view.get_line_slice(0, 3, 2), Some("👌"));
        assert_eq!(view.get_line_slice(0, 3, 3), Some("👌d"));
        assert_eq!(view.get_line_slice(0, 0, 4), Some("abc👌"));
        assert_eq!(view.get_line_slice(0, 0, 5), Some("abc👌"));
        assert_eq!(view.get_line_slice(0, 0, 6), Some("abc👌d"));
        assert_eq!(view.get_line_slice(1, 0, 4), Some("blah"));
        assert_eq!(view.get_line_slice(1, 0, 5), None);
        assert_eq!(view.get_line_slice(1, 0, 12), None);

        let view = SourceView::new("a\nb\nc\n".into());
        assert_eq!(view.get_line(0), Some("a"));
        assert_eq!(view.get_line(1), Some("b"));
        assert_eq!(view.get_line(2), Some("c"));
        assert_eq!(view.get_line(3), Some(""));
        assert_eq!(view.get_line(4), None);

        fn is_send<T: Send>() {}
        fn is_sync<T: Sync>() {}
        is_send::<SourceView>();
        is_sync::<SourceView>();
    }
}