/
printer-glimmer.js
807 lines (663 loc) · 20.9 KB
/
printer-glimmer.js
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
"use strict";
const {
builders: {
dedent,
fill,
group,
hardline,
ifBreak,
indent,
join,
line,
softline,
},
utils: { getDocParts, replaceTextEndOfLine },
} = require("../document/index.js");
const { getPreferredQuote, isNonEmptyArray } = require("../common/util.js");
const { locStart, locEnd } = require("./loc.js");
const clean = require("./clean.js");
const {
getNextNode,
getPreviousNode,
hasPrettierIgnore,
isLastNodeOfSiblings,
isNextNodeOfSomeType,
isNodeOfSomeType,
isParentOfSomeType,
isPreviousNodeOfSomeType,
isVoid,
isWhitespaceNode,
} = require("./utils.js");
const NEWLINES_TO_PRESERVE_MAX = 2;
// Formatter based on @glimmerjs/syntax's built-in test formatter:
// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
function print(path, options, print) {
const node = path.getValue();
/* istanbul ignore if*/
if (!node) {
return "";
}
if (hasPrettierIgnore(path)) {
return options.originalText.slice(locStart(node), locEnd(node));
}
const favoriteQuote = options.singleQuote ? "'" : '"';
switch (node.type) {
case "Block":
case "Program":
case "Template": {
return group(path.map(print, "body"));
}
case "ElementNode": {
const startingTag = group(printStartingTag(path, print));
const escapeNextElementNode =
options.htmlWhitespaceSensitivity === "ignore" &&
isNextNodeOfSomeType(path, ["ElementNode"])
? softline
: "";
if (isVoid(node)) {
return [startingTag, escapeNextElementNode];
}
const endingTag = ["</", node.tag, ">"];
if (node.children.length === 0) {
return [startingTag, indent(endingTag), escapeNextElementNode];
}
if (options.htmlWhitespaceSensitivity === "ignore") {
return [
startingTag,
indent(printChildren(path, options, print)),
hardline,
indent(endingTag),
escapeNextElementNode,
];
}
return [
startingTag,
indent(group(printChildren(path, options, print))),
indent(endingTag),
escapeNextElementNode,
];
}
case "BlockStatement": {
const pp = path.getParentNode(1);
const isElseIfLike =
pp &&
pp.inverse &&
pp.inverse.body.length === 1 &&
pp.inverse.body[0] === node &&
pp.inverse.body[0].path.parts[0] === pp.path.parts[0];
if (isElseIfLike) {
return [
printElseIfLikeBlock(path, print, pp.inverse.body[0].path.parts[0]),
printProgram(path, print, options),
printInverse(path, print, options),
];
}
return [
printOpenBlock(path, print),
group([
printProgram(path, print, options),
printInverse(path, print, options),
printCloseBlock(path, print, options),
]),
];
}
case "ElementModifierStatement": {
return group(["{{", printPathAndParams(path, print), "}}"]);
}
case "MustacheStatement": {
return group([
printOpeningMustache(node),
printPathAndParams(path, print),
printClosingMustache(node),
]);
}
case "SubExpression": {
return group([
"(",
printSubExpressionPathAndParams(path, print),
softline,
")",
]);
}
case "AttrNode": {
const isText = node.value.type === "TextNode";
const isEmptyText = isText && node.value.chars === "";
// If the text is empty and the value's loc start and end offsets are the
// same, there is no value for this AttrNode and it should be printed
// without the `=""`. Example: `<img data-test>` -> `<img data-test>`
if (isEmptyText && locStart(node.value) === locEnd(node.value)) {
return node.name;
}
// Let's assume quotes inside the content of text nodes are already
// properly escaped with entities, otherwise the parse wouldn't have parsed them.
const quote = isText
? getPreferredQuote(node.value.chars, favoriteQuote).quote
: node.value.type === "ConcatStatement"
? getPreferredQuote(
node.value.parts
.filter((part) => part.type === "TextNode")
.map((part) => part.chars)
.join(""),
favoriteQuote
).quote
: "";
const valueDoc = print("value");
return [
node.name,
"=",
quote,
node.name === "class" && quote ? group(indent(valueDoc)) : valueDoc,
quote,
];
}
case "ConcatStatement": {
return path.map(print, "parts");
}
case "Hash": {
return join(line, path.map(print, "pairs"));
}
case "HashPair": {
return [node.key, "=", print("value")];
}
case "TextNode": {
/* if `{{my-component}}` (or any text containing "{{")
* makes it to the TextNode, it means it was escaped,
* so let's print it escaped, ie.; `\{{my-component}}` */
let text = node.chars.replace(/{{/g, "\\{{");
const attrName = getCurrentAttributeName(path);
if (attrName) {
// TODO: format style and srcset attributes
if (attrName === "class") {
const formattedClasses = text.trim().split(/\s+/).join(" ");
let leadingSpace = false;
let trailingSpace = false;
if (isParentOfSomeType(path, ["ConcatStatement"])) {
if (
isPreviousNodeOfSomeType(path, ["MustacheStatement"]) &&
/^\s/.test(text)
) {
leadingSpace = true;
}
if (
isNextNodeOfSomeType(path, ["MustacheStatement"]) &&
/\s$/.test(text) &&
formattedClasses !== ""
) {
trailingSpace = true;
}
}
return [
leadingSpace ? line : "",
formattedClasses,
trailingSpace ? line : "",
];
}
return replaceTextEndOfLine(text);
}
const whitespacesOnlyRE = /^[\t\n\f\r ]*$/;
const isWhitespaceOnly = whitespacesOnlyRE.test(text);
const isFirstElement = !getPreviousNode(path);
const isLastElement = !getNextNode(path);
if (options.htmlWhitespaceSensitivity !== "ignore") {
// https://infra.spec.whatwg.org/#ascii-whitespace
const leadingWhitespacesRE = /^[\t\n\f\r ]*/;
const trailingWhitespacesRE = /[\t\n\f\r ]*$/;
// let's remove the file's final newline
// https://github.com/ember-cli/ember-new-output/blob/1a04c67ddd02ccb35e0ff41bb5cbce34b31173ef/.editorconfig#L16
const shouldTrimTrailingNewlines =
isLastElement && isParentOfSomeType(path, ["Template"]);
const shouldTrimLeadingNewlines =
isFirstElement && isParentOfSomeType(path, ["Template"]);
if (isWhitespaceOnly) {
if (shouldTrimLeadingNewlines || shouldTrimTrailingNewlines) {
return "";
}
let breaks = [line];
const newlines = countNewLines(text);
if (newlines) {
breaks = generateHardlines(newlines);
}
if (isLastNodeOfSiblings(path)) {
breaks = breaks.map((newline) => dedent(newline));
}
return breaks;
}
const [lead] = text.match(leadingWhitespacesRE);
const [tail] = text.match(trailingWhitespacesRE);
let leadBreaks = [];
if (lead) {
leadBreaks = [line];
const leadingNewlines = countNewLines(lead);
if (leadingNewlines) {
leadBreaks = generateHardlines(leadingNewlines);
}
text = text.replace(leadingWhitespacesRE, "");
}
let trailBreaks = [];
if (tail) {
if (!shouldTrimTrailingNewlines) {
trailBreaks = [line];
const trailingNewlines = countNewLines(tail);
if (trailingNewlines) {
trailBreaks = generateHardlines(trailingNewlines);
}
if (isLastNodeOfSiblings(path)) {
trailBreaks = trailBreaks.map((hardline) => dedent(hardline));
}
}
text = text.replace(trailingWhitespacesRE, "");
}
return [...leadBreaks, fill(getTextValueParts(text)), ...trailBreaks];
}
const lineBreaksCount = countNewLines(text);
let leadingLineBreaksCount = countLeadingNewLines(text);
let trailingLineBreaksCount = countTrailingNewLines(text);
if (
(isFirstElement || isLastElement) &&
isWhitespaceOnly &&
isParentOfSomeType(path, ["Block", "ElementNode", "Template"])
) {
return "";
}
if (isWhitespaceOnly && lineBreaksCount) {
leadingLineBreaksCount = Math.min(
lineBreaksCount,
NEWLINES_TO_PRESERVE_MAX
);
trailingLineBreaksCount = 0;
} else {
if (isNextNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
}
if (isPreviousNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
}
}
let leadingSpace = "";
let trailingSpace = "";
if (
trailingLineBreaksCount === 0 &&
isNextNodeOfSomeType(path, ["MustacheStatement"])
) {
trailingSpace = " ";
}
if (
leadingLineBreaksCount === 0 &&
isPreviousNodeOfSomeType(path, ["MustacheStatement"])
) {
leadingSpace = " ";
}
if (isFirstElement) {
leadingLineBreaksCount = 0;
leadingSpace = "";
}
if (isLastElement) {
trailingLineBreaksCount = 0;
trailingSpace = "";
}
text = text
.replace(/^[\t\n\f\r ]+/g, leadingSpace)
.replace(/[\t\n\f\r ]+$/, trailingSpace);
return [
...generateHardlines(leadingLineBreaksCount),
fill(getTextValueParts(text)),
...generateHardlines(trailingLineBreaksCount),
];
}
case "MustacheCommentStatement": {
const start = locStart(node);
const end = locEnd(node);
// Starts with `{{~`
const isLeftWhiteSpaceSensitive =
options.originalText.charAt(start + 2) === "~";
// Ends with `{{~`
const isRightWhitespaceSensitive =
options.originalText.charAt(end - 3) === "~";
const dashes = node.value.includes("}}") ? "--" : "";
return [
"{{",
isLeftWhiteSpaceSensitive ? "~" : "",
"!",
dashes,
node.value,
dashes,
isRightWhitespaceSensitive ? "~" : "",
"}}",
];
}
case "PathExpression": {
return node.original;
}
case "BooleanLiteral": {
return String(node.value);
}
case "CommentStatement": {
return ["<!--", node.value, "-->"];
}
case "StringLiteral": {
if (needsOppositeQuote(path)) {
const printFavoriteQuote = !options.singleQuote ? "'" : '"';
return printStringLiteral(node.value, printFavoriteQuote);
}
return printStringLiteral(node.value, favoriteQuote);
}
case "NumberLiteral": {
return String(node.value);
}
case "UndefinedLiteral": {
return "undefined";
}
case "NullLiteral": {
return "null";
}
/* istanbul ignore next */
default:
throw new Error("unknown glimmer type: " + JSON.stringify(node.type));
}
}
/* ElementNode print helpers */
function sortByLoc(a, b) {
return locStart(a) - locStart(b);
}
function printStartingTag(path, print) {
const node = path.getValue();
const types = ["attributes", "modifiers", "comments"].filter((property) =>
isNonEmptyArray(node[property])
);
const attributes = types.flatMap((type) => node[type]).sort(sortByLoc);
for (const attributeType of types) {
path.each((attributePath) => {
const index = attributes.indexOf(attributePath.getValue());
attributes.splice(index, 1, [line, print()]);
}, attributeType);
}
if (isNonEmptyArray(node.blockParams)) {
attributes.push(line, printBlockParams(node));
}
return ["<", node.tag, indent(attributes), printStartingTagEndMarker(node)];
}
function printChildren(path, options, print) {
const node = path.getValue();
const isEmpty = node.children.every((node) => isWhitespaceNode(node));
if (options.htmlWhitespaceSensitivity === "ignore" && isEmpty) {
return "";
}
return path.map((childPath, childIndex) => {
const printedChild = print();
if (childIndex === 0 && options.htmlWhitespaceSensitivity === "ignore") {
return [softline, printedChild];
}
return printedChild;
}, "children");
}
function printStartingTagEndMarker(node) {
if (isVoid(node)) {
return ifBreak([softline, "/>"], [" />", softline]);
}
return ifBreak([softline, ">"], ">");
}
/* MustacheStatement print helpers */
function printOpeningMustache(node) {
const mustache = node.escaped === false ? "{{{" : "{{";
const strip = node.strip && node.strip.open ? "~" : "";
return [mustache, strip];
}
function printClosingMustache(node) {
const mustache = node.escaped === false ? "}}}" : "}}";
const strip = node.strip && node.strip.close ? "~" : "";
return [strip, mustache];
}
/* BlockStatement print helpers */
function printOpeningBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.openStrip.open ? "~" : "";
return [opening, strip, "#"];
}
function printOpeningBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.openStrip.close ? "~" : "";
return [strip, closing];
}
function printClosingBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.closeStrip.open ? "~" : "";
return [opening, strip, "/"];
}
function printClosingBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.closeStrip.close ? "~" : "";
return [strip, closing];
}
function printInverseBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.inverseStrip.open ? "~" : "";
return [opening, strip];
}
function printInverseBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.inverseStrip.close ? "~" : "";
return [strip, closing];
}
function printOpenBlock(path, print) {
const node = path.getValue();
const openingMustache = printOpeningBlockOpeningMustache(node);
const closingMustache = printOpeningBlockClosingMustache(node);
const attributes = [printPath(path, print)];
const params = printParams(path, print);
if (params) {
attributes.push(line, params);
}
if (isNonEmptyArray(node.program.blockParams)) {
const block = printBlockParams(node.program);
attributes.push(line, block);
}
return group([
openingMustache,
indent(attributes),
softline,
closingMustache,
]);
}
function printElseBlock(node, options) {
return [
options.htmlWhitespaceSensitivity === "ignore" ? hardline : "",
printInverseBlockOpeningMustache(node),
"else",
printInverseBlockClosingMustache(node),
];
}
function printElseIfLikeBlock(path, print, ifLikeKeyword) {
const node = path.getValue();
let blockParams = [];
if (isNonEmptyArray(node.program.blockParams)) {
blockParams = [line, printBlockParams(node.program)];
}
const parentNode = path.getParentNode(1);
return group([
printInverseBlockOpeningMustache(parentNode),
indent(
group([
group(["else", line, ifLikeKeyword]),
line,
printParams(path, print),
])
),
indent(blockParams),
softline,
printInverseBlockClosingMustache(parentNode),
]);
}
function printCloseBlock(path, print, options) {
const node = path.getValue();
if (options.htmlWhitespaceSensitivity === "ignore") {
const escape = blockStatementHasOnlyWhitespaceInProgram(node)
? softline
: hardline;
return [
escape,
printClosingBlockOpeningMustache(node),
print("path"),
printClosingBlockClosingMustache(node),
];
}
return [
printClosingBlockOpeningMustache(node),
print("path"),
printClosingBlockClosingMustache(node),
];
}
function blockStatementHasOnlyWhitespaceInProgram(node) {
return (
isNodeOfSomeType(node, ["BlockStatement"]) &&
node.program.body.every((node) => isWhitespaceNode(node))
);
}
function blockStatementHasElseIfLike(node) {
return (
blockStatementHasElse(node) &&
node.inverse.body.length === 1 &&
isNodeOfSomeType(node.inverse.body[0], ["BlockStatement"]) &&
node.inverse.body[0].path.parts[0] === node.path.parts[0]
);
}
function blockStatementHasElse(node) {
return isNodeOfSomeType(node, ["BlockStatement"]) && node.inverse;
}
function printProgram(path, print, options) {
const node = path.getValue();
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
return "";
}
const program = print("program");
if (options.htmlWhitespaceSensitivity === "ignore") {
return indent([hardline, program]);
}
return indent(program);
}
function printInverse(path, print, options) {
const node = path.getValue();
const inverse = print("inverse");
const printed =
options.htmlWhitespaceSensitivity === "ignore"
? [hardline, inverse]
: inverse;
if (blockStatementHasElseIfLike(node)) {
return printed;
}
if (blockStatementHasElse(node)) {
return [printElseBlock(node, options), indent(printed)];
}
return "";
}
/* TextNode print helpers */
function getTextValueParts(value) {
return getDocParts(join(line, splitByHtmlWhitespace(value)));
}
function splitByHtmlWhitespace(string) {
return string.split(/[\t\n\f\r ]+/);
}
function getCurrentAttributeName(path) {
for (let depth = 0; depth < 2; depth++) {
const parentNode = path.getParentNode(depth);
if (parentNode && parentNode.type === "AttrNode") {
return parentNode.name.toLowerCase();
}
}
}
function countNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
return string.split("\n").length - 1;
}
function countLeadingNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || "";
return countNewLines(newLines);
}
function countTrailingNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || "";
return countNewLines(newLines);
}
function generateHardlines(number = 0) {
return Array.from({
length: Math.min(number, NEWLINES_TO_PRESERVE_MAX),
}).fill(hardline);
}
/* StringLiteral print helpers */
/** @typedef {import("../common/util").Quote} Quote */
/**
* Prints a string literal with the correct surrounding quotes based on
* `options.singleQuote` and the number of escaped quotes contained in
* the string literal. This function is the glimmer equivalent of `printString`
* in `common/util`, but has differences because of the way escaped characters
* are treated in hbs string literals.
* @param {string} stringLiteral - the string literal value
* @param {Quote} favoriteQuote - the user's preferred quote: `'` or `"`
*/
function printStringLiteral(stringLiteral, favoriteQuote) {
const { quote, regex } = getPreferredQuote(stringLiteral, favoriteQuote);
return [quote, stringLiteral.replace(regex, `\\${quote}`), quote];
}
function needsOppositeQuote(path) {
let index = 0;
let parentNode = path.getParentNode(index);
while (parentNode && isNodeOfSomeType(parentNode, ["SubExpression"])) {
index++;
parentNode = path.getParentNode(index);
}
if (
parentNode &&
isNodeOfSomeType(path.getParentNode(index + 1), ["ConcatStatement"]) &&
isNodeOfSomeType(path.getParentNode(index + 2), ["AttrNode"])
) {
return true;
}
return false;
}
/* SubExpression print helpers */
function printSubExpressionPathAndParams(path, print) {
const printed = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return printed;
}
return indent([printed, line, group(params)]);
}
/* misc. print helpers */
function printPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return [indent([p, line, params]), softline];
}
function printPath(path, print) {
return print("path");
}
function printParams(path, print) {
const node = path.getValue();
const parts = [];
if (node.params.length > 0) {
const params = path.map(print, "params");
parts.push(...params);
}
if (node.hash && node.hash.pairs.length > 0) {
const hash = print("hash");
parts.push(hash);
}
if (parts.length === 0) {
return "";
}
return join(line, parts);
}
function printBlockParams(node) {
return ["as |", node.blockParams.join(" "), "|"];
}
module.exports = {
print,
massageAstNode: clean,
};