@tsrx/prettier-plugin 0.4.12 → 0.5.0

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/range.js ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * @import { Parser, ParserOptions } from 'prettier'
3
+ * @import { Node } from './parse.js'
4
+ */
5
+
6
+ /**
7
+ * Formatting part of a file (`rangeStart`, `rangeEnd`). Prettier formats a
8
+ * range in two parses (`formatRange` in `src/main/core.js`): it parses the
9
+ * file and chooses the statements the range starts and ends at, then formats
10
+ * their text on its own and puts it back. It chooses those statements only for
11
+ * its own parsers, by the parser's name (`isSourceElement` in
12
+ * `src/main/range.js`), so for `tsrx` it formats nothing (#831).
13
+ *
14
+ * So the first parse names the parser `typescript` for this format, with a
15
+ * plugin that resolves that name to this parser: Prettier then chooses the
16
+ * statements as it does for TypeScript, and parses the range with this parser.
17
+ * Other files keep Prettier's own `typescript` parser. This relies on Prettier
18
+ * passing the options object that `parse` receives on to the range's format.
19
+ *
20
+ * A template's output, a directive, a template body or a directive's branch
21
+ * can't be formatted on its own: outside the template, a JSX element is an
22
+ * expression statement and gets a `;`. So when the range is template content,
23
+ * or its text doesn't parse on its own (`yield` outside its generator), the
24
+ * second parse returns the file's tree, and `printer.js` prints only the
25
+ * range's statements, where they are in it (`tsrxRange`).
26
+ *
27
+ * Prettier 3.9 can also grow a range to nodes that aren't statements: a
28
+ * selection that starts in one child of an element and ends in another becomes
29
+ * those children (prettier/prettier#19880 changes this after 3.9). One child,
30
+ * an element or a directive, prints where it is. Several children print only
31
+ * with the element's layout between them, and the range can't grow further,
32
+ * so their text stays as it is, as does a range that doesn't start and end at
33
+ * the same list's items (which #19880 can choose).
34
+ */
35
+
36
+ /** A range format's state, from its first parse to its second. */
37
+ const RANGE = Symbol('tsrx range format');
38
+
39
+ /**
40
+ * Where a range's statements are in the file's tree: the keys from the root
41
+ * to a statement, or to a list of statements and the first and last of them.
42
+ * @typedef {{ keys: Array<string | number>, first?: number, last?: number }} RangeStatements
43
+ * @typedef {{
44
+ * text: string,
45
+ * start: number,
46
+ * ast: Node,
47
+ * piece?: Node,
48
+ * standalone?: { text: string, ast: Node },
49
+ * }} RangeFormat
50
+ * @typedef {{ locStart: (node: Node) => number, locEnd: (node: Node) => number }} Loc
51
+ * @typedef {ParserOptions<Node> & {
52
+ * [RANGE]?: RangeFormat,
53
+ * cursorOffset: number,
54
+ * printer: { features?: { experimental_locForRangeFormat?: Loc } },
55
+ * }} RangeOptions
56
+ */
57
+
58
+ /**
59
+ * @param {Parser<Node>} parser
60
+ * @returns {Parser<Node>}
61
+ */
62
+ export function withRangeFormatting(parser) {
63
+ /** @type {Parser<Node>} */
64
+ const rangeParser = {
65
+ ...parser,
66
+
67
+ preprocess(text, parserOptions) {
68
+ const options = /** @type {RangeOptions} */ (parserOptions);
69
+ const range = options[RANGE];
70
+ if (!range || options.parser !== 'typescript' || text === range.text) return text;
71
+ // The second parse: `text` is the range, cut out of the file.
72
+ const start = range.text.lastIndexOf(text, range.start);
73
+ if (start === -1 || start + text.length < range.start) return text;
74
+ const end = start + text.length;
75
+ // Prettier locates the range with these (`calculateRange`).
76
+ const loc = options.printer.features?.experimental_locForRangeFormat ?? parser;
77
+ const found = findRange(range.ast, start, end, loc);
78
+ if (!found?.printable) {
79
+ const rangeText = { type: 'TSRXRangeText', start, end };
80
+ range.piece = { type: 'Program', body: [rangeText], comments: [], start, end };
81
+ return range.text;
82
+ }
83
+ const parts = directiveParts(range.ast);
84
+ const inTemplate = (/** @type {Node} */ node) =>
85
+ node.tsrxOutput ||
86
+ node.tsrxCodeBlock ||
87
+ parts.has(node) ||
88
+ !/(?:Statement|Declaration)$/u.test(node.type);
89
+ if (!found.nodes.some(inTemplate)) {
90
+ try {
91
+ range.standalone = { text, ast: /** @type {Node} */ (parser.parse(text, options)) };
92
+ return text;
93
+ } catch {
94
+ // Print it where it is instead.
95
+ }
96
+ }
97
+ range.ast.comments = /** @type {Node[]} */ (range.ast.comments).filter(
98
+ (comment) => comment.start >= start && comment.end <= end,
99
+ );
100
+ range.ast.tsrxRange = found.where;
101
+ range.piece = range.ast;
102
+ // Prettier's cursor is in the range; the text is now the file.
103
+ if (options.cursorOffset >= 0) options.cursorOffset += start;
104
+ return range.text;
105
+ },
106
+
107
+ parse(text, options) {
108
+ const rangeOptions = /** @type {RangeOptions} */ (options);
109
+ const range = rangeOptions[RANGE];
110
+ if (range?.piece && text === range.text) return range.piece;
111
+ // Only for the range's text: an embed (a `<script>` body) parses its own.
112
+ if (range?.standalone?.text === text) return range.standalone.ast;
113
+ const ast = /** @type {Node} */ (parser.parse(text, options));
114
+ if (
115
+ !range &&
116
+ options.parser === 'tsrx' &&
117
+ (options.rangeStart > 0 || options.rangeEnd < text.length)
118
+ ) {
119
+ rangeOptions[RANGE] = { text, start: contractedStart(text, options), ast };
120
+ options.parser = 'typescript';
121
+ options.plugins = [...options.plugins, { parsers: { typescript: rangeParser } }];
122
+ }
123
+ return ast;
124
+ },
125
+ };
126
+ return rangeParser;
127
+ }
128
+
129
+ /**
130
+ * Where Prettier's range starts once it skips the whitespace at its start
131
+ * (`calculateRange`): the statements it chooses contain this offset.
132
+ * @param {string} text
133
+ * @param {ParserOptions<Node>} options
134
+ * @returns {number}
135
+ */
136
+ function contractedStart(text, { rangeStart, rangeEnd }) {
137
+ const first = text.slice(rangeStart, rangeEnd).search(/\S/u);
138
+ return first === -1 ? rangeStart : rangeStart + first;
139
+ }
140
+
141
+ /** Node types whose `body` (or, for a case, `consequent`) lists statements. */
142
+ const STATEMENT_LISTS = new Set([
143
+ 'Program',
144
+ 'BlockStatement',
145
+ 'StaticBlock',
146
+ 'TSModuleBlock',
147
+ 'SwitchCase',
148
+ ]);
149
+
150
+ /** The nodes that print where they are on their own: a statement, an element, a directive. */
151
+ const PRINTABLE_ALONE = /(?:Statement|Declaration)$|^(?:DoExpression|JSXElement|JSXFragment)$/u;
152
+
153
+ /**
154
+ * The nodes from `start` to `end`, as Prettier chooses them: consecutive items
155
+ * of one list, or one node. `printable` tells whether they print where they
156
+ * are: statements, or one element or directive.
157
+ * @param {Node} ast
158
+ * @param {number} start
159
+ * @param {number} end
160
+ * @param {Loc} loc
161
+ * @returns {{ nodes: Node[], where: RangeStatements, printable: boolean } | undefined}
162
+ */
163
+ function findRange(ast, start, end, { locStart, locEnd }) {
164
+ /** @type {Array<{ node: Node, keys: Array<string | number> }>} */
165
+ const queue = [{ node: ast, keys: [] }];
166
+ for (let entry; (entry = queue.shift());) {
167
+ const { node, keys } = entry;
168
+ if (node !== ast && locStart(node) === start && locEnd(node) === end) {
169
+ return { nodes: [node], where: { keys }, printable: PRINTABLE_ALONE.test(node.type) };
170
+ }
171
+ for (const [key, value] of Object.entries(node)) {
172
+ if (key === 'comments' || !value || typeof value !== 'object') continue;
173
+ if (!Array.isArray(value)) {
174
+ if (typeof value.type === 'string') queue.push({ node: value, keys: [...keys, key] });
175
+ continue;
176
+ }
177
+ const first = value.findIndex((child) => child && locStart(child) === start);
178
+ const last = value.findLastIndex((child) => child && locEnd(child) === end);
179
+ if (first !== -1 && last >= first) {
180
+ const statements =
181
+ STATEMENT_LISTS.has(node.type) && (key === 'body' || key === 'consequent');
182
+ if (first === last && !statements) {
183
+ const child = value[first];
184
+ const printable = PRINTABLE_ALONE.test(child.type);
185
+ return { nodes: [child], where: { keys: [...keys, key, first] }, printable };
186
+ }
187
+ return {
188
+ nodes: value.slice(first, last + 1),
189
+ where: { keys: [...keys, key], first, last },
190
+ printable: statements,
191
+ };
192
+ }
193
+ value.forEach((child, index) => {
194
+ if (typeof child?.type === 'string')
195
+ queue.push({ node: child, keys: [...keys, key, index] });
196
+ });
197
+ }
198
+ }
199
+ }
200
+
201
+ /** The parts of a directive that hold its bodies. */
202
+ const DIRECTIVE_PARTS = new Set(['BlockStatement', 'IfStatement', 'SwitchCase', 'CatchClause']);
203
+
204
+ /**
205
+ * The parts of every directive (a `DoExpression` in the tree) down to their
206
+ * bodies: the bodies, an `@else if`, an `@case`, a `@catch`.
207
+ * @param {Node} ast
208
+ * @returns {Set<Node>}
209
+ */
210
+ function directiveParts(ast) {
211
+ /** @type {Set<Node>} */
212
+ const parts = new Set();
213
+ /**
214
+ * @param {Node} node
215
+ * @param {boolean} inDirective
216
+ */
217
+ const visit = (node, inDirective) => {
218
+ const isPart = inDirective && DIRECTIVE_PARTS.has(node.type);
219
+ if (isPart) parts.add(node);
220
+ for (const [key, value] of Object.entries(node)) {
221
+ if (key === 'comments' || !value || typeof value !== 'object') continue;
222
+ // A body's statements are outputs or setup, not parts.
223
+ const bodyStatements = node.type === 'BlockStatement' && Array.isArray(value);
224
+ for (const child of Array.isArray(value) ? value : [value]) {
225
+ if (typeof child?.type !== 'string') continue;
226
+ visit(
227
+ child,
228
+ child.type === 'DoExpression' ||
229
+ ((isPart || node.type === 'DoExpression') && !bodyStatements),
230
+ );
231
+ }
232
+ }
233
+ };
234
+ visit(ast, false);
235
+ return parts;
236
+ }