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
use watto::{align_to, Pod, StringTable};
use crate::{ScopeLookupResult, SourcePosition};
use super::raw;
#[derive(Debug, PartialEq)]
pub struct SourceLocation<'data> {
file: Option<File<'data>>,
line: u32,
column: u32,
name: Option<&'data str>,
scope: ScopeLookupResult<'data>,
}
impl<'data> SourceLocation<'data> {
pub fn file(&self) -> Option<File<'data>> {
self.file
}
pub fn line(&self) -> u32 {
self.line
}
pub fn column(&self) -> u32 {
self.column
}
pub fn name(&self) -> Option<&'data str> {
self.name
}
pub fn line_contents(&self) -> Option<&'data str> {
self.file().and_then(|file| file.line(self.line as usize))
}
pub fn scope(&self) -> ScopeLookupResult<'data> {
self.scope
}
pub fn file_name(&self) -> Option<&'data str> {
self.file.and_then(|file| file.name)
}
pub fn file_source(&self) -> Option<&'data str> {
self.file.and_then(|file| file.source)
}
}
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Clone)]
pub struct SourceMapCache<'data> {
header: &'data raw::Header,
min_source_positions: &'data [raw::MinifiedSourcePosition],
orig_source_locations: &'data [raw::OriginalSourceLocation],
files: &'data [raw::File],
line_offsets: &'data [raw::LineOffset],
string_bytes: &'data [u8],
}
impl<'data> std::fmt::Debug for SourceMapCache<'data> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SourceMapCache")
.field("version", &self.header.version)
.field("mappings", &self.header.num_mappings)
.field("files", &self.header.num_files)
.field("line_offsets", &self.header.num_line_offsets)
.field("string_bytes", &self.header.string_bytes)
.finish()
}
}
impl<'data> SourceMapCache<'data> {
#[tracing::instrument(level = "trace", name = "SourceMapCache::parse", skip_all)]
pub fn parse(buf: &'data [u8]) -> Result<Self> {
let (header, buf) = raw::Header::ref_from_prefix(buf).ok_or(Error::Header)?;
if header.magic == raw::SOURCEMAPCACHE_MAGIC_FLIPPED {
return Err(Error::WrongEndianness);
}
if header.magic != raw::SOURCEMAPCACHE_MAGIC {
return Err(Error::WrongFormat);
}
if header.version != raw::SOURCEMAPCACHE_VERSION {
return Err(Error::WrongVersion);
}
let (_, buf) = align_to(buf, 8).ok_or(Error::SourcePositions)?;
let num_mappings = header.num_mappings as usize;
let (min_source_positions, buf) =
raw::MinifiedSourcePosition::slice_from_prefix(buf, num_mappings)
.ok_or(Error::SourcePositions)?;
let (_, buf) = align_to(buf, 8).ok_or(Error::SourcePositions)?;
let (orig_source_locations, buf) =
raw::OriginalSourceLocation::slice_from_prefix(buf, num_mappings)
.ok_or(Error::SourceLocations)?;
let (_, buf) = align_to(buf, 8).ok_or(Error::Files)?;
let (files, buf) =
raw::File::slice_from_prefix(buf, header.num_files as usize).ok_or(Error::Files)?;
let (_, buf) = align_to(buf, 8).ok_or(Error::LineOffsets)?;
let (line_offsets, buf) =
raw::LineOffset::slice_from_prefix(buf, header.num_line_offsets as usize)
.ok_or(Error::LineOffsets)?;
let (_, buf) = align_to(buf, 8).ok_or(Error::StringBytes)?;
let string_bytes = header.string_bytes as usize;
let string_bytes = buf.get(..string_bytes).ok_or(Error::StringBytes)?;
Ok(Self {
header,
min_source_positions,
orig_source_locations,
files,
line_offsets,
string_bytes,
})
}
fn get_string(&self, offset: u32) -> Option<&'data str> {
StringTable::read(self.string_bytes, offset as usize).ok()
}
fn resolve_file(&self, raw_file: &raw::File) -> Option<File<'data>> {
let name = self.get_string(raw_file.name_offset);
let source = self.get_string(raw_file.source_offset);
let line_offsets = self
.line_offsets
.get(raw_file.line_offsets_start as usize..raw_file.line_offsets_end as usize)?;
Some(File {
name,
source,
line_offsets,
})
}
#[tracing::instrument(level = "trace", name = "SourceMapCache::lookup", skip_all)]
pub fn lookup(&self, sp: SourcePosition) -> Option<SourceLocation> {
let idx = match self.min_source_positions.binary_search(&sp.into()) {
Ok(idx) => idx,
Err(0) => 0,
Err(idx) => idx - 1,
};
let sl = self.orig_source_locations.get(idx)?;
let line = sl.line;
let column = sl.column;
let file = self
.files
.get(sl.file_idx as usize)
.and_then(|raw_file| self.resolve_file(raw_file));
let name = match sl.name_idx {
raw::NO_NAME_SENTINEL => None,
idx => self.get_string(idx),
};
let scope = match sl.scope_idx {
raw::GLOBAL_SCOPE_SENTINEL => ScopeLookupResult::Unknown,
raw::ANONYMOUS_SCOPE_SENTINEL => ScopeLookupResult::AnonymousScope,
idx => self
.get_string(idx)
.map_or(ScopeLookupResult::Unknown, ScopeLookupResult::NamedScope),
};
Some(SourceLocation {
file,
line,
column,
name,
scope,
})
}
pub fn files(&'data self) -> Files<'data> {
Files::new(self)
}
}
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("endianness mismatch")]
WrongEndianness,
#[error("wrong format magic")]
WrongFormat,
#[error("unknown SymCache version")]
WrongVersion,
#[error("invalid header")]
Header,
#[error("invalid source positions")]
SourcePositions,
#[error("invalid source locations")]
SourceLocations,
#[error("invalid string bytes")]
StringBytes,
#[error("invalid files")]
Files,
#[error("invalid line offsets")]
LineOffsets,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct File<'data> {
name: Option<&'data str>,
source: Option<&'data str>,
line_offsets: &'data [raw::LineOffset],
}
impl<'data> File<'data> {
pub fn name(&self) -> Option<&'data str> {
self.name
}
pub fn source(&self) -> Option<&'data str> {
self.source
}
pub fn line(&self, line_no: usize) -> Option<&'data str> {
let source = self.source?;
let from = self.line_offsets.get(line_no).copied()?.0 as usize;
let next_line_no = line_no.checked_add(1);
let to = next_line_no
.and_then(|next_line_no| self.line_offsets.get(next_line_no))
.map_or(source.len(), |lo| lo.0 as usize);
source.get(from..to)
}
}
pub struct Files<'data> {
cache: &'data SourceMapCache<'data>,
raw_files: std::slice::Iter<'data, raw::File>,
}
impl<'data> Files<'data> {
fn new(cache: &'data SourceMapCache<'data>) -> Self {
let raw_files = cache.files.iter();
Self { cache, raw_files }
}
}
impl<'data> Iterator for Files<'data> {
type Item = File<'data>;
fn next(&mut self) -> Option<Self::Item> {
self.raw_files
.next()
.and_then(|raw_file| self.cache.resolve_file(raw_file))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::SourceMapCacheWriter;
#[test]
fn lines_empty_file() {
let source = "";
let mut line_offsets = Vec::new();
SourceMapCacheWriter::append_line_offsets(source, &mut line_offsets);
let file = File {
name: None,
source: Some(source),
line_offsets: &line_offsets,
};
assert_eq!(file.line(0), Some(""));
assert_eq!(file.line(1), None);
}
#[test]
fn lines_almost_empty_file() {
let source = "\n";
let mut line_offsets = Vec::new();
SourceMapCacheWriter::append_line_offsets(source, &mut line_offsets);
let file = File {
name: None,
source: Some(source),
line_offsets: &line_offsets,
};
assert_eq!(file.line(0), Some("\n"));
assert_eq!(file.line(1), Some(""));
assert_eq!(file.line(2), None);
}
#[test]
fn lines_several_lines() {
let source = "a\n\nb\nc";
let mut line_offsets = Vec::new();
SourceMapCacheWriter::append_line_offsets(source, &mut line_offsets);
let file = File {
name: None,
source: Some(source),
line_offsets: &line_offsets,
};
assert_eq!(file.line(0), Some("a\n"));
assert_eq!(file.line(1), Some("\n"));
assert_eq!(file.line(2), Some("b\n"));
assert_eq!(file.line(3), Some("c"));
}
#[test]
fn lines_several_lines_trailing_newline() {
let source = "a\n\nb\nc\n";
let mut line_offsets = Vec::new();
SourceMapCacheWriter::append_line_offsets(source, &mut line_offsets);
let file = File {
name: None,
source: Some(source),
line_offsets: &line_offsets,
};
assert_eq!(file.line(0), Some("a\n"));
assert_eq!(file.line(1), Some("\n"));
assert_eq!(file.line(2), Some("b\n"));
assert_eq!(file.line(3), Some("c\n"));
assert_eq!(file.line(4), Some(""));
}
}