forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprinter.js
More file actions
667 lines (580 loc) · 18 KB
/
printer.js
File metadata and controls
667 lines (580 loc) · 18 KB
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
import { convertEndOfLineToChars } from "../common/end-of-line.js";
import getStringWidth from "../utils/get-string-width.js";
import { fill, hardlineWithoutBreakParent, indent } from "./builders.js";
import {
DOC_TYPE_ALIGN,
DOC_TYPE_ARRAY,
DOC_TYPE_BREAK_PARENT,
DOC_TYPE_CURSOR,
DOC_TYPE_FILL,
DOC_TYPE_GROUP,
DOC_TYPE_IF_BREAK,
DOC_TYPE_INDENT,
DOC_TYPE_INDENT_IF_BREAK,
DOC_TYPE_LABEL,
DOC_TYPE_LINE,
DOC_TYPE_LINE_SUFFIX,
DOC_TYPE_LINE_SUFFIX_BOUNDARY,
DOC_TYPE_STRING,
DOC_TYPE_TRIM,
} from "./constants.js";
import InvalidDocError from "./invalid-doc-error.js";
import { getDocType, propagateBreaks } from "./utils.js";
/** @typedef {typeof MODE_BREAK | typeof MODE_FLAT} Mode */
/** @typedef {{ ind: any, doc: any, mode: Mode }} Command */
/** @typedef {Record<symbol, Mode>} GroupModeMap */
/** @type {unique symbol} */
const MODE_BREAK = Symbol("MODE_BREAK");
/** @type {unique symbol} */
const MODE_FLAT = Symbol("MODE_FLAT");
const CURSOR_PLACEHOLDER = Symbol("cursor");
function rootIndent() {
return { value: "", length: 0, queue: [] };
}
function makeIndent(ind, options) {
return generateInd(ind, { type: "indent" }, options);
}
function makeAlign(indent, widthOrDoc, options) {
if (widthOrDoc === Number.NEGATIVE_INFINITY) {
return indent.root || rootIndent();
}
if (widthOrDoc < 0) {
return generateInd(indent, { type: "dedent" }, options);
}
if (!widthOrDoc) {
return indent;
}
if (widthOrDoc.type === "root") {
return { ...indent, root: indent };
}
const alignType =
typeof widthOrDoc === "string" ? "stringAlign" : "numberAlign";
return generateInd(indent, { type: alignType, n: widthOrDoc }, options);
}
function generateInd(ind, newPart, options) {
const queue =
newPart.type === "dedent"
? ind.queue.slice(0, -1)
: [...ind.queue, newPart];
let value = "";
let length = 0;
let lastTabs = 0;
let lastSpaces = 0;
for (const part of queue) {
switch (part.type) {
case "indent":
flush();
if (options.useTabs) {
addTabs(1);
} else {
addSpaces(options.tabWidth);
}
break;
case "stringAlign":
flush();
value += part.n;
length += part.n.length;
break;
case "numberAlign":
lastTabs += 1;
lastSpaces += part.n;
break;
default:
/* c8 ignore next */
throw new Error(`Unexpected type '${part.type}'`);
}
}
flushSpaces();
return { ...ind, value, length, queue };
function addTabs(count) {
value += "\t".repeat(count);
length += options.tabWidth * count;
}
function addSpaces(count) {
value += " ".repeat(count);
length += count;
}
function flush() {
if (options.useTabs) {
flushTabs();
} else {
flushSpaces();
}
}
function flushTabs() {
if (lastTabs > 0) {
addTabs(lastTabs);
}
resetLast();
}
function flushSpaces() {
if (lastSpaces > 0) {
addSpaces(lastSpaces);
}
resetLast();
}
function resetLast() {
lastTabs = 0;
lastSpaces = 0;
}
}
// Trim `Tab(U+0009)` and `Space(U+0020)` at the end of line
function trim(out) {
let trimCount = 0;
let cursorCount = 0;
let outIndex = out.length;
outer: while (outIndex--) {
const last = out[outIndex];
if (last === CURSOR_PLACEHOLDER) {
cursorCount++;
continue;
}
/* c8 ignore next 3 */
if (process.env.NODE_ENV !== "production" && typeof last !== "string") {
throw new Error(`Unexpected value in trim: '${typeof last}'`);
}
// Not using a regexp here because regexps for trimming off trailing
// characters are known to have performance issues.
for (let charIndex = last.length - 1; charIndex >= 0; charIndex--) {
const char = last[charIndex];
if (char === " " || char === "\t") {
trimCount++;
} else {
out[outIndex] = last.slice(0, charIndex + 1);
break outer;
}
}
}
if (trimCount > 0 || cursorCount > 0) {
out.length = outIndex + 1;
while (cursorCount-- > 0) {
out.push(CURSOR_PLACEHOLDER);
}
}
return trimCount;
}
/**
* @param {Command} next
* @param {Command[]} restCommands
* @param {number} width
* @param {boolean} hasLineSuffix
* @param {GroupModeMap} groupModeMap
* @param {boolean} [mustBeFlat]
* @returns {boolean}
*/
function fits(
next,
restCommands,
width,
hasLineSuffix,
groupModeMap,
mustBeFlat,
) {
if (width === Number.POSITIVE_INFINITY) {
return true;
}
let restIdx = restCommands.length;
/** @type {Array<Omit<Command, 'ind'>>} */
const cmds = [next];
// `out` is only used for width counting because `trim` requires to look
// backwards for space characters.
const out = [];
while (width >= 0) {
if (cmds.length === 0) {
if (restIdx === 0) {
return true;
}
cmds.push(restCommands[--restIdx]);
continue;
}
const { mode, doc } = cmds.pop();
const docType = getDocType(doc);
switch (docType) {
case DOC_TYPE_STRING:
out.push(doc);
width -= getStringWidth(doc);
break;
case DOC_TYPE_ARRAY:
case DOC_TYPE_FILL: {
const parts = docType === DOC_TYPE_ARRAY ? doc : doc.parts;
for (let i = parts.length - 1; i >= 0; i--) {
cmds.push({ mode, doc: parts[i] });
}
break;
}
case DOC_TYPE_INDENT:
case DOC_TYPE_ALIGN:
case DOC_TYPE_INDENT_IF_BREAK:
case DOC_TYPE_LABEL:
cmds.push({ mode, doc: doc.contents });
break;
case DOC_TYPE_TRIM:
width += trim(out);
break;
case DOC_TYPE_GROUP: {
if (mustBeFlat && doc.break) {
return false;
}
const groupMode = doc.break ? MODE_BREAK : mode;
// The most expanded state takes up the least space on the current line.
const contents =
doc.expandedStates && groupMode === MODE_BREAK
? doc.expandedStates.at(-1)
: doc.contents;
cmds.push({ mode: groupMode, doc: contents });
break;
}
case DOC_TYPE_IF_BREAK: {
const groupMode = doc.groupId
? groupModeMap[doc.groupId] || MODE_FLAT
: mode;
const contents =
groupMode === MODE_BREAK ? doc.breakContents : doc.flatContents;
if (contents) {
cmds.push({ mode, doc: contents });
}
break;
}
case DOC_TYPE_LINE:
if (mode === MODE_BREAK || doc.hard) {
return true;
}
if (!doc.soft) {
out.push(" ");
width--;
}
break;
case DOC_TYPE_LINE_SUFFIX:
hasLineSuffix = true;
break;
case DOC_TYPE_LINE_SUFFIX_BOUNDARY:
if (hasLineSuffix) {
return false;
}
break;
}
}
return false;
}
function printDocToString(doc, options) {
/** @type GroupModeMap */
const groupModeMap = {};
const width = options.printWidth;
const newLine = convertEndOfLineToChars(options.endOfLine);
let pos = 0;
// cmds is basically a stack. We've turned a recursive call into a
// while loop which is much faster. The while loop below adds new
// cmds to the array instead of recursively calling `print`.
/** @type Command[] */
const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];
const out = [];
let shouldRemeasure = false;
/** @type Command[] */
const lineSuffix = [];
let printedCursorCount = 0;
propagateBreaks(doc);
while (cmds.length > 0) {
const { ind, mode, doc } = cmds.pop();
switch (getDocType(doc)) {
case DOC_TYPE_STRING: {
const formatted =
newLine !== "\n" ? doc.replaceAll("\n", newLine) : doc;
out.push(formatted);
// Plugins may print single string, should skip measure the width
if (cmds.length > 0) {
pos += getStringWidth(formatted);
}
break;
}
case DOC_TYPE_ARRAY:
for (let i = doc.length - 1; i >= 0; i--) {
cmds.push({ ind, mode, doc: doc[i] });
}
break;
case DOC_TYPE_CURSOR:
if (printedCursorCount >= 2) {
throw new Error("There are too many 'cursor' in doc.");
}
out.push(CURSOR_PLACEHOLDER);
printedCursorCount++;
break;
case DOC_TYPE_INDENT:
cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });
break;
case DOC_TYPE_ALIGN:
cmds.push({
ind: makeAlign(ind, doc.n, options),
mode,
doc: doc.contents,
});
break;
case DOC_TYPE_TRIM:
pos -= trim(out);
break;
case DOC_TYPE_GROUP:
switch (mode) {
case MODE_FLAT:
if (!shouldRemeasure) {
cmds.push({
ind,
mode: doc.break ? MODE_BREAK : MODE_FLAT,
doc: doc.contents,
});
break;
}
// fallthrough
case MODE_BREAK: {
shouldRemeasure = false;
/** @type {Command} */
const next = { ind, mode: MODE_FLAT, doc: doc.contents };
const rem = width - pos;
const hasLineSuffix = lineSuffix.length > 0;
if (
!doc.break &&
fits(next, cmds, rem, hasLineSuffix, groupModeMap)
) {
cmds.push(next);
} else {
// Expanded states are a rare case where a document
// can manually provide multiple representations of
// itself. It provides an array of documents
// going from the least expanded (most flattened)
// representation first to the most expanded. If a
// group has these, we need to manually go through
// these states and find the first one that fits.
// eslint-disable-next-line no-lonely-if
if (doc.expandedStates) {
const mostExpanded = doc.expandedStates.at(-1);
if (doc.break) {
cmds.push({ ind, mode: MODE_BREAK, doc: mostExpanded });
break;
} else {
for (let i = 1; i < doc.expandedStates.length + 1; i++) {
if (i >= doc.expandedStates.length) {
cmds.push({ ind, mode: MODE_BREAK, doc: mostExpanded });
break;
} else {
const state = doc.expandedStates[i];
/** @type {Command} */
const cmd = { ind, mode: MODE_FLAT, doc: state };
if (fits(cmd, cmds, rem, hasLineSuffix, groupModeMap)) {
cmds.push(cmd);
break;
}
}
}
}
} else {
cmds.push({ ind, mode: MODE_BREAK, doc: doc.contents });
}
}
break;
}
}
if (doc.id) {
groupModeMap[doc.id] = cmds.at(-1).mode;
}
break;
// Fills each line with as much code as possible before moving to a new
// line with the same indentation.
//
// Expects doc.parts to be an array of alternating content and
// whitespace. The whitespace contains the linebreaks.
//
// For example:
// ["I", line, "love", line, "monkeys"]
// or
// [{ type: group, ... }, softline, { type: group, ... }]
//
// It uses this parts structure to handle three main layout cases:
// * The first two content items fit on the same line without
// breaking
// -> output the first content item and the whitespace "flat".
// * Only the first content item fits on the line without breaking
// -> output the first content item "flat" and the whitespace with
// "break".
// * Neither content item fits on the line without breaking
// -> output the first content item and the whitespace with "break".
case DOC_TYPE_FILL: {
const rem = width - pos;
const { parts } = doc;
if (parts.length === 0) {
break;
}
const [content, whitespace] = parts;
/** @type {Command} */
const contentFlatCmd = { ind, mode: MODE_FLAT, doc: content };
/** @type {Command} */
const contentBreakCmd = { ind, mode: MODE_BREAK, doc: content };
const contentFits = fits(
contentFlatCmd,
[],
rem,
lineSuffix.length > 0,
groupModeMap,
true,
);
if (parts.length === 1) {
if (contentFits) {
cmds.push(contentFlatCmd);
} else {
cmds.push(contentBreakCmd);
}
break;
}
/** @type {Command} */
const whitespaceFlatCmd = { ind, mode: MODE_FLAT, doc: whitespace };
/** @type {Command} */
const whitespaceBreakCmd = { ind, mode: MODE_BREAK, doc: whitespace };
if (parts.length === 2) {
if (contentFits) {
cmds.push(whitespaceFlatCmd, contentFlatCmd);
} else {
cmds.push(whitespaceBreakCmd, contentBreakCmd);
}
break;
}
// At this point we've handled the first pair (context, separator)
// and will create a new fill doc for the rest of the content.
// Ideally we wouldn't mutate the array here but copying all the
// elements to a new array would make this algorithm quadratic,
// which is unusable for large arrays (e.g. large texts in JSX).
parts.splice(0, 2);
/** @type {Command} */
const remainingCmd = { ind, mode, doc: fill(parts) };
const secondContent = parts[0];
/** @type {Command} */
const firstAndSecondContentFlatCmd = {
ind,
mode: MODE_FLAT,
doc: [content, whitespace, secondContent],
};
const firstAndSecondContentFits = fits(
firstAndSecondContentFlatCmd,
[],
rem,
lineSuffix.length > 0,
groupModeMap,
true,
);
if (firstAndSecondContentFits) {
cmds.push(remainingCmd, whitespaceFlatCmd, contentFlatCmd);
} else if (contentFits) {
cmds.push(remainingCmd, whitespaceBreakCmd, contentFlatCmd);
} else {
cmds.push(remainingCmd, whitespaceBreakCmd, contentBreakCmd);
}
break;
}
case DOC_TYPE_IF_BREAK:
case DOC_TYPE_INDENT_IF_BREAK: {
const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
if (groupMode === MODE_BREAK) {
const breakContents =
doc.type === DOC_TYPE_IF_BREAK
? doc.breakContents
: doc.negate
? doc.contents
: indent(doc.contents);
if (breakContents) {
cmds.push({ ind, mode, doc: breakContents });
}
}
if (groupMode === MODE_FLAT) {
const flatContents =
doc.type === DOC_TYPE_IF_BREAK
? doc.flatContents
: doc.negate
? indent(doc.contents)
: doc.contents;
if (flatContents) {
cmds.push({ ind, mode, doc: flatContents });
}
}
break;
}
case DOC_TYPE_LINE_SUFFIX:
lineSuffix.push({ ind, mode, doc: doc.contents });
break;
case DOC_TYPE_LINE_SUFFIX_BOUNDARY:
if (lineSuffix.length > 0) {
cmds.push({ ind, mode, doc: hardlineWithoutBreakParent });
}
break;
case DOC_TYPE_LINE:
switch (mode) {
case MODE_FLAT:
if (!doc.hard) {
if (!doc.soft) {
out.push(" ");
pos += 1;
}
break;
} else {
// This line was forced into the output even if we
// were in flattened mode, so we need to tell the next
// group that no matter what, it needs to remeasure
// because the previous measurement didn't accurately
// capture the entire expression (this is necessary
// for nested groups)
shouldRemeasure = true;
}
// fallthrough
case MODE_BREAK:
if (lineSuffix.length > 0) {
cmds.push({ ind, mode, doc }, ...lineSuffix.reverse());
lineSuffix.length = 0;
break;
}
if (doc.literal) {
if (ind.root) {
out.push(newLine, ind.root.value);
pos = ind.root.length;
} else {
out.push(newLine);
pos = 0;
}
} else {
pos -= trim(out);
out.push(newLine + ind.value);
pos = ind.length;
}
break;
}
break;
case DOC_TYPE_LABEL:
cmds.push({ ind, mode, doc: doc.contents });
break;
case DOC_TYPE_BREAK_PARENT:
// No op
break;
default:
throw new InvalidDocError(doc);
}
// Flush remaining line-suffix contents at the end of the document, in case
// there is no new line after the line-suffix.
if (cmds.length === 0 && lineSuffix.length > 0) {
cmds.push(...lineSuffix.reverse());
lineSuffix.length = 0;
}
}
const cursorPlaceholderIndex = out.indexOf(CURSOR_PLACEHOLDER);
if (cursorPlaceholderIndex !== -1) {
const otherCursorPlaceholderIndex = out.indexOf(
CURSOR_PLACEHOLDER,
cursorPlaceholderIndex + 1,
);
const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
const aroundCursor = out
.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex)
.join("");
const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
return {
formatted: beforeCursor + aroundCursor + afterCursor,
cursorNodeStart: beforeCursor.length,
cursorNodeText: aroundCursor,
};
}
return { formatted: out.join("") };
}
export { printDocToString };