@tsrx/prettier-plugin 0.4.12 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +186 -4
- package/package.json +9 -5
- package/src/index.js +29 -13083
- package/src/jsx.js +533 -0
- package/src/parse.js +800 -0
- package/src/printer.js +1262 -0
- package/src/range.js +236 -0
- package/src/index.test.js +0 -17983
package/src/printer.js
ADDED
|
@@ -0,0 +1,1262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @import { AstPath, Doc, ParserOptions, Printer } from 'prettier'
|
|
3
|
+
* @import { Node } from './parse.js'
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { builders, utils } from 'prettier/doc';
|
|
7
|
+
import * as estreePlugin from 'prettier/plugins/estree';
|
|
8
|
+
import * as standalone from 'prettier/standalone';
|
|
9
|
+
import { printJsxElementInternal } from './jsx.js';
|
|
10
|
+
import { TSRX_DIRECTIVES, isRawScriptElement } from './parse.js';
|
|
11
|
+
|
|
12
|
+
const {
|
|
13
|
+
breakParent,
|
|
14
|
+
group,
|
|
15
|
+
hardline,
|
|
16
|
+
ifBreak,
|
|
17
|
+
indent,
|
|
18
|
+
join,
|
|
19
|
+
line,
|
|
20
|
+
lineSuffix,
|
|
21
|
+
lineSuffixBoundary,
|
|
22
|
+
softline,
|
|
23
|
+
} = builders;
|
|
24
|
+
const { replaceEndOfLine } = utils;
|
|
25
|
+
// Prettier's text and comment helpers. `prettier/standalone` exports the same
|
|
26
|
+
// `util` as `prettier` and loads in the browser too; only its types leave
|
|
27
|
+
// `util` out.
|
|
28
|
+
const {
|
|
29
|
+
addDanglingComment,
|
|
30
|
+
hasNewline,
|
|
31
|
+
isNextLineEmpty,
|
|
32
|
+
isPreviousLineEmpty,
|
|
33
|
+
skipNewline,
|
|
34
|
+
skipSpaces,
|
|
35
|
+
} = /** @type {{ util: typeof import('prettier').util }} */ (/** @type {unknown} */ (standalone))
|
|
36
|
+
.util;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Prettier's own JS/TS printer. Everything that isn't TSRX syntax is printed by
|
|
40
|
+
* it unchanged.
|
|
41
|
+
* @type {Printer<Node>}
|
|
42
|
+
*/
|
|
43
|
+
const estree = /** @type {Printer<Node>} */ (estreePlugin.printers.estree);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @typedef {(selector?: string | number | Array<string | number> | AstPath) => Doc} Print
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/** @type {WeakMap<object, object>} */
|
|
50
|
+
const typescriptOptions = new WeakMap();
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The options as Prettier's printer sees them for its own `typescript` parser.
|
|
54
|
+
* The printer checks the parser's name in a few places, such as keeping the
|
|
55
|
+
* quotes of a class property's key, and the TSRX AST has the typescript-estree
|
|
56
|
+
* shape.
|
|
57
|
+
* @template {object} T
|
|
58
|
+
* @param {T} options
|
|
59
|
+
* @returns {T}
|
|
60
|
+
*/
|
|
61
|
+
function asTypeScript(options) {
|
|
62
|
+
let result = typescriptOptions.get(options);
|
|
63
|
+
if (!result) {
|
|
64
|
+
result = { ...options, parser: 'typescript' };
|
|
65
|
+
typescriptOptions.set(options, result);
|
|
66
|
+
}
|
|
67
|
+
return /** @type {T} */ (result);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Child keys of the TSRX nodes, which Prettier's visitor keys don't know. */
|
|
71
|
+
const TSRX_VISITOR_KEYS = /** @type {Record<string, string[]>} */ ({
|
|
72
|
+
JSXIfExpression: ['test', 'consequent', 'alternate'],
|
|
73
|
+
JSXForExpression: ['init', 'test', 'update', 'left', 'right', 'index', 'key', 'body', 'empty'],
|
|
74
|
+
JSXSwitchExpression: ['discriminant', 'cases'],
|
|
75
|
+
JSXTryExpression: ['block', 'pending', 'handler'],
|
|
76
|
+
TSRXRangeText: [],
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/** `@catch (error, reset)` has a second parameter. */
|
|
80
|
+
const CATCH_CLAUSE_KEYS = ['param', 'resetParam', 'body'];
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A shorthand attribute (`{name}`) prints only its value: its `name` is the
|
|
84
|
+
* same identifier as the value's expression, so no comment may attach to it.
|
|
85
|
+
*/
|
|
86
|
+
const SHORTHAND_ATTRIBUTE_KEYS = ['value'];
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Directives whose comments Prettier places as in the statements they're
|
|
90
|
+
* written like: a comment before `@else` or `@catch` stays after the `}` (a
|
|
91
|
+
* line comment before `@catch` moves into its body), and one before a body's
|
|
92
|
+
* `{` moves into the body.
|
|
93
|
+
*/
|
|
94
|
+
const COMMENT_STATEMENT_DIRECTIVES = new Set([
|
|
95
|
+
'JSXForExpression',
|
|
96
|
+
'JSXIfExpression',
|
|
97
|
+
'JSXSwitchExpression',
|
|
98
|
+
'JSXTryExpression',
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* One of Prettier's comment handlers, run while a directive enclosing the
|
|
103
|
+
* comment presents itself as its statement.
|
|
104
|
+
* @param {((context: any) => boolean) | undefined} handle
|
|
105
|
+
* @returns {((context: any) => boolean) | undefined}
|
|
106
|
+
*/
|
|
107
|
+
function withDirectivesAsStatements(handle) {
|
|
108
|
+
if (!handle) return handle;
|
|
109
|
+
return (context) => {
|
|
110
|
+
if (handleCommentBeforeEmpty(context)) return true;
|
|
111
|
+
const node = context.enclosingNode;
|
|
112
|
+
if (!COMMENT_STATEMENT_DIRECTIVES.has(node?.tsrxType)) return handle(context);
|
|
113
|
+
return asStatement(node, () => handle(context));
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A comment between a `@for` body and `@empty` stays there, as a comment
|
|
119
|
+
* before `else` does: it becomes a dangling comment of the `@for`, which
|
|
120
|
+
* `printFor` prints before `@empty`.
|
|
121
|
+
* @param {{ comment: Node, precedingNode?: Node, enclosingNode?: Node, followingNode?: Node, text: string }} context
|
|
122
|
+
* @returns {boolean}
|
|
123
|
+
*/
|
|
124
|
+
function handleCommentBeforeEmpty({ comment, precedingNode, enclosingNode, followingNode, text }) {
|
|
125
|
+
if (
|
|
126
|
+
enclosingNode?.tsrxType !== 'JSXForExpression' ||
|
|
127
|
+
!followingNode ||
|
|
128
|
+
precedingNode !== enclosingNode.body ||
|
|
129
|
+
followingNode !== enclosingNode.empty ||
|
|
130
|
+
!text.slice(comment.end, followingNode.start).includes('@empty')
|
|
131
|
+
) {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
addDanglingComment(enclosingNode, comment, undefined);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const estreeCommentHandlers = /** @type {Record<string, any>} */ (estree.handleComments);
|
|
139
|
+
|
|
140
|
+
/** @type {Printer<Node>} */
|
|
141
|
+
export const printer = {
|
|
142
|
+
...estree,
|
|
143
|
+
|
|
144
|
+
handleComments: {
|
|
145
|
+
...estreeCommentHandlers,
|
|
146
|
+
ownLine: withDirectivesAsStatements(estreeCommentHandlers.ownLine),
|
|
147
|
+
endOfLine: withDirectivesAsStatements(estreeCommentHandlers.endOfLine),
|
|
148
|
+
remaining: withDirectivesAsStatements(estreeCommentHandlers.remaining),
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
// Prettier's JSX printer prints an element's own comments, and so does this
|
|
152
|
+
// plugin for the elements it prints itself (`printElement`). It also prints
|
|
153
|
+
// the comments of a `@{ … }` value or a directive (inside its parentheses),
|
|
154
|
+
// and of a tag name (`printTagNameComments`).
|
|
155
|
+
/**
|
|
156
|
+
* @param {AstPath<Node>} path
|
|
157
|
+
* @param {...unknown} rest
|
|
158
|
+
*/
|
|
159
|
+
willPrintOwnComments(path, ...rest) {
|
|
160
|
+
if (isTsrxValue(path) || isCommentedTagName(path) || isCatchDirective(path)) return true;
|
|
161
|
+
const willPrintOwnComments = /** @type {(...args: unknown[]) => boolean} */ (
|
|
162
|
+
estree.willPrintOwnComments
|
|
163
|
+
);
|
|
164
|
+
return willPrintOwnComments(path, ...rest);
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
getVisitorKeys(node, nonTraversableKeys) {
|
|
168
|
+
const keys = TSRX_VISITOR_KEYS[node.tsrxType ?? node.type];
|
|
169
|
+
if (keys) return keys;
|
|
170
|
+
if (node.type === 'CatchClause' && node.resetParam) return CATCH_CLAUSE_KEYS;
|
|
171
|
+
if (node.type === 'JSXAttribute' && node.shorthand) return SHORTHAND_ATTRIBUTE_KEYS;
|
|
172
|
+
return /** @type {NonNullable<Printer<Node>['getVisitorKeys']>} */ (estree.getVisitorKeys)(
|
|
173
|
+
node,
|
|
174
|
+
nonTraversableKeys,
|
|
175
|
+
);
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
print(path, options, print, args) {
|
|
179
|
+
// A value that presents itself as a JSX element while its parent prints
|
|
180
|
+
// (`withTsrxValuesAsJsx`) prints itself as what it is.
|
|
181
|
+
const presentedAs = presentedAsJsx.get(path.node);
|
|
182
|
+
if (presentedAs !== undefined) {
|
|
183
|
+
path.node.type = presentedAs;
|
|
184
|
+
try {
|
|
185
|
+
return printNode(path, options, print, args);
|
|
186
|
+
} finally {
|
|
187
|
+
path.node.type = 'JSXElement';
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return printNode(path, options, print, args);
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
embed(path, options) {
|
|
194
|
+
const { node } = path;
|
|
195
|
+
// Prettier passes the full options, which `Printer` types loosely.
|
|
196
|
+
const printOptions = /** @type {ParserOptions<Node>} */ (options);
|
|
197
|
+
|
|
198
|
+
if (node.tsrxType === 'JSXStyleElement' && !node.openingElement.selfClosing) {
|
|
199
|
+
return async (textToDoc, print) =>
|
|
200
|
+
printRawTextElement(
|
|
201
|
+
path,
|
|
202
|
+
printOptions,
|
|
203
|
+
print,
|
|
204
|
+
node.css?.trim() ? await textToDoc(node.css, { parser: 'css' }) : '',
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (isRawScriptElement(node)) {
|
|
209
|
+
// A body is formatted as Prettier's HTML formatter formats it, with the
|
|
210
|
+
// parser for its language (`scriptBodyParser`). JavaScript and
|
|
211
|
+
// TypeScript use this plugin's own parser, so `prettier/standalone`
|
|
212
|
+
// needs no other plugin for them; JSON, HTML and Markdown use
|
|
213
|
+
// Prettier's, when they're loaded. Without a parser, or when the parser
|
|
214
|
+
// isn't loaded or can't read the body, Prettier prints the element
|
|
215
|
+
// instead, and `printRawTextKept` keeps the body as written.
|
|
216
|
+
const parser = scriptBodyParser(node, printOptions);
|
|
217
|
+
if (!parser) return null;
|
|
218
|
+
return async (textToDoc, print) => {
|
|
219
|
+
if (!node.content.trim()) return printRawTextElement(path, printOptions, print, '');
|
|
220
|
+
if (JAVASCRIPT_PARSERS.has(parser)) {
|
|
221
|
+
return printRawTextElement(
|
|
222
|
+
path,
|
|
223
|
+
printOptions,
|
|
224
|
+
print,
|
|
225
|
+
await textToDoc(node.content, { parser: 'tsrx' }),
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
// Prettier's HTML formatter reads a Markdown body without its first
|
|
229
|
+
// line break and common indentation, so its lines aren't code.
|
|
230
|
+
const value =
|
|
231
|
+
parser === 'markdown'
|
|
232
|
+
? dedentString(node.content.replace(/^[^\S\n]*\n/u, ''))
|
|
233
|
+
: node.content;
|
|
234
|
+
return printRawTextElement(
|
|
235
|
+
path,
|
|
236
|
+
printOptions,
|
|
237
|
+
print,
|
|
238
|
+
await textToDoc(value, { parser, __embeddedInHtml: true }),
|
|
239
|
+
);
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return estree.embed?.(path, asTypeScript(options)) ?? null;
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Prettier lays out a JSX element specially where it is assigned, returned,
|
|
249
|
+
* thrown, an arrow's body, or a call's last argument (inside `(` … `)`, with its
|
|
250
|
+
* comments), and checks for JSX by node type. A `@{ … }` value or a directive
|
|
251
|
+
* lays out the same way, so while Prettier prints its parent, it presents
|
|
252
|
+
* itself as a JSX element. So does a directive that is the body of a call's
|
|
253
|
+
* last-argument arrow, which the call checks (`list.map((item) => (` … `))`),
|
|
254
|
+
* and a value on the right of a logical expression, which an assignment checks
|
|
255
|
+
* to keep `a && (` on its line (Prettier's `shouldInlineLogicalExpression`).
|
|
256
|
+
* @template T
|
|
257
|
+
* @param {AstPath<Node>} path
|
|
258
|
+
* @param {() => T} callback
|
|
259
|
+
* @returns {T}
|
|
260
|
+
*/
|
|
261
|
+
function withTsrxValuesAsJsx(path, callback) {
|
|
262
|
+
const { node } = path;
|
|
263
|
+
if (JSX_LAYOUT_PARENTS.has(node.type)) return callback();
|
|
264
|
+
|
|
265
|
+
/** @type {Node[]} */
|
|
266
|
+
const values = [];
|
|
267
|
+
for (const key of Object.keys(node)) {
|
|
268
|
+
if (key === 'comments' || key === 'loc') continue;
|
|
269
|
+
for (const child of [node[key]].flat()) {
|
|
270
|
+
if (isTsrxValueNode(child, node, key)) values.push(child);
|
|
271
|
+
else if (
|
|
272
|
+
child?.type === 'LogicalExpression' &&
|
|
273
|
+
isTsrxValueNode(child.right, child, 'right')
|
|
274
|
+
) {
|
|
275
|
+
values.push(child.right);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const lastArgument = node.arguments?.at(-1);
|
|
280
|
+
if (
|
|
281
|
+
lastArgument?.type === 'ArrowFunctionExpression' &&
|
|
282
|
+
TSRX_DIRECTIVES.has(lastArgument.body.tsrxType)
|
|
283
|
+
) {
|
|
284
|
+
values.push(lastArgument.body);
|
|
285
|
+
}
|
|
286
|
+
// A value an enclosing node presents already stays presented while it prints.
|
|
287
|
+
for (let i = values.length - 1; i >= 0; i--) {
|
|
288
|
+
if (presentedAsJsx.has(values[i])) values.splice(i, 1);
|
|
289
|
+
}
|
|
290
|
+
if (values.length === 0) return callback();
|
|
291
|
+
|
|
292
|
+
for (const value of values) {
|
|
293
|
+
presentedAsJsx.set(value, value.type);
|
|
294
|
+
value.type = 'JSXElement';
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
return callback();
|
|
298
|
+
} finally {
|
|
299
|
+
for (const value of values) {
|
|
300
|
+
value.type = /** @type {string} */ (presentedAsJsx.get(value));
|
|
301
|
+
presentedAsJsx.delete(value);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Parents whose layout of a TSRX value child isn't JSX-specific. */
|
|
307
|
+
const JSX_LAYOUT_PARENTS = new Set([
|
|
308
|
+
'JSXElement',
|
|
309
|
+
'JSXFragment',
|
|
310
|
+
'ExpressionStatement',
|
|
311
|
+
'BlockStatement',
|
|
312
|
+
]);
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `@catch`, whose comments `printTsrx` prints before its `@`.
|
|
316
|
+
* @param {AstPath<Node>} path
|
|
317
|
+
* @returns {boolean}
|
|
318
|
+
*/
|
|
319
|
+
function isCatchDirective(path) {
|
|
320
|
+
return path.key === 'handler' && path.parent?.tsrxType === 'JSXTryExpression';
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* A comment, printed as Prettier prints it, and marked as printed.
|
|
325
|
+
* @param {Node} comment
|
|
326
|
+
* @param {ParserOptions<Node>} options
|
|
327
|
+
* @returns {Doc}
|
|
328
|
+
*/
|
|
329
|
+
function printCommentNode(comment, options) {
|
|
330
|
+
comment.printed = true;
|
|
331
|
+
return /** @type {NonNullable<Printer<Node>['printComment']>} */ (estree.printComment)(
|
|
332
|
+
/** @type {AstPath<Node>} */ (/** @type {unknown} */ ({ node: comment })),
|
|
333
|
+
options,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* A node's dangling comments, one per line, indented on a line of their own,
|
|
339
|
+
* as Prettier's `printDanglingComments` prints them with `indent` (which
|
|
340
|
+
* plugins can't call).
|
|
341
|
+
* @param {Node} node
|
|
342
|
+
* @param {ParserOptions<Node>} options
|
|
343
|
+
* @returns {Doc}
|
|
344
|
+
*/
|
|
345
|
+
function printDanglingComments(node, options) {
|
|
346
|
+
const dangling = /** @type {Node[]} */ (node.comments ?? []).filter(
|
|
347
|
+
(comment) => !comment.leading && !comment.trailing,
|
|
348
|
+
);
|
|
349
|
+
if (dangling.length === 0) return '';
|
|
350
|
+
return indent([
|
|
351
|
+
hardline,
|
|
352
|
+
join(
|
|
353
|
+
hardline,
|
|
354
|
+
dangling.map((comment) => printCommentNode(comment, options)),
|
|
355
|
+
),
|
|
356
|
+
]);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* A node's leading and trailing comments around its doc, laid out as Prettier's
|
|
361
|
+
* `printComments` does (which plugins can't call).
|
|
362
|
+
* @param {AstPath<Node>} path
|
|
363
|
+
* @param {ParserOptions<Node>} options
|
|
364
|
+
* @param {Doc} doc
|
|
365
|
+
* @param {{ afterText?: boolean }} [layout] `afterText`: the first comment is
|
|
366
|
+
* printed straight after other text, so a line break before it in the source
|
|
367
|
+
* doesn't count.
|
|
368
|
+
* @returns {Doc}
|
|
369
|
+
*/
|
|
370
|
+
function printOwnComments(path, options, doc, { afterText = false } = {}) {
|
|
371
|
+
const comments = /** @type {Node[] | undefined} */ (path.node.comments);
|
|
372
|
+
if (!comments?.length) return doc;
|
|
373
|
+
const text = options.originalText;
|
|
374
|
+
const first = comments.find((comment) => comment.leading);
|
|
375
|
+
const printComment = (/** @type {Node} */ comment) => printCommentNode(comment, options);
|
|
376
|
+
|
|
377
|
+
/** @type {Doc[]} */
|
|
378
|
+
const leading = [];
|
|
379
|
+
/** @type {Doc[]} */
|
|
380
|
+
const trailing = [];
|
|
381
|
+
/** @type {{ isBlock: boolean, hasLineSuffix: boolean } | undefined} */
|
|
382
|
+
let previous;
|
|
383
|
+
for (const comment of comments) {
|
|
384
|
+
const isBlock = comment.type === 'Block';
|
|
385
|
+
if (comment.leading) {
|
|
386
|
+
leading.push(printComment(comment));
|
|
387
|
+
if (isBlock) {
|
|
388
|
+
leading.push(
|
|
389
|
+
hasNewline(text, comment.end)
|
|
390
|
+
? hasNewline(text, comment.start, { backwards: true }) &&
|
|
391
|
+
!(afterText && comment === first)
|
|
392
|
+
? hardline
|
|
393
|
+
: line
|
|
394
|
+
: ' ',
|
|
395
|
+
);
|
|
396
|
+
} else {
|
|
397
|
+
leading.push(hardline);
|
|
398
|
+
}
|
|
399
|
+
// As Prettier's `printLeadingComment` checks for a blank line after it.
|
|
400
|
+
const next = skipNewline(text, skipSpaces(text, comment.end));
|
|
401
|
+
if (next !== false && hasNewline(text, next)) leading.push(hardline);
|
|
402
|
+
} else if (comment.trailing) {
|
|
403
|
+
const printed = printComment(comment);
|
|
404
|
+
if (
|
|
405
|
+
(previous?.hasLineSuffix && !previous.isBlock) ||
|
|
406
|
+
hasNewline(text, comment.start, { backwards: true })
|
|
407
|
+
) {
|
|
408
|
+
trailing.push(
|
|
409
|
+
lineSuffix([hardline, isPreviousLineEmpty(text, comment.start) ? hardline : '', printed]),
|
|
410
|
+
);
|
|
411
|
+
previous = { isBlock, hasLineSuffix: true };
|
|
412
|
+
} else if (!isBlock || previous?.hasLineSuffix) {
|
|
413
|
+
trailing.push(lineSuffix([' ', printed]), isBlock ? '' : breakParent);
|
|
414
|
+
previous = { isBlock, hasLineSuffix: true };
|
|
415
|
+
} else {
|
|
416
|
+
trailing.push([' ', printed]);
|
|
417
|
+
previous = { isBlock, hasLineSuffix: false };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return [...leading, doc, ...trailing];
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* A directive, or a `@{ … }` block used as a value (not a function's body).
|
|
426
|
+
* @param {AstPath<Node>} path
|
|
427
|
+
* @returns {boolean}
|
|
428
|
+
*/
|
|
429
|
+
function isTsrxValue(path) {
|
|
430
|
+
return isTsrxValueNode(path.node, path.parent, path.key);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* @param {unknown} node
|
|
435
|
+
* @param {Node | null} parent
|
|
436
|
+
* @param {PropertyKey | null} key
|
|
437
|
+
* @returns {boolean}
|
|
438
|
+
*/
|
|
439
|
+
function isTsrxValueNode(node, parent, key) {
|
|
440
|
+
if (!node || typeof node !== 'object') return false;
|
|
441
|
+
const { tsrxType, tsrxCodeBlock } = /** @type {Node} */ (node);
|
|
442
|
+
if (TSRX_DIRECTIVES.has(tsrxType)) return true;
|
|
443
|
+
if (!tsrxCodeBlock) return false;
|
|
444
|
+
// A function's `@{ … }` body, and a `@{ … }` that is a statement (a nested
|
|
445
|
+
// template output), aren't values.
|
|
446
|
+
return !(
|
|
447
|
+
(key === 'body' &&
|
|
448
|
+
(parent?.type === 'FunctionDeclaration' ||
|
|
449
|
+
parent?.type === 'FunctionExpression' ||
|
|
450
|
+
parent?.type === 'ArrowFunctionExpression' ||
|
|
451
|
+
parent?.type === 'BlockStatement' ||
|
|
452
|
+
parent?.type === 'StaticBlock' ||
|
|
453
|
+
parent?.type === 'Program')) ||
|
|
454
|
+
(key === 'consequent' && parent?.type === 'SwitchCase')
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* A tag's name with a comment before it (`<` `// note` `div`), including a
|
|
460
|
+
* dynamic tag's `{Tag}`.
|
|
461
|
+
* @param {AstPath<Node>} path
|
|
462
|
+
* @returns {boolean}
|
|
463
|
+
*/
|
|
464
|
+
function isCommentedTagName(path) {
|
|
465
|
+
return (
|
|
466
|
+
path.key === 'name' &&
|
|
467
|
+
(path.parent?.type === 'JSXOpeningElement' || path.parent?.type === 'JSXClosingElement') &&
|
|
468
|
+
/** @type {Node[] | undefined} */ (path.node.comments)?.some((comment) => comment.leading) ===
|
|
469
|
+
true
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* A tag name with the comments before it. Prettier prints an opening tag's name
|
|
475
|
+
* after a line comment at the indentation of its `<` (`<// note`), which TSX
|
|
476
|
+
* can't parse, so the comments and the name go on their own indented lines
|
|
477
|
+
* instead, the way Prettier prints a closing tag's: `<`, `// note`, `div`, the
|
|
478
|
+
* attributes, `>`. An element's direct child keeps Prettier's layout, since a
|
|
479
|
+
* `<` followed by a line break there is text. Block comments print as they
|
|
480
|
+
* would straight after the `<` or `</` (`</* note *\/ div />`), which is what
|
|
481
|
+
* Prettier's second format makes of a block comment on its own line.
|
|
482
|
+
* @param {AstPath<Node>} path
|
|
483
|
+
* @param {ParserOptions<Node>} options
|
|
484
|
+
* @param {Print} print
|
|
485
|
+
* @returns {Doc}
|
|
486
|
+
*/
|
|
487
|
+
function printTagNameComments(path, options, print) {
|
|
488
|
+
const name = /** @type {Doc} */ (estree.print(path, asTypeScript(options), print));
|
|
489
|
+
const hasLineComment = /** @type {Node[]} */ (path.node.comments).some(
|
|
490
|
+
(comment) => comment.leading && comment.type === 'Line',
|
|
491
|
+
);
|
|
492
|
+
if (path.parent?.type === 'JSXClosingElement') {
|
|
493
|
+
// Prettier puts the name on its own line after a line comment.
|
|
494
|
+
return printOwnComments(path, options, name, { afterText: !hasLineComment });
|
|
495
|
+
}
|
|
496
|
+
const container = path.getParentNode(2)?.type;
|
|
497
|
+
const isChild = container === 'JSXElement' || container === 'JSXFragment';
|
|
498
|
+
return hasLineComment && !isChild
|
|
499
|
+
? indent([hardline, printOwnComments(path, options, name)])
|
|
500
|
+
: printOwnComments(path, options, name, { afterText: true });
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** The parsers for JavaScript and TypeScript, which this plugin's own parser formats. */
|
|
504
|
+
const JAVASCRIPT_PARSERS = new Set([
|
|
505
|
+
'tsrx',
|
|
506
|
+
'babel',
|
|
507
|
+
'babel-flow',
|
|
508
|
+
'babel-ts',
|
|
509
|
+
'flow',
|
|
510
|
+
'typescript',
|
|
511
|
+
'acorn',
|
|
512
|
+
'espree',
|
|
513
|
+
'meriyah',
|
|
514
|
+
'oxc',
|
|
515
|
+
'oxc-ts',
|
|
516
|
+
]);
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* The parser Prettier's HTML formatter formats a `<script>` body with
|
|
520
|
+
* (`inferScriptParser`): none with `src`, JavaScript without `type` or `lang`,
|
|
521
|
+
* then the parser of the language `lang` names, or the one for the `type`.
|
|
522
|
+
* `undefined` keeps the body as written. A `type` or `lang` that is an
|
|
523
|
+
* expression can't be known, so its body is kept too.
|
|
524
|
+
* @param {Node} node A `<script>` element.
|
|
525
|
+
* @param {ParserOptions<Node>} options
|
|
526
|
+
* @returns {string | undefined}
|
|
527
|
+
*/
|
|
528
|
+
function scriptBodyParser(node, options) {
|
|
529
|
+
/** @type {Map<string, string | null>} */
|
|
530
|
+
const attributes = new Map();
|
|
531
|
+
for (const attribute of node.openingElement.attributes) {
|
|
532
|
+
if (attribute.type !== 'JSXAttribute' || attribute.name.type !== 'JSXIdentifier') continue;
|
|
533
|
+
const { value } = attribute;
|
|
534
|
+
attributes.set(
|
|
535
|
+
attribute.name.name,
|
|
536
|
+
value == null
|
|
537
|
+
? ''
|
|
538
|
+
: value.type === 'Literal' && typeof value.value === 'string'
|
|
539
|
+
? value.value
|
|
540
|
+
: null,
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
if (attributes.has('src')) return undefined;
|
|
544
|
+
const type = attributes.get('type');
|
|
545
|
+
const lang = attributes.get('lang');
|
|
546
|
+
if (type === null || lang === null) return undefined;
|
|
547
|
+
if (!type && !lang) return 'babel';
|
|
548
|
+
return (lang ? languageParser(options, lang) : undefined) ?? typeParser(type);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* The first parser of the language a name, alias or extension names, among the
|
|
553
|
+
* languages of the loaded plugins, as Prettier's `inferParser` finds it.
|
|
554
|
+
* @param {ParserOptions<Node>} options
|
|
555
|
+
* @param {string} name
|
|
556
|
+
* @returns {string | undefined}
|
|
557
|
+
*/
|
|
558
|
+
function languageParser(options, name) {
|
|
559
|
+
const languages = [.../** @type {any[]} */ (options.plugins)]
|
|
560
|
+
.reverse()
|
|
561
|
+
.flatMap((plugin) => (typeof plugin === 'object' && plugin?.languages) || []);
|
|
562
|
+
const language =
|
|
563
|
+
languages.find((language) => language.name.toLowerCase() === name) ??
|
|
564
|
+
languages.find((language) => language.aliases?.includes(name)) ??
|
|
565
|
+
languages.find((language) => language.extensions?.includes(`.${name}`));
|
|
566
|
+
return language?.parsers[0];
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Prettier's HTML formatter's parser for a `<script>` `type`
|
|
571
|
+
* (`inferParserByTypeAttribute`).
|
|
572
|
+
* @param {string | undefined} type
|
|
573
|
+
* @returns {string | undefined}
|
|
574
|
+
*/
|
|
575
|
+
function typeParser(type) {
|
|
576
|
+
switch (type) {
|
|
577
|
+
case undefined:
|
|
578
|
+
case '':
|
|
579
|
+
return undefined;
|
|
580
|
+
case 'module':
|
|
581
|
+
case 'text/javascript':
|
|
582
|
+
case 'text/babel':
|
|
583
|
+
case 'text/jsx':
|
|
584
|
+
case 'application/javascript':
|
|
585
|
+
return 'babel';
|
|
586
|
+
case 'application/x-typescript':
|
|
587
|
+
return 'typescript';
|
|
588
|
+
case 'text/markdown':
|
|
589
|
+
return 'markdown';
|
|
590
|
+
case 'text/html':
|
|
591
|
+
return 'html';
|
|
592
|
+
case 'text/x-handlebars-template':
|
|
593
|
+
return 'glimmer';
|
|
594
|
+
default:
|
|
595
|
+
return type.endsWith('json') || type.endsWith('importmap') || type === 'speculationrules'
|
|
596
|
+
? 'json'
|
|
597
|
+
: undefined;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** HTML's whitespace characters. */
|
|
602
|
+
const HTML_WHITESPACE = /[\t\n\f\r ]+$/u;
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* A text without the indentation all of its lines share, as Prettier's
|
|
606
|
+
* `dedentString` removes it: lines that are empty or only whitespace don't count.
|
|
607
|
+
* @param {string} text
|
|
608
|
+
* @returns {string}
|
|
609
|
+
*/
|
|
610
|
+
function dedentString(text) {
|
|
611
|
+
let minIndentation = Number.POSITIVE_INFINITY;
|
|
612
|
+
for (const line of text.split('\n')) {
|
|
613
|
+
if (line.length === 0) continue;
|
|
614
|
+
const indentation = /** @type {RegExpMatchArray} */ (line.match(/^[\t\n\f\r ]*/u))[0].length;
|
|
615
|
+
if (indentation === 0) return text;
|
|
616
|
+
if (indentation === line.length) continue;
|
|
617
|
+
minIndentation = Math.min(minIndentation, indentation);
|
|
618
|
+
}
|
|
619
|
+
return minIndentation === Number.POSITIVE_INFINITY
|
|
620
|
+
? text
|
|
621
|
+
: text
|
|
622
|
+
.split('\n')
|
|
623
|
+
.map((line) => line.slice(minIndentation))
|
|
624
|
+
.join('\n');
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Values that present themselves as JSX elements while their parent prints,
|
|
629
|
+
* with their own type.
|
|
630
|
+
* @type {WeakMap<object, string>}
|
|
631
|
+
*/
|
|
632
|
+
const presentedAsJsx = new WeakMap();
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* @param {AstPath<Node>} path
|
|
636
|
+
* @param {ParserOptions<Node>} options
|
|
637
|
+
* @param {Print} print
|
|
638
|
+
* @param {unknown} [args]
|
|
639
|
+
* @returns {Doc}
|
|
640
|
+
*/
|
|
641
|
+
function printNode(path, options, print, args) {
|
|
642
|
+
const doc = printTsrx(path, options, print);
|
|
643
|
+
if (doc === null) {
|
|
644
|
+
return withTsrxValuesAsJsx(
|
|
645
|
+
path,
|
|
646
|
+
() =>
|
|
647
|
+
/** @type {Doc} */ (
|
|
648
|
+
estree.print(path, asTypeScript(options), print, /** @type {any} */ (args))
|
|
649
|
+
),
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
if (!isTsrxValue(path) || rangeRoots.has(path.node)) return doc;
|
|
653
|
+
const printed = printOwnComments(path, options, doc);
|
|
654
|
+
// Like an element, a `@{ … }` value or a directive isn't a left-hand-side
|
|
655
|
+
// expression, so it's the base of a call, member access, index, non-null
|
|
656
|
+
// assertion, or tagged template only in parentheses, which Prettier's
|
|
657
|
+
// `needsParens` prints around a JSX element there.
|
|
658
|
+
switch (subscriptBaseKind(path)) {
|
|
659
|
+
case 'callee':
|
|
660
|
+
return ['(', printed, ')'];
|
|
661
|
+
case 'object':
|
|
662
|
+
return group(['(', indent([softline, printed]), softline, ')']);
|
|
663
|
+
}
|
|
664
|
+
// A `@{ … }` value or a directive gets JSX's parentheses where it is
|
|
665
|
+
// assigned, returned, thrown, or an arrow's body, with its comments inside
|
|
666
|
+
// them, as Prettier prints a JSX element.
|
|
667
|
+
return maybeWrapJsxElementInParens(path, printed);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* Whether the node at `path` is the callee of a call or `new`, or the object
|
|
672
|
+
* of a member access, index, non-null assertion, or tagged template.
|
|
673
|
+
* @param {AstPath<Node>} path
|
|
674
|
+
* @returns {'callee' | 'object' | null}
|
|
675
|
+
*/
|
|
676
|
+
function subscriptBaseKind(path) {
|
|
677
|
+
const { key, parent } = path;
|
|
678
|
+
switch (parent?.type) {
|
|
679
|
+
case 'CallExpression':
|
|
680
|
+
case 'OptionalCallExpression':
|
|
681
|
+
case 'NewExpression':
|
|
682
|
+
return key === 'callee' ? 'callee' : null;
|
|
683
|
+
case 'MemberExpression':
|
|
684
|
+
case 'OptionalMemberExpression':
|
|
685
|
+
return key === 'object' ? 'object' : null;
|
|
686
|
+
case 'TaggedTemplateExpression':
|
|
687
|
+
return key === 'tag' ? 'object' : null;
|
|
688
|
+
case 'TSNonNullExpression':
|
|
689
|
+
return key === 'expression' ? 'object' : null;
|
|
690
|
+
default:
|
|
691
|
+
return null;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* A range's one node, printed without the parentheses of a TSRX value.
|
|
697
|
+
* @type {WeakSet<Node>}
|
|
698
|
+
*/
|
|
699
|
+
const rangeRoots = new WeakSet();
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* The statements of a range (`range.js`), printed where they are in the file:
|
|
703
|
+
* one statement, or the first to the last of a list, which Prettier puts on
|
|
704
|
+
* lines of their own and keeps an empty line between.
|
|
705
|
+
* @param {AstPath<Node>} path
|
|
706
|
+
* @param {ParserOptions<Node>} options
|
|
707
|
+
* @param {Print} print
|
|
708
|
+
* @param {{ keys: Array<string | number>, first?: number, last?: number }} range
|
|
709
|
+
* @returns {Doc}
|
|
710
|
+
*/
|
|
711
|
+
function printRange(path, options, print, { keys, first, last }) {
|
|
712
|
+
// `AstPath#call` takes the keys as separate arguments.
|
|
713
|
+
const pathTo =
|
|
714
|
+
/** @type {(callback: (path: AstPath<Node>) => unknown, ...keys: Array<string | number>) => any} */ (
|
|
715
|
+
path.call.bind(path)
|
|
716
|
+
);
|
|
717
|
+
if (first === undefined || last === undefined) {
|
|
718
|
+
// A `@{ … }` value's parentheses are outside the range.
|
|
719
|
+
const node = /** @type {Node} */ (pathTo(({ node }) => node, ...keys));
|
|
720
|
+
rangeRoots.add(node);
|
|
721
|
+
try {
|
|
722
|
+
return /** @type {Doc} */ (pathTo(() => print(), ...keys));
|
|
723
|
+
} finally {
|
|
724
|
+
rangeRoots.delete(node);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return /** @type {Doc} */ (
|
|
728
|
+
pathTo(
|
|
729
|
+
(listParent) => {
|
|
730
|
+
/** @type {Doc[]} */
|
|
731
|
+
const parts = [];
|
|
732
|
+
listParent.each((statementPath, index) => {
|
|
733
|
+
const node = /** @type {Node} */ (statementPath.node);
|
|
734
|
+
if (index < first || index > last || node.type === 'EmptyStatement') return;
|
|
735
|
+
if (parts.length > 0) parts.push(hardline);
|
|
736
|
+
parts.push(print());
|
|
737
|
+
if (index < last && isNextLineEmpty(options.originalText, options.locEnd(node))) {
|
|
738
|
+
parts.push(hardline);
|
|
739
|
+
}
|
|
740
|
+
}, /** @type {string} */ (keys.at(-1)));
|
|
741
|
+
return parts;
|
|
742
|
+
},
|
|
743
|
+
...keys.slice(0, -1),
|
|
744
|
+
)
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* Print a TSRX node, or return `null` to let Prettier's estree printer print it.
|
|
750
|
+
* @param {AstPath<Node>} path
|
|
751
|
+
* @param {ParserOptions<Node>} options
|
|
752
|
+
* @param {Print} print
|
|
753
|
+
* @returns {Doc | null}
|
|
754
|
+
*/
|
|
755
|
+
function printTsrx(path, options, print) {
|
|
756
|
+
const { node, parent } = path;
|
|
757
|
+
if (node.type === 'Program' && node.tsrxRange) {
|
|
758
|
+
return printRange(path, options, print, node.tsrxRange);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
switch (node.tsrxType ?? node.type) {
|
|
762
|
+
// A range that can't be formatted keeps its text (`range.js`).
|
|
763
|
+
case 'TSRXRangeText':
|
|
764
|
+
return replaceEndOfLine(options.originalText.slice(node.start, node.end));
|
|
765
|
+
|
|
766
|
+
case 'BlockStatement':
|
|
767
|
+
return node.tsrxCodeBlock
|
|
768
|
+
? ['@', /** @type {Doc} */ (estree.print(path, asTypeScript(options), print))]
|
|
769
|
+
: null;
|
|
770
|
+
|
|
771
|
+
case 'ExpressionStatement':
|
|
772
|
+
return node.tsrxOutput ? print('expression') : null;
|
|
773
|
+
|
|
774
|
+
// With embedded formatting off, Prettier doesn't call `embed()`: a
|
|
775
|
+
// `<style>` body is printed as written, and a `<script>` body is kept as
|
|
776
|
+
// Prettier's HTML formatter keeps it, as when it has no parser.
|
|
777
|
+
case 'JSXStyleElement':
|
|
778
|
+
return node.tsrxRawText === undefined ? null : printRawTextAsWritten(path, options, print);
|
|
779
|
+
|
|
780
|
+
case 'JSXElement':
|
|
781
|
+
case 'JSXFragment':
|
|
782
|
+
if (node.tsrxRawText !== undefined && isRawScriptElement(node)) {
|
|
783
|
+
return printRawTextKept(path, options, print);
|
|
784
|
+
}
|
|
785
|
+
if (huggedCodeBlock(node) !== -1) return printHuggedCodeBlock(path, options, print);
|
|
786
|
+
if (!node.tsrxPrintsChildren && !node.tsrxKeepParens) return null;
|
|
787
|
+
return printElement(path, options, printJsxElementInternal(path, options, print));
|
|
788
|
+
|
|
789
|
+
case 'JSXExpressionContainer':
|
|
790
|
+
// `{@{ … }}` hugs its braces, as Prettier hugs a function or a `do`
|
|
791
|
+
// expression there (decision 57 of #852).
|
|
792
|
+
if (node.expression.tsrxCodeBlock && !hasOwnComments(node.expression)) {
|
|
793
|
+
return group(['{', print('expression'), lineSuffixBoundary, '}']);
|
|
794
|
+
}
|
|
795
|
+
if (node.tsrxComment) {
|
|
796
|
+
// A comment between children, laid out as `{/* … *\/}` and printed
|
|
797
|
+
// without the braces, like any comment: a line comment ends its line,
|
|
798
|
+
// and a JSDoc-style block comment is re-indented.
|
|
799
|
+
const comment = node.tsrxComment;
|
|
800
|
+
const printed = /** @type {NonNullable<Printer<Node>['printComment']>} */ (
|
|
801
|
+
estree.printComment
|
|
802
|
+
)(/** @type {AstPath<Node>} */ (/** @type {unknown} */ ({ node: comment })), options);
|
|
803
|
+
return comment.type === 'Line' ? [printed, breakParent] : printed;
|
|
804
|
+
}
|
|
805
|
+
return isCommentedTagName(path) ? printTagNameComments(path, options, print) : null;
|
|
806
|
+
|
|
807
|
+
case 'JSXIdentifier':
|
|
808
|
+
case 'JSXMemberExpression':
|
|
809
|
+
case 'JSXNamespacedName':
|
|
810
|
+
return isCommentedTagName(path) ? printTagNameComments(path, options, print) : null;
|
|
811
|
+
|
|
812
|
+
case 'JSXAttribute':
|
|
813
|
+
// A shorthand (`{name}`) is its value, printed as Prettier prints the
|
|
814
|
+
// braces of `name={name}`
|
|
815
|
+
return node.shorthand ? print('value') : null;
|
|
816
|
+
|
|
817
|
+
case 'IfStatement':
|
|
818
|
+
return node.tsrxElseIf ? printIf(path, options, print, 'if') : null;
|
|
819
|
+
|
|
820
|
+
case 'JSXIfExpression':
|
|
821
|
+
return printIf(path, options, print, '@if');
|
|
822
|
+
|
|
823
|
+
// `@catch (error, reset)`, which Prettier can't print: a `catch` has one
|
|
824
|
+
// parameter. Its parentheses break as Prettier's `printCatchClause` breaks
|
|
825
|
+
// them around a parameter with a comment by it, a parameter on each line.
|
|
826
|
+
case 'CatchClause': {
|
|
827
|
+
if (!node.resetParam) return null;
|
|
828
|
+
const params = [print('param'), ',', line, print('resetParam')];
|
|
829
|
+
return [
|
|
830
|
+
'catch ',
|
|
831
|
+
[node.param, node.resetParam].some((param) => hasParameterComment(param, options))
|
|
832
|
+
? ['(', indent([softline, ...params]), softline, ') ']
|
|
833
|
+
: ['(', print('param'), ', ', print('resetParam'), ') '],
|
|
834
|
+
print('body'),
|
|
835
|
+
];
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
case 'JSXForExpression':
|
|
839
|
+
return printFor(path, options, print);
|
|
840
|
+
|
|
841
|
+
case 'JSXSwitchExpression':
|
|
842
|
+
return [
|
|
843
|
+
group(['@switch (', indent([softline, print('discriminant')]), softline, ')']),
|
|
844
|
+
' {',
|
|
845
|
+
node.cases.length > 0
|
|
846
|
+
? indent([
|
|
847
|
+
hardline,
|
|
848
|
+
join(
|
|
849
|
+
hardline,
|
|
850
|
+
path.map(
|
|
851
|
+
({ node: switchCase, isLast }) => [
|
|
852
|
+
print(),
|
|
853
|
+
!isLast &&
|
|
854
|
+
isNextLineEmpty(options.originalText, /** @type {Node} */ (switchCase).end)
|
|
855
|
+
? hardline
|
|
856
|
+
: '',
|
|
857
|
+
],
|
|
858
|
+
'cases',
|
|
859
|
+
),
|
|
860
|
+
),
|
|
861
|
+
])
|
|
862
|
+
: // A comment in an empty body, as in Prettier's `switch` (#835)
|
|
863
|
+
printDanglingComments(node, options),
|
|
864
|
+
hardline,
|
|
865
|
+
'}',
|
|
866
|
+
];
|
|
867
|
+
|
|
868
|
+
case 'SwitchCase':
|
|
869
|
+
if (parent?.tsrxType !== 'JSXSwitchExpression') return null;
|
|
870
|
+
return [
|
|
871
|
+
node.test ? ['@case ', print('test'), ':'] : '@default:',
|
|
872
|
+
' ',
|
|
873
|
+
print(['consequent', 0]),
|
|
874
|
+
];
|
|
875
|
+
|
|
876
|
+
case 'JSXTryExpression':
|
|
877
|
+
return asStatement(node, () => [
|
|
878
|
+
'@try ',
|
|
879
|
+
print('block'),
|
|
880
|
+
node.pending ? [' @pending ', print('pending')] : '',
|
|
881
|
+
// A comment before `@catch` is the clause's, as in Prettier's
|
|
882
|
+
// `try`, and goes before the `@`.
|
|
883
|
+
node.handler
|
|
884
|
+
? [
|
|
885
|
+
' ',
|
|
886
|
+
path.call((handler) => printOwnComments(handler, options, ['@', print()]), 'handler'),
|
|
887
|
+
]
|
|
888
|
+
: '',
|
|
889
|
+
]);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
return null;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* Whether a `catch` parameter has a comment that breaks its parentheses, as in
|
|
897
|
+
* Prettier's `printCatchClause`: a line comment, or a block comment with a line
|
|
898
|
+
* break on its outer side.
|
|
899
|
+
* @param {Node} param
|
|
900
|
+
* @param {ParserOptions<Node>} options
|
|
901
|
+
* @returns {boolean}
|
|
902
|
+
*/
|
|
903
|
+
function hasParameterComment(param, options) {
|
|
904
|
+
return /** @type {Node[]} */ (param.comments ?? []).some(
|
|
905
|
+
(comment) =>
|
|
906
|
+
comment.type !== 'Block' ||
|
|
907
|
+
(comment.leading && hasNewline(options.originalText, options.locEnd(comment))) ||
|
|
908
|
+
(comment.trailing &&
|
|
909
|
+
hasNewline(options.originalText, options.locStart(comment), { backwards: true })),
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* `@if (test) { … } @else …`, with the head laid out like Prettier's `if`.
|
|
915
|
+
* @param {AstPath<Node>} path
|
|
916
|
+
* @param {ParserOptions<Node>} options
|
|
917
|
+
* @param {Print} print
|
|
918
|
+
* @param {string} keyword
|
|
919
|
+
* @returns {Doc}
|
|
920
|
+
*/
|
|
921
|
+
function printIf(path, options, print, keyword) {
|
|
922
|
+
const { node } = path;
|
|
923
|
+
/** @type {Doc[]} */
|
|
924
|
+
const parts = [
|
|
925
|
+
group([
|
|
926
|
+
keyword,
|
|
927
|
+
' (',
|
|
928
|
+
group([indent([softline, asStatement(node, () => print('test'))]), softline]),
|
|
929
|
+
')',
|
|
930
|
+
]),
|
|
931
|
+
' ',
|
|
932
|
+
asStatement(node, () => print('consequent')),
|
|
933
|
+
];
|
|
934
|
+
if (!node.alternate) return parts;
|
|
935
|
+
parts.push(
|
|
936
|
+
printBeforeBranch(node, options),
|
|
937
|
+
'@else ',
|
|
938
|
+
asStatement(node, () => print('alternate')),
|
|
939
|
+
);
|
|
940
|
+
return parts;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* What goes between a directive's `}` and its next branch (`@else`, `@empty`):
|
|
945
|
+
* a space, or the comments written there, laid out as Prettier's `if` prints a
|
|
946
|
+
* comment before `else` (a dangling comment of the `if`).
|
|
947
|
+
* @param {Node} node
|
|
948
|
+
* @param {ParserOptions<Node>} options
|
|
949
|
+
* @returns {Doc}
|
|
950
|
+
*/
|
|
951
|
+
function printBeforeBranch(node, options) {
|
|
952
|
+
const text = options.originalText;
|
|
953
|
+
const dangling = /** @type {Node[]} */ (node.comments ?? []).filter(
|
|
954
|
+
(comment) => !comment.leading && !comment.trailing,
|
|
955
|
+
);
|
|
956
|
+
if (dangling.length === 0) return ' ';
|
|
957
|
+
const first = /** @type {Node} */ (dangling[0]);
|
|
958
|
+
const last = /** @type {Node} */ (dangling.at(-1));
|
|
959
|
+
return [
|
|
960
|
+
isPreviousLineEmpty(text, first.start)
|
|
961
|
+
? [hardline, hardline]
|
|
962
|
+
: hasNewline(text, first.start, { backwards: true })
|
|
963
|
+
? hardline
|
|
964
|
+
: ' ',
|
|
965
|
+
join(
|
|
966
|
+
hardline,
|
|
967
|
+
dangling.map((comment) => printCommentNode(comment, options)),
|
|
968
|
+
),
|
|
969
|
+
last.type === 'Line' || hasNewline(text, last.end) ? hardline : ' ',
|
|
970
|
+
];
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/**
|
|
974
|
+
* `@for (head; index i; key k) { … } @empty { … }`. The head is laid out like
|
|
975
|
+
* Prettier's `for`: a `for…of`/`for…in` head stays on one line, and a head with
|
|
976
|
+
* several clauses breaks after each `;`.
|
|
977
|
+
* @param {AstPath<Node>} path
|
|
978
|
+
* @param {ParserOptions<Node>} options
|
|
979
|
+
* @param {Print} print
|
|
980
|
+
* @returns {Doc}
|
|
981
|
+
*/
|
|
982
|
+
function printFor(path, options, print) {
|
|
983
|
+
const { node } = path;
|
|
984
|
+
const clauses = asStatement(node, () => {
|
|
985
|
+
/** @type {Doc[]} */
|
|
986
|
+
const clauses =
|
|
987
|
+
node.statementType === 'ForStatement'
|
|
988
|
+
? [print('init'), print('test'), print('update')]
|
|
989
|
+
: [
|
|
990
|
+
[
|
|
991
|
+
print('left'),
|
|
992
|
+
node.statementType === 'ForOfStatement' ? ' of ' : ' in ',
|
|
993
|
+
print('right'),
|
|
994
|
+
],
|
|
995
|
+
];
|
|
996
|
+
if (node.index) clauses.push(['index ', print('index')]);
|
|
997
|
+
if (node.key) clauses.push(['key ', print('key')]);
|
|
998
|
+
return clauses;
|
|
999
|
+
});
|
|
1000
|
+
const head =
|
|
1001
|
+
clauses.length === 1
|
|
1002
|
+
? clauses
|
|
1003
|
+
: group([indent([softline, join([';', line], clauses)]), softline]);
|
|
1004
|
+
return [
|
|
1005
|
+
group(['@for', node.await ? ' await' : '', ' (', head, ')']),
|
|
1006
|
+
' ',
|
|
1007
|
+
asStatement(node, () => print('body')),
|
|
1008
|
+
node.empty
|
|
1009
|
+
? [printBeforeBranch(node, options), '@empty ', asStatement(node, () => print('empty'))]
|
|
1010
|
+
: '',
|
|
1011
|
+
];
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/**
|
|
1015
|
+
* Print a directive's children while the directive presents itself as its
|
|
1016
|
+
* statement (`IfStatement`, `ForOfStatement`, …), so Prettier lays them out as
|
|
1017
|
+
* it would inside that statement: a broken `if` test, a `for` declaration
|
|
1018
|
+
* without a semicolon, an empty body on two lines (`{`, `}`), except a
|
|
1019
|
+
* `@catch` body, which stays `{}` as a `catch` without `finally` does. An
|
|
1020
|
+
* `@else if` is an `IfStatement` already.
|
|
1021
|
+
* @template T
|
|
1022
|
+
* @param {Node} node
|
|
1023
|
+
* @param {() => T} callback
|
|
1024
|
+
* @returns {T}
|
|
1025
|
+
*/
|
|
1026
|
+
function asStatement(node, callback) {
|
|
1027
|
+
if (!node.statementType) return callback();
|
|
1028
|
+
const { type } = node;
|
|
1029
|
+
node.type = node.statementType;
|
|
1030
|
+
try {
|
|
1031
|
+
return callback();
|
|
1032
|
+
} finally {
|
|
1033
|
+
node.type = type;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/**
|
|
1038
|
+
* A `<style>` or `<script>` element whose body is formatted as CSS or TypeScript.
|
|
1039
|
+
* @param {AstPath<Node>} path
|
|
1040
|
+
* @param {ParserOptions<Node>} options
|
|
1041
|
+
* @param {Print} print
|
|
1042
|
+
* @param {Doc} body
|
|
1043
|
+
* @returns {Doc}
|
|
1044
|
+
*/
|
|
1045
|
+
function printRawTextElement(path, options, print, body) {
|
|
1046
|
+
return printElement(path, options, [
|
|
1047
|
+
print('openingElement'),
|
|
1048
|
+
body ? [indent([hardline, body]), hardline] : '',
|
|
1049
|
+
print('closingElement'),
|
|
1050
|
+
]);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/**
|
|
1054
|
+
* A `<script>` element whose body isn't formatted, laid out as Prettier's HTML
|
|
1055
|
+
* formatter lays out such a body (`getTextValueParts`): as written, on lines
|
|
1056
|
+
* of its own one level in, without its trailing whitespace, its first blank
|
|
1057
|
+
* line, or the indentation its lines share. That happens when no parser fits
|
|
1058
|
+
* the body, when the parser isn't loaded or can't read it, and when embedded
|
|
1059
|
+
* formatting is off.
|
|
1060
|
+
* @param {AstPath<Node>} path
|
|
1061
|
+
* @param {ParserOptions<Node>} options
|
|
1062
|
+
* @param {Print} print
|
|
1063
|
+
* @returns {Doc}
|
|
1064
|
+
*/
|
|
1065
|
+
function printRawTextKept(path, options, print) {
|
|
1066
|
+
const text = dedentString(
|
|
1067
|
+
path.node.tsrxRawText.replace(HTML_WHITESPACE, '').replace(/^[\t\f\r ]*\n/u, ''),
|
|
1068
|
+
);
|
|
1069
|
+
return printRawTextElement(path, options, print, text ? replaceEndOfLine(text, hardline) : '');
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* A `<style>` or `<script>` element with its body as written.
|
|
1074
|
+
* @param {AstPath<Node>} path
|
|
1075
|
+
* @param {ParserOptions<Node>} options
|
|
1076
|
+
* @param {Print} print
|
|
1077
|
+
* @returns {Doc}
|
|
1078
|
+
*/
|
|
1079
|
+
function printRawTextAsWritten(path, options, print) {
|
|
1080
|
+
return printElement(path, options, [
|
|
1081
|
+
print('openingElement'),
|
|
1082
|
+
replaceEndOfLine(path.node.tsrxRawText),
|
|
1083
|
+
print('closingElement'),
|
|
1084
|
+
]);
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* The index of the `@{ … }` block that is an element's or fragment's only
|
|
1089
|
+
* child, apart from whitespace with a line break (which renders nothing), or
|
|
1090
|
+
* -1.
|
|
1091
|
+
* @param {Node} node
|
|
1092
|
+
* @returns {number}
|
|
1093
|
+
*/
|
|
1094
|
+
function huggedCodeBlock(node) {
|
|
1095
|
+
let index = -1;
|
|
1096
|
+
for (const [i, child] of node.children.entries()) {
|
|
1097
|
+
if (child.type === 'JSXText' && /^\s*$/u.test(child.value) && child.value.includes('\n')) {
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
if (index !== -1 || !child.tsrxCodeBlock || hasOwnComments(child)) return -1;
|
|
1101
|
+
index = i;
|
|
1102
|
+
}
|
|
1103
|
+
return index;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* An element whose only child is a `@{ … }` block hugs it, as a function's
|
|
1108
|
+
* `@{ … }` body hugs its `)`: `<div>@{`, the block's statements, `}</div>`
|
|
1109
|
+
* (decision 57 of #852).
|
|
1110
|
+
* @param {AstPath<Node>} path
|
|
1111
|
+
* @param {ParserOptions<Node>} options
|
|
1112
|
+
* @param {Print} print
|
|
1113
|
+
* @returns {Doc}
|
|
1114
|
+
*/
|
|
1115
|
+
function printHuggedCodeBlock(path, options, print) {
|
|
1116
|
+
const { node } = path;
|
|
1117
|
+
const fragment = node.type === 'JSXFragment';
|
|
1118
|
+
return printElement(path, options, [
|
|
1119
|
+
print(fragment ? 'openingFragment' : 'openingElement'),
|
|
1120
|
+
print(['children', huggedCodeBlock(node)]),
|
|
1121
|
+
print(fragment ? 'closingFragment' : 'closingElement'),
|
|
1122
|
+
]);
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* Whether Prettier attached comments to a node.
|
|
1127
|
+
* @param {Node} node
|
|
1128
|
+
* @returns {boolean}
|
|
1129
|
+
*/
|
|
1130
|
+
function hasOwnComments(node) {
|
|
1131
|
+
return !!node.comments?.length;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
/**
|
|
1135
|
+
* An element this plugin prints itself (one with comment children, a `<style>`
|
|
1136
|
+
* or a `<script>`), around it what Prettier's `printJsxElement` and `print`
|
|
1137
|
+
* add around every element: its own comments, then the layout parentheses, and
|
|
1138
|
+
* the parentheses `needsParens` asks for.
|
|
1139
|
+
* @param {AstPath<Node>} path
|
|
1140
|
+
* @param {ParserOptions<Node>} options
|
|
1141
|
+
* @param {Doc} element
|
|
1142
|
+
* @returns {Doc}
|
|
1143
|
+
*/
|
|
1144
|
+
function printElement(path, options, element) {
|
|
1145
|
+
const needsParens = jsxNeedsParens(path);
|
|
1146
|
+
const printed = maybeWrapJsxElementInParens(
|
|
1147
|
+
path,
|
|
1148
|
+
printOwnComments(path, options, element),
|
|
1149
|
+
needsParens,
|
|
1150
|
+
);
|
|
1151
|
+
return needsParens ? ['(', printed, ')'] : printed;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/**
|
|
1155
|
+
* The `JSXElement` case of Prettier's `needsParens`, which Prettier doesn't
|
|
1156
|
+
* export. (Its checks on the parent give nothing else for an element in a
|
|
1157
|
+
* strict-mode module.)
|
|
1158
|
+
* @param {AstPath<Node>} path
|
|
1159
|
+
* @returns {boolean}
|
|
1160
|
+
*/
|
|
1161
|
+
function jsxNeedsParens(path) {
|
|
1162
|
+
const { key, parent } = path;
|
|
1163
|
+
if (!parent) return false;
|
|
1164
|
+
// An element that starts a statement where TSRX would read it as output
|
|
1165
|
+
// (`parse.js`, `keepStatementParens`).
|
|
1166
|
+
if (path.node.tsrxKeepParens) return true;
|
|
1167
|
+
return (
|
|
1168
|
+
key === 'callee' ||
|
|
1169
|
+
(key === 'left' && parent.type === 'BinaryExpression' && parent.operator === '<') ||
|
|
1170
|
+
(!JSX_NO_PARENS_PARENTS.has(parent.type) &&
|
|
1171
|
+
!(key === 'declaration' && parent.type === 'ExportDefaultDeclaration'))
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/** Parents where an element needs no parentheses, from Prettier's `needsParens`. */
|
|
1176
|
+
const JSX_NO_PARENS_PARENTS = new Set([
|
|
1177
|
+
'ArrayExpression',
|
|
1178
|
+
'ArrowFunctionExpression',
|
|
1179
|
+
'AssignmentExpression',
|
|
1180
|
+
'AssignmentPattern',
|
|
1181
|
+
'BinaryExpression',
|
|
1182
|
+
'ConditionalExpression',
|
|
1183
|
+
'ExpressionStatement',
|
|
1184
|
+
'JsExpressionRoot',
|
|
1185
|
+
'JSXAttribute',
|
|
1186
|
+
'JSXElement',
|
|
1187
|
+
'JSXExpressionContainer',
|
|
1188
|
+
'JSXFragment',
|
|
1189
|
+
'LogicalExpression',
|
|
1190
|
+
'CallExpression',
|
|
1191
|
+
'OptionalCallExpression',
|
|
1192
|
+
'NewExpression',
|
|
1193
|
+
'ObjectProperty',
|
|
1194
|
+
'Property',
|
|
1195
|
+
'ReturnStatement',
|
|
1196
|
+
'ThrowStatement',
|
|
1197
|
+
'TypeCastExpression',
|
|
1198
|
+
'VariableDeclarator',
|
|
1199
|
+
'YieldExpression',
|
|
1200
|
+
'MatchExpressionCase',
|
|
1201
|
+
]);
|
|
1202
|
+
|
|
1203
|
+
/** Parents that never need parentheses around a multi-line JSX element. */
|
|
1204
|
+
const NO_WRAP_PARENTS = new Set([
|
|
1205
|
+
'ArrayExpression',
|
|
1206
|
+
'JSXAttribute',
|
|
1207
|
+
'JSXElement',
|
|
1208
|
+
'JSXExpressionContainer',
|
|
1209
|
+
'JSXFragment',
|
|
1210
|
+
'ExpressionStatement',
|
|
1211
|
+
'NewExpression',
|
|
1212
|
+
'CallExpression',
|
|
1213
|
+
'OptionalCallExpression',
|
|
1214
|
+
'ConditionalExpression',
|
|
1215
|
+
'JsExpressionRoot',
|
|
1216
|
+
'MatchExpressionCase',
|
|
1217
|
+
]);
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* Prettier's `maybeWrapJsxElementInParens`: the parentheses of a multi-line
|
|
1221
|
+
* element, left out where `needsParens` already adds them.
|
|
1222
|
+
* @param {AstPath<Node>} path
|
|
1223
|
+
* @param {Doc} element
|
|
1224
|
+
* @param {boolean} [needsParens]
|
|
1225
|
+
* @returns {Doc}
|
|
1226
|
+
*/
|
|
1227
|
+
function maybeWrapJsxElementInParens(path, element, needsParens = false) {
|
|
1228
|
+
if (!path.parent || NO_WRAP_PARENTS.has(path.parent.type)) {
|
|
1229
|
+
return element;
|
|
1230
|
+
}
|
|
1231
|
+
const any = () => true;
|
|
1232
|
+
const isCall = (/** @type {Node} */ node) =>
|
|
1233
|
+
node.type === 'CallExpression' || node.type === 'OptionalCallExpression';
|
|
1234
|
+
const shouldBreak =
|
|
1235
|
+
path.match(
|
|
1236
|
+
any,
|
|
1237
|
+
(node, key) => key === 'body' && node.type === 'ArrowFunctionExpression',
|
|
1238
|
+
(node, key) => key === 'arguments' && isCall(node),
|
|
1239
|
+
) &&
|
|
1240
|
+
(path.match(
|
|
1241
|
+
any,
|
|
1242
|
+
any,
|
|
1243
|
+
any,
|
|
1244
|
+
(node, key) => key === 'expression' && node.type === 'JSXExpressionContainer',
|
|
1245
|
+
) ||
|
|
1246
|
+
path.match(
|
|
1247
|
+
any,
|
|
1248
|
+
any,
|
|
1249
|
+
any,
|
|
1250
|
+
(node, key) => key === 'expression' && node.type === 'ChainExpression',
|
|
1251
|
+
(node, key) => key === 'expression' && node.type === 'JSXExpressionContainer',
|
|
1252
|
+
));
|
|
1253
|
+
return group(
|
|
1254
|
+
[
|
|
1255
|
+
needsParens ? '' : ifBreak('('),
|
|
1256
|
+
indent([softline, element]),
|
|
1257
|
+
softline,
|
|
1258
|
+
needsParens ? '' : ifBreak(')'),
|
|
1259
|
+
],
|
|
1260
|
+
{ shouldBreak },
|
|
1261
|
+
);
|
|
1262
|
+
}
|