Debian Codegraph @

packages/babel-generator/src/buffer.ts

raw symbols SCIP
1 import type SourceMap from "./source-map";
2 import * as charcodes from "charcodes";
3
4 export type Pos = {
5 line: number;
6 column: number;
7 };
8 export type Loc = {
9 start?: Pos;
10 end?: Pos;
11 identifierName?: string;
12 filename?: string;
13 };
14 type SourcePos = {
15 identifierName: string | undefined;
16 line: number | undefined;
17 column: number | undefined;
18 filename: string | undefined;
19 };
20
21 type QueueItem = {
22 char: number;
23 repeat: number;
24 line: number | undefined;
25 column: number | undefined;
26 identifierName: string | undefined;
27 filename: string | undefined;
28 };
29
30 export default class Buffer {
31 constructor(map?: SourceMap | null) {
32 this._map = map;
33
34 this._allocQueue();
35 }
36
37 _map: SourceMap = null;
38 _buf = "";
39 _str = "";
40 _appendCount = 0;
41 _last = 0;
42 _queue: QueueItem[] = [];
43 _queueCursor = 0;
44
45 _position = {
46 line: 1,
47 column: 0,
48 };
49 _sourcePosition: SourcePos = {
50 identifierName: undefined,
51 line: undefined,
52 column: undefined,
53 filename: undefined,
54 };
55
56 _allocQueue() {
57 const queue = this._queue;
58
59 for (let i = 0; i < 16; i++) {
60 queue.push({
61 char: 0,
62 repeat: 1,
63 line: undefined,
64 column: undefined,
65 identifierName: undefined,
66 filename: "",
67 });
68 }
69 }
70
71 _pushQueue(
72 char: number,
73 repeat: number,
74 line: number | undefined,
75 column: number | undefined,
76 identifierName: string | undefined,
77 filename: string | undefined,
78 ) {
79 const cursor = this._queueCursor;
80 if (cursor === this._queue.length) {
81 this._allocQueue();
82 }
83 const item = this._queue[cursor];
84 item.char = char;
85 item.repeat = repeat;
86 item.line = line;
87 item.column = column;
88 item.identifierName = identifierName;
89 item.filename = filename;
90
91 this._queueCursor++;
92 }
93
94 _popQueue(): QueueItem {
95 if (this._queueCursor === 0) {
96 throw new Error("Cannot pop from empty queue");
97 }
98 return this._queue[--this._queueCursor];
99 }
100
101 /**
102 * Get the final string output from the buffer, along with the sourcemap if one exists.
103 */
104
105 get() {
106 this._flush();
107
108 const map = this._map;
109 const result = {
110 // Whatever trim is used here should not execute a regex against the
111 // source string since it may be arbitrarily large after all transformations
112 code: (this._buf + this._str).trimRight(),
113 // Decoded sourcemap is free to generate.
114 decodedMap: map?.getDecoded(),
115
116 // Encoding the sourcemap is moderately CPU expensive.
117 get map() {
118 const resultMap = map ? map.get() : null;
119 result.map = resultMap;
120 return resultMap;
121 },
122 set map(value) {
123 Object.defineProperty(result, "map", { value, writable: true });
124 },
125 // Retrieving the raw mappings is very memory intensive.
126 get rawMappings() {
127 const mappings = map?.getRawMappings();
128 result.rawMappings = mappings;
129 return mappings;
130 },
131 set rawMappings(value) {
132 Object.defineProperty(result, "rawMappings", { value, writable: true });
133 },
134 };
135
136 return result;
137 }
138
139 /**
140 * Add a string to the buffer that cannot be reverted.
141 */
142
143 append(str: string, maybeNewline: boolean): void {
144 this._flush();
145
146 this._append(str, this._sourcePosition, maybeNewline);
147 }
148
149 appendChar(char: number): void {
150 this._flush();
151 this._appendChar(char, 1, this._sourcePosition);
152 }
153
154 /**
155 * Add a string to the buffer than can be reverted.
156 */
157 queue(char: number): void {
158 // Drop trailing spaces when a newline is inserted.
159 if (char === charcodes.lineFeed) {
160 while (this._queueCursor !== 0) {
161 const char = this._queue[this._queueCursor - 1].char;
162 if (char !== charcodes.space && char !== charcodes.tab) {
163 break;
164 }
165
166 this._queueCursor--;
167 }
168 }
169
170 const sourcePosition = this._sourcePosition;
171 this._pushQueue(
172 char,
173 1,
174 sourcePosition.line,
175 sourcePosition.column,
176 sourcePosition.identifierName,
177 sourcePosition.filename,
178 );
179 }
180
181 /**
182 * Same as queue, but this indentation will never have a sourcmap marker.
183 */
184 queueIndentation(char: number, repeat: number): void {
185 this._pushQueue(char, repeat, undefined, undefined, undefined, undefined);
186 }
187
188 _flush(): void {
189 const queueCursor = this._queueCursor;
190 const queue = this._queue;
191 for (let i = 0; i < queueCursor; i++) {
192 const item: QueueItem = queue[i];
193 this._appendChar(item.char, item.repeat, item);
194 }
195 this._queueCursor = 0;
196 }
197
198 _appendChar(char: number, repeat: number, sourcePos: SourcePos): void {
199 this._last = char;
200
201 this._str +=
202 repeat > 1
203 ? String.fromCharCode(char).repeat(repeat)
204 : String.fromCharCode(char);
205
206 if (char !== charcodes.lineFeed) {
207 this._mark(
208 sourcePos.line,
209 sourcePos.column,
210 sourcePos.identifierName,
211 sourcePos.filename,
212 );
213 this._position.column += repeat;
214 } else {
215 this._position.line++;
216 this._position.column = 0;
217 }
218 }
219
220 _append(str: string, sourcePos: SourcePos, maybeNewline: boolean): void {
221 const len = str.length;
222 const position = this._position;
223
224 this._last = str.charCodeAt(len - 1);
225
226 if (++this._appendCount > 4096) {
227 +this._str; // Unexplainable huge performance boost. Ref: https://github.com/davidmarkclements/flatstr License: MIT
228 this._buf += this._str;
229 this._str = str;
230 this._appendCount = 0;
231 } else {
232 this._str += str;
233 }
234
235 if (!maybeNewline && !this._map) {
236 position.column += len;
237 return;
238 }
239
240 const { column, identifierName, filename } = sourcePos;
241 let line = sourcePos.line;
242
243 // Search for newline chars. We search only for `\n`, since both `\r` and
244 // `\r\n` are normalized to `\n` during parse. We exclude `\u2028` and
245 // `\u2029` for performance reasons, they're so uncommon that it's probably
246 // ok. It's also unclear how other sourcemap utilities handle them...
247 let i = str.indexOf("\n");
248 let last = 0;
249
250 // If the string starts with a newline char, then adding a mark is redundant.
251 // This catches both "no newlines" and "newline after several chars".
252 if (i !== 0) {
253 this._mark(line, column, identifierName, filename);
254 }
255
256 // Now, find each reamining newline char in the string.
257 while (i !== -1) {
258 position.line++;
259 position.column = 0;
260 last = i + 1;
261
262 // We mark the start of each line, which happens directly after this newline char
263 // unless this is the last char.
264 // When manually adding multi-line content (such as a comment), `line` will be `undefined`.
265 if (last < len && line !== undefined) {
266 this._mark(++line, 0, identifierName, filename);
267 }
268 i = str.indexOf("\n", last);
269 }
270 position.column += len - last;
271 }
272
273 _mark(
274 line: number | undefined,
275 column: number | undefined,
276 identifierName: string | undefined,
277 filename: string | undefined,
278 ): void {
279 this._map?.mark(this._position, line, column, identifierName, filename);
280 }
281
282 removeTrailingNewline(): void {
283 const queueCursor = this._queueCursor;
284 if (
285 queueCursor !== 0 &&
286 this._queue[queueCursor - 1].char === charcodes.lineFeed
287 ) {
288 this._queueCursor--;
289 }
290 }
291
292 removeLastSemicolon(): void {
293 const queueCursor = this._queueCursor;
294 if (
295 queueCursor !== 0 &&
296 this._queue[queueCursor - 1].char === charcodes.semicolon
297 ) {
298 this._queueCursor--;
299 }
300 }
301
302 getLastChar(): number {
303 const queueCursor = this._queueCursor;
304 return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last;
305 }
306
307 /**
308 * This will only detect at most 1 newline after a call to `flush()`,
309 * but this has not been found so far, and an accurate count can be achieved if needed later.
310 */
311 getNewlineCount(): number {
312 const queueCursor = this._queueCursor;
313 let count = 0;
314 if (queueCursor === 0) return this._last === charcodes.lineFeed ? 1 : 0;
315 for (let i = queueCursor - 1; i >= 0; i--) {
316 if (this._queue[i].char !== charcodes.lineFeed) {
317 break;
318 }
319 count++;
320 }
321 return count === queueCursor && this._last === charcodes.lineFeed
322 ? count + 1
323 : count;
324 }
325
326 /**
327 * check if current _last + queue ends with newline, return the character before newline
328 *
329 * @param {*} ch
330 * @memberof Buffer
331 */
332 endsWithCharAndNewline(): number {
333 const queue = this._queue;
334 const queueCursor = this._queueCursor;
335 if (queueCursor !== 0) {
336 // every element in queue is one-length whitespace string
337 const lastCp = queue[queueCursor - 1].char;
338 if (lastCp !== charcodes.lineFeed) return;
339 if (queueCursor > 1) {
340 return queue[queueCursor - 2].char;
341 } else {
342 return this._last;
343 }
344 }
345 // We assume that everything being matched is at most a single token plus some whitespace,
346 // which everything currently is, but otherwise we'd have to expand _last or check _buf.
347 }
348
349 hasContent(): boolean {
350 return this._queueCursor !== 0 || !!this._last;
351 }
352
353 /**
354 * Certain sourcemap usecases expect mappings to be more accurate than
355 * Babel's generic sourcemap handling allows. For now, we special-case
356 * identifiers to allow for the primary cases to work.
357 * The goal of this line is to ensure that the map output from Babel will
358 * have an exact range on identifiers in the output code. Without this
359 * line, Babel would potentially include some number of trailing tokens
360 * that are printed after the identifier, but before another location has
361 * been assigned.
362 * This allows tooling like Rollup and Webpack to more accurately perform
363 * their own transformations. Most importantly, this allows the import/export
364 * transformations performed by those tools to loose less information when
365 * applying their own transformations on top of the code and map results
366 * generated by Babel itself.
367 *
368 * The primary example of this is the snippet:
369 *
370 * import mod from "mod";
371 * mod();
372 *
373 * With this line, there will be one mapping range over "mod" and another
374 * over "();", where previously it would have been a single mapping.
375 */
376 exactSource(loc: Loc | undefined, cb: () => void) {
377 if (!this._map) return cb();
378
379 this.source("start", loc);
380
381 cb();
382
383 this.source("end", loc);
384 }
385
386 /**
387 * Sets a given position as the current source location so generated code after this call
388 * will be given this position in the sourcemap.
389 */
390
391 source(prop: "start" | "end", loc: Loc | undefined): void {
392 if (!this._map) return;
393
394 // Since this is called extremely often, we re-use the same _sourcePosition
395 // object for the whole lifetime of the buffer.
396 this._normalizePosition(prop, loc, 0, 0);
397 }
398
399 sourceWithOffset(
400 prop: "start" | "end",
401 loc: Loc | undefined,
402 lineOffset: number,
403 columnOffset: number,
404 ): void {
405 if (!this._map) return;
406
407 this._normalizePosition(prop, loc, lineOffset, columnOffset);
408 }
409
410 /**
411 * Call a callback with a specific source location
412 */
413
414 withSource(prop: "start" | "end", loc: Loc, cb: () => void): void {
415 if (!this._map) return cb();
416
417 this.source(prop, loc);
418
419 cb();
420 }
421
422 _normalizePosition(
423 prop: "start" | "end",
424 loc: Loc,
425 lineOffset: number,
426 columnOffset: number,
427 ) {
428 const pos = loc[prop];
429 const target = this._sourcePosition;
430
431 target.identifierName =
432 (prop === "start" && loc.identifierName) || undefined;
433 if (pos) {
434 target.line = pos.line + lineOffset;
435 target.column = pos.column + columnOffset;
436 target.filename = loc.filename;
437 }
438 }
439
440 getCurrentColumn(): number {
441 const queue = this._queue;
442 const queueCursor = this._queueCursor;
443
444 let lastIndex = -1;
445 let len = 0;
446 for (let i = 0; i < queueCursor; i++) {
447 const item = queue[i];
448 if (item.char === charcodes.lineFeed) {
449 lastIndex = len;
450 }
451 len += item.repeat;
452 }
453
454 return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex;
455 }
456
457 getCurrentLine(): number {
458 let count = 0;
459
460 const queue = this._queue;
461 for (let i = 0; i < this._queueCursor; i++) {
462 if (queue[i].char === charcodes.lineFeed) {
463 count++;
464 }
465 }
466
467 return this._position.line + count;
468 }
469 }