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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
|
#include "slang-json-source-map-util.h"
#include "slang-com-helper.h"
#include "../core/slang-string-util.h"
#include "../core/slang-blob.h"
#include "slang-json-native.h"
namespace Slang {
/*
Support for source maps. Source maps provide a standardized mechanism to associate a location in one output file
with another.
* [Source Map Proposal](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US&pli=1&pli=1)
* [Chrome Source Map post](https://developer.chrome.com/blog/sourcemaps/)
* [Base64 VLQs in Source Maps](https://www.lucidchart.com/techblog/2019/08/22/decode-encoding-base64-vlqs-source-maps/)
Example...
{
"version" : 3,
"file": "out.js",
"sourceRoot": "",
"sources": ["foo.js", "bar.js"],
"sourcesContent": [null, null],
"names": ["src", "maps", "are", "fun"],
"mappings": "A,AAAB;;ABCDE;"
}
*/
namespace { // anonymous
struct JSONSourceMap
{
/// File version (always the first entry in the object) and must be a positive integer.
int32_t version = 3;
/// An optional name of the generated code that this source map is associated with.
String file;
/// An optional source root, useful for relocating source files on a server or removing repeated values in
/// the “sources” entry. This value is prepended to the individual entries in the “source” field.
String sourceRoot;
/// A list of original sources used by the “mappings” entry.
List<UnownedStringSlice> sources;
/// An optional list of source content, useful when the “source” can’t be hosted. The contents are listed in the same order as the sources in line 5.
/// “null” may be used if some original sources should be retrieved by name.
/// Because could be a string or nullptr, we use JSONValue to hold value.
List<JSONValue> sourcesContent;
/// A list of symbol names used by the “mappings” entry.
List<UnownedStringSlice> names;
/// A string with the encoded mapping data.
UnownedStringSlice mappings;
static const StructRttiInfo g_rttiInfo;
};
} // anonymous
static const StructRttiInfo _makeJSONSourceMap_Rtti()
{
JSONSourceMap obj;
StructRttiBuilder builder(&obj, "SourceMap", nullptr);
builder.addField("version", &obj.version);
builder.addField("file", &obj.file);
builder.addField("sourceRoot", &obj.sourceRoot, StructRttiInfo::Flag::Optional);
builder.addField("sources", &obj.sources);
builder.addField("sourcesContent", &obj.sourcesContent, StructRttiInfo::Flag::Optional);
builder.addField("names", &obj.names, StructRttiInfo::Flag::Optional);
builder.addField("mappings", &obj.mappings);
return builder.make();
}
/* static */const StructRttiInfo JSONSourceMap::g_rttiInfo = _makeJSONSourceMap_Rtti();
// Encode a 6 bit value to VLQ encoding
static const unsigned char g_vlqEncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
struct VlqDecodeTable
{
VlqDecodeTable()
{
::memset(map, -1, sizeof(map));
for (Index i = 0; i < SLANG_COUNT_OF(g_vlqEncodeTable); ++i)
{
map[g_vlqEncodeTable[i]] = int8_t(i);
}
}
/// Returns a *negative* value if invalid
SLANG_FORCE_INLINE int8_t operator[](unsigned char c) const { return (c & ~char(0x7f)) ? -1 : map[c]; }
int8_t map[128];
};
static const VlqDecodeTable g_vlqDecodeTable;
/*
https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US&pli=1&pli=1#
The VLQ is a Base64 value, where the most significant bit (the 6th bit) is used as the continuation
bit, and the “digits” are encoded into the string least significant first, and where the least significant
bit of the first digit is used as the sign bit. */
static SlangResult _decode(UnownedStringSlice& ioEncoded, Index& out)
{
Index v = 0;
const char* cur = ioEncoded.begin();
const char* end = ioEncoded.end();
{
Index shift = 0;
Index decodeValue = 0;
do
{
// Must have a char to decode
if (cur >= end)
{
return SLANG_FAIL;
}
decodeValue = g_vlqDecodeTable[*cur++];
if (decodeValue < 0)
{
return SLANG_FAIL;
}
v += (decodeValue & 0x1f) << shift;
shift += 5;
}
while (decodeValue & 0x20);
}
// Save out the remaining part
ioEncoded = UnownedStringSlice(cur, end);
// Handle negating
out = (v & 1) ? -(v >> 1) : (v >> 1);
return SLANG_OK;
}
void _encode(Index v, StringBuilder& out)
{
// Double to free up low bit to hold the sign
v += v;
// We want to make v always positive to encode
// we use the last bit to indicate negativity
v = (v < 0) ? (1 - v) : v;
// We'll use a simple buffer, so as to not have to constantly update he StringBuffer
char dst[8];
char* cur = dst;
do
{
const Index nextV = v >> 5;
const Index encodeValue = (v & 0x1f) + (nextV ? 0x20 : 0);
// Encode 5 bits, plus continuation bit
char c = g_vlqEncodeTable[encodeValue];
// Save the char
*cur++ = c;
v = nextV;
}
while (v);
out.append(dst, cur);
}
/* static */SlangResult JSONSourceMapUtil::decode(JSONContainer* container, JSONValue root, DiagnosticSink* sink, SourceMap& outSourceMap)
{
outSourceMap.clear();
// Let's try and decode the JSON into native types to make this easier...
RttiTypeFuncsMap typeMap = JSONNativeUtil::getTypeFuncsMap();
// Convert to native
JSONSourceMap native;
{
JSONToNativeConverter converter(container, &typeMap, sink);
// Convert to the native type
SLANG_RETURN_ON_FAIL(converter.convert(root, GetRttiInfo<JSONSourceMap>::get(), &native));
}
outSourceMap.m_file = native.file;
outSourceMap.m_sourceRoot = native.sourceRoot;
const Count sourcesCount = native.sources.getCount();
// These should all be unique, but for simplicity, we build a table
outSourceMap.m_sources.setCount(sourcesCount);
for (Index i = 0; i < sourcesCount; ++i)
{
outSourceMap.m_sources[i] = outSourceMap.m_slicePool.add(native.sources[i]);
}
Count sourcesContentCount = native.sourcesContent.getCount();
sourcesContentCount = std::min(sourcesContentCount, sourcesCount);
outSourceMap.m_sourcesContent.setCount(sourcesContentCount);
for (auto& cur : outSourceMap.m_sourcesContent)
{
cur = StringSlicePool::kNullHandle;
}
// Special case sourcesContent, because needs to be able to handle null or string
for (Index i = 0; i < sourcesContentCount; ++i)
{
auto value = native.sourcesContent[i];
if (value.type != JSONValue::Type::Null)
{
if (value.getKind() == JSONValue::Kind::String)
{
auto stringValue = container->getString(value);
outSourceMap.m_sourcesContent[i] = outSourceMap.m_slicePool.add(stringValue);
}
}
}
// Copy over the names
{
const auto namesCount = native.names.getCount();
outSourceMap.m_names.setCount(namesCount);
for (Index i = 0; i < namesCount; ++i)
{
outSourceMap.m_names[i] = outSourceMap.m_slicePool.add(native.names[i]);
}
}
List<UnownedStringSlice> lines;
StringUtil::split(native.mappings, ';', lines);
List<UnownedStringSlice> segments;
// Index into sources
Index sourceFileIndex = 0;
Index sourceLine = 0;
Index sourceColumn = 0;
Index nameIndex = 0;
const Count linesCount = lines.getCount();
outSourceMap.m_lineStarts.setCount(linesCount + 1);
for (Index generatedLine = 0; generatedLine < linesCount; ++generatedLine)
{
const auto line = lines[generatedLine];
outSourceMap.m_lineStarts[generatedLine] = outSourceMap.m_lineEntries.getCount();
// If it's empty move to next line
if (line.getLength() == 0)
{
continue;
}
// Split the line into segments
segments.clear();
StringUtil::split(line, ',', segments);
Index generatedColumn = 0;
for (auto segment : segments)
{
Index colDelta;
SLANG_RETURN_ON_FAIL(_decode(segment, colDelta));
generatedColumn += colDelta;
SLANG_ASSERT(generatedColumn >= 0);
// It can be 4 or 5 parts
if (segment.getLength())
{
/* If present, an zero-based index into the "sources" list. This field is a base 64 VLQ relative to the previous occurrence of this field, unless this is the first occurrence of this field, in which case the whole value is represented.
If present, the zero-based starting line in the original source represented. This field is a base 64 VLQ relative to the previous occurrence of this field, unless this is the first occurrence of this field, in which case the whole value is represented. Always present if there is a source field.
If present, the zero-based starting column of the line in the source represented. This field is a base 64 VLQ relative to the previous occurrence of this field, unless this is the first occurrence of this field, in which case the whole value is represented. Always present if there is a source field.
*/
Index sourceFileDelta;
Index sourceLineDelta;
Index sourceColumnDelta;
SLANG_RETURN_ON_FAIL(_decode(segment, sourceFileDelta));
SLANG_RETURN_ON_FAIL(_decode(segment, sourceLineDelta));
SLANG_RETURN_ON_FAIL(_decode(segment, sourceColumnDelta));
sourceFileIndex += sourceFileDelta;
sourceLine += sourceLineDelta;
sourceColumn += sourceColumnDelta;
SLANG_ASSERT(sourceFileIndex >= 0);
SLANG_ASSERT(sourceLine >= 0);
SLANG_ASSERT(sourceColumn >= 0);
// 5 parts
if (segment.getLength() > 0)
{
/* If present, the zero - based index into the "names" list associated with this segment.
This field is a base 64 VLQ relative to the previous occurrence of this field, unless this is the first occurrence
of this field, in which case the whole value is represented.
*/
Index nameDelta;
SLANG_RETURN_ON_FAIL(_decode(segment, nameDelta));
nameIndex += nameDelta;
SLANG_ASSERT(nameIndex >= 0);
}
}
SourceMap::Entry entry;
entry.generatedColumn = generatedColumn;
entry.sourceColumn = sourceColumn;
entry.sourceLine = sourceLine;
entry.sourceFileIndex = sourceFileIndex;
entry.nameIndex = nameIndex;
outSourceMap.m_lineEntries.add(entry);
}
}
// Mark the end
outSourceMap.m_lineStarts[linesCount] = outSourceMap.m_lineEntries.getCount();
return SLANG_OK;
}
SlangResult JSONSourceMapUtil::encode(const SourceMap& sourceMap, JSONContainer* container, DiagnosticSink* sink, JSONValue& outValue)
{
// Convert to native
JSONSourceMap native;
native.file = sourceMap.m_file;
native.sourceRoot = sourceMap.m_sourceRoot;
// Copy over the sources
{
const auto count = sourceMap.m_sources.getCount();
native.sources.setCount(count);
for (Index i = 0; i < count; ++i)
{
native.sources[i] = sourceMap.m_slicePool.getSlice(sourceMap.m_sources[i]);
}
}
// Copy out the sourcesContent, care is needed around handling null
{
const auto count = sourceMap.m_sourcesContent.getCount();
native.sourcesContent.setCount(count);
for (Index i = 0; i < count; ++i)
{
const auto srcValue = sourceMap.m_sourcesContent[i];
const JSONValue dstValue = (srcValue == StringSlicePool::kNullHandle) ?
native.sourcesContent[i] = JSONValue::makeNull() :
container->createString(sourceMap.m_slicePool.getSlice(srcValue));
native.sourcesContent[i] = dstValue;
}
}
// Copy out the names
{
const auto count = sourceMap.m_names.getCount();
native.names.setCount(count);
for (Index i = 0; i < count; ++i)
{
native.names[i] = sourceMap.m_slicePool.getSlice(sourceMap.m_names[i]);
}
}
StringBuilder mappings;
// Do the encoding!
{
const Count linesCount = sourceMap.getGeneratedLineCount();
Index sourceFileIndex = 0;
Index sourceLine = 0;
Index sourceColumn = 0;
Index nameIndex = 0;
for (Index i = 0; i < linesCount; ++i)
{
// Add the semicolon to start the line
if (i > 0)
{
mappings.appendChar(';');
}
const auto entries = sourceMap.getEntriesForLine(i);
const auto entriesCount = entries.getCount();
if (entriesCount == 0)
{
continue;
}
// We reset the generated column index at the start of each new generated line
Index generatedColumn = 0;
for (Index j = 0; j < entriesCount; ++j)
{
auto entry = entries[j];
if (j > 0)
{
mappings.appendChar(',');
}
Index generatedDelta = entry.generatedColumn - generatedColumn;
generatedColumn = entry.generatedColumn;
_encode(generatedDelta, mappings);
// See if there any other deltas we need to handle
const Index sourceFileDelta = entry.sourceFileIndex - sourceFileIndex;
const Index sourceLineDelta = entry.sourceLine - sourceLine;
const Index sourceColumnDelta = entry.sourceColumn - sourceColumn;
const Index nameIndexDelta = entry.nameIndex - nameIndex;
if (sourceFileDelta || sourceLineDelta || sourceColumnDelta || nameIndex)
{
// Okay we have to encode all these deltae
_encode(sourceFileDelta, mappings);
_encode(sourceLineDelta, mappings);
_encode(sourceColumnDelta, mappings);
// Update these values
sourceFileIndex = entry.sourceFileIndex;
sourceLine = entry.sourceLine;
sourceColumn = entry.sourceColumn;
if (nameIndexDelta)
{
_encode(nameIndexDelta, mappings);
nameIndex = entry.nameIndex;
}
}
}
}
}
// Set the mappings
native.mappings = mappings.getUnownedSlice();
// Write it out
{
RttiTypeFuncsMap typeMap = JSONNativeUtil::getTypeFuncsMap();
NativeToJSONConverter converter(container, &typeMap, sink);
SLANG_RETURN_ON_FAIL(converter.convert(GetRttiInfo<JSONSourceMap>::get(), &native, outValue));
}
return SLANG_OK;
}
/* static */SlangResult JSONSourceMapUtil::read(ISlangBlob* blob, SourceMap& outSourceMap)
{
return read(blob, nullptr, outSourceMap);
}
SlangResult JSONSourceMapUtil::read(ISlangBlob* blob, DiagnosticSink* parentSink, SourceMap& outSourceMap)
{
outSourceMap.clear();
SourceManager sourceManager;
sourceManager.initialize(nullptr, nullptr);
DiagnosticSink sink(&sourceManager, nullptr);
sink.setParentSink(parentSink);
RefPtr<JSONContainer> container = new JSONContainer(&sourceManager);
JSONValue rootValue;
{
// Now need to parse as JSON
SourceFile* sourceFile = sourceManager.createSourceFileWithBlob(PathInfo::makeUnknown(), blob);
SourceView* sourceView = sourceManager.createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
lexer.init(sourceView, &sink);
JSONBuilder builder(container);
JSONParser parser;
SLANG_RETURN_ON_FAIL(parser.parse(&lexer, sourceView, &builder, &sink));
rootValue = builder.getRootValue();
}
SLANG_RETURN_ON_FAIL(decode(container, rootValue, &sink, outSourceMap));
return SLANG_OK;
}
/* static */SlangResult JSONSourceMapUtil::write(const SourceMap& sourceMap, ComPtr<ISlangBlob>& outBlob)
{
SourceManager sourceMapSourceManager;
sourceMapSourceManager.initialize(nullptr, nullptr);
// Create a sink
DiagnosticSink sourceMapSink(&sourceMapSourceManager, nullptr);
SLANG_RETURN_ON_FAIL(write(sourceMap, &sourceMapSink, outBlob));
return SLANG_OK;
}
/* static */ SlangResult JSONSourceMapUtil::write(const SourceMap& sourceMap, DiagnosticSink* sink, ComPtr<ISlangBlob>& outBlob)
{
auto sourceManager = sink->getSourceManager();
// Write it out
String json;
{
RefPtr<JSONContainer> jsonContainer(new JSONContainer(sourceManager));
JSONValue jsonValue;
SLANG_RETURN_ON_FAIL(JSONSourceMapUtil::encode(sourceMap, jsonContainer, sink, jsonValue));
// Convert into a string
JSONWriter writer(JSONWriter::IndentationStyle::Allman);
jsonContainer->traverseRecursively(jsonValue, &writer);
json = writer.getBuilder();
}
outBlob = StringBlob::moveCreate(json);
return SLANG_OK;
}
} // namespace Slang
|