@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/src/parse.js ADDED
@@ -0,0 +1,800 @@
1
+ /**
2
+ * @import { ParserOptions } from 'prettier'
3
+ */
4
+
5
+ import { DIAGNOSTIC_CODES, parseModule } from '@tsrx/core';
6
+ import { parsers as acornParsers } from 'prettier/plugins/acorn';
7
+
8
+ /**
9
+ * A loosely typed AST node. The parser's acorn-typescript output is reshaped in
10
+ * place, so the adapter reads and writes properties that the core types don't
11
+ * declare.
12
+ * @typedef {Record<string, any> & { type: string, start: number, end: number }} Node
13
+ */
14
+
15
+ /**
16
+ * @typedef {{ type: 'Line' | 'Block', value: string, start: number, end: number }} Comment
17
+ */
18
+
19
+ /** TSRX template directives, printed by `printer.js`. */
20
+ export const TSRX_DIRECTIVES = new Set([
21
+ 'JSXIfExpression',
22
+ 'JSXForExpression',
23
+ 'JSXSwitchExpression',
24
+ 'JSXTryExpression',
25
+ ]);
26
+
27
+ /**
28
+ * Markup that breaks TSRX's grammar: an unclosed or mismatched tag, after which
29
+ * the parser guessed at the markup's structure, and a dynamic tag whose
30
+ * expression isn't an identifier, a member access or a string literal
31
+ * (`<{getTag()} />`, TSRX2014, decision 58 of #852).
32
+ */
33
+ const BROKEN_MARKUP_CODES = new Set([
34
+ DIAGNOSTIC_CODES.UNCLOSED_TAG,
35
+ DIAGNOSTIC_CODES.MISMATCHED_CLOSING_TAG,
36
+ DIAGNOSTIC_CODES.DYNAMIC_TAG_EXPRESSION,
37
+ ]);
38
+
39
+ /**
40
+ * The codes of the mistakes the parser records when collecting that Prettier's
41
+ * `typescript` parser rejects: a declaration list without a declarator
42
+ * (`const` on its own, `for (const of x)`), a modifier on a type member or type
43
+ * parameter or where only a type parameter takes one, a second accessibility
44
+ * modifier, a parameter property outside a constructor, with a binding pattern
45
+ * or on a rest parameter, decorators before anything but a class or a class
46
+ * member other than a constructor, `abstract` before anything but a class or a
47
+ * class member, a class member's modifier before a module element
48
+ * (`public class A {}`), `readonly`, `accessor` or `async` where they can't
49
+ * appear, `async` with `declare` or in a `declare` context (TS1040),
50
+ * `declare` before a `using` declaration, and `import.source`.
51
+ *
52
+ * It formats the others, and leaves out what its tree has no place for, as the
53
+ * output does: a repeated modifier, a modifier in a block, `declare` before an
54
+ * import. TS1039 isn't here: Prettier rejects an
55
+ * initializer in an ambient variable declaration (`declare let x = 1`), but not
56
+ * in an ambient class (`declare class A { x = 1 }`).
57
+ */
58
+ const REJECTED_CODES = new Set([
59
+ 'TS1123',
60
+ 'TS1070',
61
+ 'TS1273',
62
+ 'TS1274',
63
+ 'TS1028',
64
+ 'TS1187',
65
+ 'TS1317',
66
+ 'TS2369',
67
+ 'TS1206',
68
+ 'TS1242',
69
+ 'TS1044',
70
+ 'TS1024',
71
+ 'TS1040',
72
+ 'TS1275',
73
+ 'TS1042',
74
+ 'TS1491',
75
+ 'TS1495',
76
+ 'TS17012',
77
+ ]);
78
+
79
+ /**
80
+ * Whether `error` is for a modifier before `export` (`abstract export class A
81
+ * {}`): TS1029 at the `export`. Prettier's `typescript` parser drops the
82
+ * `export` there (`abstract class A {}`), which only its own tree gives, so the
83
+ * plugin rejects it (decision 60 of #852). A class member's modifiers out of
84
+ * order (`static public x`) are TS1029 too, and Prettier prints them in order,
85
+ * as the plugin does.
86
+ * @param {ParseError} error
87
+ * @param {string} text
88
+ * @returns {boolean}
89
+ */
90
+ function isModifierBeforeExport(error, text) {
91
+ return error.code === 'TS1029' && error.pos !== undefined && text.startsWith('export', error.pos);
92
+ }
93
+
94
+ /**
95
+ * @param {ParseError} error
96
+ * @param {string} text
97
+ * @returns {boolean}
98
+ */
99
+ function isRejected(error, text) {
100
+ return (
101
+ !!error.code &&
102
+ (BROKEN_MARKUP_CODES.has(error.code) ||
103
+ REJECTED_CODES.has(error.code) ||
104
+ isModifierBeforeExport(error, text))
105
+ );
106
+ }
107
+
108
+ /** The statements whose `__contentEnd` Prettier's comment handling reads. */
109
+ const CONTENT_END_STATEMENTS = new Set([
110
+ 'ExpressionStatement',
111
+ 'ImportDeclaration',
112
+ 'ExportDefaultDeclaration',
113
+ 'ExportNamedDeclaration',
114
+ 'ExportAllDeclaration',
115
+ 'ReturnStatement',
116
+ 'ThrowStatement',
117
+ 'DoWhileStatement',
118
+ ]);
119
+
120
+ /** Nodes that can be the output of a `@{ … }` or directive body. */
121
+ const TSRX_OUTPUT = new Set(['JSXElement', 'JSXFragment', 'JSXStyleElement', ...TSRX_DIRECTIVES]);
122
+
123
+ /**
124
+ * Parse a `.tsrx` module into the ESTree shape that Prettier's own estree
125
+ * printer expects (the `typescript` parser's typescript-estree shape), plus
126
+ * the TSRX nodes that `printer.js` prints itself.
127
+ * @param {string} text
128
+ * @param {ParserOptions} options
129
+ * @returns {Node}
130
+ */
131
+ export function parse(text, options) {
132
+ /** @type {Comment[]} */
133
+ const comments = [];
134
+ /** @type {ParseError[]} */
135
+ const errors = [];
136
+ /** @type {Node} */
137
+ let ast;
138
+ try {
139
+ ast = /** @type {Node} */ (
140
+ /** @type {unknown} */ (
141
+ parseModule(text, options.filepath || 'Component.tsrx', {
142
+ // Collecting keeps parsing past mistakes TypeScript reports only as
143
+ // diagnostics, such as a redeclared variable, which don't change the
144
+ // tree. Recovered markup does, so it is still an error here, and so
145
+ // are the mistakes Prettier's own parser rejects.
146
+ collect: true,
147
+ errors: /** @type {any} */ (errors),
148
+ comments: /** @type {any} */ (comments),
149
+ })
150
+ )
151
+ );
152
+ } catch (error) {
153
+ throw createParseError(/** @type {ParseError} */ (error));
154
+ }
155
+ const rejected = errors.find((error) => isRejected(error, text));
156
+ if (rejected) throw createParseError(rejected);
157
+ const adapter = new Adapter(text, comments);
158
+ const program = adapter.visit(ast);
159
+ program.comments = mergeNestledJsdocComments(
160
+ comments
161
+ .filter((comment) => !adapter.jsxComments.has(comment))
162
+ .map(({ type, value, start, end }) => ({ type, value, start, end })),
163
+ );
164
+ return program;
165
+ }
166
+
167
+ /**
168
+ * @typedef {Error & {
169
+ * code?: string,
170
+ * pos?: number,
171
+ * loc?: { line: number, column: number } | { start: { line: number, column: number } },
172
+ * }} ParseError
173
+ */
174
+
175
+ /**
176
+ * A parse error as Prettier's own parsers report one: at a 1-based column in
177
+ * `loc.start`, which Prettier's code frame marks, and in the message.
178
+ * @param {ParseError} error A thrown error (acorn's `loc`) or a collected one
179
+ * (`loc.start`).
180
+ * @returns {Error}
181
+ */
182
+ function createParseError(error) {
183
+ const start = error.loc && ('start' in error.loc ? error.loc.start : error.loc);
184
+ if (!start) return error;
185
+ const loc = { start: { line: start.line, column: start.column + 1 } };
186
+ const message = error.message.replace(/ \(\d+:\d+\)$/u, '');
187
+ return Object.assign(new SyntaxError(`${message} (${loc.start.line}:${loc.start.column})`), {
188
+ loc,
189
+ cause: error,
190
+ });
191
+ }
192
+
193
+ /**
194
+ * Prettier's parsers join JSDoc-style block comments that touch
195
+ * (`/** a *\//** b *\/`) into one comment.
196
+ * @param {Comment[]} comments
197
+ * @returns {Comment[]}
198
+ */
199
+ function mergeNestledJsdocComments(comments) {
200
+ for (let i = comments.length - 2; i >= 0; i--) {
201
+ const comment = comments[i];
202
+ const following = comments[i + 1];
203
+ if (
204
+ comment.end === following.start &&
205
+ isIndentableBlockComment(comment) &&
206
+ isIndentableBlockComment(following)
207
+ ) {
208
+ comment.value += `*//*${following.value}`;
209
+ comment.end = following.end;
210
+ comments.splice(i + 1, 1);
211
+ }
212
+ }
213
+ return comments;
214
+ }
215
+
216
+ /**
217
+ * A block comment whose every line starts with `*`, like a JSDoc comment.
218
+ * @param {Comment} comment
219
+ * @returns {boolean}
220
+ */
221
+ function isIndentableBlockComment(comment) {
222
+ if (comment.type !== 'Block') return false;
223
+ const lines = `*${comment.value}*`.split('\n');
224
+ return lines.length > 1 && lines.every((line) => line.trimStart()[0] === '*');
225
+ }
226
+
227
+ /**
228
+ * Prettier's own location and pragma functions for JavaScript parsers.
229
+ * `locEnd` reads the `__contentEnd` the adapter sets on statements.
230
+ */
231
+ export const { locStart, locEnd, hasPragma, hasIgnorePragma } = acornParsers.acorn;
232
+
233
+ class Adapter {
234
+ /**
235
+ * @param {string} text
236
+ * @param {Comment[]} comments
237
+ */
238
+ constructor(text, comments) {
239
+ this.text = text;
240
+ this.comments = comments;
241
+ // The core parser dedents a multi-line block comment's value for its own
242
+ // printer; Prettier prints comments from their source text.
243
+ for (const comment of comments) {
244
+ comment.value =
245
+ comment.type === 'Block'
246
+ ? text.slice(comment.start + 2, comment.end - 2)
247
+ : text.slice(comment.start + 2, comment.end);
248
+ }
249
+ /**
250
+ * Comments between JSX children, which are `{…}` children instead of
251
+ * comments for Prettier to attach.
252
+ * @type {Set<Comment>}
253
+ */
254
+ this.jsxComments = new Set();
255
+ }
256
+
257
+ /**
258
+ * The source with every comment blanked out, to find a token without
259
+ * matching one inside a comment.
260
+ * @type {string | undefined}
261
+ */
262
+ #blankedText;
263
+
264
+ get textWithoutComments() {
265
+ this.#blankedText ??= this.comments.reduce(
266
+ (text, comment) =>
267
+ text.slice(0, comment.start) +
268
+ ' '.repeat(comment.end - comment.start) +
269
+ text.slice(comment.end),
270
+ this.text,
271
+ );
272
+ return this.#blankedText;
273
+ }
274
+
275
+ /**
276
+ * Prettier's parsers record where a statement's content ends when comments
277
+ * separate it from its semicolon (`foo // c` + newline + `;`); Prettier's
278
+ * comment handling reads it.
279
+ * @param {Node} node
280
+ */
281
+ setContentEnd(node) {
282
+ const end = node.end - 1;
283
+ if (this.text[end] !== ';') return;
284
+ const content = this.textWithoutComments.slice(node.start, end);
285
+ node.__contentEnd = end - (content.length - content.trimEnd().length);
286
+ }
287
+
288
+ /**
289
+ * The parser gives an element's children as TSX's parsers do, text exactly
290
+ * as written, and a TSRX comment between children (`// …` or `/* … *\/`,
291
+ * which TSX would read as text) as the `{…}` child that `{/* … *\/}` is in
292
+ * TSX, with no braces in the source. That child becomes the plugin's comment
293
+ * child: Prettier lays it out as `{/* … *\/}`, and `printer.js` prints the
294
+ * comment without the braces.
295
+ * @param {Node} node
296
+ */
297
+ markJsxComments(node) {
298
+ let marked = false;
299
+ node.children = node.children.map((/** @type {Node} */ child) => {
300
+ if (
301
+ child.type !== 'JSXExpressionContainer' ||
302
+ child.expression.type !== 'JSXEmptyExpression' ||
303
+ this.text[child.start] === '{'
304
+ ) {
305
+ return child;
306
+ }
307
+ const comment = this.comments.find(({ start }) => start === child.start);
308
+ if (!comment) return child;
309
+ this.jsxComments.add(comment);
310
+ marked = true;
311
+ return this.jsxComment(comment);
312
+ });
313
+ // `jsx.js` prints a line comment where it stays a comment.
314
+ if (marked) node.tsrxPrintsChildren = true;
315
+ }
316
+
317
+ /**
318
+ * A comment between children, as the `{…}` child that `{/* … *\/}` is in
319
+ * TSX. It spans only the comment, which `printer.js` prints. A
320
+ * `prettier-ignore` comment keeps the next child as written, as
321
+ * `{/* prettier-ignore *\/}` does in Prettier.
322
+ * @param {Comment} comment
323
+ * @returns {Node}
324
+ */
325
+ jsxComment(comment) {
326
+ const { start, end } = comment;
327
+ return {
328
+ type: 'JSXExpressionContainer',
329
+ start,
330
+ end,
331
+ expression: {
332
+ type: 'JSXEmptyExpression',
333
+ start,
334
+ end,
335
+ prettierIgnore: comment.value.trim() === 'prettier-ignore',
336
+ },
337
+ tsrxComment: { type: comment.type, value: comment.value, start, end },
338
+ };
339
+ }
340
+
341
+ /**
342
+ * @param {any} value
343
+ * @returns {any}
344
+ */
345
+ visit(value) {
346
+ if (Array.isArray(value)) {
347
+ return value.map((item) => this.visit(item));
348
+ }
349
+ if (!value || typeof value !== 'object' || typeof value.type !== 'string') {
350
+ return value;
351
+ }
352
+ /** @type {Node} */
353
+ const node = value;
354
+
355
+ if (node.type === 'TSParenthesizedType') {
356
+ return this.visit(node.typeAnnotation);
357
+ }
358
+
359
+ // The core parser attaches comments itself; Prettier attaches them again
360
+ // from `program.comments`.
361
+ delete node.leadingComments;
362
+ delete node.trailingComments;
363
+ delete node.innerComments;
364
+ delete node.comments;
365
+ delete node.metadata;
366
+
367
+ if (node.type === 'JSXStyleElement' || isRawScriptElement(node)) {
368
+ // `embed()` prints the CSS or `<script>` body from `node.css` or
369
+ // `node.content`. (A stylesheet's own positions are CSS offsets.)
370
+ // A body `embed()` doesn't format is printed from this text.
371
+ if (node.closingElement) {
372
+ node.tsrxRawText = this.text.slice(node.openingElement.end, node.closingElement.start);
373
+ }
374
+ if (node.type === 'JSXStyleElement') node.children = [];
375
+ }
376
+
377
+ for (const key of Object.keys(node)) {
378
+ if (key === 'loc' || key === 'range') continue;
379
+ node[key] = this.visit(node[key]);
380
+ }
381
+
382
+ return this.reshape(node);
383
+ }
384
+
385
+ /**
386
+ * Rename acorn-typescript shapes to typescript-estree ones and wrap the TSRX
387
+ * nodes so Prettier's layout rules treat them like their closest JS
388
+ * relatives.
389
+ * @param {Node} node
390
+ * @returns {Node}
391
+ */
392
+ reshape(node) {
393
+ if (CONTENT_END_STATEMENTS.has(node.type)) {
394
+ this.setContentEnd(node);
395
+ }
396
+
397
+ switch (node.type) {
398
+ // Prettier's parsers rebalance `a || (b || c)` into `(a || b) || c`.
399
+ case 'LogicalExpression':
400
+ return rebalanceLogicalTree(node);
401
+
402
+ // …and drop a union or intersection of one type.
403
+ case 'TSUnionType':
404
+ case 'TSIntersectionType':
405
+ if (node.types.length === 1) return node.types[0];
406
+ break;
407
+
408
+ case 'JSXElement':
409
+ case 'JSXFragment':
410
+ if (!isRawScriptElement(node)) this.markJsxComments(node);
411
+ break;
412
+
413
+ // A JSX statement outside a template body is a plain expression
414
+ // statement, printed as Prettier prints it (`<div />;`): at module
415
+ // level, in a `static` block or a namespace, and as the single-statement
416
+ // body of an `if`, a loop or a label (#923).
417
+ case 'Program':
418
+ case 'StaticBlock':
419
+ case 'TSModuleBlock':
420
+ node.body = node.body.map(plainStatement);
421
+ break;
422
+ case 'IfStatement':
423
+ node.consequent = plainStatement(node.consequent);
424
+ if (node.alternate) node.alternate = plainStatement(node.alternate);
425
+ break;
426
+ case 'ForStatement':
427
+ case 'ForInStatement':
428
+ case 'ForOfStatement':
429
+ case 'WhileStatement':
430
+ case 'DoWhileStatement':
431
+ case 'LabeledStatement':
432
+ node.body = plainStatement(node.body);
433
+ break;
434
+
435
+ // `@{ … }` is a block whose last statement is the output node. Prettier
436
+ // prints it like any block; `printer.js` adds the `@`.
437
+ case 'JSXCodeBlock': {
438
+ const body = (node.render ? [...node.body, node.render] : node.body).map(templateStatement);
439
+ keepStatementParens(body, true);
440
+ return {
441
+ type: 'BlockStatement',
442
+ tsrxCodeBlock: true,
443
+ start: node.start,
444
+ end: node.end,
445
+ body,
446
+ };
447
+ }
448
+
449
+ // Directive and case bodies hold bare JSX output as statements.
450
+ case 'BlockStatement':
451
+ node.body = node.body.map(templateStatement);
452
+ keepStatementParens(node.body, false);
453
+ break;
454
+ case 'SwitchCase':
455
+ node.consequent = node.consequent.map(templateStatement);
456
+ break;
457
+
458
+ // `<style>` is a JSX element whose body `embed()` prints as CSS.
459
+ case 'JSXStyleElement':
460
+ node.tsrxType = node.type;
461
+ node.type = 'JSXElement';
462
+ break;
463
+
464
+ case 'JSXIfExpression': {
465
+ keepStatementParens(node.consequent.body, true);
466
+ let alternate = node.alternate;
467
+ for (; alternate?.type === 'IfStatement'; alternate = alternate.alternate) {
468
+ alternate.tsrxElseIf = true;
469
+ keepStatementParens(alternate.consequent.body, true);
470
+ }
471
+ if (alternate) keepStatementParens(alternate.body, true);
472
+ break;
473
+ }
474
+
475
+ case 'JSXForExpression':
476
+ keepStatementParens(node.body.body, true);
477
+ if (node.empty) keepStatementParens(node.empty.body, true);
478
+ break;
479
+
480
+ case 'JSXTryExpression':
481
+ for (const block of [node.block, node.pending, node.handler?.body, node.finalizer]) {
482
+ if (block) keepStatementParens(block.body, true);
483
+ }
484
+ break;
485
+
486
+ case 'JSXSwitchExpression':
487
+ for (const switchCase of node.cases) {
488
+ keepStatementParens(switchCase.consequent, true);
489
+ for (const statement of switchCase.consequent) {
490
+ if (statement.type === 'BlockStatement') keepStatementParens(statement.body, true);
491
+ }
492
+ }
493
+ break;
494
+
495
+ case 'PropertyDefinition':
496
+ // typescript-estree names an abstract member's type, and Prettier
497
+ // checks it: it unquotes an abstract field's key (#903).
498
+ if (node.accessor) {
499
+ node.type = node.abstract ? 'TSAbstractAccessorProperty' : 'AccessorProperty';
500
+ delete node.accessor;
501
+ } else if (node.abstract) {
502
+ node.type = 'TSAbstractPropertyDefinition';
503
+ }
504
+ break;
505
+
506
+ case 'TSImportEqualsDeclaration':
507
+ if (node.isExport) {
508
+ delete node.isExport;
509
+ const exportDeclaration = {
510
+ type: 'ExportNamedDeclaration',
511
+ start: node.start,
512
+ end: node.end,
513
+ declaration: node,
514
+ specifiers: [],
515
+ source: null,
516
+ exportKind: 'value',
517
+ attributes: [],
518
+ };
519
+ node.start = this.textWithoutComments.indexOf('import', node.start);
520
+ this.setContentEnd(exportDeclaration);
521
+ return exportDeclaration;
522
+ }
523
+ break;
524
+
525
+ case 'TSModuleDeclaration':
526
+ // `namespace A.B {}` is one declaration named by a qualified name.
527
+ while (node.body?.type === 'TSModuleDeclaration') {
528
+ const inner = node.body;
529
+ node.id = {
530
+ type: 'TSQualifiedName',
531
+ start: node.id.start,
532
+ end: inner.id.end,
533
+ left: node.id,
534
+ right: inner.id,
535
+ };
536
+ node.body = inner.body;
537
+ }
538
+ break;
539
+
540
+ case 'MethodDefinition':
541
+ if (node.abstract) node.type = 'TSAbstractMethodDefinition';
542
+ // A method without a body (an overload, an abstract method, a method
543
+ // of a `declare class`): Prettier reads `TSDeclareMethod` as babel's
544
+ // whole method and prints its `async`, `*` and key again (#916).
545
+ if (node.value.type === 'TSDeclareMethod')
546
+ node.value.type = 'TSEmptyBodyFunctionExpression';
547
+ if (node.typeParameters) {
548
+ // The function starts at its type parameters, as in typescript-estree,
549
+ // so a comment inside them belongs to the function.
550
+ node.value.typeParameters = node.typeParameters;
551
+ node.value.start = node.typeParameters.start;
552
+ if (node.value.range) node.value.range = [node.value.start, node.value.range[1]];
553
+ delete node.typeParameters;
554
+ }
555
+ break;
556
+
557
+ case 'ClassDeclaration':
558
+ case 'ClassExpression':
559
+ rename(node, 'superTypeParameters', 'superTypeArguments');
560
+ for (const heritage of node.implements ?? []) heritage.type = 'TSClassImplements';
561
+ break;
562
+
563
+ case 'TSInterfaceDeclaration':
564
+ for (const heritage of node.extends ?? []) heritage.type = 'TSInterfaceHeritage';
565
+ break;
566
+
567
+ case 'TSExpressionWithTypeArguments':
568
+ rename(node, 'typeParameters', 'typeArguments');
569
+ // `extends a.b.C` names an expression, not a type.
570
+ node.expression = qualifiedNameToMemberExpression(node.expression);
571
+ break;
572
+
573
+ case 'TSParameterProperty':
574
+ // `constructor(@d private x)`: the decorators belong to the property.
575
+ if (node.parameter.decorators?.length) {
576
+ node.decorators = node.parameter.decorators;
577
+ node.parameter.decorators = [];
578
+ }
579
+ break;
580
+
581
+ case 'TSFunctionType':
582
+ case 'TSConstructorType':
583
+ case 'TSCallSignatureDeclaration':
584
+ case 'TSConstructSignatureDeclaration':
585
+ case 'TSMethodSignature':
586
+ rename(node, 'parameters', 'params');
587
+ rename(node, 'typeAnnotation', 'returnType');
588
+ break;
589
+
590
+ // typescript-estree gives a template literal type its own node, with its
591
+ // `${…}` types in `types`. Prettier's comment handling keeps a comment in
592
+ // a `TemplateLiteral`'s `${…}`, but moves one in a type's (#904).
593
+ case 'TSLiteralType':
594
+ if (node.literal.type === 'TemplateLiteral') {
595
+ node.type = 'TSTemplateLiteralType';
596
+ node.quasis = node.literal.quasis;
597
+ node.types = node.literal.expressions;
598
+ delete node.literal;
599
+ }
600
+ break;
601
+
602
+ case 'TSImportType':
603
+ if (node.argument) {
604
+ // Older Prettier printers read `argument` with its TSLiteralType
605
+ // wrapper; newer ones read `source`. Keep both: each printer's
606
+ // visitor keys select the shape it uses for comments and printing.
607
+ node.source =
608
+ node.argument.type === 'TSLiteralType' ? node.argument.literal : node.argument;
609
+ }
610
+ break;
611
+
612
+ case 'TSMappedType':
613
+ if (node.typeParameter) {
614
+ node.key = node.typeParameter.name;
615
+ node.constraint = node.typeParameter.constraint;
616
+ delete node.typeParameter;
617
+ }
618
+ break;
619
+ }
620
+
621
+ // Directives are block-shaped expressions. Prettier's closest relative is
622
+ // `do { … }`, so layout decisions (hugging an arrow body, a JSX expression
623
+ // container, a last call argument) treat them the same way. `printer.js`
624
+ // prints each directive's head as its statement (`node.statementType`).
625
+ if (TSRX_DIRECTIVES.has(node.type)) {
626
+ node.tsrxType = node.type;
627
+ node.type = 'DoExpression';
628
+ }
629
+
630
+ return node;
631
+ }
632
+ }
633
+
634
+ /**
635
+ * @param {Node} node
636
+ * @returns {Node}
637
+ */
638
+ function qualifiedNameToMemberExpression(node) {
639
+ if (node.type !== 'TSQualifiedName') return node;
640
+ return {
641
+ type: 'MemberExpression',
642
+ start: node.start,
643
+ end: node.end,
644
+ object: qualifiedNameToMemberExpression(node.left),
645
+ property: node.right,
646
+ computed: false,
647
+ optional: false,
648
+ };
649
+ }
650
+
651
+ /**
652
+ * @param {Node} node
653
+ * @returns {Node}
654
+ */
655
+ function rebalanceLogicalTree(node) {
656
+ const { left, right, operator } = node;
657
+ if (right.type !== 'LogicalExpression' || right.operator !== operator) {
658
+ return node;
659
+ }
660
+ return rebalanceLogicalTree({
661
+ type: 'LogicalExpression',
662
+ operator,
663
+ left: rebalanceLogicalTree({
664
+ type: 'LogicalExpression',
665
+ operator,
666
+ left,
667
+ right: right.left,
668
+ start: locStart(left),
669
+ end: locEnd(right.left),
670
+ }),
671
+ right: right.right,
672
+ start: locStart(node),
673
+ end: locEnd(node),
674
+ });
675
+ }
676
+
677
+ /**
678
+ * @param {Node | null | undefined} node
679
+ * @returns {boolean}
680
+ */
681
+ export function isRawScriptElement(node) {
682
+ return (
683
+ node?.type === 'JSXElement' &&
684
+ node.openingElement?.name?.type === 'JSXIdentifier' &&
685
+ node.openingElement.name.name === 'script' &&
686
+ typeof node.content === 'string'
687
+ );
688
+ }
689
+
690
+ /**
691
+ * @param {Node} node
692
+ * @returns {boolean}
693
+ */
694
+ function isTsrxOutput(node) {
695
+ return TSRX_OUTPUT.has(node.tsrxType ?? node.type);
696
+ }
697
+
698
+ /**
699
+ * @param {Node} node
700
+ * @returns {Node}
701
+ */
702
+ function expressionStatement(node) {
703
+ return { type: 'ExpressionStatement', expression: node, start: node.start, end: node.end };
704
+ }
705
+
706
+ /**
707
+ * Mark the element that starts a statement where it has parentheses TSRX needs:
708
+ * without them, an element that starts a statement is a template's output, as
709
+ * `{` starts a block and `function` a declaration in JavaScript, where
710
+ * Prettier keeps the parentheses too (decision 63 of #852). In a template body
711
+ * (`template`), an element that starts a statement ends it, so
712
+ * `(<hr />) + 1;` keeps its parentheses; in any other block, only a statement
713
+ * that is just the element does (`(<div />);`), since `<hr /> + 1` reads the
714
+ * same there.
715
+ * @param {Node[]} statements
716
+ * @param {boolean} template
717
+ */
718
+ function keepStatementParens(statements, template) {
719
+ for (const statement of statements) {
720
+ if (statement.type !== 'ExpressionStatement' || statement.tsrxOutput) continue;
721
+ const start = template ? leftmostExpression(statement.expression) : statement.expression;
722
+ if (start.type === 'JSXElement' || start.type === 'JSXFragment') start.tsrxKeepParens = true;
723
+ }
724
+ }
725
+
726
+ /**
727
+ * The expression a printed expression starts with, as Prettier's
728
+ * `startsWithNoLookaheadToken` walks it.
729
+ * @param {Node} node
730
+ * @returns {Node}
731
+ */
732
+ function leftmostExpression(node) {
733
+ for (;;) {
734
+ switch (node.type) {
735
+ case 'BinaryExpression':
736
+ case 'LogicalExpression':
737
+ case 'AssignmentExpression':
738
+ node = node.left;
739
+ break;
740
+ case 'ConditionalExpression':
741
+ node = node.test;
742
+ break;
743
+ case 'SequenceExpression':
744
+ node = node.expressions[0];
745
+ break;
746
+ case 'MemberExpression':
747
+ node = node.object;
748
+ break;
749
+ case 'CallExpression':
750
+ node = node.callee;
751
+ break;
752
+ case 'TaggedTemplateExpression':
753
+ node = node.tag;
754
+ break;
755
+ case 'TSAsExpression':
756
+ case 'TSSatisfiesExpression':
757
+ case 'TSNonNullExpression':
758
+ case 'ChainExpression':
759
+ node = node.expression;
760
+ break;
761
+ case 'UpdateExpression':
762
+ if (node.prefix) return node;
763
+ node = node.argument;
764
+ break;
765
+ default:
766
+ return node;
767
+ }
768
+ }
769
+ }
770
+
771
+ /**
772
+ * A JSX statement outside a template body, printed with a semicolon.
773
+ * @param {Node} node
774
+ * @returns {Node}
775
+ */
776
+ function plainStatement(node) {
777
+ return isTsrxOutput(node) ? expressionStatement(node) : node;
778
+ }
779
+
780
+ /**
781
+ * A template body's output node, printed without a semicolon.
782
+ * @param {Node} node
783
+ * @returns {Node}
784
+ */
785
+ function templateStatement(node) {
786
+ if (!isTsrxOutput(node)) return node;
787
+ return { ...expressionStatement(node), tsrxOutput: true };
788
+ }
789
+
790
+ /**
791
+ * @param {Node} node
792
+ * @param {string} from
793
+ * @param {string} to
794
+ */
795
+ function rename(node, from, to) {
796
+ if (node[from] !== undefined) {
797
+ node[to] ??= node[from];
798
+ delete node[from];
799
+ }
800
+ }