prettier-plugin-julia 0.0.0-stage → 0.2.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/printer.js ADDED
@@ -0,0 +1,1661 @@
1
+ // The Prettier doc printer for the full JuliaSyntax tree (src/tree.js).
2
+ //
3
+ // The printer walks the tree itself with a small context and returns one Prettier doc.
4
+ // Every kind without a dedicated printer goes through `printTokens`: all tokens in order,
5
+ // whitespace between them normalized (runs of spaces -> one space or none as written, line
6
+ // breaks kept, continuation lines re-indented). Nodes the verifier protected, `# prettier-ignore`
7
+ // statements and `#! format: off` regions are printed verbatim.
8
+ //
9
+ // Line breaks are only introduced where Julia reads them as whitespace or continuation:
10
+ // after `(`/`[`/`{` and commas inside brackets, after binary and assignment operators
11
+ // outside space-sensitive contexts (matrix rows, macro arguments), and between statements.
12
+ import { builders } from 'prettier/doc';
13
+ import { utils as prettierDocUtils } from 'prettier/doc';
14
+ import { CLASS } from './tree.js';
15
+
16
+ // Prettier's willBreak walks the whole sub-doc on every call; the printer asks it at every
17
+ // level, so memoize per doc object (docs are never mutated after construction).
18
+ const breakMemo = new WeakMap();
19
+ function willBreak(d) {
20
+ if (typeof d === 'string' || d === null || d === undefined) return false;
21
+ const m = breakMemo.get(d);
22
+ if (m !== undefined) return m;
23
+ let r;
24
+ if (Array.isArray(d)) r = d.some(willBreak);
25
+ else
26
+ switch (d.type) {
27
+ case 'line':
28
+ r = Boolean(d.hard);
29
+ break;
30
+ case 'break-parent':
31
+ r = true;
32
+ break;
33
+ case 'group':
34
+ r = Boolean(d.break) || willBreak(d.contents) || (d.expandedStates ? d.expandedStates.some(willBreak) : false);
35
+ break;
36
+ case 'if-break':
37
+ r = willBreak(d.breakContents) || willBreak(d.flatContents);
38
+ break;
39
+ case 'fill':
40
+ r = willBreak(d.parts);
41
+ break;
42
+ default:
43
+ r = d.contents !== undefined ? willBreak(d.contents) : false;
44
+ }
45
+ breakMemo.set(d, r);
46
+ return r;
47
+ }
48
+ const docUtils = { willBreak, removeLines: prettierDocUtils.removeLines };
49
+
50
+ const {
51
+ group,
52
+ indent,
53
+ line,
54
+ softline,
55
+ hardline,
56
+ join,
57
+ ifBreak,
58
+ lineSuffix,
59
+ breakParent,
60
+ indentIfBreak,
61
+ hardlineWithoutBreakParent,
62
+ } = builders;
63
+
64
+ // ─── Tree helpers ──────────────────────────────────────────────────────
65
+
66
+ const isLeaf = (n) => n.text !== undefined;
67
+ const isWs = (n) => isLeaf(n) && (n.kind === 'Whitespace' || n.kind === 'NewlineWs');
68
+ const isComment = (n) => isLeaf(n) && n.kind === 'Comment';
69
+ const isTriviaLeaf = (n) => isLeaf(n) && Boolean(n.cls & CLASS.TRIVIA) && !(n.cls & CLASS.ERROR);
70
+ const isLineComment = (n) => isComment(n) && !n.text.startsWith('#=');
71
+ const tok = (n, text) => isLeaf(n) && isTriviaLeaf(n) && n.text === text;
72
+ const STATEMENT_LISTS = new Set(['block', 'toplevel', 'toplevel-file']);
73
+ const VERBATIM_KINDS = new Set(['string', 'cmdstring', 'char', 'Char']);
74
+ const flag = (n, bit) => Boolean(n.flags & bit);
75
+ const isInfixCall = (n) => (n.kind === 'call' || n.kind === 'dotcall') && (n.flags & 24) === 8;
76
+ const isPrefixOpCall = (n) => (n.kind === 'call' || n.kind === 'dotcall') && (n.flags & 24) === 16;
77
+ const isPostfixOpCall = (n) => (n.kind === 'call' || n.kind === 'dotcall') && (n.flags & 24) === 24;
78
+ const isNumber = (n) => isLeaf(n) && ['Integer', 'Float', 'Float32', 'BinInt', 'HexInt', 'OctInt'].includes(n.kind);
79
+
80
+ /**
81
+ * Move leading/trailing whitespace and comments out of interior nodes into their parent
82
+ * (except out of statement lists and verbatim kinds), so trivia sits between siblings.
83
+ * Also records parents (for escalating protected regions).
84
+ */
85
+ export function normalizeTree(root) {
86
+ const edge = (k) => isWs(k) || isComment(k);
87
+ const hoistable = (c) =>
88
+ !(isLeaf(c) || STATEMENT_LISTS.has(c.kind) || VERBATIM_KINDS.has(c.kind) || isStringMacro(c)) &&
89
+ c.children.length > 0 &&
90
+ (edge(c.children[0]) || edge(c.children.at(-1)));
91
+ const visit = (n) => {
92
+ if (isLeaf(n)) return;
93
+ for (const c of n.children) visit(c);
94
+ if (VERBATIM_KINDS.has(n.kind) || isStringMacro(n) || !n.children.some(hoistable)) return;
95
+ const out = [];
96
+ for (const c of n.children) {
97
+ if (!hoistable(c)) {
98
+ out.push(c);
99
+ continue;
100
+ }
101
+ let i = 0,
102
+ j = c.children.length;
103
+ while (i < j && edge(c.children[i])) i++;
104
+ while (j > i && edge(c.children[j - 1])) j--;
105
+ if (i === j) {
106
+ // only whitespace/comments inside (`do # c` puts them in an empty tuple): hoist all
107
+ const t = c.children;
108
+ if (t.some(isComment)) {
109
+ c.children = [];
110
+ c.end = c.start;
111
+ out.push(...t, c);
112
+ } else out.push(c);
113
+ continue;
114
+ }
115
+ const lead = c.children.slice(0, i),
116
+ trail = c.children.slice(j);
117
+ c.children = c.children.slice(i, j);
118
+ c.start = c.children[0].start;
119
+ c.end = c.children.at(-1).end;
120
+ out.push(...lead, c, ...trail);
121
+ }
122
+ n.children = out;
123
+ };
124
+ visit(root);
125
+ }
126
+
127
+ /** Parent of every node (only needed when a region must be protected). */
128
+ export function parentsOf(root) {
129
+ const parents = new Map();
130
+ const walk = (n) => {
131
+ if (!isLeaf(n))
132
+ for (const c of n.children) {
133
+ parents.set(c, n);
134
+ walk(c);
135
+ }
136
+ };
137
+ walk(root);
138
+ return parents;
139
+ }
140
+
141
+ function isStringMacro(n) {
142
+ return (
143
+ !isLeaf(n) &&
144
+ n.kind === 'macrocall' &&
145
+ n.children.length > 0 &&
146
+ isLeaf(n.children[0]) &&
147
+ (n.children[0].kind === 'StrMacroName' || n.children[0].kind === 'CmdMacroName')
148
+ );
149
+ }
150
+
151
+ // ─── Entry point ───────────────────────────────────────────────────────
152
+
153
+ /**
154
+ * @param tree { root } from parseTree, already normalized
155
+ * @param text the source
156
+ * @param protect Set of nodes to print verbatim
157
+ */
158
+ export function printJulia(tree, text, protect = new Set(), mutate = null) {
159
+ TEXT = text;
160
+ ROOT = tree.root;
161
+ const ctx = { text, protect, flat: false, compact: false, parent: null, mutate };
162
+ const { doc, empty } = printStatements(tree.root.children, ctx, { top: true });
163
+ return empty ? '' : [doc, hardline];
164
+ }
165
+
166
+ const sub = (ctx, patch) => ({ ...ctx, ...patch });
167
+
168
+ function print(n, ctx, parent = null) {
169
+ if (ctx.mutate && !ctx.protect.has(n)) {
170
+ // test hook: a deliberately wrong printer for some nodes
171
+ const d = ctx.mutate(n, ctx.text);
172
+ if (d !== undefined) return d;
173
+ }
174
+ return print1(n, ctx, parent);
175
+ }
176
+
177
+ function print1(n, ctx, parent) {
178
+ const c = parent === ctx.parent ? ctx : sub(ctx, { parent });
179
+ if (ctx.protect.has(n)) return printVerbatim(n, ctx);
180
+ if (isLeaf(n)) return printLeaf(n, ctx);
181
+ const f = PRINTERS[n.kind];
182
+ if (f) {
183
+ const d = f(n, c);
184
+ if (d !== null && d !== undefined) return d;
185
+ }
186
+ if (n.kind === 'comparison') {
187
+ const { xs, comments } = parts(n);
188
+ const d = printInfix(n, xs, comments, c);
189
+ if (d) return d;
190
+ }
191
+ if (n.kind === 'call' || n.kind === 'dotcall') {
192
+ const d = printCall(n, c);
193
+ if (d) return d;
194
+ }
195
+ return printTokens(n, c);
196
+ }
197
+
198
+ function printLeaf(n, ctx) {
199
+ if (isComment(n)) return printCommentInline(n, ctx);
200
+ if (n.kind === 'for' || n.kind === 'in' || n.kind === 'where') return n.text;
201
+ return n.text.includes('\n') ? literalText(n.text) : n.text;
202
+ }
203
+
204
+ let TEXT = '',
205
+ ROOT = null;
206
+ /** Comments inside an expression: all at the end of the current line, one per line, in order. */
207
+ function commentGroup(cs) {
208
+ if (!cs.length) return '';
209
+ const texts = cs.map((c) => c.text.trimEnd());
210
+ if (cs.length === 1 && !isLineComment(cs[0]) && !texts[0].includes('\n')) return [' ', texts[0], ' '];
211
+ const body = [gapBefore(TEXT, cs[0])];
212
+ texts.forEach((t, i) => {
213
+ if (i) body.push(hardlineWithoutBreakParent);
214
+ body.push(t.includes('\n') ? literalText(t) : t);
215
+ });
216
+ return [lineSuffix(body), breakParent];
217
+ }
218
+ function printCommentInline(n) {
219
+ if (isLineComment(n)) return [lineSuffix(gapBefore(TEXT, n) + n.text.trimEnd()), breakParent];
220
+ return n.text.includes('\n') ? literalText(n.text) : n.text;
221
+ }
222
+
223
+ // Multi-line text printed exactly (columns kept). It breaks the enclosing groups, so that
224
+ // the text never sits inside a flat `indent` whose depth could change on the next run.
225
+ const literalText = (s) => join(builders.literalline, s.split('\n'));
226
+
227
+ // ─── Verbatim ──────────────────────────────────────────────────────────
228
+
229
+ /** The original text of a node; re-indented by its first line's indentation when safe. */
230
+ function printVerbatim(n, ctx) {
231
+ return verbatimSlice(ctx.text, n.start, n.end, n);
232
+ }
233
+
234
+ function lineStart(text, i) {
235
+ const k = text.lastIndexOf('\n', i - 1);
236
+ return k + 1;
237
+ }
238
+
239
+ function hasMultilineLeaf(n) {
240
+ if (isLeaf(n)) return !isWs(n) && n.text.includes('\n');
241
+ return n.children.some(hasMultilineLeaf);
242
+ }
243
+
244
+ function verbatimSlice(text, start, end, node) {
245
+ const s = text.slice(start, end);
246
+ if (!s.includes('\n')) return s;
247
+ const lines = s.split('\n');
248
+ const ls = lineStart(text, start);
249
+ const indentStr = /^[ \t]*/.exec(text.slice(ls, start))[0];
250
+ const literal =
251
+ (node && hasMultilineLeaf(node)) ||
252
+ lines.slice(1).some((l) => l.trim() !== '' && !l.startsWith(indentStr)) ||
253
+ (node && lineStartsInsideOther(node, ls));
254
+ if (literal) return literalText(s);
255
+ return join(
256
+ hardline,
257
+ lines.map((l, i) => (i === 0 ? l : l.trim() === '' ? '' : l.slice(indentStr.length))),
258
+ );
259
+ }
260
+
261
+ const KEPT_MULTILINE = new Set([
262
+ 'vcat',
263
+ 'hcat',
264
+ 'ncat',
265
+ 'typed_vcat',
266
+ 'typed_hcat',
267
+ 'typed_ncat',
268
+ 'string',
269
+ 'cmdstring',
270
+ ]);
271
+ /**
272
+ * Does the line `node` starts on begin inside another region printed as written (a
273
+ * multi-line matrix, string or comment)? Then that line's indentation isn't the printer's,
274
+ * and re-indenting relative to it would drift on every run: keep exact columns instead.
275
+ */
276
+ function lineStartsInsideOther(node, ls) {
277
+ if (ls === 0 || !ROOT) return false;
278
+ const nl = ls - 1;
279
+ let n = ROOT;
280
+ for (;;) {
281
+ const c = isLeaf(n) ? null : n.children.find((k) => k.start <= nl && nl < k.end);
282
+ if (!c) return false;
283
+ if (c.start <= node.start && node.end <= c.end) {
284
+ if (c === node) return false;
285
+ n = c;
286
+ continue;
287
+ }
288
+ if (isLeaf(c)) return !isWs(c);
289
+ if (KEPT_MULTILINE.has(c.kind) || isStringMacro(c)) return true;
290
+ n = c;
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Triple-quoted strings: all continuation lines move with the line the string starts on
296
+ * (a uniform shift keeps the value: JuliaSyntax removes the common indentation). Other
297
+ * multi-line strings are printed exactly as written.
298
+ */
299
+ function printString(n, ctx) {
300
+ const s = ctx.text.slice(n.start, n.end);
301
+ if (!s.includes('\n')) return s;
302
+ const triple = flag(n, 0x100) || (isStringMacro(n) && n.children.some((c) => !isLeaf(c) && flag(c, 0x100)));
303
+ const lines = s.split('\n');
304
+ if (!triple || lines.some((l) => /[ \t]$/.test(l))) return literalText(s);
305
+ const ls = lineStart(ctx.text, n.start);
306
+ const indentStr = /^[ \t]*/.exec(ctx.text.slice(ls, n.start))[0];
307
+ if (lines.slice(1).some((l) => l !== '' && !l.startsWith(indentStr)) || lineStartsInsideOther(n, ls))
308
+ return literalText(s);
309
+ return join(
310
+ hardline,
311
+ lines.map((l, i) => (i === 0 ? l : l.slice(indentStr.length))),
312
+ );
313
+ }
314
+
315
+ // ─── Statement lists ───────────────────────────────────────────────────
316
+
317
+ const countNl = (s) => {
318
+ let k = 0;
319
+ for (const ch of s) if (ch === '\n') k++;
320
+ return k;
321
+ };
322
+ const IGNORE_RE = /^#\s*prettier-ignore\s*$/;
323
+ const OFF_RE = /^#!\s*format\s*:\s*off\b/;
324
+ const ON_RE = /^#!\s*format\s*:\s*on\b/;
325
+
326
+ /**
327
+ * Print a statement list (file, block body). Returns { doc, empty, headerComments }:
328
+ * `headerComments` are comments on the line before the first statement (`if a # c`).
329
+ */
330
+ function printStatements(children, ctx, { top = false, keepEdgeBlank = false } = {}) {
331
+ const items = [];
332
+ let nl = 0,
333
+ semi = false,
334
+ prev = null;
335
+ const headerComments = [];
336
+ let ignoreNext = false;
337
+ const kids = flattenToplevel(children);
338
+ for (let idx = 0; idx < kids.length; idx++) {
339
+ const c = kids[idx];
340
+ if (isWs(c)) {
341
+ nl += countNl(c.text);
342
+ continue;
343
+ }
344
+ if (isLeaf(c) && tok(c, ';')) {
345
+ semi = true;
346
+ continue;
347
+ }
348
+ if (isComment(c)) {
349
+ if (prev === null && nl === 0 && !top && !ownLine(ctx.text, c)) {
350
+ headerComments.push({ c, gap: gapBefore(ctx.text, c) });
351
+ continue;
352
+ }
353
+ if (prev !== null && nl === 0 && prev.type === 'stmt') {
354
+ prev.trailing.push({ c, gap: gapBefore(ctx.text, c) });
355
+ continue;
356
+ }
357
+ if (OFF_RE.test(c.text)) {
358
+ // Verbatim region up to the matching `#! format: on` (or the end of the list).
359
+ let j = idx + 1,
360
+ endPos = c.end;
361
+ for (; j < kids.length; j++) {
362
+ const k = kids[j];
363
+ if (!isWs(k)) endPos = k.end;
364
+ if (isComment(k) && ON_RE.test(k.text)) break;
365
+ }
366
+ const node = { type: 'raw', doc: literalText(ctx.text.slice(c.start, endPos)), blank: nl >= 2, trailing: [] };
367
+ items.push(node);
368
+ prev = node;
369
+ nl = 0;
370
+ semi = false;
371
+ idx = j;
372
+ continue;
373
+ }
374
+ const item = { type: 'comment', c, blank: nl >= 2, trailing: [] };
375
+ items.push(item);
376
+ if (IGNORE_RE.test(c.text)) ignoreNext = true;
377
+ prev = item;
378
+ nl = 0;
379
+ semi = false;
380
+ continue;
381
+ }
382
+ const item = {
383
+ type: 'stmt',
384
+ n: c,
385
+ blank: nl >= 2,
386
+ sameLine: prev !== null && nl === 0 && semi && prev.type === 'stmt',
387
+ trailing: [],
388
+ ignore: ignoreNext,
389
+ };
390
+ ignoreNext = false;
391
+ items.push(item);
392
+ prev = item;
393
+ nl = 0;
394
+ semi = false;
395
+ }
396
+ if (!items.length) return { doc: '', empty: true, headerComments, trailingBlank: false };
397
+ const parts = [];
398
+ items.forEach((it, i) => {
399
+ if (i > 0) parts.push(it.sameLine ? '; ' : it.blank ? [hardline, hardline] : hardline);
400
+ else if (it.blank && keepEdgeBlank) parts.push(hardline);
401
+ if (it.type === 'comment') parts.push(printOwnLineComment(it.c));
402
+ else if (it.type === 'raw') parts.push(it.doc);
403
+ else
404
+ parts.push(it.ignore ? printVerbatim(it.n, ctx) : print(it.n, sub(ctx, { flat: false, compact: false }), null));
405
+ for (const t of it.trailing) parts.push(trailingComment(t));
406
+ });
407
+ return { doc: parts, empty: false, headerComments, trailingBlank: nl >= 2 };
408
+ }
409
+
410
+ function flattenToplevel(children) {
411
+ // A file is (toplevel-file (toplevel ...)); its statements are the inner toplevel's children.
412
+ if (children.length === 1 && !isLeaf(children[0]) && children[0].kind === 'toplevel') return children[0].children;
413
+ const out = [];
414
+ for (const c of children) {
415
+ if (!isLeaf(c) && c.kind === 'toplevel' && !flag(c, 0x100)) out.push(...c.children);
416
+ else out.push(c);
417
+ }
418
+ return out;
419
+ }
420
+
421
+ const ownLine = (text, c) => text.slice(lineStart(text, c.start), c.start).trim() === '';
422
+
423
+ function gapBefore(text, c) {
424
+ const ls = lineStart(text, c.start);
425
+ const m = /[ \t]*$/.exec(text.slice(ls, c.start))[0];
426
+ return m.length ? m : ' ';
427
+ }
428
+
429
+ function trailingComment({ c, gap }) {
430
+ if (isLineComment(c)) return [lineSuffix(gap + c.text.trimEnd()), breakParent];
431
+ return [' ', c.text.includes('\n') ? literalText(c.text) : c.text];
432
+ }
433
+
434
+ function printOwnLineComment(c) {
435
+ const t = c.text.trimEnd();
436
+ return t.includes('\n') ? literalText(t) : t;
437
+ }
438
+
439
+ /**
440
+ * A block body: [indent([hardline, statements]), hardline] or a single line break.
441
+ * `header` is printed before it; `endKw` after.
442
+ */
443
+ function blockBody(block, ctx, { endKw = 'end', keepEdgeBlank = false, noIndent = false, skipKw = [] } = {}) {
444
+ let kids = block ? (blockPre.get(block) ?? []).concat(block.children) : [];
445
+ if (skipKw.length) kids = kids.filter((k) => !(isLeaf(k) && isTriviaLeaf(k) && skipKw.includes(k.text)));
446
+ const r = printStatements(kids, ctx, { keepEdgeBlank });
447
+ const head = r.headerComments.map(trailingComment);
448
+ if (r.empty) return [head, endKw === null ? '' : [hardline, endKw]];
449
+ const body = [hardline, r.doc];
450
+ const tail = keepEdgeBlank && r.trailingBlank ? [hardline] : [];
451
+ return [head, noIndent ? body : indent(body), tail, endKw === null ? '' : [hardline, endKw]];
452
+ }
453
+
454
+ // ─── Token printer (generic) ───────────────────────────────────────────
455
+
456
+ const OPENERS = new Set(['(', '[', '{']);
457
+ const CLOSERS = new Set([')', ']', '}', 'end']);
458
+
459
+ /** All tokens in order; whitespace normalized; line breaks kept; continuation indented. */
460
+ /** Debug counter: which kinds reach the token printer (set by scripts/coverage.mjs). */
461
+ export const tokenPrinterStats = { enabled: false, kinds: new Map() };
462
+
463
+ function printTokens(n, ctx) {
464
+ if (tokenPrinterStats.enabled) tokenPrinterStats.kinds.set(n.kind, (tokenPrinterStats.kinds.get(n.kind) ?? 0) + 1);
465
+ const out = [];
466
+ let ws = '',
467
+ prev = null;
468
+ for (const c of n.children) {
469
+ if (isWs(c)) {
470
+ ws += c.text;
471
+ continue;
472
+ }
473
+ if (!isLeaf(c) && c.children.length && c.children.every(isWs)) {
474
+ ws += c.children.map((k) => k.text).join('');
475
+ continue;
476
+ }
477
+ const gap = prev === null ? '' : ws + trailingWs(prev) + leadingWs(c);
478
+ const nls = countNl(gap);
479
+ if (!isLeaf(c) && c.kind === 'block' && !isKeywordBlock(c) && !c.children.some((k) => kw(k, ',') || kw(k, '('))) {
480
+ // a statement list inside a construct we don't know: one statement per line, indented
481
+ const r = printStatements(c.children, ctx);
482
+ if (prev !== null && !nls && !hasNewline(ctx.text, c.start, c.end)) {
483
+ out.push(gap ? ' ' : '', printTokens(c, ctx));
484
+ } else {
485
+ out.push(r.headerComments.map(trailingComment), r.empty ? '' : indent([hardline, r.doc]));
486
+ prev = c;
487
+ ws = '\n';
488
+ continue;
489
+ }
490
+ prev = c;
491
+ ws = '';
492
+ continue;
493
+ }
494
+ if (prev !== null) {
495
+ if (nls > 0) {
496
+ const brk = nls >= 2 ? [hardline, hardline] : hardline;
497
+ if (isLeaf(c) && CLOSERS.has(c.text) && isTriviaLeaf(c)) out.push(brk, printLeaf(c, ctx));
498
+ else if (isComment(c)) out.push(indent([brk, printOwnLineComment(c)]));
499
+ else out.push(indent([brk, printChild(c, n, ctx)]));
500
+ prev = c;
501
+ ws = '';
502
+ continue;
503
+ }
504
+ out.push(spaceBetween(prev, c, gap));
505
+ }
506
+ out.push(isLeaf(c) && isLineComment(c) ? [c.text.trimEnd(), breakParent] : printChild(c, n, ctx));
507
+ prev = c;
508
+ ws = '';
509
+ }
510
+ return out;
511
+ }
512
+
513
+ const isKeywordBlock = (b) => {
514
+ const { xs } = parts(b);
515
+ return xs.length >= 2 && (kw(xs[0], 'begin') || kw(xs[0], 'quote')) && kw(xs.at(-1), 'end');
516
+ };
517
+
518
+ function leadingWs(n) {
519
+ if (isLeaf(n) || !n.children.length) return '';
520
+ let s = '',
521
+ i = 0;
522
+ while (i < n.children.length && isWs(n.children[i])) s += n.children[i++].text;
523
+ if (s || i >= n.children.length) return s;
524
+ return leadingWs(n.children[0]);
525
+ }
526
+
527
+ function trailingWs(n) {
528
+ if (isLeaf(n) || !n.children.length) return '';
529
+ let s = '',
530
+ j = n.children.length - 1;
531
+ while (j >= 0 && isWs(n.children[j])) s = n.children[j--].text + s;
532
+ if (s || j < 0) return s;
533
+ return trailingWs(n.children.at(-1));
534
+ }
535
+
536
+ function printChild(c, parent, ctx) {
537
+ if (isLeaf(c)) return ctx.protect.has(c) ? printVerbatim(c, ctx) : printLeaf(c, ctx);
538
+ const opensBracket = parent.children.some((k) => isLeaf(k) && isTriviaLeaf(k) && OPENERS.has(k.text));
539
+ return print(c, opensBracket && !isMatrixKind(parent.kind) ? sub(ctx, { flat: false }) : ctx, parent);
540
+ }
541
+
542
+ function spaceBetween(prev, c, ws) {
543
+ const pt = isLeaf(prev) ? prev.text : null,
544
+ ct = isLeaf(c) ? c.text : null;
545
+ if (ct === ',' || ct === ';') return '';
546
+ if (pt === ',') return ' ';
547
+ if (pt === ';') return ws ? ' ' : '';
548
+ if (pt !== null && OPENERS.has(pt) && isTriviaLeaf(prev)) return '';
549
+ if (ct !== null && CLOSERS.has(ct) && ct !== 'end' && isTriviaLeaf(c)) return '';
550
+ return ws ? ' ' : '';
551
+ }
552
+
553
+ const isMatrixKind = (k) =>
554
+ ['hcat', 'vcat', 'ncat', 'typed_hcat', 'typed_vcat', 'typed_ncat', 'row', 'nrow'].includes(k);
555
+
556
+ // ─── Helpers for dedicated printers ────────────────────────────────────
557
+
558
+ /**
559
+ * Non-whitespace children; comments are returned separately in order with their index.
560
+ * Whitespace and comments right before a `block` child belong to that block's body
561
+ * (`blockBody` prints them) and are left out of `comments`.
562
+ */
563
+ const blockPre = new WeakMap();
564
+ function parts(n) {
565
+ const xs = [],
566
+ comments = [];
567
+ let pending = [],
568
+ pendingComments = [];
569
+ for (const c of n.children) {
570
+ if (isWs(c)) {
571
+ pending.push(c);
572
+ continue;
573
+ }
574
+ if (isComment(c)) {
575
+ pending.push(c);
576
+ pendingComments.push({ c, at: xs.length });
577
+ continue;
578
+ }
579
+ if (!isLeaf(c) && c.kind === 'block' && pendingComments.length) blockPre.set(c, pending);
580
+ else comments.push(...pendingComments);
581
+ pending = [];
582
+ pendingComments = [];
583
+ xs.push(c);
584
+ }
585
+ comments.push(...pendingComments);
586
+ return { xs, comments };
587
+ }
588
+
589
+ /** Comments that end up at index `at` (before xs[at]) as line suffixes. */
590
+ const commentsAt = (comments, at) => commentGroup(comments.filter((k) => k.at === at).map((k) => k.c));
591
+
592
+ const kw = (n, text) => isLeaf(n) && isTriviaLeaf(n) && n.text === text;
593
+
594
+ const ln = (ctx) => (ctx.flat ? ' ' : line);
595
+
596
+ // ─── Blocks and keyword constructs ─────────────────────────────────────
597
+
598
+ const PRINTERS = {
599
+ toplevel: (n, ctx) => {
600
+ const r = printStatements(n.children, ctx);
601
+ return r.empty ? '' : r.doc;
602
+ },
603
+ block: printBlockNode,
604
+ function: printFunction,
605
+ macro: printFunction,
606
+ if: printIf,
607
+ while: (n, ctx) => printKeywordBlock(n, ctx, 'while'),
608
+ for: printFor,
609
+ let: printLet,
610
+ try: printTry,
611
+ struct: printStruct,
612
+ module: printModule,
613
+ baremodule: printModule,
614
+ do: printDo,
615
+ doc: printDoc,
616
+ string: printString,
617
+ cmdstring: printString,
618
+ char: (n, ctx) => printVerbatim(n, ctx),
619
+ var: (n, ctx) => printVerbatim(n, ctx),
620
+ macrocall: printMacrocall,
621
+ tuple: printTuple,
622
+ vect: (n, ctx) => printBracketList(n, ctx, '[', ']'),
623
+ braces: (n, ctx) => printBracketList(n, ctx, '{', '}'),
624
+ curly: printCalleeList,
625
+ ref: printCalleeList,
626
+ parens: printParens,
627
+ '=': printAssignment,
628
+ 'op=': printAssignment,
629
+ '.op=': printAssignment,
630
+ '.=': printAssignment,
631
+ ':=': printAssignment,
632
+ '&&': printChain,
633
+ '||': printChain,
634
+ '->': (n, ctx) => printSpacedBinary(n, ctx, '->'),
635
+ where: printWhere,
636
+ '?': printTernary,
637
+ '::': printTight,
638
+ '.': printTight,
639
+ '...': printTight,
640
+ '<:': printSubtype,
641
+ '>:': printSubtype,
642
+ in: printIn,
643
+ const: printKeywordPrefix,
644
+ global: printKeywordPrefix,
645
+ local: printKeywordPrefix,
646
+ return: printKeywordPrefix,
647
+ export: printImportList,
648
+ public: printImportList,
649
+ using: printImportList,
650
+ import: printImportList,
651
+ generator: printGenerator,
652
+ comprehension: printComprehension,
653
+ typed_comprehension: printComprehension,
654
+ hcat: printMatrix,
655
+ vcat: printMatrix,
656
+ ncat: printMatrix,
657
+ typed_hcat: printMatrix,
658
+ typed_vcat: printMatrix,
659
+ typed_ncat: printMatrix,
660
+ };
661
+
662
+ /** `begin … end`, `quote … end`; a bare block (e.g. `(a; b)`) goes to the token printer. */
663
+ function printBlockNode(n, ctx) {
664
+ const { xs } = parts(n);
665
+ const firstTok = xs[0],
666
+ lastTok = xs.at(-1);
667
+ if (!firstTok || !(kw(firstTok, 'begin') || kw(firstTok, 'quote')) || !kw(lastTok, 'end')) return null;
668
+ const inner = n.children.slice(n.children.indexOf(firstTok) + 1, n.children.lastIndexOf(lastTok));
669
+ const r = printStatements(inner, ctx);
670
+ const head = r.headerComments.map(trailingComment);
671
+ if (r.empty) return [firstTok.text, head, hasNewline(ctx.text, firstTok.end, lastTok.start) ? hardline : ' ', 'end'];
672
+ return [firstTok.text, head, indent([hardline, r.doc]), hardline, 'end'];
673
+ }
674
+
675
+ const hasNewline = (text, a, b) => text.slice(a, b).includes('\n');
676
+
677
+ /** Generic "kw header… block end" printer: header parts joined with single spaces. */
678
+ function printKeywordBlock(n, ctx, word) {
679
+ const { xs, comments } = parts(n);
680
+ if (!kw(xs[0], word) || !kw(xs.at(-1), 'end')) return null;
681
+ const block = xs.at(-2);
682
+ if (!block || block.kind !== 'block') return null;
683
+ const header = xs.slice(1, -2);
684
+ const h = [word];
685
+ header.forEach((x, i) => {
686
+ h.push(' ', print(x, ctx, n), commentsAt(comments, i + 2));
687
+ });
688
+ return [commentsAt(comments, 1), h, blockBody(block, ctx)];
689
+ }
690
+
691
+ function printFunction(n, ctx) {
692
+ const { xs, comments } = parts(n);
693
+ const word = n.kind;
694
+ if (flag(n, 0x100)) {
695
+ // short form: sig = body
696
+ const eq = xs.findIndex((x) => kw(x, '='));
697
+ if (eq !== 1 || xs.length !== 3 || comments.length) return null;
698
+ return assignmentLayout(print(xs[0], ctx, n), '=', xs[2], ctx, n);
699
+ }
700
+ if (!kw(xs[0], word) || !kw(xs.at(-1), 'end')) return null;
701
+ if (xs.length === 3) return [word, ' ', print(xs[1], ctx, n), ' end', commentsAt(comments, 2)]; // `function f end`
702
+ const block = xs.at(-2);
703
+ if (block.kind !== 'block' || xs.length !== 4) return null;
704
+ if (comments.some((k) => k.at !== 3 && k.at !== 2)) return null;
705
+ return [word, ' ', print(xs[1], ctx, n), commentGroup(comments.map((k) => k.c)), blockBody(block, ctx)];
706
+ }
707
+
708
+ function printIf(n, ctx) {
709
+ const out = [];
710
+ let cur = n,
711
+ first = true;
712
+ for (;;) {
713
+ const { xs, comments } = parts(cur);
714
+ if (comments.some((k) => k.at !== 2 && k.at !== 3)) return null;
715
+ const word = first ? 'if' : 'elseif';
716
+ if (!kw(xs[0], word)) return null;
717
+ const cond = xs[1],
718
+ block = xs[2];
719
+ if (!block || block.kind !== 'block') return null;
720
+ out.push(
721
+ word,
722
+ ' ',
723
+ print(cond, ctx, cur),
724
+ commentGroup(comments.map((k) => k.c)),
725
+ blockBody(block, ctx, { endKw: null }),
726
+ );
727
+ let i = 3;
728
+ const next = xs[i];
729
+ if (next && !isLeaf(next) && next.kind === 'elseif') {
730
+ out.push(hardline);
731
+ cur = next;
732
+ first = false;
733
+ continue;
734
+ }
735
+ if (next && kw(next, 'else')) {
736
+ const eb = xs[i + 1];
737
+ if (!eb || eb.kind !== 'block') return null;
738
+ out.push(hardline, 'else', blockBody(eb, ctx, { endKw: null }));
739
+ i += 2;
740
+ }
741
+ if (first) {
742
+ if (!kw(xs[i], 'end') || xs.length !== i + 1) return null;
743
+ } else if (xs.length !== i) return null;
744
+ break;
745
+ }
746
+ return [out, hardline, 'end'];
747
+ }
748
+
749
+ function printFor(n, ctx) {
750
+ const { xs, comments } = parts(n);
751
+ if (!kw(xs[0], 'for') || !kw(xs.at(-1), 'end') || xs.length !== 4 || xs[2].kind !== 'block') return null;
752
+ if (comments.some((k) => k.at !== 2 && k.at !== 3)) return null;
753
+ return ['for ', print(xs[1], ctx, n), commentGroup(comments.map((k) => k.c)), blockBody(xs[2], ctx)];
754
+ }
755
+
756
+ /** `i in x`, `i = x`, `i ∈ x` in iterations; `=` becomes `in` (Runic does the same). */
757
+ function printIn(n, ctx) {
758
+ const { xs, comments } = parts(n);
759
+ if (xs.length !== 3 || comments.length) return null;
760
+ const op = xs[1].text === '=' ? 'in' : xs[1].text;
761
+ return [print(xs[0], ctx, n), ' ', op, ' ', print(xs[2], ctx, n)];
762
+ }
763
+
764
+ function printLet(n, ctx) {
765
+ let { xs, comments } = parts(n);
766
+ if (xs.length === 5 && kw(xs[2], ';') && !comments.some((k) => k.at >= 2)) xs = [xs[0], xs[1], xs[3], xs[4]];
767
+ if (!kw(xs[0], 'let') || !kw(xs.at(-1), 'end') || xs.length !== 4 || comments.length) return null;
768
+ const [, binds, body] = xs;
769
+ if (binds.kind !== 'block' || body.kind !== 'block') return null;
770
+ const bp = parts(binds);
771
+ if (bp.comments.length) return null;
772
+ if (bp.xs.some((x) => isLeaf(x) && isTriviaLeaf(x) && x.text !== ',')) return null;
773
+ const items = bp.xs.filter((x) => !kw(x, ','));
774
+ if (bp.xs.length !== 2 * items.length - 1 && items.length) return null;
775
+ const multi = binds.children.some((c) => isWs(c) && c.text.includes('\n'));
776
+ const docs = items.map((x) => print(x, ctx, binds));
777
+ // the first binding sits on the `let` line, outside the indent (a multi-line string there
778
+ // must line up with that line, not with the continuation indent)
779
+ const head = !items.length
780
+ ? 'let'
781
+ : multi
782
+ ? ['let ', docs[0], indent(docs.slice(1).map((d) => [',', hardline, d]))]
783
+ : ['let ', join(', ', docs)];
784
+ return [head, blockBody(body, ctx)];
785
+ }
786
+
787
+ function printTry(n, ctx) {
788
+ const { xs, comments } = parts(n);
789
+ if (comments.length || !kw(xs[0], 'try') || !kw(xs.at(-1), 'end') || xs[1]?.kind !== 'block') return null;
790
+ const out = ['try', blockBody(xs[1], ctx, { endKw: null })];
791
+ for (let i = 2; i < xs.length - 1; i++) {
792
+ const x = xs[i];
793
+ if (!isLeaf(x) && x.kind === 'catch') {
794
+ const p = parts(x);
795
+ if (
796
+ p.comments.some((k) => k.at !== 2 && k.at !== 3) ||
797
+ !kw(p.xs[0], 'catch') ||
798
+ p.xs.length !== 3 ||
799
+ p.xs[2].kind !== 'block'
800
+ )
801
+ return null;
802
+ const v = p.xs[1];
803
+ const hasVar = !(isLeaf(v) && v.kind === 'Placeholder' && v.text === '');
804
+ out.push(
805
+ hardline,
806
+ 'catch',
807
+ hasVar ? [' ', print(v, ctx, x)] : '',
808
+ commentGroup(p.comments.map((k) => k.c)),
809
+ blockBody(p.xs[2], ctx, { endKw: null }),
810
+ );
811
+ } else if (!isLeaf(x) && x.kind === 'finally') {
812
+ const p = parts(x);
813
+ if (p.comments.length || !kw(p.xs[0], 'finally') || p.xs.length !== 2) return null;
814
+ out.push(hardline, 'finally', blockBody(p.xs[1], ctx, { endKw: null }));
815
+ } else if (!isLeaf(x) && x.kind === 'else') {
816
+ const p = parts(x);
817
+ if (p.comments.length || !kw(p.xs[0], 'else') || p.xs.length !== 2) return null;
818
+ out.push(hardline, 'else', blockBody(p.xs[1], ctx, { endKw: null }));
819
+ } else if (kw(x, 'else') && xs[i + 1]?.kind === 'block') {
820
+ out.push(hardline, 'else', blockBody(xs[i + 1], ctx, { endKw: null }));
821
+ i++;
822
+ } else return null;
823
+ }
824
+ return [out, hardline, 'end'];
825
+ }
826
+
827
+ function printStruct(n, ctx) {
828
+ const { xs, comments } = parts(n);
829
+ let i = 0;
830
+ const head = [];
831
+ if (kw(xs[i], 'mutable')) {
832
+ head.push('mutable ');
833
+ i++;
834
+ }
835
+ if (!kw(xs[i], 'struct')) return null;
836
+ i++;
837
+ if (xs.length !== i + 3 || xs[i + 1].kind !== 'block' || !kw(xs[i + 2], 'end')) return null;
838
+ if (comments.some((k) => k.at !== i + 1 && k.at !== i + 2)) return null;
839
+ const block = xs[i + 1];
840
+ head.push('struct ', print(xs[i], ctx, n), commentGroup(comments.map((k) => k.c)));
841
+ const r = parts(block);
842
+ if (!r.xs.length && !r.comments.length && !hasNewline(ctx.text, xs[i].end, xs[i + 2].start)) return [head, ' end'];
843
+ return [head, blockBody(block, ctx)];
844
+ }
845
+
846
+ function printModule(n, ctx) {
847
+ const { xs, comments } = parts(n);
848
+ const word = xs[0]?.text;
849
+ if (
850
+ !(kw(xs[0], 'module') || kw(xs[0], 'baremodule')) ||
851
+ !kw(xs.at(-1), 'end') ||
852
+ xs.length !== 4 ||
853
+ xs[2].kind !== 'block'
854
+ )
855
+ return null;
856
+ if (comments.some((k) => k.at !== 2 && k.at !== 3)) return null;
857
+ // Module bodies are not indented (Runic, BlueStyle); one blank line after the header and
858
+ // before `end` is kept when written.
859
+ return [
860
+ word,
861
+ ' ',
862
+ print(xs[1], ctx, n),
863
+ commentGroup(comments.map((k) => k.c)),
864
+ blockBody(xs[2], ctx, { keepEdgeBlank: true, noIndent: true }),
865
+ ];
866
+ }
867
+
868
+ function printDo(n, ctx) {
869
+ const { xs, comments } = parts(n);
870
+ if (!kw(xs[0], 'do') || !kw(xs.at(-1), 'end') || comments.some((k) => k.at > xs.length - 2)) return null;
871
+ const block = xs.at(-2);
872
+ if (!block || block.kind !== 'block') return null;
873
+ const args = xs.slice(1, -2);
874
+ if (args.length > 1) return null;
875
+ const a =
876
+ args.length && !(args[0].kind === 'tuple' && parts(args[0]).xs.length === 0) ? [' ', print(args[0], ctx, n)] : '';
877
+ return ['do', a, commentGroup(comments.map((k) => k.c)), blockBody(block, ctx)];
878
+ }
879
+
880
+ /** `"""doc""" f`: the docstring, then the documented expression on the next line (or same line as written). */
881
+ function printDoc(n, ctx) {
882
+ const { xs, comments } = parts(n);
883
+ if (xs.length !== 2 || comments.length) return null;
884
+ const sameLine = !hasNewline(ctx.text, xs[0].end, xs[1].start);
885
+ return [print(xs[0], ctx, n), sameLine ? ' ' : hardline, print(xs[1], ctx, n)];
886
+ }
887
+
888
+ function printKeywordPrefix(n, ctx) {
889
+ const { xs, comments } = parts(n);
890
+ if (comments.length || !kw(xs[0], n.kind)) return null;
891
+ if (xs.length === 1) return n.kind;
892
+ if (xs.length !== 2) return null;
893
+ return [n.kind, ' ', print(xs[1], ctx, n)];
894
+ }
895
+
896
+ // ─── Macros ────────────────────────────────────────────────────────────
897
+
898
+ function printMacrocall(n, ctx) {
899
+ if (isStringMacro(n)) return printVerbatim(n, ctx);
900
+ const { xs, comments } = parts(n);
901
+ if (!xs.length) return null;
902
+ const name = xs[0];
903
+ if (flag(n, 0x100) || (xs[1] && kw(xs[1], '('))) {
904
+ // `@m(a, b)` (with an optional do block)
905
+ if (xs[1] && kw(xs[1], '(')) return printListAfter(n, ctx, 1, print(name, ctx, n));
906
+ return null;
907
+ }
908
+ if (comments.length) return null;
909
+ // `@m a b`: arguments separated by single spaces; no optional line breaks at this level.
910
+ const flat = sub(ctx, { flat: true });
911
+ const out = [print(name, ctx, n)];
912
+ let prev = name;
913
+ for (const a of xs.slice(1)) {
914
+ if (isLeaf(a) && isTriviaLeaf(a)) return null;
915
+ // `@NamedTuple{a::Int}` / `@m[1]`: no space where none was written
916
+ out.push(hasWsBetween(n, prev, a) ? ' ' : '', print(a, flat, n));
917
+ prev = a;
918
+ }
919
+ return out;
920
+ }
921
+
922
+ // ─── Lists ─────────────────────────────────────────────────────────────
923
+
924
+ /**
925
+ * Elements between an opening bracket at xs-index `openIdx` and its closer, with commas,
926
+ * an optional `parameters` child (`; k=1`), comments and a trailing `do` block.
927
+ */
928
+ function collectList(n, openIdx) {
929
+ const kids = n.children;
930
+ const openTok = parts(n).xs[openIdx];
931
+ let i = kids.indexOf(openTok) + 1;
932
+ const open = openTok.text,
933
+ close = { '(': ')', '[': ']', '{': '}' }[open];
934
+ const elems = [];
935
+ let params = null,
936
+ closeTok = null,
937
+ pendingLead = [],
938
+ lastSep = 'open',
939
+ nlSince = false;
940
+ for (; i < kids.length; i++) {
941
+ const c = kids[i];
942
+ if (isWs(c)) {
943
+ if (c.text.includes('\n')) nlSince = true;
944
+ continue;
945
+ }
946
+ if (isComment(c)) {
947
+ const prevElem = elems.at(-1);
948
+ if (!nlSince && prevElem && (lastSep === ',' || lastSep === 'elem')) prevElem.trailing.push(c);
949
+ else if (params && !nlSince && params.elems.length) params.elems.at(-1).trailing.push(c);
950
+ else pendingLead.push(c);
951
+ continue;
952
+ }
953
+ nlSince = false;
954
+ if (kw(c, close)) {
955
+ closeTok = c;
956
+ i++;
957
+ break;
958
+ }
959
+ if (kw(c, ',')) {
960
+ if (lastSep === ',' || lastSep === 'open') return null;
961
+ lastSep = ',';
962
+ continue;
963
+ }
964
+ if (!isLeaf(c) && c.kind === 'parameters') {
965
+ if (params) return null;
966
+ params = collectParams(c);
967
+ if (!params) return null;
968
+ if (pendingLead.length) {
969
+ // comments before `;`: after the last positional element, else before the first keyword
970
+ if (elems.length) elems.at(-1).trailing.push(...pendingLead);
971
+ else if (params.elems.length) params.elems[0].lead.unshift(...pendingLead);
972
+ else params.semiTrail.unshift(...pendingLead);
973
+ pendingLead = [];
974
+ }
975
+ lastSep = 'params';
976
+ continue;
977
+ }
978
+ if (isLeaf(c) && isTriviaLeaf(c)) return null;
979
+ if (params || lastSep === 'elem') return null;
980
+ elems.push({ n: c, lead: pendingLead, trailing: [] });
981
+ pendingLead = [];
982
+ lastSep = 'elem';
983
+ }
984
+ if (!closeTok) return null;
985
+ const trailingComma = lastSep === ',';
986
+ const after = kids.slice(i).filter((c) => !isWs(c));
987
+ return { elems, params, open, close, trailingComma, dangling: pendingLead, after };
988
+ }
989
+
990
+ function collectParams(p) {
991
+ const kids = p.children;
992
+ const elems = [];
993
+ let lead = [],
994
+ nlSince = false,
995
+ seenSemi = false;
996
+ const semiTrail = [];
997
+ for (const c of kids) {
998
+ if (isWs(c)) {
999
+ if (c.text.includes('\n')) nlSince = true;
1000
+ continue;
1001
+ }
1002
+ if (isComment(c)) {
1003
+ if (!nlSince && elems.length) elems.at(-1).trailing.push(c);
1004
+ else if (!nlSince && seenSemi && !elems.length && !lead.length) semiTrail.push(c);
1005
+ else lead.push(c);
1006
+ continue;
1007
+ }
1008
+ nlSince = false;
1009
+ if (kw(c, ';')) {
1010
+ if (seenSemi) return null;
1011
+ seenSemi = true;
1012
+ continue;
1013
+ }
1014
+ if (kw(c, ',')) continue;
1015
+ if (isLeaf(c) && isTriviaLeaf(c)) return null;
1016
+ elems.push({ n: c, lead, trailing: [] });
1017
+ lead = [];
1018
+ }
1019
+ if (!seenSemi) return null;
1020
+ if (lead.length) {
1021
+ if (!elems.length) return null;
1022
+ elems.at(-1).trailing.push(...lead);
1023
+ }
1024
+ return { elems, lead: [], semiTrail };
1025
+ }
1026
+
1027
+ function printElem(e, ctx, parent) {
1028
+ const lead = e.lead.map((c) => [printOwnLineComment(c), hardline]);
1029
+ const trail = e.trailing.map((c) => trailingComment({ c, gap: gapBefore(TEXT, c) }));
1030
+ return { doc: [lead, print(e.n, ctx, parent)], trail };
1031
+ }
1032
+
1033
+ /**
1034
+ * Print `open elems ; params close` after `prefix`, breaking one element per line with a
1035
+ * trailing comma when it doesn't fit.
1036
+ */
1037
+ function printListBody(L, n, ctx, prefix, { noTrailingComma = false } = {}) {
1038
+ const inner = sub(ctx, { flat: false, compact: false });
1039
+ const elems = L.elems.map((e) => printElem(e, inner, n));
1040
+ const params = L.params ? L.params.elems.map((e) => printElem(e, inner, n)) : null;
1041
+ const hasComments =
1042
+ L.elems.some((e) => e.lead.length || e.trailing.length) ||
1043
+ (L.params && (L.params.semiTrail.length || L.params.elems.some((e) => e.lead.length || e.trailing.length))) ||
1044
+ L.dangling.length;
1045
+ const items = [];
1046
+ elems.forEach((e, i) => {
1047
+ const last = i === elems.length - 1;
1048
+ // the last positional element's comments go after the `;` (where a reparse puts them)
1049
+ items.push([e.doc, last ? '' : ',', last && params ? '' : e.trail, last ? '' : line]);
1050
+ });
1051
+ const semiTrail = params
1052
+ ? [
1053
+ elems.length ? elems.at(-1).trail : '',
1054
+ L.params.semiTrail.map((c) => trailingComment({ c, gap: gapBefore(TEXT, c) })),
1055
+ ]
1056
+ : '';
1057
+ const single = elems.length === 1 && !params;
1058
+ const lastN = params ? L.params.elems.at(-1)?.n : L.elems.at(-1)?.n;
1059
+ const lastIsGenerator =
1060
+ (lastN && ['generator', 'flatten'].includes(lastN.kind) && !params) || (lastN && endsOpen(lastN));
1061
+ let tail = '';
1062
+ // a one-element tuple's comma is part of its meaning (`(a,)`, `((x, y),) -> …`): as written
1063
+ if (n.kind === 'tuple' && single) tail = L.trailingComma ? ',' : '';
1064
+ else if (!noTrailingComma && !lastIsGenerator && (params ? params.length : elems.length)) tail = ifBreak(',');
1065
+ const content = [];
1066
+ if (elems.length) content.push(items);
1067
+ if (params) {
1068
+ content.push(n.kind === 'tuple' && elems.length === 1 ? ',;' : ';', semiTrail, params.length ? line : '');
1069
+ params.forEach((e, i) => {
1070
+ const last = i === params.length - 1;
1071
+ content.push(e.doc, last ? '' : ',', e.trail, last ? '' : line);
1072
+ });
1073
+ }
1074
+ const hugKind =
1075
+ !hasComments &&
1076
+ !params &&
1077
+ L.elems.length &&
1078
+ !L.elems.at(-1).lead.length &&
1079
+ !L.dangling.length &&
1080
+ huggable(L.elems.at(-1).n, ctx, elems.at(-1).doc);
1081
+ if (single && hugKind) {
1082
+ const broken = group([L.open, indent([softline, elems[0].doc, tail]), softline, L.close]);
1083
+ return [
1084
+ prefix,
1085
+ hugChoice(null, L.open, elems[0].doc, [tail === ',' ? ',' : '', L.close], broken, hugKind),
1086
+ printAfter(L, n, ctx),
1087
+ ];
1088
+ }
1089
+ if (single && L.elems[0] && !L.elems[0].lead.length) {
1090
+ // the one element's own trailing comment goes after the (optional) comma
1091
+ const e = elems[0];
1092
+ content.length = 0;
1093
+ content.push(e.doc);
1094
+ const dangling = L.dangling.map((c) => [hardline, printOwnLineComment(c)]);
1095
+ return [
1096
+ prefix,
1097
+ group([L.open, indent([softline, content, tail, e.trail, dangling]), softline, L.close]),
1098
+ printAfter(L, n, ctx),
1099
+ ];
1100
+ }
1101
+ if (!elems.length && !params) {
1102
+ if (!L.dangling.length) return [prefix, L.open, L.close, printAfter(L, n, ctx)];
1103
+ return [
1104
+ prefix,
1105
+ L.open,
1106
+ indent(L.dangling.map((c) => [hardline, printOwnLineComment(c)])),
1107
+ hardline,
1108
+ L.close,
1109
+ printAfter(L, n, ctx),
1110
+ ];
1111
+ }
1112
+ // A last parameter's trailing comment comes after the trailing comma.
1113
+ const dangling = L.dangling.map((c) => [hardline, printOwnLineComment(c)]);
1114
+ const doc = group([L.open, indent([softline, content, tail, dangling]), softline, L.close]);
1115
+ if (hugKind && elems.length > 1 && !elems.slice(0, -1).some((e) => docUtils.willBreak(e.doc))) {
1116
+ // `f(a, b, [` … `])`: the last argument opens on the first line and closes the call
1117
+ const head = [
1118
+ L.open,
1119
+ join(
1120
+ ', ',
1121
+ elems.slice(0, -1).map((e) => e.doc),
1122
+ ),
1123
+ ', ',
1124
+ ];
1125
+ return [prefix, hugChoice(null, head, elems.at(-1).doc, L.close, doc, hugKind), printAfter(L, n, ctx)];
1126
+ }
1127
+ return [prefix, hasComments ? [breakParent, doc] : doc, printAfter(L, n, ctx)];
1128
+ }
1129
+
1130
+ const BRACKET_HUG = new Set(['vect', 'braces', 'comprehension', 'typed_comprehension']);
1131
+ const BLOCK_HUG = new Set([
1132
+ 'vcat',
1133
+ 'hcat',
1134
+ 'ncat',
1135
+ 'typed_vcat',
1136
+ 'typed_hcat',
1137
+ 'typed_ncat',
1138
+ 'string',
1139
+ 'cmdstring',
1140
+ 'function',
1141
+ 'macrocall',
1142
+ 'do',
1143
+ 'let',
1144
+ 'block',
1145
+ 'quote',
1146
+ 'call',
1147
+ 'dotcall',
1148
+ 'ref',
1149
+ 'curly',
1150
+ 'tuple',
1151
+ 'parens',
1152
+ ]);
1153
+ /**
1154
+ * May this last list element (or right operand) open on the first line and close the
1155
+ * expression (`f(a, [` … `])`)? Brackets always may (deterministic, as Prettier does for
1156
+ * arrays and objects); other kinds only when their printed doc has forced line breaks
1157
+ * (blocks, multi-line strings, kept-as-written regions), which then stay at a stable
1158
+ * indentation.
1159
+ */
1160
+ function huggable(n, ctx, doc = null) {
1161
+ if (!ctx.protect.has(n) && (BRACKET_HUG.has(n.kind) || (n.kind === 'tuple' && kw(parts(n).xs[0] ?? n, '('))))
1162
+ return 'bracket';
1163
+ if (doc && docUtils.willBreak(doc) && (ctx.protect.has(n) || BLOCK_HUG.has(n.kind) || isLeaf(n))) return 'forced';
1164
+ return false;
1165
+ }
1166
+
1167
+ /** A copy of `doc` whose first group is broken (for "hug, but break the last element" states). */
1168
+ function breakFirstGroup(doc) {
1169
+ let done = false;
1170
+ const walk = (d) => {
1171
+ if (done || d === null || typeof d !== 'object') return d;
1172
+ if (Array.isArray(d)) return d.map(walk);
1173
+ if (d.type === 'group') {
1174
+ done = true;
1175
+ return { ...d, break: true };
1176
+ }
1177
+ if (d.contents !== undefined) return { ...d, contents: walk(d.contents) };
1178
+ if (d.parts !== undefined) return { ...d, parts: walk(d.parts) };
1179
+ return d;
1180
+ };
1181
+ return walk(doc);
1182
+ }
1183
+
1184
+ /** Layout choices for "prefix + last" where last may hug: flat, hugged with last broken, `broken`. */
1185
+ function hugChoice(flatDoc, huggedPrefix, lastDoc, suffix, broken, kind) {
1186
+ const states =
1187
+ kind === 'bracket'
1188
+ ? [[huggedPrefix, lastDoc, suffix], [huggedPrefix, breakFirstGroup(lastDoc), suffix], broken]
1189
+ : [[huggedPrefix, lastDoc, suffix], broken];
1190
+ // conditionalGroup doesn't pass forced breaks to enclosing groups; do it here so they
1191
+ // never keep a multi-line part inside a flat `indent` (which would shift it each run).
1192
+ return [builders.conditionalGroup(states), kind === 'forced' ? breakParent : ''];
1193
+ }
1194
+
1195
+ const OPEN_ENDED = new Set(['return', 'continue', 'break', 'const', 'global', 'local']);
1196
+ /** Does the expression end in a form that a following `,` would extend (`@m a`, `return x`)? */
1197
+ function endsOpen(n) {
1198
+ for (;;) {
1199
+ if (isLeaf(n)) return OPEN_ENDED.has(n.text) && n.kind === n.text;
1200
+ if (OPEN_ENDED.has(n.kind)) return true;
1201
+ if (n.kind === 'macrocall' && !hasParen(n) && !isStringMacro(n)) return true;
1202
+ const last = n.children.filter((c) => !isWs(c) && !isComment(c)).at(-1);
1203
+ if (!last || (isLeaf(last) && isTriviaLeaf(last))) return false;
1204
+ n = last;
1205
+ }
1206
+ }
1207
+
1208
+ function printAfter(L, n, ctx) {
1209
+ if (!L.after.length) return '';
1210
+ if (L.after.length === 1 && L.after[0].kind === 'do') return [' ', print(L.after[0], ctx, n)];
1211
+ return null;
1212
+ }
1213
+
1214
+ function printListAfter(n, ctx, openIdx, prefix, opts) {
1215
+ const L = collectList(n, openIdx);
1216
+ if (!L) return null;
1217
+ const d = printListBody(L, n, ctx, prefix, opts);
1218
+ if (d.at(-1) === null) return null;
1219
+ return d;
1220
+ }
1221
+
1222
+ function printBracketList(n, ctx, open) {
1223
+ const { xs } = parts(n);
1224
+ if (!kw(xs[0], open)) return null;
1225
+ return printListAfter(n, ctx, 0, '');
1226
+ }
1227
+
1228
+ function printCalleeList(n, ctx) {
1229
+ const { xs } = parts(n);
1230
+ if (xs.length < 3 || !(kw(xs[1], '{') || kw(xs[1], '['))) return null;
1231
+ if (hasWsBetween(n, xs[0], xs[1])) return null; // `A {T}`: keep as written
1232
+ return printListAfter(n, ctx, 1, print(xs[0], ctx, n));
1233
+ }
1234
+
1235
+ function hasWsBetween(n, a, b) {
1236
+ const i = n.children.indexOf(a),
1237
+ j = n.children.indexOf(b);
1238
+ return n.children.slice(i + 1, j).some((c) => isWs(c) || isComment(c));
1239
+ }
1240
+
1241
+ function printTuple(n, ctx) {
1242
+ const { xs, comments } = parts(n);
1243
+ if (xs.length && kw(xs[0], '(')) return printListAfter(n, ctx, 0, '');
1244
+ // bare tuple `a, b` (assignment sides, `return a, b`, `for (a, b) in …` handled above)
1245
+ if (comments.length) return null;
1246
+ const items = [];
1247
+ for (const x of xs) {
1248
+ if (kw(x, ',')) continue;
1249
+ if (isLeaf(x) && isTriviaLeaf(x)) return null;
1250
+ items.push(print(x, ctx, n));
1251
+ }
1252
+ const trailing = xs.length && kw(xs.at(-1), ',');
1253
+ if (!items.length) return null;
1254
+ return [join(', ', items), trailing ? ',' : ''];
1255
+ }
1256
+
1257
+ function printParens(n, ctx) {
1258
+ const { xs, comments } = parts(n);
1259
+ if (xs.length !== 3 || !kw(xs[0], '(') || !kw(xs[2], ')') || comments.length) return null;
1260
+ if (n.children.some((c) => isWs(c) && c.text.includes('\n'))) return null;
1261
+ return ['(', print(xs[1], sub(ctx, { flat: false, compact: false }), n), ')'];
1262
+ }
1263
+
1264
+ // ─── Calls and operators ───────────────────────────────────────────────
1265
+
1266
+ // Infix operators printed without spaces (Runic: `:` `^`; `::` and `.` are node kinds).
1267
+ const TIGHT_OPS = new Set([':', '^', '.^']);
1268
+ const WORD_OPS = new Set(['in', 'isa', 'where']);
1269
+ const OP_CHARS = /^[+\-*/\\^%<>=!~&|:$.'÷⊻∘√∛∜⋅×∈∉∋∌⊆⊇⊂⊃≤≥≠≡≢≈≉⊗⊕⊖⊙⊘→←↔⇒∪∩]/u;
1270
+
1271
+ function printCall(n, ctx) {
1272
+ const { xs, comments } = parts(n);
1273
+ if (isInfixCall(n)) return printInfix(n, xs, comments, ctx);
1274
+ if (isPrefixOpCall(n)) {
1275
+ if (comments.length) return null;
1276
+ let op = xs[0],
1277
+ i = 1,
1278
+ opText = op.text;
1279
+ if (n.kind === 'dotcall' && kw(xs[0], '.')) {
1280
+ opText = '.' + xs[1].text;
1281
+ i = 2;
1282
+ }
1283
+ if (xs.length !== i + 1 || !isLeaf(op)) return null;
1284
+ const operand = xs[i];
1285
+ const spaced = hasWsBetween(n, xs[i - 1], operand);
1286
+ // Keep `- 2` (a call; `-2` is a literal) and `- (x)` (≠ `-(x)`) as written.
1287
+ const keep =
1288
+ spaced &&
1289
+ (isNumber(operand) ||
1290
+ /^[0-9.(]/.test(ctx.text[operand.start]) ||
1291
+ operand.kind === 'parens' ||
1292
+ operand.kind === 'tuple' ||
1293
+ OP_CHARS.test(ctx.text[operand.start]));
1294
+ return [opText, keep ? ' ' : '', print(operand, ctx, n)];
1295
+ }
1296
+ if (isPostfixOpCall(n)) return null;
1297
+ // f(args) / f.(args)
1298
+ if (xs.length < 3) return null;
1299
+ let open = 1,
1300
+ prefix;
1301
+ if (n.kind === 'dotcall') {
1302
+ if (!kw(xs[1], '.') || !kw(xs[2], '(')) return null;
1303
+ if (hasWsBetween(n, xs[0], xs[1]) || hasWsBetween(n, xs[1], xs[2])) return null;
1304
+ open = 2;
1305
+ prefix = [print(xs[0], ctx, n), '.'];
1306
+ } else {
1307
+ if (!kw(xs[1], '(')) return null;
1308
+ if (hasWsBetween(n, xs[0], xs[1])) return null;
1309
+ prefix = print(xs[0], ctx, n);
1310
+ }
1311
+ return printListAfter(n, ctx, open, prefix);
1312
+ }
1313
+
1314
+ function printInfix(n, xs, comments, ctx) {
1315
+ // operand (op operand)+ ; in a dotcall the op is `.` followed by the operator
1316
+ const operands = [],
1317
+ ops = [];
1318
+ let i = 0;
1319
+ operands.push(xs[i++]);
1320
+ while (i < xs.length) {
1321
+ let op = xs[i];
1322
+ if (!isLeaf(op)) return null;
1323
+ let text = op.text;
1324
+ const opAt = i;
1325
+ if (n.kind === 'dotcall' && kw(op, '.')) {
1326
+ if (!isLeaf(xs[i + 1])) return null;
1327
+ text = '.' + xs[i + 1].text;
1328
+ i++;
1329
+ }
1330
+ i++;
1331
+ if (i >= xs.length) return null;
1332
+ ops.push({ text, at: i, opAt });
1333
+ operands.push(xs[i++]);
1334
+ }
1335
+ if (!ops.length) return null;
1336
+ const opText = ops[0].text;
1337
+ if (n.kind !== 'comparison' && ops.some((o) => o.text !== opText)) return null;
1338
+ if (n.kind === 'comparison' && ops.some((o) => TIGHT_OPS.has(o.text) || (WORD_OPS.has(o.text) && false))) return null;
1339
+ const isRange = opText === ':';
1340
+ const tight = TIGHT_OPS.has(opText) || (ctx.compact && !WORD_OPS.has(opText) && !/^\p{L}/u.test(opText));
1341
+ const inner = isRange ? sub(ctx, { compact: true }) : ctx;
1342
+ const docs = operands.map((o) => print(o, inner, n));
1343
+ // Comments inside an infix expression: keep each one at the end of its line.
1344
+ // comments before an operator (or between `.` and it) and right after it: at the operator
1345
+ const cm = (lo, hi) => commentGroup(comments.filter((c) => c.at > lo && c.at <= hi).map((c) => c.c));
1346
+ if (comments.some((c) => c.at > ops.at(-1).at)) return null;
1347
+ if (tight) {
1348
+ const out = [docs[0]];
1349
+ ops.forEach((o, k) => {
1350
+ const l = operands[k],
1351
+ r = operands[k + 1];
1352
+ // spaces only where gluing would make a different token (`a: :b` ≠ `a::b`)
1353
+ const lc = ctx.text[l.end - 1],
1354
+ rc = ctx.text[r.start];
1355
+ const needSpace =
1356
+ opText === ':' || opText === '^' || opText === '.^'
1357
+ ? /[:=<>.]/.test(rc) || /[:.]/.test(lc) || (o.text.startsWith('.') && /[0-9]/.test(lc))
1358
+ : OP_CHARS.test(rc) || /[+\-*/\\^%<>=!~&|:.]$/u.test(lc);
1359
+ const sp = needSpace ? ' ' : '';
1360
+ out.push(sp, o.text, cm(o.opAt - 1, o.at), sp, docs[k + 1]);
1361
+ });
1362
+ return out;
1363
+ }
1364
+ // spaced, breakable after the operator
1365
+ const lastOp = operands.at(-1);
1366
+ // Never indent a part that will break without a line break before it (keeps verbatim
1367
+ // regions and multi-line strings at a stable indentation).
1368
+ const hugKind = ops.length === 1 && !comments.length && huggable(lastOp, ctx, docs.at(-1));
1369
+ const forced = docs.slice(1).some((d) => docUtils.willBreak(d));
1370
+ const hasCm = (o) => comments.some((c) => c.at > o.opAt - 1 && c.at <= o.at);
1371
+ // a line comment after an operator needs the line break right there (legal after a binary operator)
1372
+ const rest = ops.map((o, k) => [
1373
+ ' ',
1374
+ o.text,
1375
+ cm(o.opAt - 1, o.at),
1376
+ hasCm(o) ? hardline : forced || ctx.flat ? ' ' : line,
1377
+ docs[k + 1],
1378
+ ]);
1379
+ if (ctx.flat || forced) return [docs[0], comments.length ? indent(rest) : rest];
1380
+ // a multi-line first operand (`"""...""" |> f |> g`): the rest may stay on its last line
1381
+ if (docUtils.willBreak(docs[0])) return [docs[0], group(indent(rest))];
1382
+ if (hugKind === 'bracket') {
1383
+ // `x in (` … `)` rather than breaking after `in`
1384
+ const broken = group([docs[0], indent(rest)]);
1385
+ return hugChoice(null, [docs[0], ' ', ops[0].text, ' '], docs[1], '', broken, hugKind);
1386
+ }
1387
+ return group([docs[0], indent(rest)]);
1388
+ }
1389
+
1390
+ /** `a && b && c`, `a || b`: like spaced infix, flattening same-operator chains. */
1391
+ function printChain(n, ctx) {
1392
+ const op = n.kind;
1393
+ const operands = [];
1394
+ const collect = (m) => {
1395
+ const { xs, comments } = parts(m);
1396
+ if (comments.length || xs.length !== 3 || !kw(xs[1], op)) return false;
1397
+ for (const x of [xs[0], xs[2]]) {
1398
+ if (!isLeaf(x) && x.kind === op && !ctx.protect.has(x)) {
1399
+ if (!collect(x)) return false;
1400
+ } else operands.push({ x, parent: m });
1401
+ }
1402
+ return true;
1403
+ };
1404
+ if (!collect(n)) return null;
1405
+ const docs = operands.map((o) => print(o.x, ctx, o.parent));
1406
+ if (ctx.flat || docs.slice(1).some((d) => docUtils.willBreak(d)))
1407
+ return [docs[0], docs.slice(1).map((d) => [' ', op, ' ', d])];
1408
+ const rest = docs.slice(1).map((d) => [' ', op, line, d]);
1409
+ return group([docs[0], indent(rest)]);
1410
+ }
1411
+
1412
+ function printSpacedBinary(n, ctx, op) {
1413
+ const { xs, comments } = parts(n);
1414
+ if (xs.length !== 3 || comments.length || !kw(xs[1], op)) return null;
1415
+ return [print(xs[0], ctx, n), ' ', op, ' ', print(xs[2], ctx, n)];
1416
+ }
1417
+
1418
+ function printWhere(n, ctx) {
1419
+ const { xs, comments } = parts(n);
1420
+ if (comments.length || xs.length < 3 || !kw(xs[1], 'where')) return null;
1421
+ const rest = xs.slice(2);
1422
+ if (rest.length !== 1) return null;
1423
+ return [print(xs[0], ctx, n), ' where ', print(rest[0], ctx, n)];
1424
+ }
1425
+
1426
+ function printTernary(n, ctx) {
1427
+ const { xs, comments } = parts(n);
1428
+ if (comments.length || xs.length !== 5 || !kw(xs[1], '?') || !kw(xs[3], ':')) return null;
1429
+ const [c, , a, , b] = xs;
1430
+ const [dc, da, db] = [print(c, ctx, n), print(a, ctx, n), print(b, ctx, n)];
1431
+ if (ctx.flat || [da, db].some((d) => docUtils.willBreak(d))) return [dc, ' ? ', da, ' : ', db];
1432
+ return group([dc, indent([' ?', line, da, ' :', line, db])]);
1433
+ }
1434
+
1435
+ /** `x::T`, `a.b`, `x...`: no spaces (as Runic). */
1436
+ function printTight(n, ctx) {
1437
+ const { xs, comments } = parts(n);
1438
+ if (comments.length) return null;
1439
+ const out = [];
1440
+ for (const x of xs) out.push(isLeaf(x) && isTriviaLeaf(x) ? x.text : print(x, ctx, n));
1441
+ // keep a space where removing it would glue tokens (`a. b` is unusual; `x :: T` is fine)
1442
+ return out;
1443
+ }
1444
+
1445
+ function printSubtype(n, ctx) {
1446
+ const { xs, comments } = parts(n);
1447
+ if (comments.length) return null;
1448
+ if (xs.length === 2) return [xs[0].text, print(xs[1], ctx, n)]; // `<:T`
1449
+ if (xs.length !== 3) return null;
1450
+ const inBraces = ctx.parent && (ctx.parent.kind === 'curly' || ctx.parent.kind === 'braces');
1451
+ const sp = inBraces ? '' : ' ';
1452
+ return [print(xs[0], ctx, n), sp, xs[1].text, sp, print(xs[2], ctx, n)];
1453
+ }
1454
+
1455
+ const KWARG_PARENTS = new Set([
1456
+ 'call',
1457
+ 'dotcall',
1458
+ 'parameters',
1459
+ 'tuple',
1460
+ 'macrocall',
1461
+ 'curly',
1462
+ 'ref',
1463
+ 'vect',
1464
+ 'braces',
1465
+ ]);
1466
+
1467
+ function printAssignment(n, ctx) {
1468
+ const { xs, comments } = parts(n);
1469
+ if (comments.length) return null;
1470
+ // lhs, op tokens…, rhs
1471
+ const lhs = xs[0],
1472
+ rhs = xs.at(-1);
1473
+ if (xs.length < 3) return null;
1474
+ const opToks = xs.slice(1, -1);
1475
+ if (opToks.some((t) => !isLeaf(t))) return null;
1476
+ const op = opToks.map((t) => t.text).join('');
1477
+ const lhsDoc = print(lhs, ctx, n);
1478
+ if (ctx.parent && ctx.parent.kind === 'macrocall' && !hasParen(ctx.parent)) {
1479
+ // `@m a = b` / `@kw x=1`: keep the spacing as written
1480
+ const sp = hasWsBetween(n, lhs, opToks[0]) || hasWsBetween(n, opToks.at(-1), rhs) ? ' ' : '';
1481
+ return [lhsDoc, sp, op, sp, print(rhs, ctx, n)];
1482
+ }
1483
+ if (op === '=' && ctx.parent && KWARG_PARENTS.has(ctx.parent.kind)) {
1484
+ const glue =
1485
+ /[!<>=:~+\-*/\\^%&|.$']$/.test(ctx.text.slice(lhs.start, lhs.end)) || /^[=>:]/.test(ctx.text[rhs.start]);
1486
+ return glue ? [lhsDoc, ' = ', print(rhs, ctx, n)] : [lhsDoc, '=', print(rhs, ctx, n)];
1487
+ }
1488
+ return assignmentLayout(lhsDoc, op, rhs, ctx, n);
1489
+ }
1490
+
1491
+ const hasParen = (m) => parts(m).xs.some((x) => kw(x, '('));
1492
+
1493
+ const BLOCKISH = new Set([
1494
+ 'function',
1495
+ 'if',
1496
+ 'for',
1497
+ 'while',
1498
+ 'let',
1499
+ 'try',
1500
+ 'struct',
1501
+ 'module',
1502
+ 'macro',
1503
+ 'block',
1504
+ 'quote',
1505
+ 'do',
1506
+ 'string',
1507
+ 'cmdstring',
1508
+ 'vcat',
1509
+ 'hcat',
1510
+ 'ncat',
1511
+ 'typed_vcat',
1512
+ 'typed_hcat',
1513
+ 'typed_ncat',
1514
+ 'comprehension',
1515
+ 'typed_comprehension',
1516
+ 'generator',
1517
+ ]);
1518
+
1519
+ function assignmentLayout(lhsDoc, op, rhs, ctx, parent) {
1520
+ const rhsDoc = print(rhs, ctx, parent);
1521
+ if (
1522
+ ctx.flat ||
1523
+ BLOCKISH.has(rhs.kind) ||
1524
+ isStringMacro(rhs) ||
1525
+ rhs.kind === 'macrocall' ||
1526
+ docUtils.willBreak(rhsDoc) ||
1527
+ (rhs.kind === 'call' && !isInfixCall(rhs) && !isPrefixOpCall(rhs))
1528
+ ) {
1529
+ return [lhsDoc, ' ', op, ' ', rhsDoc];
1530
+ }
1531
+ const id = Symbol('assign');
1532
+ return group([lhsDoc, ' ', op, group(indent(line), { id }), indentIfBreak(rhsDoc, { groupId: id })]);
1533
+ }
1534
+
1535
+ // ─── Matrices ──────────────────────────────────────────────────────────
1536
+
1537
+ /** Single-line matrix literals: elements separated by one space. Multi-line ones verbatim. */
1538
+ function printMatrix(n, ctx) {
1539
+ if (hasNewline(ctx.text, n.start, n.end)) return printVerbatim(n, ctx);
1540
+ const flat = sub(ctx, { flat: true });
1541
+ const out = [];
1542
+ let semi = false;
1543
+ const walk = (m) => {
1544
+ let ws = false,
1545
+ first = true;
1546
+ for (const c of m.children) {
1547
+ if (isWs(c)) {
1548
+ ws = true;
1549
+ continue;
1550
+ }
1551
+ if (isComment(c)) return false;
1552
+ if (!isLeaf(c) && (c.kind === 'row' || c.kind === 'nrow')) {
1553
+ if (!first && (ws || semi)) out.push(' ');
1554
+ semi = false;
1555
+ if (walk(c) === false) return false;
1556
+ ws = false;
1557
+ first = false;
1558
+ continue;
1559
+ }
1560
+ if (isLeaf(c) && isTriviaLeaf(c)) {
1561
+ if (/^;+$/.test(c.text)) {
1562
+ out.push(c.text);
1563
+ ws = false;
1564
+ first = false;
1565
+ semi = true;
1566
+ continue;
1567
+ }
1568
+ if (!first && (ws || semi) && !CLOSERS.has(c.text)) out.push(' ');
1569
+ out.push(c.text);
1570
+ ws = false;
1571
+ semi = false;
1572
+ first = OPENERS.has(c.text);
1573
+ continue;
1574
+ }
1575
+ if (!first && (ws || semi)) out.push(' ');
1576
+ out.push(print(c, flat, m));
1577
+ ws = false;
1578
+ first = false;
1579
+ semi = false;
1580
+ }
1581
+ return true;
1582
+ };
1583
+ if (walk(n) === false) return printVerbatim(n, ctx);
1584
+ // a matrix written on one line stays on one line (a line break would add a row)
1585
+ return docUtils.removeLines(out);
1586
+ }
1587
+
1588
+ // ─── using / import / export, generators ───────────────────────────────
1589
+
1590
+ /** `export a, b, …` / `using A: b, c`: items filled to the line width, continuation indented. */
1591
+ function printImportList(n, ctx) {
1592
+ let { xs, comments } = parts(n);
1593
+ if (comments.length) return null;
1594
+ let kwTok = xs[0],
1595
+ head = null,
1596
+ node = n;
1597
+ if (xs.length === 1 && !isLeaf(xs[0]) && xs[0].kind === ':') {
1598
+ node = xs[0];
1599
+ const p = parts(node);
1600
+ if (p.comments.length) return null;
1601
+ xs = p.xs;
1602
+ kwTok = xs[0];
1603
+ if (!kw(xs[2], ':')) return null;
1604
+ head = xs[1];
1605
+ xs = [xs[0], ...xs.slice(3)];
1606
+ }
1607
+ if (!kw(kwTok, n.kind)) return null;
1608
+ const items = [];
1609
+ for (let i = 1; i < xs.length; i++) {
1610
+ if (i % 2 === 0) {
1611
+ if (!kw(xs[i], ',')) return null;
1612
+ continue;
1613
+ }
1614
+ if (isLeaf(xs[i]) && isTriviaLeaf(xs[i])) return null;
1615
+ items.push(print(xs[i], ctx, node));
1616
+ }
1617
+ if (!items.length || xs.length % 2 !== 0) return null;
1618
+ const fillParts = [];
1619
+ items.forEach((d, i) => {
1620
+ if (i) fillParts.push([',', ctx.flat ? ' ' : line]);
1621
+ fillParts.push(d);
1622
+ });
1623
+ return [n.kind, ' ', head ? [print(head, ctx, node), ': '] : '', indent(builders.fill(fillParts))];
1624
+ }
1625
+
1626
+ /** `body for x in xs if c`: may break before `for` and `if`. */
1627
+ function printGenerator(n, ctx) {
1628
+ const { xs, comments } = parts(n);
1629
+ if (comments.length || xs.length < 3) return null;
1630
+ const out = [print(xs[0], ctx, n)];
1631
+ for (let i = 1; i < xs.length; i++) {
1632
+ const x = xs[i];
1633
+ if (kw(x, 'for')) {
1634
+ out.push(ln(ctx), 'for ');
1635
+ continue;
1636
+ }
1637
+ if (isLeaf(x) && isTriviaLeaf(x)) return null;
1638
+ if (!isLeaf(x) && x.kind === 'filter') {
1639
+ const p = parts(x);
1640
+ if (p.comments.length || p.xs.length !== 3 || !kw(p.xs[1], 'if')) return null;
1641
+ out.push(print(p.xs[0], ctx, x), ln(ctx), 'if ', print(p.xs[2], ctx, x));
1642
+ continue;
1643
+ }
1644
+ out.push(print(x, ctx, n));
1645
+ }
1646
+ return ctx.flat ? out : group([out[0], indent(out.slice(1))]);
1647
+ }
1648
+
1649
+ function printComprehension(n, ctx) {
1650
+ const { xs, comments } = parts(n);
1651
+ if (comments.length) return null;
1652
+ let i = 0,
1653
+ prefix = '';
1654
+ if (n.kind === 'typed_comprehension') {
1655
+ prefix = print(xs[0], ctx, n);
1656
+ i = 1;
1657
+ }
1658
+ if (!kw(xs[i], '[') || !kw(xs[i + 2], ']') || xs.length !== i + 3) return null;
1659
+ const inner = sub(ctx, { flat: false, compact: false });
1660
+ return [prefix, group(['[', indent([softline, print(xs[i + 1], inner, n)]), softline, ']'])];
1661
+ }