Skip to content

Commit 4d330e2

Browse files
jackyzha0aduh95
authored andcommitted
module: store source map mappings in a typed array
SourceMap kept one six-element array per mapping segment. Bundled applications have millions of segments, and with --enable-source-maps a parsed map lives for the life of the process: a 63 MB source map with 2.9 million segments retained about 290 MiB of heap. Store the segments in a single Int32Array, six fields per segment, and resolve source URLs and names through per-map tables. Segments are counted before parsing so storage is allocated once, and sorting is skipped when the mappings are already in order. The public API and the objects returned by findEntry() and findOrigin() are unchanged. Signed-off-by: Jacky Zhao <j.zhao2k19@gmail.com> PR-URL: #66261 Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent f53eeb2 commit 4d330e2

5 files changed

Lines changed: 352 additions & 56 deletions

File tree

‎lib/internal/source_map/source_map.js‎

Lines changed: 203 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -71,21 +71,40 @@ const {
7171
ArrayPrototypePush,
7272
ArrayPrototypeSlice,
7373
ArrayPrototypeSort,
74+
Int32Array,
75+
MathMax,
7476
ObjectFreeze,
7577
ObjectPrototypeHasOwnProperty,
7678
StringPrototypeCharAt,
7779
Symbol,
80+
TypedArrayPrototypeSet,
81+
TypedArrayPrototypeSlice,
82+
TypedArrayPrototypeSubarray,
7883
} = primordials;
7984

80-
const { validateObject } = require('internal/validators');
85+
const {
86+
validateInt32,
87+
validateObject,
88+
} = require('internal/validators');
8189

8290
let base64Map;
8391

8492
const VLQ_BASE_SHIFT = 5;
8593
const VLQ_BASE_MASK = (1 << 5) - 1;
8694
const VLQ_CONTINUATION_MASK = 1 << 5;
8795

88-
const kMappings = Symbol('kMappings');
96+
const kFirstEntry = Symbol('kFirstEntry');
97+
98+
// Each entry is stored as kEntrySize consecutive Int32 fields: generated line,
99+
// generated column, source index, original line, original column and name
100+
// index. Large maps have millions of entries, and one array per entry costs
101+
// several times more memory than the numbers it holds.
102+
const kEntrySize = 6;
103+
// Source index of an entry that has only a generated column.
104+
const kNoSource = -1;
105+
// Source index of an entry whose source index is outside `sources`.
106+
const kUnknownSource = -2;
107+
const kNoName = -1;
89108

90109
class StringCharIterator {
91110
/**
@@ -126,7 +145,15 @@ class StringCharIterator {
126145
*/
127146
class SourceMap {
128147
#payload;
129-
#mappings = [];
148+
#entries;
149+
#entryCount = 0;
150+
#sourceURLs = [];
151+
// Names of each map, indexed by the entries through a single index space
152+
// that starts at #nameBases[i] for #nameTables[i]. Kept as is instead of
153+
// being copied into one array.
154+
#nameTables = [];
155+
#nameBases = [];
156+
#nameCount = 0;
130157
#sources = {};
131158
#sourceContentByURL = {};
132159
#lineLengths = undefined;
@@ -156,8 +183,8 @@ class SourceMap {
156183
return this.#payload;
157184
}
158185

159-
get [kMappings]() {
160-
return this.#mappings;
186+
get [kFirstEntry]() {
187+
return this.#entryCount ? this.#entryAt(0) : {};
161188
}
162189

163190
/**
@@ -168,20 +195,138 @@ class SourceMap {
168195
}
169196

170197
#parseMappingPayload = () => {
171-
if (this.#payload.sections) {
172-
this.#parseSections(this.#payload.sections);
198+
const { sections } = this.#payload;
199+
let segments = 0;
200+
if (sections) {
201+
for (let i = 0; i < sections.length; ++i) {
202+
segments += estimateSegments(sections[i]?.map?.mappings);
203+
}
204+
} else {
205+
segments = estimateSegments(this.#payload.mappings);
206+
}
207+
this.#entries = new Int32Array(segments * kEntrySize);
208+
if (sections) {
209+
this.#parseSections(sections);
173210
} else {
174211
this.#parseMap(this.#payload, 0, 0);
175212
}
176-
ArrayPrototypeSort(this.#mappings, compareSourceMapEntry);
213+
this.#sortEntries();
177214
};
178215

216+
#sortEntries() {
217+
const entries = this.#entries;
218+
const count = this.#entryCount;
219+
const compare = (a, b) => {
220+
const lineDelta = entries[a * kEntrySize] - entries[b * kEntrySize];
221+
return lineDelta ||
222+
entries[a * kEntrySize + 1] - entries[b * kEntrySize + 1];
223+
};
224+
let sorted = true;
225+
for (let i = 1; i < count; ++i) {
226+
if (compare(i - 1, i) > 0) {
227+
sorted = false;
228+
break;
229+
}
230+
}
231+
if (sorted) {
232+
if (entries.length !== count * kEntrySize) {
233+
this.#entries =
234+
TypedArrayPrototypeSlice(entries, 0, count * kEntrySize);
235+
}
236+
return;
237+
}
238+
// Sorting indices keeps equal positions in insertion order, like the
239+
// stable sort of entries this replaces.
240+
const order = [];
241+
for (let i = 0; i < count; ++i) {
242+
ArrayPrototypePush(order, i);
243+
}
244+
ArrayPrototypeSort(order, compare);
245+
const sortedEntries = new Int32Array(count * kEntrySize);
246+
for (let i = 0; i < count; ++i) {
247+
const offset = order[i] * kEntrySize;
248+
TypedArrayPrototypeSet(
249+
sortedEntries,
250+
TypedArrayPrototypeSubarray(entries, offset, offset + kEntrySize),
251+
i * kEntrySize,
252+
);
253+
}
254+
this.#entries = sortedEntries;
255+
}
256+
257+
#pushEntry(lineNumber, columnNumber, sourceIndex, sourceLineNumber,
258+
sourceColumnNumber, nameIndex) {
259+
const offset = this.#entryCount * kEntrySize;
260+
if (offset === this.#entries.length) {
261+
// Only reached when the parser finds more segments than
262+
// estimateSegments(), which happens for malformed mappings.
263+
const grown =
264+
new Int32Array(MathMax(this.#entries.length * 2, kEntrySize * 16));
265+
TypedArrayPrototypeSet(grown, this.#entries);
266+
this.#entries = grown;
267+
}
268+
const entries = this.#entries;
269+
entries[offset] = lineNumber;
270+
entries[offset + 1] = columnNumber;
271+
entries[offset + 2] = sourceIndex;
272+
entries[offset + 3] = sourceLineNumber;
273+
entries[offset + 4] = sourceColumnNumber;
274+
entries[offset + 5] = nameIndex;
275+
this.#entryCount++;
276+
}
277+
278+
#nameAt(index) {
279+
const bases = this.#nameBases;
280+
// Find the last table starting at or before the index.
281+
let low = 0;
282+
let high = bases.length - 1;
283+
while (low < high) {
284+
const middle = (low + high + 1) >> 1;
285+
if (bases[middle] <= index) {
286+
low = middle;
287+
} else {
288+
high = middle - 1;
289+
}
290+
}
291+
return this.#nameTables[low][index - bases[low]];
292+
}
293+
294+
#entryAt(index) {
295+
const entries = this.#entries;
296+
const offset = index * kEntrySize;
297+
const sourceIndex = entries[offset + 2];
298+
if (sourceIndex === kNoSource) {
299+
return {
300+
generatedLine: entries[offset],
301+
generatedColumn: entries[offset + 1],
302+
originalSource: undefined,
303+
originalLine: undefined,
304+
originalColumn: undefined,
305+
name: undefined,
306+
};
307+
}
308+
const nameIndex = entries[offset + 5];
309+
return {
310+
generatedLine: entries[offset],
311+
generatedColumn: entries[offset + 1],
312+
originalSource: sourceIndex === kUnknownSource ?
313+
undefined : this.#sourceURLs[sourceIndex],
314+
originalLine: entries[offset + 3],
315+
originalColumn: entries[offset + 4],
316+
name: nameIndex === kNoName ? undefined : this.#nameAt(nameIndex),
317+
};
318+
}
319+
179320
/**
180321
* @param {Array.<SourceMapV3.Section>} sections
181322
*/
182323
#parseSections = (sections) => {
183324
for (let i = 0; i < sections.length; ++i) {
184325
const section = sections[i];
326+
// The offsets seed the Int32Array entries below, so reject anything
327+
// that would otherwise be implicitly coerced.
328+
validateInt32(section.offset.line, 'section.offset.line', 0);
329+
validateInt32(section.offset.column, 'section.offset.column', 0);
185330
this.#parseMap(section.map, section.offset.line, section.offset.column);
186331
}
187332
};
@@ -192,35 +337,30 @@ class SourceMap {
192337
* @returns {object} representing start of range if found, or empty object
193338
*/
194339
findEntry(lineOffset, columnOffset) {
340+
const entries = this.#entries;
195341
let first = 0;
196-
let count = this.#mappings.length;
342+
let count = this.#entryCount;
343+
if (!count) {
344+
return {};
345+
}
197346
while (count > 1) {
198347
const step = count >> 1;
199348
const middle = first + step;
200-
const mapping = this.#mappings[middle];
201-
if (lineOffset < mapping[0] ||
202-
(lineOffset === mapping[0] && columnOffset < mapping[1])) {
349+
const line = entries[middle * kEntrySize];
350+
if (lineOffset < line ||
351+
(lineOffset === line &&
352+
columnOffset < entries[middle * kEntrySize + 1])) {
203353
count = step;
204354
} else {
205355
first = middle;
206356
count -= step;
207357
}
208358
}
209-
const entry = this.#mappings[first];
210-
if (!first && entry && (lineOffset < entry[0] ||
211-
(lineOffset === entry[0] && columnOffset < entry[1]))) {
212-
return {};
213-
} else if (!entry) {
359+
if (!first && (lineOffset < entries[0] ||
360+
(lineOffset === entries[0] && columnOffset < entries[1]))) {
214361
return {};
215362
}
216-
return {
217-
generatedLine: entry[0],
218-
generatedColumn: entry[1],
219-
originalSource: entry[2],
220-
originalLine: entry[3],
221-
originalColumn: entry[4],
222-
name: entry[5],
223-
};
363+
return this.#entryAt(first);
224364
}
225365

226366
/**
@@ -260,18 +400,24 @@ class SourceMap {
260400

261401
const sources = [];
262402
const originalToCanonicalURLMap = {};
403+
const sourceBase = this.#sourceURLs.length;
263404
for (let i = 0; i < map.sources.length; ++i) {
264405
const url = map.sources[i];
265406
originalToCanonicalURLMap[url] = url;
266407
ArrayPrototypePush(sources, url);
408+
ArrayPrototypePush(this.#sourceURLs, url);
267409
this.#sources[url] = true;
268410

269411
if (map.sourcesContent?.[i])
270412
this.#sourceContentByURL[url] = map.sourcesContent[i];
271413
}
414+
const names = map.names ?? [];
415+
const nameBase = this.#nameCount;
416+
ArrayPrototypePush(this.#nameTables, names);
417+
ArrayPrototypePush(this.#nameBases, nameBase);
418+
this.#nameCount += names.length;
272419

273420
const stringCharIterator = new StringCharIterator(map.mappings);
274-
let sourceURL = sources[sourceIndex];
275421
while (true) {
276422
if (stringCharIterator.peek() === ',')
277423
stringCharIterator.next();
@@ -287,33 +433,51 @@ class SourceMap {
287433

288434
columnNumber += decodeVLQ(stringCharIterator);
289435
if (isSeparator(stringCharIterator.peek())) {
290-
ArrayPrototypePush(this.#mappings, [lineNumber, columnNumber]);
436+
this.#pushEntry(lineNumber, columnNumber, kNoSource, 0, 0, kNoName);
291437
continue;
292438
}
293439

294-
const sourceIndexDelta = decodeVLQ(stringCharIterator);
295-
if (sourceIndexDelta) {
296-
sourceIndex += sourceIndexDelta;
297-
sourceURL = sources[sourceIndex];
298-
}
440+
sourceIndex += decodeVLQ(stringCharIterator);
299441
sourceLineNumber += decodeVLQ(stringCharIterator);
300442
sourceColumnNumber += decodeVLQ(stringCharIterator);
301443

302-
let name;
444+
let entryNameIndex = kNoName;
303445
if (!isSeparator(stringCharIterator.peek())) {
304446
nameIndex += decodeVLQ(stringCharIterator);
305-
name = map.names?.[nameIndex];
447+
if (nameIndex >= 0 && nameIndex < names.length) {
448+
entryNameIndex = nameBase + nameIndex;
449+
}
306450
}
307451

308-
ArrayPrototypePush(
309-
this.#mappings,
310-
[lineNumber, columnNumber, sourceURL, sourceLineNumber,
311-
sourceColumnNumber, name],
452+
this.#pushEntry(
453+
lineNumber,
454+
columnNumber,
455+
sourceIndex >= 0 && sourceIndex < sources.length ?
456+
sourceBase + sourceIndex : kUnknownSource,
457+
sourceLineNumber,
458+
sourceColumnNumber,
459+
entryNameIndex,
312460
);
313461
}
314462
}
315463
}
316464

465+
/**
466+
* Estimates the number of segments in a mappings string, so entry storage
467+
* can be allocated up front without a separate pass over the string. A
468+
* segment takes four to five VLQ digits and a separator in typical maps.
469+
* #pushEntry grows the storage if the estimate turns out to be too low, and
470+
* #sortEntries trims it if it is too high.
471+
* @param {string} mappings
472+
* @returns {number}
473+
*/
474+
function estimateSegments(mappings) {
475+
if (typeof mappings !== 'string') {
476+
return 0;
477+
}
478+
return (mappings.length + 3) >> 2;
479+
}
480+
317481
/**
318482
* @param {string} char
319483
* @returns {boolean}
@@ -370,22 +534,7 @@ function cloneSourceMapV3(payload) {
370534
return ObjectFreeze(payload);
371535
}
372536

373-
/**
374-
* @param {Array} entry1 source map entry [lineNumber, columnNumber, sourceURL,
375-
* sourceLineNumber, sourceColumnNumber]
376-
* @param {Array} entry2 source map entry.
377-
* @returns {number}
378-
*/
379-
function compareSourceMapEntry(entry1, entry2) {
380-
const { 0: lineNumber1, 1: columnNumber1 } = entry1;
381-
const { 0: lineNumber2, 1: columnNumber2 } = entry2;
382-
if (lineNumber1 !== lineNumber2) {
383-
return lineNumber1 - lineNumber2;
384-
}
385-
return columnNumber1 - columnNumber2;
386-
}
387-
388537
module.exports = {
389-
kMappings,
538+
kFirstEntry,
390539
SourceMap,
391540
};

‎lib/internal/test_runner/coverage.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ const { isWindows, setupCoverageHooks } = require('internal/util');
3131
const { tmpdir } = require('os');
3232
const { join, resolve, relative } = require('path');
3333
const { fileURLToPath, pathToFileURL, URL } = require('internal/url');
34-
const { kMappings, SourceMap } = require('internal/source_map/source_map');
34+
const { kFirstEntry, SourceMap } = require('internal/source_map/source_map');
3535
const {
3636
codes: {
3737
ERR_OPERATION_FAILED,
@@ -521,7 +521,7 @@ class TestCoverage {
521521
if (!startEntry.originalSource && endEntry.originalSource &&
522522
lines[0].line === 1 && startOffset === 0 && lines[0].startOffset === 0) {
523523
// Edge case when the first line is not mappable
524-
const { 2: originalSource, 3: originalLine, 4: originalColumn } = sourceMap[kMappings][0];
524+
const { originalSource, originalLine, originalColumn } = sourceMap[kFirstEntry];
525525
startEntry = { __proto__: null, originalSource, originalLine, originalColumn };
526526
}
527527

0 commit comments

Comments
 (0)