@live-codes/prettier-plugin-rust 0.1.9

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/index.js ADDED
@@ -0,0 +1,4272 @@
1
+ import { DelimKind, rs, NodeType, TK, PRCD } from 'jinx-rust';
2
+ import { is_BlockCommentKind, is_StructLiteralProperty, is_CallExpression, is_Node, is_NodeWithBodyOrCases, is_AttributeOrDocComment, start, ownStart, end, insertNode, is_Comment, is_MissingNode, is_PunctuationToken, insertNodes, is_ExpressionStatement, hasAttributes, getBodyOrCases, is_ExpressionWithBodyOrCases, is_StructLiteralPropertySpread, is_ReassignmentNode, nisAnyOf, hasOuterAttributes, is_FunctionDeclaration, is_StatementNode, is_FlowControlExpression, is_FunctionNode, getLastParameter, is_MacroRule, is_IfBlockExpression, is_LocArray, is_MacroInvocation, is_Snippet, is_Program, each_childNode, reassignNodeProperty, is_ClosureFunctionExpression, is_BlockExpression, transferAttributes, hasTypeBounds, is_TypeDynBounds, is_TypeImplBounds, unsafe_set_nodeType, is_TypeTraitBound, is_TypeBoundsStandaloneNode, is_DocCommentAttribute, deleteAttributes, getNodeChildren, is_NodeWithBodyNoBody, is_LineCommentNode, is_BlockCommentNode, is_Attribute, is_UnionPattern, is_ExpressionAsTypeCast, is_FlowControlMaybeValueExpression, is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation, is_MemberExpression, is_ElseBlock, is_NodeWithMaybePatternNoUnionBody, is_UnaryExpression, is_ReturnExpression, is_YieldExpression, can_have_OuterAttributes, is_Identifier, is_Literal, is_LiteralNumberLike, is_StructLiteral, is_ParenthesizedNode, is_RangeLiteral, is_LogicalExpression, is_PostfixExpression, is_OperationExpression, is_ComparisonExpression, is_LetScrutinee, is_TypeFunctionNode, is_UnaryType, is_PatternVariableDeclaration, is_BitwiseOperator, is_EqualityOperator, getPrecedence, is_multiplicativeOperator, is_bitshiftOperator, getAstPath, is_MatchExpressionCase, is_EnumMemberDeclaration, is_StructPropertyDeclaration, is_StructPatternProperty, is_LineCommentKind, is_CommentOrDocComment, is_ExternSpecifier, getMacroName, hasMethod, includesTK, is_BareTypeTraitBound, hasSuffix, getDelimChars, is_ArrayOrTupleLiteral, is_MatchExpression, is_SourceFile, is_MacroGroup, is_DelimGroup, is_MacroParameterDeclaration, is_MacroInlineRuleDeclaration, is_ExpressionPath, is_ReassignmentExpression, is_GenericParameterDeclaration, is_TypeCallNamedArgument, is_VariableDeclarationNode, is_LiteralStringLike, is_UnwrapExpression, is_IdentifierOrIndex, is_ExpressionTypeCast, hasSemiNoBody, is_OrExpression, is_ImplDeclarationNode, is_TupleStructDeclaration, hasParameters, hasSelfParameter, is_ClosureBlock, hasCondition, is_TupleNode, hasProperties, hasItems, is_TupleLiteral, is_TuplePattern, is_RangePattern, is_RestPattern, is_TypeTuple, hasSemiNoProperties, is_StructPattern, is_UnionDeclaration, is_StructDeclaration, is_EnumMemberStructDeclaration, getParameters, is_FunctionParameterDeclaration, isInner, is_FunctionSpread, hasLetScrutineeCondition, is_ImplicitReturnAbleNode, is_ExpressionWithBody, is_ForInBlockExpression, is_LoopBlockExpression, is_WhileBlockExpression, hasBody, is_MinusExpression, is_StructPatternPropertyDestructured, is_StructProperty, is_LiteralBooleanLike, isTK, getOwnChildAstPath } from 'jinx-rust/utils';
3
+ import { builders, utils } from 'prettier/doc';
4
+
5
+ // src/format/plugin.ts
6
+
7
+ // src/utils/debug.ts
8
+ var cwd = (
9
+ // @ts-expect-error
10
+ typeof process === "object" && typeof process?.cwd === "function" ? /* @__PURE__ */ normPath(/* @__PURE__ */ process.cwd() ?? "") : ""
11
+ );
12
+ function normPath_strip_cwd(filepath) {
13
+ let normFilePath = normPath(filepath);
14
+ return normFilePath.startsWith(cwd) ? normFilePath.slice(cwd.length + 1) : normFilePath;
15
+ }
16
+ var StackLine = class {
17
+ constructor(raw) {
18
+ ({
19
+ 1: this.callee = "",
20
+ 2: this.filepath = "",
21
+ 3: this.line = "",
22
+ 4: this.col = "",
23
+ 5: this.other = ""
24
+ } = (this.raw = raw).match(/at (?:(.+?)\s+\()?(?:(.+?):([0-9]+)(?::([0-9]+))?|([^)]+))\)?/) ?? ["", "", "", "", "", ""]);
25
+ this.url = this.filepath ? normPath_strip_cwd(this.filepath) + (this.line && this.col && `:${this.line}:${this.col}`) : this.other === "native" ? "<native>" : "";
26
+ }
27
+ };
28
+ function getPrintWidth() {
29
+ return clamp(0, getTerminalWidth(128), 200) - 4;
30
+ }
31
+ var StackItem = class extends StackLine {
32
+ constructor(stack, i, raw) {
33
+ super(raw);
34
+ this.stack = stack;
35
+ this.i = i;
36
+ this.hidden = false;
37
+ }
38
+ hide() {
39
+ this.hidden = true;
40
+ return this;
41
+ }
42
+ hideNext(n) {
43
+ for (let i = 0; i < n; i++)
44
+ this.at(i)?.hide();
45
+ }
46
+ hideWhileTrue(test) {
47
+ let line2 = this;
48
+ while (line2 && test(line2))
49
+ line2 = line2.hide().next();
50
+ }
51
+ at(relIndex) {
52
+ return this.i + relIndex >= this.stack.length || this.i + relIndex < 0 ? void 0 : this.stack[this.i + relIndex];
53
+ }
54
+ next() {
55
+ return this.at(1);
56
+ }
57
+ toString() {
58
+ const url = this.url;
59
+ const calleeColor = this.stack.style?.callee?.(this.callee, this) ?? color.cyan;
60
+ const urlColor = this.stack.style?.url?.(url, this) ?? color.grey;
61
+ return compose2Cols(" at " + calleeColor(this.callee), urlColor(url), getPrintWidth());
62
+ }
63
+ };
64
+ function createStack(message, Error_stack, style) {
65
+ for (var STACK = [], i = 0, stack = Error_stack.split("\n").slice(2); i < stack.length; i++)
66
+ STACK[i] = new StackItem(STACK, i, stack[i]);
67
+ return STACK.message = message, STACK.style = style, STACK;
68
+ }
69
+ function composeStack(stack) {
70
+ var hidden = 0;
71
+ var str = stack.message;
72
+ for (var item of stack)
73
+ item.hidden ? ++hidden : str += "\n" + item.toString();
74
+ return str + (hidden > 0 ? "\n" + color.grey(compose2Cols("", `...filtered ${hidden} lines`, getPrintWidth())) : "");
75
+ }
76
+ function createCustomError({
77
+ message = "Unknown Error",
78
+ editStack = (stack) => {
79
+ },
80
+ style = void 0,
81
+ stackTraceLimit = 20
82
+ }) {
83
+ const _stackTraceLimit = Error.stackTraceLimit;
84
+ const _prepareStackTrace = Error.prepareStackTrace;
85
+ Error.stackTraceLimit = stackTraceLimit;
86
+ const _ctx = {};
87
+ Error.captureStackTrace(_ctx, createCustomError);
88
+ const stack = createStack(message, _ctx.stack, style);
89
+ Error.prepareStackTrace = function(err2, calls) {
90
+ editStack(stack);
91
+ return composeStack(stack);
92
+ };
93
+ const err = new Error(message);
94
+ err.stack = err.stack;
95
+ Error.stackTraceLimit = _stackTraceLimit;
96
+ Error.prepareStackTrace = _prepareStackTrace;
97
+ return err;
98
+ }
99
+ function compose2Cols(left, right, len = 64, min = 1) {
100
+ return left + " ".repeat(clamp(min, len, len - (color.unstyledLength(left) + color.unstyledLength(right)))) + right;
101
+ }
102
+ function exit(message, ...ctx2) {
103
+ if (ctx2.length > 0)
104
+ console.log("Error context:", { ...ctx2 });
105
+ throw createCustomError({ message });
106
+ }
107
+ exit.never = function never(...ctx2) {
108
+ exit("Reached unreachable code", ...ctx2);
109
+ };
110
+ function assert(predicate, err, ...ctx2) {
111
+ if (false === predicate)
112
+ exit(err ?? "Assertion failed", ...ctx2);
113
+ }
114
+ function Identity(v) {
115
+ return v;
116
+ }
117
+ function last_of(arr) {
118
+ return arr[arr.length - 1];
119
+ }
120
+ function normPath(filepath) {
121
+ return filepath.replace(/^file:\/\/\//, "").replace(/\\\\?/g, "/");
122
+ }
123
+ function binarySearchIn(array, target, toValue) {
124
+ if (isEmpty(array))
125
+ return -1;
126
+ let i = 0;
127
+ let low = 0;
128
+ let high = array.length - 1;
129
+ let value = toValue(array[high]);
130
+ if (target >= value)
131
+ return high;
132
+ else
133
+ high--;
134
+ while (low <= high) {
135
+ i = low + (high - low >> 1);
136
+ value = toValue(array[i]);
137
+ if (target === value)
138
+ return i;
139
+ if (target > value)
140
+ low = i + 1;
141
+ else
142
+ high = i - 1;
143
+ }
144
+ return low - 1;
145
+ }
146
+ function getTerminalWidth(fallbackWidth = 200) {
147
+ return globalThis?.process?.stdout?.columns ?? fallbackWidth;
148
+ }
149
+ var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
150
+ var color = ((cfn, mfn) => ({
151
+ black: cfn(30),
152
+ red: cfn(31),
153
+ green: cfn(32),
154
+ yellow: cfn(33),
155
+ blue: cfn(34),
156
+ magenta: cfn(35),
157
+ cyan: cfn(36),
158
+ white: cfn(37),
159
+ grey: cfn(90),
160
+ bold: mfn(1, 22),
161
+ italic: mfn(3, 23),
162
+ underline: mfn(4, 24),
163
+ hidden: mfn(8, 28),
164
+ hiddenCursor: (str) => `\x1B[?25l${str}\x1B[?25h`,
165
+ unstyle: (str) => str.replace(/\x1B\[[0-9][0-9]?m/g, ""),
166
+ unstyledLength: (str) => str.replace(/\x1B\[[0-9][0-9]?m/g, "").length,
167
+ link: (str) => color.underline(color.blue(str))
168
+ }))(
169
+ (c1) => isBrowser ? Identity : (str) => `\x1B[${c1}m${str.replace(/\x1B\[39m/g, `\x1B[${c1}m`)}\x1B[39m`,
170
+ (c1, c2) => isBrowser ? Identity : (str) => `\x1B[${c1}m${str}\x1B[${c2}m`
171
+ );
172
+ function Map_get(map, key, init) {
173
+ if (!map.has(key))
174
+ map.set(key, init(key));
175
+ return map.get(key);
176
+ }
177
+ function isEmpty(array) {
178
+ return 0 === array.length;
179
+ }
180
+ function Array_splice(array, target, index = array.indexOf(target)) {
181
+ array.splice(index, 1);
182
+ }
183
+ function Array_replace(array, target, ...replacements) {
184
+ array.indexOf(target);
185
+ array.splice(array.indexOf(target), 1, ...replacements);
186
+ }
187
+ function has_key_defined(o, k) {
188
+ return k in o && void 0 !== o[k];
189
+ }
190
+ function is_array(data) {
191
+ return Array.isArray(data);
192
+ }
193
+ function each(data, callback) {
194
+ switch (data.constructor) {
195
+ case Array: {
196
+ let i = 0;
197
+ for (; i < data.length; i++)
198
+ callback(data[i], i);
199
+ return;
200
+ }
201
+ case Object: {
202
+ let k;
203
+ for (k in data)
204
+ callback(data[k], k);
205
+ return;
206
+ }
207
+ case Set: {
208
+ let d;
209
+ for (d of data)
210
+ callback(d, void 0);
211
+ return;
212
+ }
213
+ case Map: {
214
+ let e;
215
+ for (e of data)
216
+ callback(e[1], e[0]);
217
+ return;
218
+ }
219
+ default: {
220
+ let x;
221
+ for (x of data)
222
+ callback(x, void 0);
223
+ return;
224
+ }
225
+ }
226
+ }
227
+ function iLast(index, array) {
228
+ return 1 + index === array.length;
229
+ }
230
+ function try_eval(fn) {
231
+ try {
232
+ return fn();
233
+ } catch (e) {
234
+ return void 0;
235
+ }
236
+ }
237
+ function clamp(min, max, value) {
238
+ return value > min ? value < max ? value : max : min;
239
+ }
240
+ function flat(arr) {
241
+ return arr.flat(Infinity);
242
+ }
243
+ function map_tagged_template(args, map) {
244
+ const arr = [args[0][0]];
245
+ for (var i = 1; i < args.length; i++)
246
+ arr.push(map(args[i]), args[0][i]);
247
+ return arr;
248
+ }
249
+ function spliceAll(array) {
250
+ const r = [...array];
251
+ array.length = 0;
252
+ return r;
253
+ }
254
+ function spread(fn) {
255
+ return [...fn()];
256
+ }
257
+ var {
258
+ join,
259
+ line,
260
+ softline,
261
+ hardline,
262
+ literalline,
263
+ group,
264
+ conditionalGroup,
265
+ fill,
266
+ lineSuffix,
267
+ lineSuffixBoundary,
268
+ cursor,
269
+ breakParent,
270
+ ifBreak,
271
+ trim,
272
+ indent,
273
+ indentIfBreak,
274
+ align,
275
+ addAlignmentToDoc,
276
+ markAsRoot,
277
+ dedentToRoot,
278
+ dedent,
279
+ hardlineWithoutBreakParent,
280
+ literallineWithoutBreakParent,
281
+ label
282
+ } = builders;
283
+ var { willBreak, traverseDoc, findInDoc, mapDoc, removeLines, stripTrailingHardline, canBreak } = utils;
284
+ function cleanDoc(doc) {
285
+ if (!Array.isArray(doc))
286
+ return doc;
287
+ const parts = [];
288
+ for (const part of doc) {
289
+ if (!part)
290
+ continue;
291
+ const cleaned = cleanDoc(part);
292
+ const items = Array.isArray(cleaned) ? cleaned : [cleaned];
293
+ for (const item of items) {
294
+ if (typeof item === "string" && typeof parts[parts.length - 1] === "string") {
295
+ parts[parts.length - 1] = parts[parts.length - 1] + item;
296
+ } else {
297
+ parts.push(item);
298
+ }
299
+ }
300
+ }
301
+ return parts;
302
+ }
303
+ var Symbol_comments = Symbol.for("comments");
304
+ var DCM = /* @__PURE__ */ ((DCM2) => {
305
+ DCM2["arguments"] = "arguments";
306
+ DCM2["parameters"] = "parameters";
307
+ DCM2["items"] = "items";
308
+ DCM2["properties"] = "properties";
309
+ DCM2["members"] = "members";
310
+ DCM2["body"] = "body";
311
+ DCM2["cases"] = "cases";
312
+ DCM2["typeArguments"] = "typeArguments";
313
+ DCM2["ltParameters"] = "ltParameters";
314
+ DCM2["generics"] = "generics";
315
+ DCM2["specifiers"] = "specifiers";
316
+ DCM2["rules"] = "rules";
317
+ DCM2["match"] = "match";
318
+ DCM2["transform"] = "transform";
319
+ DCM2["segments"] = "segments";
320
+ return DCM2;
321
+ })(DCM || {});
322
+
323
+ // src/format/complexity.ts
324
+ var DEPTH = 0;
325
+ var ANCESTRY = [];
326
+ var LONE_SHORT_ARGUMENT_THRESHOLD_RATE = 0.25;
327
+ function withCheckContext(fn) {
328
+ if (0 === DEPTH) {
329
+ return fn();
330
+ } else {
331
+ DEPTH = 0;
332
+ const prev = spliceAll(ANCESTRY);
333
+ try {
334
+ return fn();
335
+ } finally {
336
+ DEPTH = ANCESTRY.push(...prev);
337
+ }
338
+ }
339
+ }
340
+ function is_short(str) {
341
+ return str.length <= LONE_SHORT_ARGUMENT_THRESHOLD_RATE * getOptions().printWidth;
342
+ }
343
+ function print(target) {
344
+ const current = getNode();
345
+ const keys = [...getAstPath(ANCESTRY[0], getNode())];
346
+ for (let i = 1; i < ANCESTRY.length; i++)
347
+ keys.push(...getOwnChildAstPath(ANCESTRY[i - 1], ANCESTRY[i]));
348
+ keys.push(...getOwnChildAstPath(last_of(ANCESTRY), target));
349
+ try {
350
+ return getContext().path.call(() => getPrintFn()(), ...keys);
351
+ } catch (e) {
352
+ console.log({ current, target, keys, ANCESTRY });
353
+ throw e;
354
+ }
355
+ }
356
+ function IsSimpleFunction(fn) {
357
+ return function(node) {
358
+ if (0 !== DEPTH && node === ANCESTRY[DEPTH - 1]) {
359
+ return fn(node);
360
+ }
361
+ if (DEPTH >= 2) {
362
+ return isShortBasic(node);
363
+ }
364
+ try {
365
+ return fn(ANCESTRY[DEPTH++] = node);
366
+ } finally {
367
+ ANCESTRY.length = --DEPTH;
368
+ }
369
+ };
370
+ }
371
+ function HasComplexFunction(fn) {
372
+ return function(node) {
373
+ if (0 !== DEPTH && node === ANCESTRY[DEPTH - 1]) {
374
+ return fn(node);
375
+ }
376
+ if (DEPTH >= 2) {
377
+ return !isShortBasic(node);
378
+ }
379
+ try {
380
+ return fn(ANCESTRY[DEPTH++] = node);
381
+ } finally {
382
+ ANCESTRY.length = --DEPTH;
383
+ }
384
+ };
385
+ }
386
+ var isShortBasic = (node) => {
387
+ switch (node.nodeType) {
388
+ case NodeType.MissingNode:
389
+ return true;
390
+ case NodeType.Identifier:
391
+ case NodeType.Index:
392
+ case NodeType.LtIdentifier:
393
+ case NodeType.LbIdentifier:
394
+ case NodeType.McIdentifier:
395
+ return is_short(node.name);
396
+ case NodeType.Literal:
397
+ return is_short(node.value) && !/\n/.test(node.value);
398
+ }
399
+ return false;
400
+ };
401
+ var isSimpleType = IsSimpleFunction((node) => {
402
+ switch (node.nodeType) {
403
+ case NodeType.MissingNode:
404
+ case NodeType.FunctionSpread:
405
+ return true;
406
+ case NodeType.MacroInvocation:
407
+ return false;
408
+ case NodeType.Identifier:
409
+ case NodeType.TypeNever:
410
+ case NodeType.TypeInferred:
411
+ return true;
412
+ case NodeType.TypePath:
413
+ return isShortBasic(node.segment) && (!node.namespace || isSimpleType(node.namespace));
414
+ case NodeType.TypeCall:
415
+ return isSimpleType(node.typeCallee) && !hasComplexTypeArguments(node);
416
+ case NodeType.ExpressionTypeSelector:
417
+ return isSimpleType(node.typeTarget) && (!node.typeExpression || isSimpleType(node.typeExpression));
418
+ case NodeType.TypeDynBounds:
419
+ return !hasComplexTypeBounds(node);
420
+ case NodeType.TypeImplBounds:
421
+ return !hasComplexTypeBounds(node);
422
+ case NodeType.TypeFnPointer: {
423
+ const param = node.parameters[0];
424
+ return (!node.extern || !node.extern.abi || isShortBasic(node.extern.abi)) && !hasComplexLtParameters(node) && (node.parameters.length === 0 || node.parameters.length === 1 && (is_FunctionSpread(param) || !is_TypeFunctionNode(param.typeAnnotation) && isSimpleType(param.typeAnnotation))) && (!node.returnType || isSimpleType(node.returnType));
425
+ }
426
+ case NodeType.TypeFunction:
427
+ return isSimpleType(node.callee) && node.parameters.every(isSimpleType) && (!node.returnType || isSimpleType(node.returnType));
428
+ case NodeType.TypeSizedArray:
429
+ return isSimpleType(node.typeExpression) && isShortBasic(node.sizeExpression);
430
+ case NodeType.TypeSlice:
431
+ return isSimpleType(node.typeExpression);
432
+ case NodeType.TypeTuple:
433
+ return node.items.length === 0 || node.items.length === 1 && isSimpleType(node.items[0]);
434
+ case NodeType.TypeReference:
435
+ case NodeType.TypeDereferenceMut:
436
+ case NodeType.TypeDereferenceConst:
437
+ case NodeType.TypeParenthesized:
438
+ return isSimpleType(node.typeExpression);
439
+ default:
440
+ return false;
441
+ }
442
+ });
443
+ var hasComplexTypeBounds = HasComplexFunction((node) => {
444
+ return !!node.typeBounds && node.typeBounds.length > 1 && !node.typeBounds.every(isSimpleTypeBound);
445
+ });
446
+ var isSimpleTypeBound = (node) => {
447
+ switch (node.nodeType) {
448
+ case NodeType.TypeParenthesized:
449
+ return isSimpleTypeBound(node.typeExpression);
450
+ case NodeType.LtIdentifier:
451
+ case NodeType.LtElided:
452
+ case NodeType.LtStatic:
453
+ return true;
454
+ case NodeType.TypeTraitBound:
455
+ return is_BareTypeTraitBound(node) && isSimpleTypeNamespaceTargetNoSelector(node.typeExpression);
456
+ default:
457
+ return false;
458
+ }
459
+ function isSimpleTypeNamespaceTargetNoSelector(node2) {
460
+ switch (node2.nodeType) {
461
+ case NodeType.Identifier:
462
+ return true;
463
+ case NodeType.TypePath:
464
+ return void 0 === node2.namespace || isSimpleTypeNamespaceTargetNoSelector(node2.namespace);
465
+ case NodeType.TypeCall:
466
+ return false;
467
+ case NodeType.TypeFunction:
468
+ return isSimpleTypeNamespaceTargetNoSelector(node2.callee) && node2.parameters.length === 0 && !node2.returnType;
469
+ default:
470
+ return false;
471
+ }
472
+ }
473
+ };
474
+ var hasComplexTypeArguments = HasComplexFunction(
475
+ (node) => !node.typeArguments || node.typeArguments.length === 0 ? false : node.typeArguments.length === 1 ? (() => {
476
+ const arg = node.typeArguments[0];
477
+ return is_TypeBoundsStandaloneNode(arg) || canBreak(print(arg));
478
+ })() : true
479
+ );
480
+ var hasComplexLtParameters = HasComplexFunction((node) => {
481
+ const ltParameters = node.ltParameters;
482
+ if (!ltParameters || ltParameters.length === 0) {
483
+ return false;
484
+ }
485
+ if (ltParameters.length === 1) {
486
+ const arg = ltParameters[0];
487
+ if (arg.ltBounds && arg.ltBounds.length > 1) {
488
+ return true;
489
+ }
490
+ return false;
491
+ }
492
+ return true;
493
+ });
494
+ var isShortGenericParameterDeclaration = IsSimpleFunction((node) => {
495
+ switch (node.nodeType) {
496
+ case NodeType.GenericTypeParameterDeclaration:
497
+ return !node.typeBounds && !node.typeDefault;
498
+ case NodeType.ConstTypeParameterDeclaration:
499
+ return (!node.typeAnnotation || is_MissingNode(node)) && !node.typeDefault;
500
+ case NodeType.GenericLtParameterDeclaration:
501
+ return !node.ltBounds;
502
+ default:
503
+ exit.never();
504
+ }
505
+ });
506
+ var hasComplexGenerics = HasComplexFunction((node) => {
507
+ return has_key_defined(node, "generics") && node.generics.length > 0 && !node.generics.every(isShortGenericParameterDeclaration);
508
+ });
509
+ var hasComplexTypeAnnotation = HasComplexFunction((node) => {
510
+ if (is_VariableDeclarationNode(node) && !is_LetScrutinee(node)) {
511
+ const { typeAnnotation } = node;
512
+ return !!typeAnnotation && !is_MissingNode(typeAnnotation) && !isSimpleType(typeAnnotation);
513
+ } else {
514
+ return false;
515
+ }
516
+ });
517
+ function needsOuterSoftbreakParens(node) {
518
+ const parent = getParentNode();
519
+ if (!parent)
520
+ return false;
521
+ if (is_ExpressionAsTypeCast(node)) {
522
+ return precedenceNeedsParens(node, parent);
523
+ }
524
+ if (is_FlowControlMaybeValueExpression(parent) && //
525
+ parent.expression === node && flowControlExpressionNeedsOuterParens(parent)) {
526
+ return true;
527
+ }
528
+ if (is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(node) && (is_MemberExpression(parent) && parent.expression === node || is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(parent) && !is_ElseBlock(node, parent))) {
529
+ return true;
530
+ }
531
+ if (is_UnionPattern(node) && is_NodeWithMaybePatternNoUnionBody(parent)) {
532
+ return true;
533
+ }
534
+ if (hasComment(node)) {
535
+ if (is_UnaryExpression(parent)) {
536
+ return true;
537
+ }
538
+ if (hasComment(node, 32 /* Line */)) {
539
+ if (is_ReturnExpression(parent) || is_YieldExpression(parent) && parent.expression === node) {
540
+ return true;
541
+ }
542
+ }
543
+ if (hasComment(node, 2 /* Leading */, (comment) => is_Attribute(comment) && !comment.inner) && !can_have_OuterAttributes(node, parent, true)) {
544
+ return true;
545
+ }
546
+ }
547
+ return false;
548
+ }
549
+ function needsInnerParens(node) {
550
+ if (needsOuterSoftbreakParens(node)) {
551
+ return false;
552
+ }
553
+ const parent = getParentNode();
554
+ if (!parent) {
555
+ return false;
556
+ }
557
+ if (is_Identifier(node)) {
558
+ return false;
559
+ }
560
+ if (is_Literal(node)) {
561
+ return is_LiteralNumberLike(node) && is_MemberExpression(parent) && node === parent.expression;
562
+ }
563
+ if (is_CallExpression(parent) && parent.callee === node && is_MemberExpression(node)) {
564
+ return !getOptions().actuallyMethodNodes.has(node);
565
+ }
566
+ if (is_ReassignmentNode(node)) {
567
+ if (is_printing_macro()) {
568
+ return false;
569
+ }
570
+ if (is_ClosureFunctionExpression(parent) && node === parent.expression) {
571
+ return true;
572
+ }
573
+ if (is_ExpressionStatement(parent)) {
574
+ return is_StructLiteral(node.left);
575
+ }
576
+ if (is_ReassignmentNode(parent)) {
577
+ return false;
578
+ }
579
+ return true;
580
+ }
581
+ if (is_ParenthesizedNode(parent)) {
582
+ return false;
583
+ }
584
+ if (is_ExpressionStatement(parent)) {
585
+ return false;
586
+ }
587
+ if (is_RangeLiteral(node)) {
588
+ return is_ExpressionAsTypeCast(parent) || is_LogicalExpression(parent) || is_UnaryExpression(parent) || is_PostfixExpression(parent) || is_MemberExpression(parent) && node === parent.expression || is_CallExpression(parent) && node === parent.callee || is_OperationExpression(parent) || is_ComparisonExpression(parent);
589
+ }
590
+ if (is_LetScrutinee(parent) && is_LogicalExpression(node) && parent.expression === node) {
591
+ return true;
592
+ }
593
+ if (is_UnaryExpression(node)) {
594
+ switch (parent.nodeType) {
595
+ case NodeType.MemberExpression:
596
+ case NodeType.AwaitExpression:
597
+ return node === parent.expression;
598
+ case NodeType.CallExpression:
599
+ return node === parent.callee;
600
+ default:
601
+ return false;
602
+ }
603
+ }
604
+ if (is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(node)) {
605
+ if (is_ExpressionWithBodyOrCases(parent)) {
606
+ return !is_ElseBlock(node, parent);
607
+ }
608
+ if (is_LetScrutinee(parent) && parent.expression === node && is_ExpressionWithBodyOrCases(getGrandParentNode())) {
609
+ return true;
610
+ }
611
+ return is_ExpressionAsTypeCast(parent) || is_LogicalExpression(parent) || is_UnaryExpression(parent) || is_PostfixExpression(parent) || is_MemberExpression(parent) && node === parent.expression || is_CallExpression(parent) && node === parent.callee || is_OperationExpression(parent) || is_ComparisonExpression(parent) || is_RangeLiteral(parent);
612
+ }
613
+ if (is_StructLiteral(node)) {
614
+ if (is_ExpressionWithBodyOrCases(parent)) {
615
+ return true;
616
+ }
617
+ if (is_LetScrutinee(parent) && parent.expression === node && is_ExpressionWithBodyOrCases(getGrandParentNode())) {
618
+ return true;
619
+ }
620
+ if (is_UnaryExpression(parent) || is_PostfixExpression(parent) || is_MemberExpression(parent)) {
621
+ return parent.expression === node;
622
+ }
623
+ if (is_CallExpression(parent)) {
624
+ return parent.callee === node;
625
+ }
626
+ }
627
+ if (is_LogicalExpression(node) || is_OperationExpression(node) || is_ComparisonExpression(node) || is_ClosureFunctionExpression(node)) {
628
+ return precedenceNeedsParens(node, parent);
629
+ }
630
+ if (is_TypeFunctionNode(node)) {
631
+ const gp = getGrandParentNode();
632
+ if (node.returnType && is_TypeTraitBound(parent) && is_TypeBoundsStandaloneNode(gp) && last_of(gp.typeBounds) !== parent) {
633
+ return true;
634
+ }
635
+ }
636
+ if (is_TypeBoundsStandaloneNode(node)) {
637
+ return is_UnaryType(parent) && node.typeBounds.length > 1 || is_TypeBoundsStandaloneNode(parent) || is_TypeTraitBound(parent) || is_TypeFunctionNode(parent) && parent.returnType === node;
638
+ }
639
+ if (is_PatternVariableDeclaration(parent)) {
640
+ return is_UnionPattern(node);
641
+ }
642
+ return false;
643
+ }
644
+ function precedenceNeedsParens(node, parent) {
645
+ if (is_UnaryExpression(parent) || is_PostfixExpression(parent))
646
+ return true;
647
+ if (is_ReassignmentNode(parent))
648
+ return parent.left === node;
649
+ if (is_MemberExpression(parent))
650
+ return parent.expression === node;
651
+ if (is_CallExpression(parent))
652
+ return parent.callee === node;
653
+ if (is_ExpressionAsTypeCast(parent))
654
+ return !is_ExpressionAsTypeCast(node);
655
+ if (is_LogicalExpression(parent))
656
+ return is_LogicalExpression(node) ? parent.nodeType !== node.nodeType : evalPrecedence(node, parent);
657
+ if (is_OperationExpression(parent) || is_ComparisonExpression(parent))
658
+ return evalPrecedence(node, parent);
659
+ return false;
660
+ function evalPrecedence(child, parent2) {
661
+ if (is_ExpressionAsTypeCast(child) || is_ClosureFunctionExpression(child)) {
662
+ return true;
663
+ }
664
+ function getPrec(node2, bool) {
665
+ return getPrecedence(node2, bool);
666
+ }
667
+ const childPRCD = getPrec(child, is_insideScrutinee(child));
668
+ const parentPRCD = getPrec(parent2, is_insideScrutinee(parent2));
669
+ if (parentPRCD > childPRCD) {
670
+ return true;
671
+ }
672
+ if (parentPRCD === childPRCD && parent2.right === child) {
673
+ return true;
674
+ }
675
+ if (parentPRCD === childPRCD && !shouldFlatten(parent2, child)) {
676
+ return true;
677
+ }
678
+ if (parentPRCD < childPRCD && child.tk === TK["%"]) {
679
+ return parentPRCD === PRCD["+-"];
680
+ }
681
+ if (is_BitwiseOperator(parent2.tk) || is_BitwiseOperator(child.tk) && is_EqualityOperator(parent2.tk)) {
682
+ return true;
683
+ }
684
+ return false;
685
+ }
686
+ }
687
+ function shouldFlatten(parent, node) {
688
+ if (getPrecedence(node, is_insideScrutinee(node)) !== getPrecedence(parent, is_insideScrutinee(parent)))
689
+ return false;
690
+ if (is_ComparisonExpression(parent) && is_ComparisonExpression(node))
691
+ return false;
692
+ if (is_OperationExpression(parent) && is_OperationExpression(node)) {
693
+ if (node.tk === TK["%"] && is_multiplicativeOperator(parent.tk) || parent.tk === TK["%"] && is_multiplicativeOperator(node.tk) || node.tk !== parent.tk && is_multiplicativeOperator(node.tk) && is_multiplicativeOperator(parent.tk) || is_bitshiftOperator(node.tk) && is_bitshiftOperator(parent.tk))
694
+ return false;
695
+ }
696
+ return true;
697
+ }
698
+ function needsParens(node) {
699
+ return needsOuterSoftbreakParens(node) || needsInnerParens(node);
700
+ }
701
+ function stmtNeedsSemi(stmt, disregardExprType = false) {
702
+ return pathCallParentOf(stmt, (parent) => needsSemi(parent, stmt, disregardExprType));
703
+ }
704
+ var NoNode = { nodeType: 0 };
705
+ function needsSemi(parent, stmt, disregardExprType = false) {
706
+ const expr = disregardExprType ? NoNode : stmt.expression;
707
+ const hadSemi = !disregardExprType && stmt.semi;
708
+ return !!expr && (forcePreserveSemi() ? true : shouldNeverSemi() ? false : shouldPreserveSemi() ? hadSemi || shouldAlwaysSemi() || canAutoCompleteSemi() : true);
709
+ function forcePreserveSemi() {
710
+ return hadSemi && stmt === last_of(parent.body) && (is_IfBlockExpression(expr) && hasLetScrutineeCondition(expr) && !(is_LetScrutinee(expr.condition) && is_Identifier(expr.condition.expression)) || is_MatchExpression(expr) && !is_Identifier(expr.expression));
711
+ }
712
+ function shouldNeverSemi() {
713
+ return is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(expr);
714
+ }
715
+ function shouldPreserveSemi() {
716
+ return stmt === last_of(parent.body) && (is_ImplicitReturnAbleNode(parent) || is_BlockLikeMacroInvocation(parent));
717
+ }
718
+ function shouldAlwaysSemi() {
719
+ return is_FlowControlExpression(expr) || is_ReassignmentNode(expr);
720
+ }
721
+ function canAutoCompleteSemi() {
722
+ return withPathAt(parent, function checkParent(child) {
723
+ return pathCallParentOf(child, (parent2) => {
724
+ if (is_IfBlockExpression(parent2) && parent2.else === child) {
725
+ return checkParent(parent2);
726
+ }
727
+ if (is_ExpressionStatement(parent2)) {
728
+ if (hasOuterAttributes(parent2))
729
+ return false;
730
+ return stmtNeedsSemi(parent2, true);
731
+ }
732
+ if (is_MatchExpressionCase(parent2) && parent2.expression === child) {
733
+ return pathCallParentOf(parent2, checkParent);
734
+ }
735
+ return false;
736
+ });
737
+ });
738
+ }
739
+ }
740
+ function canInlineBlockBody(node) {
741
+ if (!is_ExpressionWithBody(node)) {
742
+ return false;
743
+ }
744
+ const body = node.body;
745
+ if (body.length === 0) {
746
+ return canInlineInlineable(node);
747
+ }
748
+ if (body.length === 1) {
749
+ const stmt = body[0];
750
+ if (is_AttributeOrDocComment(stmt)) {
751
+ return true;
752
+ }
753
+ if (is_ExpressionStatement(stmt) && !needsSemi(node, stmt)) {
754
+ const expr = stmt.expression;
755
+ if (is_FlowControlExpression(expr) || //
756
+ is_ClosureFunctionExpression(expr) || is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(expr)) {
757
+ return false;
758
+ }
759
+ return canInlineInlineable(node);
760
+ }
761
+ }
762
+ return false;
763
+ }
764
+ function canInlineInlineable(node) {
765
+ if (is_ForInBlockExpression(node) || is_LoopBlockExpression(node)) {
766
+ return false;
767
+ }
768
+ if (is_WhileBlockExpression(node)) {
769
+ return true;
770
+ }
771
+ const parent = getParentNode();
772
+ if (is_ExpressionStatement(parent) && (!is_ImplicitReturnAbleNode(node) || pathCallAtParent(parent, (parent2) => stmtNeedsSemi(parent2, true)))) {
773
+ return false;
774
+ }
775
+ if (is_ElseBlock(node, parent)) {
776
+ return pathCallAtParent(parent, canInlineBlockBody);
777
+ }
778
+ if (is_IfBlockExpression(node)) {
779
+ if (!node.else || // hasLetScrutineeCondition(node) ||
780
+ is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(node.condition) || willBreak(getPrintFn()("condition"))) {
781
+ return false;
782
+ }
783
+ const grandparent = getGrandParentNode();
784
+ if (is_ExpressionStatement(parent) && hasBody(grandparent) && grandparent.body.length > 1) {
785
+ return false;
786
+ }
787
+ }
788
+ return true;
789
+ }
790
+ function emptyContent(node) {
791
+ switch (node.nodeType) {
792
+ case NodeType.Program:
793
+ case NodeType.MacroRulesDeclaration:
794
+ case NodeType.MacroDeclaration:
795
+ case NodeType.ExternBlockDeclaration:
796
+ case NodeType.ModuleDeclaration:
797
+ case NodeType.TraitDeclaration:
798
+ case NodeType.StructDeclaration:
799
+ case NodeType.MacroInvocation:
800
+ case NodeType.FunctionDeclaration:
801
+ case NodeType.ImplDeclaration:
802
+ case NodeType.UnionDeclaration:
803
+ case NodeType.EnumDeclaration:
804
+ case NodeType.EnumMemberStructDeclaration:
805
+ case NodeType.StructLiteral:
806
+ case NodeType.StructPattern:
807
+ return "";
808
+ case NodeType.BlockExpression:
809
+ case NodeType.WhileBlockExpression:
810
+ case NodeType.ForInBlockExpression:
811
+ case NodeType.TryBlockExpression:
812
+ case NodeType.IfBlockExpression:
813
+ return canInlineInlineable(node) ? is_IfBlockExpression(node) || is_ElseBlock(node, getParentNode()) ? softline : "" : hardline;
814
+ case NodeType.LoopBlockExpression:
815
+ case NodeType.MatchExpression:
816
+ return hardline;
817
+ default:
818
+ if (is_NodeWithBodyNoBody(node)) {
819
+ return "";
820
+ }
821
+ return "";
822
+ }
823
+ }
824
+ function is_insideScrutinee(target) {
825
+ return withPathAt(target, (n) => stackIncludes("condition") && r(n));
826
+ function r(CHILD) {
827
+ switch (CHILD.nodeType) {
828
+ case NodeType.OrExpression:
829
+ case NodeType.AndExpression:
830
+ return pathCallParentOf(
831
+ CHILD,
832
+ (PARENT) => hasCondition(PARENT) && PARENT.condition === CHILD ? hasLetScrutineeCondition(PARENT) : r(PARENT)
833
+ );
834
+ case NodeType.LetScrutinee:
835
+ return true;
836
+ default:
837
+ return false;
838
+ }
839
+ }
840
+ }
841
+ function withPathAt(target, callback) {
842
+ if (target === getNode())
843
+ return callback(target);
844
+ if (target === getParentNode())
845
+ return pathCallAtParent(target, () => callback(target));
846
+ if (stackIncludes(target))
847
+ return pathCallAtParent(getParentNode(), () => withPathAt(target, callback));
848
+ return getContext().path.call(() => {
849
+ return callback(target);
850
+ }, ...getAstPath(getNode(), target));
851
+ }
852
+ function shouldPrintOuterAttributesAbove(node) {
853
+ return is_StatementNode(node) || is_MatchExpressionCase(node) || hasAttributes(node) && node.attributes.some(
854
+ canInlineOuterAttribute(node) ? (attr) => is_DocCommentAttribute(attr) || hasBreaklineAfter(attr) : is_DocCommentAttribute
855
+ );
856
+ function canInlineOuterAttribute(node2) {
857
+ return is_EnumMemberDeclaration(node2) || is_StructPropertyDeclaration(node2) || is_StructLiteralProperty(node2) || is_StructPatternProperty(node2);
858
+ }
859
+ }
860
+
861
+ // src/format/core.ts
862
+ function isNoopExpressionStatement(node) {
863
+ return is_ExpressionStatement(node) && void 0 === node.expression && !hasAttributes(node) && !hasComment(node);
864
+ }
865
+ function is_xVariableEqualishLike(node) {
866
+ switch (node.nodeType) {
867
+ case NodeType.LetScrutinee:
868
+ case NodeType.LetVariableDeclaration:
869
+ case NodeType.ConstVariableDeclaration:
870
+ case NodeType.StaticVariableDeclaration:
871
+ case NodeType.TypeAliasDeclaration:
872
+ case NodeType.TraitAliasDeclaration:
873
+ return true;
874
+ default:
875
+ return false;
876
+ }
877
+ }
878
+ function is_BinaryishExpression(node) {
879
+ switch (node.nodeType) {
880
+ case NodeType.OrExpression:
881
+ case NodeType.AndExpression:
882
+ case NodeType.OperationExpression:
883
+ case NodeType.ComparisonExpression:
884
+ return true;
885
+ default:
886
+ return false;
887
+ }
888
+ }
889
+ function is_StructSpread(node) {
890
+ switch (node.nodeType) {
891
+ case NodeType.StructLiteralPropertySpread:
892
+ case NodeType.StructLiteralRestUnassigned:
893
+ case NodeType.RestPattern:
894
+ return true;
895
+ default:
896
+ return false;
897
+ }
898
+ }
899
+ function isConciselyPrintedArray(node) {
900
+ return node.items.length > 1 && node.items.every(
901
+ (element) => (is_LiteralNumberLike(element) || is_MinusExpression(element) && is_LiteralNumberLike(element.expression) && !hasComment(element.expression)) && !hasComment(element, 4 /* Trailing */ | 32 /* Line */, (comment) => !hasBreaklineBefore(comment))
902
+ );
903
+ }
904
+ function printNumber(rawNumber) {
905
+ return rawNumber.toLowerCase().replace(/^([\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3").replace(/^(\d+)e[+-]?0+$/, "$1.0").replace(/^([\d.]+)e[+-]?0+$/, "$1").replace(/\.(\d+?)0+(?=e|$)/, ".$1").replace(/\.(?=e|$)/, ".0");
906
+ }
907
+ function printOnOwnLine(node, printed) {
908
+ return [printed, maybeEmptyLine(node)];
909
+ }
910
+ function maybeEmptyLine(node) {
911
+ return isNextLineEmpty(node) ? [hardline, hardline] : hardline;
912
+ }
913
+ function printBodyOrCases(print4, node) {
914
+ const p = [];
915
+ if (is_MatchExpression(node)) {
916
+ pathCallEach(node, "cases", (mCase) => {
917
+ p.push({
918
+ node: mCase,
919
+ doc: is_MatchExpressionCase(mCase) && !is_ExpressionWithBodyOrCases(mCase.expression) ? [print4(), ","] : print4()
920
+ });
921
+ });
922
+ } else {
923
+ pathCallEach(node, "body", (stmt) => {
924
+ if (!isNoopExpressionStatement(stmt)) {
925
+ p.push({ node: stmt, doc: print4() });
926
+ }
927
+ });
928
+ }
929
+ const printed = bumpInnerAttributes(p).map(
930
+ ({ doc, node: node2 }, i, a) => iLast(i, a) ? group(doc) : printOnOwnLine(node2, group(doc))
931
+ );
932
+ const comments = printDanglingCommentsForInline(node, "body" /* body */);
933
+ if (comments)
934
+ printed.push(comments);
935
+ const ccomments = printDanglingCommentsForInline(node, "cases" /* cases */);
936
+ if (ccomments)
937
+ printed.push(ccomments);
938
+ if (is_Program(node) && is_SourceFile(getParentNode()) && printed.length > 0 && !comments) {
939
+ printed.push(hardline);
940
+ }
941
+ return printed;
942
+ function bumpInnerAttributes(arr) {
943
+ return arr.sort((a, b) => ownStart(a.node) - ownStart(b.node));
944
+ }
945
+ }
946
+ function printMacroRules(print4, node) {
947
+ return !Array.isArray(node.rules) ? print4("rules") : node.rules.length > 0 ? [" {", indent([hardline, ...print4.join("rules", (rule) => maybeEmptyLine(rule))]), hardline, "}"] : [" {", printDanglingCommentsForInline(node, "rules" /* rules */) || emptyContent(node), "}"];
948
+ }
949
+ function is_unary_token(item) {
950
+ switch (item && is_PunctuationToken(item) ? item.tk : TK.None) {
951
+ case TK["-"]:
952
+ case TK["*"]:
953
+ case TK["&"]:
954
+ case TK["#"]:
955
+ case TK["!"]:
956
+ case TK["~"]:
957
+ return true;
958
+ case TK["?"]:
959
+ return !/\s/.test(getOptions().originalText.charAt(end(item)));
960
+ default:
961
+ return false;
962
+ }
963
+ }
964
+ function can_unary(node) {
965
+ return (!is_PunctuationToken(node) || is_unary_token(node)) && (!is_MacroGroup(node) || is_optional_unary(node));
966
+ }
967
+ function is_optional_token(item) {
968
+ return !!item && is_MacroGroup(item) && item.kind === "?" && item.segments.length === 1 && is_PunctuationToken(item.segments[0]);
969
+ }
970
+ function is_optional_unary(item) {
971
+ return is_optional_token(item) && is_unary_token(item.segments[0]);
972
+ }
973
+ function printRuleMatch(print4, rule) {
974
+ return print_map(rule, "match");
975
+ function print_map(node, property) {
976
+ const arr = node[property];
977
+ const shouldHug = should_hug(arr);
978
+ const dline = arr.dk === DelimKind["{}"] ? line : shouldHug ? "" : softline;
979
+ const isParamsLike = is_params_like(arr);
980
+ const shouldBreak = should_break(arr);
981
+ const d = getDelimChars(arr);
982
+ if (arr.length === 0)
983
+ return [d.left, printDanglingCommentsForInline(node, DCM[property]), d.right];
984
+ const printed = flat(print4.map_join(property, print_item, join_item));
985
+ return group([d.left, !dline ? printed : [indent([dline, printed]), dline], d.right], {
986
+ shouldBreak,
987
+ id: getMacroGroupId(node)
988
+ });
989
+ function should_hug(arr2) {
990
+ if (node === rule)
991
+ return false;
992
+ let has_nonToken = false;
993
+ return arr2.every((item) => !is_MacroGroup(item) && (is_PunctuationToken(item) || has_nonToken !== (has_nonToken = true)));
994
+ }
995
+ function should_break(arr2) {
996
+ let has_decl = false;
997
+ return arr2.some(
998
+ (item, i, a) => is_match_any(item) && arr2.length !== 1 || !iLast(i, a) && isDeclStart(item, a[i + 1]) && has_decl === (has_decl = true)
999
+ );
1000
+ }
1001
+ function print_item(item, index, arr2) {
1002
+ switch (item.nodeType) {
1003
+ case NodeType.Identifier:
1004
+ case NodeType.LtIdentifier:
1005
+ case NodeType.Literal:
1006
+ case NodeType.PunctuationToken:
1007
+ case NodeType.MacroParameterDeclaration:
1008
+ return print4();
1009
+ case NodeType.MacroGroup:
1010
+ return printComments(["$", print_map(item, "segments"), print4("sep"), item.kind]);
1011
+ case NodeType.DelimGroup:
1012
+ return printComments(print_map(item, "segments"));
1013
+ }
1014
+ function printComments(doc) {
1015
+ const printed2 = withComments(item, doc);
1016
+ const comment = getFirstComment(item, 2 /* Leading */ | 32 /* Line */);
1017
+ return comment && index !== 0 ? isPreviousLineEmpty(comment) && typeof join_item(arr2[index - 1], item, index === 1 ? void 0 : arr2[index - 2]) === "string" ? [hardline, hardline, printed2] : [hardline, printed2] : printed2;
1018
+ }
1019
+ }
1020
+ function is_params_like(arr2) {
1021
+ return arr2.some(function isComma(item) {
1022
+ switch (item.nodeType) {
1023
+ case NodeType.PunctuationToken:
1024
+ return TK[","] === item.tk;
1025
+ case NodeType.MacroGroup:
1026
+ return !!item.sep && isComma(item.sep) || is_params_like(item.segments);
1027
+ }
1028
+ });
1029
+ }
1030
+ function join_item(item, next, prev) {
1031
+ if (is_PunctuationToken(item)) {
1032
+ switch (item.tk) {
1033
+ case TK[","]:
1034
+ case TK[";"]:
1035
+ return line;
1036
+ case TK["::"]:
1037
+ case TK[".."]:
1038
+ case TK["..."]:
1039
+ case TK["."]:
1040
+ case TK["#"]:
1041
+ return "";
1042
+ case TK["!"]:
1043
+ if (prev && is_ident(prev) && is_DelimGroup(next)) {
1044
+ return next.segments.dk === DelimKind["{}"] ? " " : "";
1045
+ }
1046
+ break;
1047
+ case TK["@"]:
1048
+ return is_ident(next) && (!prev || is_MacroGroup(prev) || is_DelimGroup(prev)) ? "" : " ";
1049
+ }
1050
+ return is_unary_token(item) && //
1051
+ (!prev || !is_ident(prev)) && can_unary(next) ? "" : " ";
1052
+ }
1053
+ switch (is_PunctuationToken(next) ? next.tk : TK.None) {
1054
+ case TK[","]:
1055
+ case TK[";"]:
1056
+ case TK[":"]:
1057
+ case TK["::"]:
1058
+ case TK[".."]:
1059
+ case TK["..."]:
1060
+ case TK["."]:
1061
+ return "";
1062
+ case TK["!"]:
1063
+ if (is_ident(item)) {
1064
+ return "";
1065
+ }
1066
+ }
1067
+ if (is_match_any(item)) {
1068
+ return line;
1069
+ }
1070
+ {
1071
+ const sep_tk = is_MacroGroup(item) && item.sep && is_PunctuationToken(item.sep) ? item.sep.tk : TK.None;
1072
+ switch (sep_tk) {
1073
+ case TK["::"]:
1074
+ case TK["."]:
1075
+ return "";
1076
+ case TK[","]:
1077
+ case TK[";"]:
1078
+ return sep_tk === maybe_tk(next) ? ifBreak(line, " ", { groupId: getMacroGroupId(item) }) : line;
1079
+ }
1080
+ }
1081
+ if (is_optional_token(item)) {
1082
+ switch (item.segments[0].tk) {
1083
+ case TK["+"]:
1084
+ case TK["|"]:
1085
+ return " ";
1086
+ case TK["::"]:
1087
+ return "";
1088
+ }
1089
+ if (is_unary_token(item.segments[0])) {
1090
+ return "";
1091
+ }
1092
+ }
1093
+ if (is_DelimGroup(item) || is_MacroGroup(item)) {
1094
+ if (item.segments.dk === DelimKind["{}"]) {
1095
+ return line;
1096
+ }
1097
+ if (is_MacroGroup(item) && item.segments.length === 2) {
1098
+ const { 0: left, 1: right } = item.segments;
1099
+ if (is_PunctuationToken(left) && is_DelimGroup(right) && left.tk === TK["#"] && right.segments.dk === DelimKind["[]"]) {
1100
+ return hardline;
1101
+ }
1102
+ }
1103
+ return isParamsLike || is_tk(next) ? " " : line;
1104
+ }
1105
+ const next_1 = next !== last_of(arr) && arr[arr.indexOf(next) + 1];
1106
+ if (is_ident(item) && is_DelimGroup(next) && next.segments.dk === DelimKind["()"]) {
1107
+ if (!next_1 || !is_match_any(next_1)) {
1108
+ return "";
1109
+ }
1110
+ }
1111
+ if (is_match_any(next) && (!is_DelimGroup(next) || next_1 && is_match_any(next_1))) {
1112
+ return line;
1113
+ }
1114
+ return " ";
1115
+ }
1116
+ }
1117
+ function is_ident(item) {
1118
+ switch (item.nodeType) {
1119
+ case NodeType.Identifier:
1120
+ return true;
1121
+ case NodeType.MacroParameterDeclaration:
1122
+ return item.ty.name === "ident";
1123
+ default:
1124
+ return false;
1125
+ }
1126
+ }
1127
+ function is_tk(item) {
1128
+ return is_PunctuationToken(item) || is_optional_token(item);
1129
+ }
1130
+ function maybe_tk(item) {
1131
+ switch (item.nodeType) {
1132
+ case NodeType.PunctuationToken:
1133
+ return item.tk;
1134
+ case NodeType.MacroGroup:
1135
+ return is_optional_token(item) ? item.segments[0].tk : TK.None;
1136
+ default:
1137
+ return TK.None;
1138
+ }
1139
+ }
1140
+ function isDeclStart(item, next) {
1141
+ if (is_Identifier(item)) {
1142
+ switch (item.name) {
1143
+ case "fn":
1144
+ case "mod":
1145
+ case "use":
1146
+ case "struct":
1147
+ case "trait":
1148
+ case "union":
1149
+ case "enum":
1150
+ case "impl":
1151
+ case "type":
1152
+ case "let":
1153
+ case "static":
1154
+ case "const":
1155
+ if (is_ident(next)) {
1156
+ return true;
1157
+ }
1158
+ }
1159
+ }
1160
+ return false;
1161
+ }
1162
+ function is_match_any(item) {
1163
+ return !!item && (is_MacroGroup(item) && !item.sep && (item.kind === "*" || item.kind === "+") && item.segments.length === 1 && is_MacroParameterDeclaration(item.segments[0]) && item.segments[0].ty.name === "tt" || is_DelimGroup(item) && item.segments.length === 1 && is_match_any(item.segments[0]));
1164
+ }
1165
+ }
1166
+ function printRuleTransform(print4, node, t = getDelimChars(node.transform)) {
1167
+ const text = node.transform.loc.sliceText();
1168
+ const fline = is_MacroInlineRuleDeclaration(node) ? hardline : line;
1169
+ if (/^. *\n/.test(text)) {
1170
+ return [
1171
+ dedentToRoot([
1172
+ t.left,
1173
+ fline,
1174
+ text.slice(1, -1).replace(/^ *\n|\n\s*$/g, "")
1175
+ ]),
1176
+ fline,
1177
+ t.right
1178
+ ];
1179
+ } else if (/\n/.test(text) && node.transform.length === 1) {
1180
+ const segment = node.transform[0];
1181
+ if (is_DelimGroup(segment) || is_MacroGroup(segment)) {
1182
+ const inner = is_DelimGroup(segment) ? getDelimChars(segment.segments) : { left: "$(", right: `)${segment.sep?.loc.getOwnText() ?? ""}${segment.kind}` };
1183
+ return [
1184
+ dedentToRoot([
1185
+ t.left,
1186
+ [
1187
+ indent(indent([fline, inner.left])),
1188
+ line,
1189
+ segment.segments.loc.sliceText(1, -1).replace(/^ *\n|\n\s*$/g, ""),
1190
+ indent(indent([line, inner.right]))
1191
+ ]
1192
+ ]),
1193
+ fline,
1194
+ t.right
1195
+ ];
1196
+ }
1197
+ }
1198
+ return text;
1199
+ }
1200
+ function is_AssignmentOrVariableDeclarator(node) {
1201
+ return is_ReassignmentNode(node) || is_VariableDeclarationNode(node);
1202
+ }
1203
+ function hasLeadingOwnLineComment(node) {
1204
+ if (is_NodeWithBodyOrCases(node) && hasComment(node, 2 /* Leading */, is_Attribute)) {
1205
+ return true;
1206
+ }
1207
+ return hasComment(
1208
+ node,
1209
+ 2 /* Leading */,
1210
+ (comment) => hasNewline(end(comment)) && !getContext().options.danglingAttributes.includes(comment)
1211
+ );
1212
+ }
1213
+ function isComplexDestructuring(node) {
1214
+ if (is_ReassignmentExpression(node)) {
1215
+ const leftNode = node.left;
1216
+ return is_StructLiteral(leftNode) && //
1217
+ leftNode.properties.length > 2 && leftNode.properties.some((property) => is_StructLiteralProperty(property) || is_StructLiteralPropertySpread(property));
1218
+ }
1219
+ if (is_VariableDeclarationNode(node) || is_MatchExpressionCase(node) || is_LetScrutinee(node)) {
1220
+ const leftNode = node.pattern;
1221
+ return is_StructPattern(leftNode) && //
1222
+ leftNode.properties.length > 2 && leftNode.properties.some((property) => is_StructPatternPropertyDestructured(property));
1223
+ }
1224
+ return false;
1225
+ }
1226
+ function isArrowFunctionVariableDeclarator(node) {
1227
+ return is_VariableDeclarationNode(node) && node.expression && is_ClosureFunctionExpression(node.expression);
1228
+ }
1229
+ function isObjectPropertyWithShortKey(node, keyDoc) {
1230
+ if (!is_StructProperty(node))
1231
+ return false;
1232
+ keyDoc = cleanDoc(keyDoc);
1233
+ const MIN_OVERLAP_FOR_BREAK = 3;
1234
+ return typeof keyDoc === "string" && keyDoc.length < getContext().options.tabWidth + MIN_OVERLAP_FOR_BREAK;
1235
+ }
1236
+ function print_CallExpression_end(print4, node) {
1237
+ return [f`::${printTypeArguments(print4, node)}`, printCallArguments(print4, node)];
1238
+ }
1239
+ function printCallExpression(print4, node) {
1240
+ if (shouldPrint_CallExpression_chain(node) && !pathCall(node, "callee", (node2) => needsParens(node2))) {
1241
+ return printMemberChain(print4, node);
1242
+ }
1243
+ const contents = [print4("callee"), ...print_CallExpression_end(print4, node)];
1244
+ if (is_CallExpression_or_CallLikeMacroInvocation(node.callee)) {
1245
+ return group(contents);
1246
+ }
1247
+ return contents;
1248
+ }
1249
+ function printTypeAnnotation(print4, node) {
1250
+ return node.typeAnnotation && !is_MissingNode(node.typeAnnotation) ? [": ", print4("typeAnnotation")] : "";
1251
+ }
1252
+ function printAnnotatedPattern(print4, node) {
1253
+ return [print4("pattern"), printTypeAnnotation(print4, node)];
1254
+ }
1255
+ function isLoneShortArgument(node) {
1256
+ if (hasComment(node)) {
1257
+ return false;
1258
+ }
1259
+ if (is_Identifier(node) && is_short(node.name) || is_LiteralNumberLike(node) && !hasComment(node)) {
1260
+ return true;
1261
+ }
1262
+ if (is_LiteralStringLike(node)) {
1263
+ return is_short(node.value) && !node.value.includes("\n");
1264
+ }
1265
+ return is_LiteralBooleanLike(node);
1266
+ }
1267
+ var toLayout = ["break-after-operator", "never-break-after-operator", "fluid", "break-lhs", "chain", "chain-tail", "chain-tail-arrow-chain", "only-left"];
1268
+ function printMemberExpression(print4, node) {
1269
+ const objectDoc = print4("expression");
1270
+ const lookupDoc = printMemberLookup(print4, node);
1271
+ const shouldInline = shouldInlineMemberExpression(node, objectDoc);
1272
+ return label(objectDoc.label === "member-chain" ? "member-chain" : "member", [
1273
+ objectDoc,
1274
+ shouldInline ? lookupDoc : group(indent([softline, lookupDoc]))
1275
+ ]);
1276
+ }
1277
+ function shouldInlineMemberExpression(node, objectDoc) {
1278
+ const { path } = getContext();
1279
+ const parent = getParentNode();
1280
+ let i = 0;
1281
+ let nmparent = parent;
1282
+ while (nmparent && (is_MemberExpression(nmparent) || is_PostfixExpression(nmparent))) {
1283
+ nmparent = path.getParentNode(i++);
1284
+ }
1285
+ const shouldInline = nmparent && (is_ExpressionPath(nmparent) || is_ReassignmentNode(nmparent) && !is_Identifier(nmparent.left)) || !node.computed || is_Identifier(node.expression) && is_Identifier(node.property) && !is_MemberExpression(parent) || is_AssignmentOrVariableDeclarator(parent) && (is_CallExpression_or_CallLikeMacroInvocation(node.expression) && node.expression.arguments.length > 0 || is_PostfixExpression(node.expression) && is_CallExpression_or_CallLikeMacroInvocation(node.expression.expression) && node.expression.expression.arguments.length > 0 || objectDoc.label === "member-chain");
1286
+ return shouldInline;
1287
+ }
1288
+ function printAssignment(leftDoc, operator, rightPropertyName) {
1289
+ const assignmentNode = getNode();
1290
+ const rightNode = assignmentNode[rightPropertyName];
1291
+ if (!rightNode)
1292
+ return group(leftDoc);
1293
+ const layout = chooseLayout();
1294
+ const rightDoc = getPrintFn()(rightPropertyName, { assignmentLayout: layout });
1295
+ const res = function() {
1296
+ switch (layout) {
1297
+ case 0 /* break-after-operator */:
1298
+ return group([group(leftDoc), operator, group(indent([line, rightDoc]))]);
1299
+ case 1 /* never-break-after-operator */:
1300
+ return group([group(leftDoc), operator, " ", rightDoc]);
1301
+ case 2 /* fluid */: {
1302
+ const groupId = Symbol("assignment");
1303
+ return group([
1304
+ group(leftDoc),
1305
+ operator,
1306
+ //
1307
+ group(indent(line), { id: groupId }),
1308
+ lineSuffixBoundary,
1309
+ indentIfBreak(rightDoc, { groupId })
1310
+ ]);
1311
+ }
1312
+ case 3 /* break-lhs */:
1313
+ return group([leftDoc, operator, " ", group(rightDoc)]);
1314
+ case 4 /* chain */:
1315
+ return [group(leftDoc), operator, line, rightDoc];
1316
+ case 5 /* chain-tail */:
1317
+ return [group(leftDoc), operator, indent([line, rightDoc])];
1318
+ case 6 /* chain-tail-arrow-chain */:
1319
+ return [group(leftDoc), operator, rightDoc];
1320
+ default:
1321
+ exit.never();
1322
+ }
1323
+ }();
1324
+ return label(toLayout[layout], res);
1325
+ function chooseLayout() {
1326
+ if (is_ReassignmentExpression(assignmentNode) && is_printing_macro() || is_GenericParameterDeclaration(assignmentNode) || is_TypeCallNamedArgument(assignmentNode)) {
1327
+ return 1 /* never-break-after-operator */;
1328
+ }
1329
+ const isTail = !is_ReassignmentNode(rightNode);
1330
+ const shouldUseChainFormatting = getContext().path.match(
1331
+ is_ReassignmentNode,
1332
+ is_AssignmentOrVariableDeclarator,
1333
+ (node) => !isTail || !is_ExpressionStatement(node) && !is_VariableDeclarationNode(node)
1334
+ );
1335
+ if (shouldUseChainFormatting) {
1336
+ return !isTail ? 4 /* chain */ : is_ClosureFunctionExpression(rightNode) && is_ClosureFunctionExpression(rightNode.expression) ? 6 /* chain-tail-arrow-chain */ : 5 /* chain-tail */;
1337
+ }
1338
+ const isHeadOfLongChain = !isTail && is_ReassignmentNode(rightNode.right);
1339
+ if (isHeadOfLongChain || hasLeadingOwnLineComment(rightNode)) {
1340
+ return 0 /* break-after-operator */;
1341
+ }
1342
+ if (isComplexDestructuring(assignmentNode) || hasComplexGenerics(assignmentNode) || hasComplexTypeAnnotation(assignmentNode) || isArrowFunctionVariableDeclarator(assignmentNode) && canBreak(leftDoc)) {
1343
+ return 3 /* break-lhs */;
1344
+ }
1345
+ const hasShortKey = isObjectPropertyWithShortKey(assignmentNode, leftDoc);
1346
+ if (pathCall(assignmentNode, rightPropertyName, (rightNode2) => shouldBreakAfterOperator(rightNode2, hasShortKey))) {
1347
+ return 0 /* break-after-operator */;
1348
+ }
1349
+ if (hasShortKey || is_Literal(rightNode)) {
1350
+ return 1 /* never-break-after-operator */;
1351
+ }
1352
+ return 2 /* fluid */;
1353
+ }
1354
+ function shouldBreakAfterOperator(rightNode2, hasShortKey) {
1355
+ if (is_MemberExpression(rightNode2) && shouldInlineMemberExpression(rightNode2, getPrintFn()("expression"))) {
1356
+ return false;
1357
+ }
1358
+ if (is_BinaryishExpression(rightNode2) && !shouldInlineLogicalExpression(rightNode2)) {
1359
+ return true;
1360
+ }
1361
+ if (is_IfBlockExpression(rightNode2)) {
1362
+ return false;
1363
+ }
1364
+ if (hasShortKey) {
1365
+ return false;
1366
+ }
1367
+ return function unwrap(node) {
1368
+ if (is_UnaryExpression(node) || is_PostfixExpression(node)) {
1369
+ return pathCall(node, "expression", unwrap);
1370
+ }
1371
+ if (is_LiteralStringLike(node)) {
1372
+ return true;
1373
+ }
1374
+ return isPoorlyBreakableMemberOrCallChain(node);
1375
+ }(rightNode2);
1376
+ function isPoorlyBreakableMemberOrCallChain(topNode) {
1377
+ return function unwrap(node) {
1378
+ if (is_MemberExpression(node) || is_PostfixExpression(node) || is_UnaryExpression(node)) {
1379
+ return pathCall(node, "expression", unwrap);
1380
+ }
1381
+ if (is_ExpressionPath(node)) {
1382
+ return pathCall(node, "namespace", (namespace) => !namespace || unwrap(namespace));
1383
+ }
1384
+ if (is_CallExpression_or_CallLikeMacroInvocation(node)) {
1385
+ const doc = printCallExpression(getPrintFn(), node);
1386
+ if (doc.label === "member-chain") {
1387
+ return false;
1388
+ }
1389
+ const args = node.arguments;
1390
+ const isPoorlyBreakableCall = args.length === 0 || args.length === 1 && isLoneShortArgument(args[0]);
1391
+ if (!isPoorlyBreakableCall) {
1392
+ return false;
1393
+ }
1394
+ if (hasComplexTypeArguments(node)) {
1395
+ return false;
1396
+ }
1397
+ return pathCall(node, "callee", unwrap);
1398
+ }
1399
+ return topNode === node ? false : is_Identifier(node);
1400
+ }(topNode);
1401
+ }
1402
+ }
1403
+ }
1404
+ function is_MemberExpression_with_RangeOrLiteral_Property(node) {
1405
+ return !!node && is_MemberExpression(node) && (node.computed ? is_Literal_or_SimpleRangeLiteral(node.property) : is_Literal(node.property));
1406
+ }
1407
+ function is_Literal_or_SimpleRangeLiteral(node) {
1408
+ return is_Literal(node) ? true : is_RangeLiteral(node) ? (!node.lower || is_Literal(node.lower)) && (!node.upper || is_Literal(node.upper)) : false;
1409
+ }
1410
+ function printMemberLookup(print4, node) {
1411
+ return !node.computed ? [".", print4("property")] : is_Literal_or_SimpleRangeLiteral(node.property) ? ["[", print4("property"), "]"] : group(["[", indent([softline, print4("property")]), softline, "]"]);
1412
+ }
1413
+ function shouldPrint_CallExpression_chain(node) {
1414
+ return is_MemberAccessLike(node.callee) || is_CallExpression_or_CallLikeMacroInvocation(node.callee);
1415
+ }
1416
+ function is_MemberAccessLike(node) {
1417
+ switch (node.nodeType) {
1418
+ case NodeType.ExpressionPath:
1419
+ case NodeType.MemberExpression:
1420
+ return true;
1421
+ default:
1422
+ return false;
1423
+ }
1424
+ }
1425
+ function printMemberChain(print4, node) {
1426
+ const parent = getParentNode();
1427
+ const isExpressionStatement = !parent || is_ExpressionStatement(parent);
1428
+ const { printedNodes, groups } = splitCallChains(node);
1429
+ const shouldMerge = groups.length >= 2 && !hasComment(groups[1][0].node) && shouldNotWrap(groups);
1430
+ const printedGroups = groups.map(printGroup);
1431
+ const oneLine = printedGroups;
1432
+ const cutoff = shouldMerge ? 3 : 2;
1433
+ const nodeHasComment = printedNodes.slice(1, -1).some(({ node: node2 }) => hasComment(node2, 2 /* Leading */)) || printedNodes.slice(0, -1).some(({ node: node2 }) => hasComment(node2, 4 /* Trailing */)) || groups[cutoff] && hasComment(groups[cutoff][0].node, 2 /* Leading */);
1434
+ if (groups.length <= cutoff && !nodeHasComment) {
1435
+ return isLongCurriedCallExpression(node) ? oneLine : group(oneLine);
1436
+ }
1437
+ const lastNodeBeforeIndent = last_of(groups[shouldMerge ? 1 : 0]).node;
1438
+ const shouldHaveEmptyLineBeforeIndent = !is_CallExpression_or_CallLikeMacroInvocation(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
1439
+ const expanded = [
1440
+ printGroup(groups[0]),
1441
+ shouldMerge ? groups.slice(1, 2).map(printGroup) : "",
1442
+ shouldHaveEmptyLineBeforeIndent ? hardline : "",
1443
+ printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))
1444
+ ];
1445
+ const callExpressions = printedNodes.map(({ node: node2 }) => node2).filter(is_CallExpression_or_CallLikeMacroInvocation);
1446
+ const result = nodeHasComment || callExpressions.length > 2 && callExpressions.some((expr) => expr.arguments.some((arg) => !isSimpleCallArgument(arg, 0))) || printedGroups.slice(0, -1).some(willBreak) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments() ? group(expanded) : [shouldHaveEmptyLineBeforeIndent || willBreak(oneLine) ? breakParent : "", conditionalGroup([oneLine, expanded])];
1447
+ return label("member-chain", result);
1448
+ function shouldInsertEmptyLineAfter(node2) {
1449
+ let start8 = end(node2);
1450
+ const last = getNextNonSpaceNonCommentCharacterIndex(node2);
1451
+ const { originalText } = getContext().options;
1452
+ while (start8 < last) {
1453
+ if (originalText.charAt(start8) === ")") {
1454
+ return isNextLineEmptyAfterIndex(start8 + 1);
1455
+ }
1456
+ start8++;
1457
+ }
1458
+ return isNextLineEmpty(node2);
1459
+ }
1460
+ function isFactory(name) {
1461
+ return /^[A-Z]|^[$_]+$/.test(name);
1462
+ }
1463
+ function isShort(name) {
1464
+ return name.length <= getContext().options.tabWidth;
1465
+ }
1466
+ function shouldNotWrap(groups2) {
1467
+ const hasComputed = groups2[1].length > 0 && is_MemberExpression(groups2[1][0].node) && groups2[1][0].node.computed;
1468
+ if (groups2[0].length === 1) {
1469
+ const firstNode = groups2[0][0].node;
1470
+ return is_Identifier(firstNode) && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed);
1471
+ }
1472
+ const lastNode = last_of(groups2[0]).node;
1473
+ const lastNodeLeft = is_ExpressionPath(lastNode) ? lastNode.namespace : is_MemberExpression(lastNode) ? lastNode.expression : void 0;
1474
+ return lastNodeLeft && is_Identifier(lastNodeLeft) && (isFactory(lastNodeLeft.name) || hasComputed);
1475
+ }
1476
+ function printGroup(g) {
1477
+ const printed = [];
1478
+ if (printedNodes[0] === g[0]) {
1479
+ for (const item of printedNodes) {
1480
+ if (item.needsParens)
1481
+ printed.unshift("(");
1482
+ }
1483
+ }
1484
+ for (const item of g) {
1485
+ printed.push(item.printed);
1486
+ if (item.needsParens)
1487
+ printed.push(")");
1488
+ }
1489
+ return printed;
1490
+ }
1491
+ function printIndentedGroup(groups2) {
1492
+ if (groups2.length === 0)
1493
+ return "";
1494
+ return indent(group([hardline, join(hardline, groups2.map(printGroup))]));
1495
+ }
1496
+ function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
1497
+ const lastGroupNode = last_of(last_of(groups)).node;
1498
+ const lastGroupDoc = last_of(printedGroups);
1499
+ return is_CallExpression_or_CallLikeMacroInvocation(lastGroupNode) && willBreak(lastGroupDoc) && callExpressions.slice(0, -1).some((node2) => node2.arguments.some(is_ClosureFunctionExpression));
1500
+ }
1501
+ function splitCallChains(topNode) {
1502
+ const printedNodes2 = [
1503
+ {
1504
+ node: topNode,
1505
+ needsParens: false,
1506
+ printed: print_CallExpression_end(print4, node)
1507
+ }
1508
+ ];
1509
+ pathCall(topNode, "callee", function READ_LEFT(node2) {
1510
+ if (is_CallExpression_or_CallLikeMacroInvocation(node2) && shouldPrint_CallExpression_chain(node2)) {
1511
+ unshift(print_CallExpression_end(print4, node2), shouldInsertEmptyLineAfter(node2));
1512
+ pathCall(node2, "callee", READ_LEFT);
1513
+ } else if (is_MemberExpression(node2)) {
1514
+ unshift(printMemberLookup(print4, node2));
1515
+ pathCall(node2, "expression", READ_LEFT);
1516
+ } else if (is_ExpressionPath(node2)) {
1517
+ unshift(["::", print4("segment")]);
1518
+ if (node2.namespace) {
1519
+ pathCall(node2, "namespace", READ_LEFT);
1520
+ }
1521
+ } else if (is_PostfixExpression(node2)) {
1522
+ unshift(is_UnwrapExpression(node2) ? "?" : ".await");
1523
+ pathCall(node2, "expression", READ_LEFT);
1524
+ } else {
1525
+ printedNodes2.unshift({ node: node2, needsParens: false, printed: print4() });
1526
+ }
1527
+ function unshift(printed, needsHardlineAfter = false) {
1528
+ printedNodes2.unshift({
1529
+ node: node2,
1530
+ needsParens: is_MemberAccessLike(node2) && needsParens(node2),
1531
+ printed: [withComments(node2, printed), needsHardlineAfter ? hardline : ""]
1532
+ });
1533
+ }
1534
+ });
1535
+ const groups2 = spread(function* () {
1536
+ let i = 0;
1537
+ let currentItem = printedNodes2[i];
1538
+ function testNextItem(fn) {
1539
+ return i + 1 < printedNodes2.length && fn(printedNodes2[i + 1]);
1540
+ }
1541
+ function readGroup(fn) {
1542
+ return spread(function* () {
1543
+ for (var _item of fn()) {
1544
+ yield currentItem;
1545
+ if (++i < printedNodes2.length)
1546
+ currentItem = printedNodes2[i];
1547
+ else
1548
+ break;
1549
+ }
1550
+ });
1551
+ }
1552
+ function* loop(condition) {
1553
+ while (condition(currentItem))
1554
+ yield currentItem;
1555
+ }
1556
+ function* until(condition) {
1557
+ while (!condition(currentItem))
1558
+ yield currentItem;
1559
+ }
1560
+ yield readGroup(function* () {
1561
+ const isCallExpression = is_CallExpression_or_CallLikeMacroInvocation(currentItem.node);
1562
+ yield currentItem;
1563
+ yield* loop(
1564
+ ({ node: node2, needsParens: needsParens2 }) => is_PostfixExpression(node2) || is_CallExpression_or_CallLikeMacroInvocation(node2) || is_MemberExpression_with_RangeOrLiteral_Property(node2) || needsParens2
1565
+ );
1566
+ if (!isCallExpression) {
1567
+ yield* loop(
1568
+ ({ node: node2, needsParens: needsParens2 }) => is_MemberAccessLike(node2) && //
1569
+ testNextItem(({ node: node3 }) => is_MemberAccessLike(node3))
1570
+ );
1571
+ }
1572
+ });
1573
+ while (i < printedNodes2.length) {
1574
+ yield readGroup(function* () {
1575
+ let isCallExpression = false;
1576
+ yield* until(
1577
+ ({ node: node2 }) => (isCallExpression = is_CallExpression_or_CallLikeMacroInvocation(node2)) || //
1578
+ hasComment(node2, 4 /* Trailing */)
1579
+ );
1580
+ yield currentItem;
1581
+ if (isCallExpression) {
1582
+ yield* loop(({ node: node2 }) => is_MemberExpression_with_RangeOrLiteral_Property(node2));
1583
+ yield* until(
1584
+ ({ node: node2 }) => is_MemberAccessLike(node2) || //
1585
+ hasComment(node2, 4 /* Trailing */)
1586
+ );
1587
+ }
1588
+ });
1589
+ }
1590
+ });
1591
+ return { printedNodes: printedNodes2, groups: groups2 };
1592
+ }
1593
+ }
1594
+ function isSimpleCallArgument(node, depth) {
1595
+ if (depth >= 2)
1596
+ return false;
1597
+ if (is_IdentifierOrIndex(node)) {
1598
+ return true;
1599
+ }
1600
+ if (is_Literal(node)) {
1601
+ return !is_LiteralStringLike(node) || !node.value.includes("\n");
1602
+ }
1603
+ if (is_ArrayOrTupleLiteral(node)) {
1604
+ return node.items.every(isChildSimple);
1605
+ }
1606
+ if (is_StructLiteral(node)) {
1607
+ return isSimpleCallArgument(node.struct, depth) && node.properties.every(
1608
+ (prop) => is_StructLiteralPropertySpread(prop) ? isChildSimple(prop.expression) : is_StructLiteralProperty(prop) ? isChildSimple(prop.value) : true
1609
+ );
1610
+ }
1611
+ if (is_CallExpression_or_CallLikeMacroInvocation(node)) {
1612
+ return isSimpleCallArgument(node.callee, depth) && (node.typeArguments ?? []).every(isChildSimple) && node.arguments.every(isChildSimple);
1613
+ }
1614
+ if (is_MemberExpression(node)) {
1615
+ return isSimpleCallArgument(node.expression, depth) && isSimpleCallArgument(node.property, depth);
1616
+ }
1617
+ if (is_ExpressionTypeCast(node)) {
1618
+ return isSimpleCallArgument(node.typeCallee, depth) && node.typeArguments.every(isChildSimple);
1619
+ }
1620
+ if (is_ExpressionPath(node)) {
1621
+ const namespace = node.namespace;
1622
+ return !namespace || isSimpleCallArgument(namespace, depth);
1623
+ }
1624
+ if (is_UnaryExpression(node) || is_PostfixExpression(node)) {
1625
+ return isSimpleCallArgument(node.expression, depth);
1626
+ }
1627
+ return false;
1628
+ function isChildSimple(child) {
1629
+ return isSimpleCallArgument(child, depth + 1);
1630
+ }
1631
+ }
1632
+ function isLongCurriedCallExpression(node) {
1633
+ const parent = getParentNode();
1634
+ return is_CallExpression_or_CallLikeMacroInvocation(node) && is_CallExpression_or_CallLikeMacroInvocation(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
1635
+ }
1636
+ function printTypeArguments(print4, node) {
1637
+ return !node.typeArguments ? "" : node.typeArguments.length === 0 ? ["<", printDanglingCommentsForInline(node, "typeArguments" /* typeArguments */), ">"] : hasComplexTypeArguments(node) ? group(
1638
+ [
1639
+ "<",
1640
+ //
1641
+ indent([softline, print4.join("typeArguments", [",", line])]),
1642
+ softline,
1643
+ ">"
1644
+ ],
1645
+ { id: getTypeParametersGroupId(node) }
1646
+ ) : ["<", print4.join("typeArguments", ", "), ">"];
1647
+ }
1648
+ function printLtParameters(print4, node) {
1649
+ return !node.ltParameters ? "" : node.ltParameters.length === 0 ? ["for<", printDanglingCommentsForInline(node, "ltParameters" /* ltParameters */), "> "] : hasComplexLtParameters(node) ? group(
1650
+ [
1651
+ "for<",
1652
+ //
1653
+ indent([softline, print4.join("ltParameters", [",", line])]),
1654
+ softline,
1655
+ "> "
1656
+ ],
1657
+ { id: getTypeParametersGroupId(node) }
1658
+ ) : ["for<", print4.join("ltParameters", ", "), "> "];
1659
+ }
1660
+ function printGenerics(print4, node) {
1661
+ return group(
1662
+ !node.generics ? "" : hasComplexGenerics(node) ? [
1663
+ "<",
1664
+ indent([softline, print4.join("generics", [",", line])]),
1665
+ //
1666
+ hasMultipleHeritage(node) ? indent([softline, ">"]) : [softline, ">"]
1667
+ ] : [
1668
+ "<",
1669
+ print4.join("generics", ", "),
1670
+ //
1671
+ printDanglingCommentsForInline(node, "generics" /* generics */),
1672
+ ">"
1673
+ ]
1674
+ );
1675
+ }
1676
+ function getPrintedTypeBounds(print4, node) {
1677
+ if (!hasTypeBounds(node) || node.typeBounds.length === 0)
1678
+ return "";
1679
+ if (node.typeBounds.length === 1)
1680
+ return print4.map("typeBounds");
1681
+ const printed = print4.join("typeBounds", (_, __, prev) => !prev ? " +" : [" +", line]);
1682
+ return [printed.shift(), indent([line, printed])];
1683
+ }
1684
+ function printTypeBounds(operator, print4, node) {
1685
+ if (!hasTypeBounds(node))
1686
+ return "";
1687
+ const printed = getPrintedTypeBounds(print4, node);
1688
+ return printed ? group([operator, " ", printed]) : operator;
1689
+ }
1690
+ function printLtBounds(left, print4, node) {
1691
+ return group(
1692
+ !node.ltBounds ? "" : node.ltBounds.length === 0 ? [left, " "] : [left, " ", print4.map("ltBounds", (typeBound, i) => i === 0 ? print4() : indent([line, "+ ", print4()]))]
1693
+ );
1694
+ }
1695
+ function printWhereBounds(print4, node) {
1696
+ if (!node.whereBounds || node.whereBounds.length === 0)
1697
+ return "";
1698
+ return adjustDeclarationClause(
1699
+ node,
1700
+ //
1701
+ "where",
1702
+ print4.join("whereBounds", [",", line])
1703
+ );
1704
+ }
1705
+ function printDeclarationTypeBounds(print4, node, operator) {
1706
+ return hasTypeBounds(node) ? adjustDeclarationClause(node, operator, getPrintedTypeBounds(print4, node)) : "";
1707
+ }
1708
+ function printImplTraitForType(print4, node) {
1709
+ return node.trait ? [print4("trait"), adjustDeclarationClause(node, "for", print4("typeTarget"))] : print4("typeTarget");
1710
+ }
1711
+ function adjustDeclarationClause(node, clause, content) {
1712
+ const isTypeBoundsClause = clause === ":" || clause === " =";
1713
+ return (clause === "where" || hasMultipleHeritage(node) ? indent : Identity)([
1714
+ clause === "->" ? hasMultipleHeritage(node) && node.whereBounds.length > 1 ? line : " " : clause === "where" ? line : isTypeBoundsClause ? hasMultipleHeritage(node) ? softline : "" : line,
1715
+ clause,
1716
+ content && group(
1717
+ clause === "where" ? indent([line, content]) : clause === "->" || isTypeBoundsClause ? [" ", content] : [line, content]
1718
+ )
1719
+ ]);
1720
+ }
1721
+ function hasNonWhereHeritageClause(node) {
1722
+ switch (node.nodeType) {
1723
+ case NodeType.FunctionDeclaration:
1724
+ return !!node.returnType;
1725
+ case NodeType.StructDeclaration:
1726
+ case NodeType.TupleStructDeclaration:
1727
+ case NodeType.UnionDeclaration:
1728
+ case NodeType.EnumDeclaration:
1729
+ return false;
1730
+ case NodeType.TypeAliasDeclaration:
1731
+ case NodeType.TraitDeclaration:
1732
+ case NodeType.TraitAliasDeclaration:
1733
+ return hasTypeBounds(node);
1734
+ case NodeType.ImplDeclaration:
1735
+ case NodeType.NegativeImplDeclaration:
1736
+ return !!node.trait;
1737
+ }
1738
+ }
1739
+ function hasMultipleHeritage(node) {
1740
+ return !!node.whereBounds && hasNonWhereHeritageClause(node);
1741
+ }
1742
+ var getMacroGroupId = createGroupIdMapper("MacroGroup");
1743
+ var getHeritageGroupId = createGroupIdMapper("heritageGroup");
1744
+ var getTypeParametersGroupId = createGroupIdMapper("typeParameters");
1745
+ function createGroupIdMapper(description) {
1746
+ const groupIds = /* @__PURE__ */ new WeakMap();
1747
+ return (node) => Map_get(groupIds, node, () => Symbol(description));
1748
+ }
1749
+ function printDanglingCommentsForInline(node, marker) {
1750
+ const hasOnlyBlockComments = !hasComment(node, 32 /* Line */ | 8 /* Dangling */, (comment) => !marker || comment.marker === marker) || is_Program(node);
1751
+ const printed = printDanglingComments(node, hasOnlyBlockComments, marker);
1752
+ return printed && (hasOnlyBlockComments && !is_Program(node) ? willBreak(printed) ? [indent([hardline, printed]), hardline] : [printed] : [printed, hardline]);
1753
+ }
1754
+ function isFormatLikeCall(node) {
1755
+ if (is_Identifier(node.callee) && !node.typeArguments) {
1756
+ const [first, ...rest] = node.arguments;
1757
+ if (is_Literal(first) && is_LiteralStringLike(first) && first.value.includes("{}") && rest.every(is_Identifier)) {
1758
+ return true;
1759
+ }
1760
+ }
1761
+ return false;
1762
+ }
1763
+ var ArgExpansionBailout = class extends Error {
1764
+ };
1765
+ function printCallArguments(print4, node) {
1766
+ const args = node.arguments;
1767
+ const { left: LEFT, right: RIGHT } = getDelimChars(args);
1768
+ if (args.length === 0)
1769
+ return [LEFT, printDanglingCommentsForInline(node, "arguments" /* arguments */), RIGHT];
1770
+ if (args.length === 2 && isFormatLikeCall(node)) {
1771
+ return [LEFT, print4(["arguments", 0]), ", ", print4(["arguments", 1]), RIGHT];
1772
+ }
1773
+ let anyArgEmptyLine = false;
1774
+ let hasEmptyLineFollowingFirstArg = false;
1775
+ const lastArgIndex = args.length - 1;
1776
+ const trailingComma = "";
1777
+ const printedArguments = print4.map("arguments", (arg, index, arr) => {
1778
+ if (index === lastArgIndex) {
1779
+ return [print4()];
1780
+ } else if (isNextLineEmpty(arg)) {
1781
+ if (index === 0)
1782
+ hasEmptyLineFollowingFirstArg = true;
1783
+ anyArgEmptyLine = true;
1784
+ return [print4(), ",", hardline, hardline];
1785
+ } else {
1786
+ return [print4(), ",", line];
1787
+ }
1788
+ });
1789
+ if (anyArgEmptyLine || isFunctionCompositionArgs(args)) {
1790
+ return allArgsBrokenOut();
1791
+ }
1792
+ const shouldGroupFirst = shouldGroupFirstArg(args);
1793
+ const shouldGroupLast = shouldGroupLastArg(args);
1794
+ if (shouldGroupFirst || shouldGroupLast) {
1795
+ if (shouldGroupFirst ? printedArguments.slice(1).some(willBreak) : printedArguments.slice(0, -1).some(willBreak)) {
1796
+ return allArgsBrokenOut();
1797
+ }
1798
+ let printedExpanded = [];
1799
+ const { path } = getContext();
1800
+ const stackBackup = [...path.stack];
1801
+ try {
1802
+ path_try(() => {
1803
+ getContext().path.each((p, i) => {
1804
+ if (shouldGroupFirst && i === 0) {
1805
+ printedExpanded = [
1806
+ [
1807
+ print4([], { expandFirstArg: true }),
1808
+ printedArguments.length > 1 ? "," : "",
1809
+ hasEmptyLineFollowingFirstArg ? hardline : line,
1810
+ hasEmptyLineFollowingFirstArg ? hardline : ""
1811
+ ],
1812
+ ...printedArguments.slice(1)
1813
+ ];
1814
+ }
1815
+ if (shouldGroupLast && i === lastArgIndex) {
1816
+ printedExpanded = [...printedArguments.slice(0, -1), print4([], { expandLastArg: true })];
1817
+ }
1818
+ }, "arguments");
1819
+ });
1820
+ } catch (caught) {
1821
+ path.stack.length = 0;
1822
+ path.stack.push(...stackBackup);
1823
+ if (caught instanceof ArgExpansionBailout)
1824
+ return allArgsBrokenOut();
1825
+ throw caught;
1826
+ }
1827
+ return [
1828
+ printedArguments.some(willBreak) ? breakParent : "",
1829
+ conditionalGroup([
1830
+ [LEFT, ...printedExpanded, RIGHT],
1831
+ shouldGroupFirst ? [LEFT, group(printedExpanded[0], { shouldBreak: true }), ...printedExpanded.slice(1), RIGHT] : [LEFT, ...printedArguments.slice(0, -1), group(printedExpanded[lastArgIndex], { shouldBreak: true }), RIGHT],
1832
+ allArgsBrokenOut()
1833
+ ])
1834
+ ];
1835
+ }
1836
+ const contents = [LEFT, indent([softline, ...printedArguments]), ifBreak(trailingComma), softline, RIGHT];
1837
+ return isLongCurriedCallExpression(node) ? contents : group(contents, { shouldBreak: anyArgEmptyLine || printedArguments.some(willBreak) });
1838
+ function allArgsBrokenOut() {
1839
+ return group([LEFT, indent([line, ...printedArguments]), trailingComma, line, RIGHT], { shouldBreak: true });
1840
+ }
1841
+ }
1842
+ function shouldHugFunctionParameters(node) {
1843
+ if (!node)
1844
+ return false;
1845
+ const parameters = getParameters(node);
1846
+ if (parameters.length !== 1)
1847
+ return false;
1848
+ const param = parameters[0];
1849
+ if (hasComment(param))
1850
+ return false;
1851
+ switch (param.nodeType) {
1852
+ case NodeType.FunctionSelfParameterDeclaration:
1853
+ case NodeType.FunctionSpread:
1854
+ case NodeType.TypeFnPointerParameter:
1855
+ default:
1856
+ return false;
1857
+ case NodeType.FunctionParameterDeclaration:
1858
+ case NodeType.ClosureFunctionParameterDeclaration:
1859
+ return "items" in param.pattern || "properties" in param.pattern;
1860
+ }
1861
+ }
1862
+ function shouldGroupFunctionParameters(functionNode, returnTypeDoc) {
1863
+ const returnType = functionNode.returnType;
1864
+ const generics = functionNode.generics;
1865
+ const whereBounds = functionNode.whereBounds;
1866
+ if (!returnType)
1867
+ return false;
1868
+ if (generics) {
1869
+ if (generics.length > 1)
1870
+ return false;
1871
+ if (generics.length === 1 && !isShortGenericParameterDeclaration(generics[0]))
1872
+ return false;
1873
+ }
1874
+ if (whereBounds) {
1875
+ if (whereBounds.length > 1)
1876
+ return false;
1877
+ }
1878
+ return getParameters(functionNode).length === 1 && (willBreak(returnTypeDoc) || willBreak(printWhereBounds(getPrintFn(), functionNode)));
1879
+ }
1880
+ function printBlockBody(print4, node) {
1881
+ const body = printBodyOrCases(print4, node);
1882
+ return [
1883
+ "{",
1884
+ body.length > 0 ? getBodyOrCases(node)?.length ? canInlineBlockBody(node) ? [indent([line, body]), line] : group([indent([line, body]), line], { shouldBreak: true }) : body : emptyContent(node),
1885
+ "}"
1886
+ ];
1887
+ }
1888
+ function printMaybeBlockBody(print4, node) {
1889
+ return hasSemiNoBody(node) ? ";" : adjustClause(node, printBlockBody(print4, node));
1890
+ }
1891
+ function printArrowFunction(print4, node) {
1892
+ const signatures = [];
1893
+ const body = [];
1894
+ const { args, path } = getContext();
1895
+ let chainShouldBreak = false;
1896
+ let tailNode = node;
1897
+ (function rec(node2) {
1898
+ tailNode = node2;
1899
+ const doc = printArrowFunctionSignature(print4, node2);
1900
+ if (signatures.length === 0) {
1901
+ signatures.push(doc);
1902
+ } else {
1903
+ const { leading, trailing } = printCommentsSeparately();
1904
+ signatures.push([leading, doc]);
1905
+ body.unshift(trailing);
1906
+ }
1907
+ chainShouldBreak || (chainShouldBreak = !!node2.returnType || !node2.parameters.every((param) => isSimplePattern(param.pattern)));
1908
+ if (!is_ClosureFunctionExpression(node2.expression) || args && args.expandLastArg) {
1909
+ body.unshift(print4("expression", args));
1910
+ } else {
1911
+ pathCall(node2, "expression", rec);
1912
+ }
1913
+ })(node);
1914
+ if (signatures.length > 1) {
1915
+ return printArrowChain(signatures, chainShouldBreak, body, tailNode);
1916
+ } else {
1917
+ const printed = signatures[0];
1918
+ if (!hasLeadingOwnLineComment(node.expression) && (is_ArrayOrTupleLiteral(node.expression) || is_StructLiteral(node.expression) || is_ExpressionWithBodyOrCases(node.expression) || is_ClosureFunctionExpression(node.expression))) {
1919
+ return group([printed, " ", body]);
1920
+ }
1921
+ const shouldAddSoftLine = args && args.expandLastArg && !hasComment(node);
1922
+ const printTrailingComma = args && args.expandLastArg && false;
1923
+ const shouldAddParens = is_OrExpression(node.expression);
1924
+ return group([
1925
+ printed,
1926
+ group([
1927
+ indent(shouldAddParens ? [line, ifBreak("", "("), body, ifBreak("", ")")] : [line, body]),
1928
+ shouldAddSoftLine ? [ifBreak(printTrailingComma ? "," : ""), softline] : ""
1929
+ ])
1930
+ ]);
1931
+ }
1932
+ }
1933
+ function printArrowChain(signatures, shouldBreak, bodyDoc, tailNode) {
1934
+ const { args } = getContext();
1935
+ const parent = getParentNode();
1936
+ const isCallee = is_CallExpression_or_CallLikeMacroInvocation(parent) && parent.callee === getNode();
1937
+ const isAssignmentRhs = !!(args && args.assignmentLayout);
1938
+ const shouldPutBodyOnSeparateLine = !is_ExpressionWithBodyOrCases(tailNode.expression) && !is_StructLiteral(tailNode.expression);
1939
+ const shouldBreakBeforeChain = isCallee && shouldPutBodyOnSeparateLine || args && args.assignmentLayout === 6 /* chain-tail-arrow-chain */;
1940
+ const groupId = Symbol("arrow-chain");
1941
+ return group([
1942
+ group(
1943
+ indent([isCallee || isAssignmentRhs ? softline : "", group(join(line, signatures), { shouldBreak })]),
1944
+ //
1945
+ { id: groupId, shouldBreak: shouldBreakBeforeChain }
1946
+ ),
1947
+ indentIfBreak(shouldPutBodyOnSeparateLine ? indent([line, bodyDoc]) : [" ", bodyDoc], { groupId }),
1948
+ isCallee ? ifBreak(softline, "", { groupId }) : ""
1949
+ ]);
1950
+ }
1951
+ function printArrowFunctionSignature(print4, node) {
1952
+ const { args } = getContext();
1953
+ const expandArg = args && (args.expandLastArg || args.expandFirstArg);
1954
+ let returnTypeDoc = printReturnType(print4, node);
1955
+ if (expandArg) {
1956
+ if (willBreak(returnTypeDoc))
1957
+ throw new ArgExpansionBailout();
1958
+ else
1959
+ returnTypeDoc = group(removeLines(returnTypeDoc));
1960
+ }
1961
+ return [
1962
+ print4.b("static"),
1963
+ print4.b("async"),
1964
+ print4.b("move"),
1965
+ //
1966
+ group([printFunctionParameters(print4, node, expandArg), returnTypeDoc])
1967
+ ];
1968
+ }
1969
+ function printGenerics_x_whereBounds(print4, node, xDoc) {
1970
+ const generics = is_ImplDeclarationNode(node) ? [printGenerics(print4, node), " "] : [" ", print4("id"), printGenerics(print4, node)];
1971
+ const whereBoundsDoc = printWhereBounds(print4, node);
1972
+ return is_TupleStructDeclaration(node) ? [...generics, xDoc, group(whereBoundsDoc, { id: getHeritageGroupId(node) })] : [...generics, group([xDoc, whereBoundsDoc], { id: getHeritageGroupId(node) })];
1973
+ }
1974
+ function adjustClause(node, doc) {
1975
+ return [
1976
+ "whereBounds" in node && (!!node.whereBounds || hasTypeBounds(node) && node.typeBounds.length > 1) && willBreak(doc) ? ifBreak(hardline, " ", { groupId: getHeritageGroupId(node) }) : " ",
1977
+ doc
1978
+ ];
1979
+ }
1980
+ function printParametersAndReturnType(node) {
1981
+ const parametersDoc = printFunctionParameters(getPrintFn(), node);
1982
+ const returnTypeDoc = printReturnType(getPrintFn(), node);
1983
+ return is_FunctionDeclaration(node) && shouldGroupFunctionParameters(node, returnTypeDoc) ? group([group(parametersDoc), returnTypeDoc]) : group([parametersDoc, returnTypeDoc]);
1984
+ }
1985
+ function printFlowControlExpression(print4, node) {
1986
+ return !node.expression ? "" : (
1987
+ // : hasLeadingComment(node.expression)
1988
+ // ? [" (", indent([hardline, print("expression")]), hardline, ")"]
1989
+ is_BinaryishExpression(node.expression) && !flowControlExpressionNeedsOuterParens(node) ? group([" ", ifBreak("("), indent([softline, print4("expression")]), softline, ifBreak(")")]) : [" ", print4("expression")]
1990
+ );
1991
+ }
1992
+ function flowControlExpressionNeedsOuterParens(flow) {
1993
+ return flow.expression && function hasLeadingComment(node) {
1994
+ if (hasLeadingOwnLineComment(node))
1995
+ return true;
1996
+ if (hasNakedLeftSide(node)) {
1997
+ let leftMost = node;
1998
+ while (leftMost = getLeftSide(leftMost)) {
1999
+ if (hasLeadingOwnLineComment(leftMost))
2000
+ return true;
2001
+ }
2002
+ }
2003
+ return false;
2004
+ }(flow.expression);
2005
+ }
2006
+ function getLeftSide(node, includeAttributes = false) {
2007
+ let target = node.left ?? node.callee ?? node.namespace ?? node.label ?? node.lower ?? node.struct ?? node.condition ?? node.expression;
2008
+ if (target && includeAttributes && hasAttributes(node)) {
2009
+ node.attributes.forEach((attr) => {
2010
+ if (start(attr) < start(target))
2011
+ target = attr;
2012
+ });
2013
+ }
2014
+ return target;
2015
+ }
2016
+ function hasNakedLeftSide(node) {
2017
+ return is_BinaryishExpression(node) || is_ReassignmentNode(node) || is_CallExpression_or_CallLikeMacroInvocation(node) || is_MemberAccessLike(node) || is_PostfixExpression(node) || is_ExpressionAsTypeCast(node);
2018
+ }
2019
+ function printReturnType(print4, node) {
2020
+ return node.returnType ? is_FunctionDeclaration(node) ? adjustDeclarationClause(node, "->", print4("returnType")) : [" -> ", print4("returnType")] : "";
2021
+ }
2022
+ function printFunctionParameters(print4, node, expandArg = false, printTypeParams = false) {
2023
+ const { left: leftDelim, right: rightDelim } = getDelimChars(node.parameters);
2024
+ const generics = printTypeParams && is_FunctionDeclaration(node) ? printGenerics(print4, node) : "";
2025
+ if (!hasParameters(node)) {
2026
+ return [
2027
+ generics,
2028
+ //
2029
+ leftDelim,
2030
+ printDanglingCommentsForInline(node, "parameters" /* parameters */),
2031
+ rightDelim
2032
+ ];
2033
+ }
2034
+ const isParametersInTestCall = false;
2035
+ const shouldHugParameters = shouldHugFunctionParameters(node);
2036
+ const printed = print4.join("parameters", sepFn);
2037
+ if (hasSelfParameter(node)) {
2038
+ printed.unshift(getContext().path.call(() => [print4(), printed.length ? sepFn(node.parameters.self) : ""], "parameters", "self"));
2039
+ }
2040
+ if (expandArg) {
2041
+ if (willBreak(generics) || willBreak(printed))
2042
+ throw new ArgExpansionBailout();
2043
+ return group([removeLines(generics), leftDelim, removeLines(printed), rightDelim]);
2044
+ } else if (shouldHugParameters || isParametersInTestCall) {
2045
+ return [generics, leftDelim, ...printed, rightDelim];
2046
+ } else {
2047
+ return [generics, leftDelim, indent([softline, ...printed]), softline, rightDelim];
2048
+ }
2049
+ function sepFn(param) {
2050
+ return shouldHugParameters || isParametersInTestCall ? ", " : isNextLineEmpty(param) ? [",", hardline, hardline] : [",", line];
2051
+ }
2052
+ }
2053
+ function path_try(callback) {
2054
+ const { stack } = getContext().path;
2055
+ const stackBackup = [...stack];
2056
+ try {
2057
+ return callback();
2058
+ } finally {
2059
+ stack.length = 0;
2060
+ stack.push(...stackBackup);
2061
+ }
2062
+ }
2063
+ function shouldGroupFirstArg(args) {
2064
+ if (args.length !== 2)
2065
+ return false;
2066
+ const [firstArg, secondArg] = args;
2067
+ return !hasComment(firstArg) && is_ClosureFunctionExpression(firstArg) && is_ExpressionWithBodyOrCases(firstArg.expression) && !is_ClosureFunctionExpression(secondArg) && !couldGroupArg(secondArg);
2068
+ }
2069
+ function shouldGroupLastArg(args) {
2070
+ const lastArg = last_of(args);
2071
+ const preLastArg = args[args.length - 2];
2072
+ return !hasComment(lastArg, 2 /* Leading */) && !hasComment(lastArg, 4 /* Trailing */) && couldGroupArg(lastArg) && (!preLastArg || preLastArg.nodeType !== lastArg.nodeType) && (args.length !== 2 || !is_ClosureFunctionExpression(preLastArg) || !is_ArrayOrTupleLiteral(lastArg)) && !(args.length > 1 && is_ArrayOrTupleLiteral(lastArg) && isConciselyPrintedArray(lastArg)) && (args.length !== 1 || !is_IfBlockExpression(lastArg));
2073
+ }
2074
+ function couldGroupArg(arg, arrowChainRecursion = false) {
2075
+ return is_StructLiteral(arg) && (arg.properties.length > 0 || hasComment(arg)) || is_ArrayOrTupleLiteral(arg) && (arg.items.length > 0 || hasComment(arg)) || is_ExpressionAsTypeCast(arg) && couldGroupArg(arg.expression) || is_ClosureFunctionExpression(arg) && (!arg.returnType || is_Identifier(arg.returnType) || !isNonEmptyBlockStatement(arg.expression)) && (isNonEmptyBlockStatement(arg.expression) || is_ClosureFunctionExpression(arg.expression) && couldGroupArg(arg.expression, true) || is_StructLiteral(arg.expression) || is_ArrayOrTupleLiteral(arg.expression) || !arrowChainRecursion && is_CallExpression_or_CallLikeMacroInvocation(arg.expression)) || is_ExpressionWithBodyOrCases(arg);
2076
+ }
2077
+ function isNonEmptyBlockStatement(node) {
2078
+ if (is_MatchExpression(node))
2079
+ return node.cases.length > 0;
2080
+ return is_ExpressionWithBodyOrCases(node) && node.body.length > 0;
2081
+ }
2082
+ function isFunctionCompositionArgs(args) {
2083
+ if (args.length <= 1) {
2084
+ return false;
2085
+ }
2086
+ let count = 0;
2087
+ for (const arg of args) {
2088
+ if (is_ClosureFunctionExpression(arg)) {
2089
+ if (++count > 1)
2090
+ return true;
2091
+ } else if (is_CallExpression_or_CallLikeMacroInvocation(arg)) {
2092
+ for (const childArg of arg.arguments) {
2093
+ if (is_ClosureFunctionExpression(childArg)) {
2094
+ return true;
2095
+ }
2096
+ }
2097
+ }
2098
+ }
2099
+ return false;
2100
+ }
2101
+ function printBinaryishExpression(print4, node) {
2102
+ const parent = getParentNode();
2103
+ const grandParent = getGrandParentNode();
2104
+ const isInsideParenthesis = "condition" in parent && parent.condition === node || is_MatchExpression(parent);
2105
+ const parts = printBinaryishExpressions(false, isInsideParenthesis);
2106
+ if (isInsideParenthesis)
2107
+ return parts;
2108
+ if (is_CallExpression_or_CallLikeMacroInvocation(parent) && parent.callee === node || //
2109
+ is_UnaryExpression(parent) || is_MemberExpression(parent)) {
2110
+ return group([indent([softline, ...parts]), softline]);
2111
+ }
2112
+ const shouldNotIndent = is_FlowControlExpression(parent) || is_ClosureFunctionExpression(parent) && parent.expression === node || is_ExpressionWithBodyOrCases(parent);
2113
+ const shouldIndentIfInlining = is_ReassignmentNode(parent) || is_VariableDeclarationNode(parent) || is_StructLiteral(parent) || is_StructLiteral(grandParent);
2114
+ const samePrecedenceSubExpression = is_BinaryishExpression(node.left) && shouldFlatten(node, node.left);
2115
+ if (shouldNotIndent || shouldInlineLogicalExpression(node) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(node) && shouldIndentIfInlining) {
2116
+ return group(parts);
2117
+ }
2118
+ if (parts.length === 0)
2119
+ return "";
2120
+ const firstGroupIndex = parts.findIndex((part) => typeof part !== "string" && !Array.isArray(part) && part.type === "group");
2121
+ const leading = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1);
2122
+ return group([...leading, indent(parts.slice(leading.length))], { id: Symbol("logicalChain") });
2123
+ function printBinaryishExpressions(isNested, isInsideParenthesis2) {
2124
+ const { path, print: print5, options: options2 } = getContext();
2125
+ const node2 = path.getValue();
2126
+ if (!is_BinaryishExpression(node2)) {
2127
+ return [group(print5())];
2128
+ }
2129
+ const parts2 = [];
2130
+ if (shouldFlatten(node2, node2.left)) {
2131
+ parts2.push(...pathCall(node2, "left", () => printBinaryishExpressions(true, isInsideParenthesis2)));
2132
+ } else {
2133
+ parts2.push(group(print5("left")));
2134
+ }
2135
+ const shouldInline = shouldInlineLogicalExpression(node2);
2136
+ const operator = node2.kind;
2137
+ const right = [
2138
+ operator,
2139
+ shouldInline ? " " : line,
2140
+ // this is a hack (should always be 'print("right")')
2141
+ !shouldInline && is_LogicalExpression(node2.right) && shouldFlatten(node2.right, node2) ? pathCall(node2, "right", () => printBinaryishExpressions(true, isInsideParenthesis2)) : print5("right")
2142
+ ];
2143
+ const shouldBreak = hasComment(node2.left, 4 /* Trailing */ | 32 /* Line */);
2144
+ const shouldGroup = shouldBreak || !(isInsideParenthesis2 && is_LogicalExpression(node2)) && path.getParentNode().nodeType !== node2.nodeType && node2.left.nodeType !== node2.nodeType && node2.right.nodeType !== node2.nodeType;
2145
+ parts2.push(" ", shouldGroup ? group(right, { shouldBreak }) : right);
2146
+ if (isNested && hasComment(node2)) {
2147
+ const printed = cleanDoc(withComments(node2, parts2));
2148
+ if (Array.isArray(printed))
2149
+ return printed;
2150
+ if (printed.type === "fill")
2151
+ return printed.parts;
2152
+ return [printed];
2153
+ }
2154
+ return parts2;
2155
+ }
2156
+ }
2157
+ function shouldInlineLogicalExpression(node) {
2158
+ if (is_LogicalExpression(node)) {
2159
+ if (is_StructLiteral(node.right))
2160
+ return node.right.properties.length > 0;
2161
+ if (is_ArrayOrTupleLiteral(node.right))
2162
+ return node.right.items.length > 0;
2163
+ }
2164
+ return false;
2165
+ }
2166
+ function printUnaryExpression(leftDoc, node) {
2167
+ const printed = getPrintFn()("expression");
2168
+ return group([leftDoc, printed]);
2169
+ }
2170
+ function printIfBlock(print4, node) {
2171
+ let printed = [
2172
+ printIfBlockCondition(print4, node),
2173
+ //
2174
+ printBlockBody(print4, node),
2175
+ f` else ${print4("else")}`
2176
+ ];
2177
+ const parent = getParentNode();
2178
+ if (is_ClosureBlock(node, parent)) {
2179
+ printed = parenthesize_if_break([indent([softline, printed]), softline]);
2180
+ } else if (!is_ElseBlock(node, parent)) ;
2181
+ return printed;
2182
+ }
2183
+ function printIfBlockCondition(print4, node) {
2184
+ if (!hasCondition(node))
2185
+ return "";
2186
+ return f`if ${printCondition(print4, node)}`;
2187
+ }
2188
+ function printCondition(print4, node) {
2189
+ return pathCall(node, "condition", (condition) => {
2190
+ if (!condition)
2191
+ return "";
2192
+ if (needsParens(condition))
2193
+ return [print4(), " "];
2194
+ const id = Symbol("condition");
2195
+ const printed = [indent([softline , print4()]), softline];
2196
+ return [group(printed, { id }), ifBreak("", " ", { groupId: id })];
2197
+ });
2198
+ }
2199
+ function parenthesize_if_break(doc) {
2200
+ return conditionalGroup([doc, ["(", doc, ")"]], { shouldBreak: willBreak(doc) });
2201
+ }
2202
+ function isSimplePattern(node) {
2203
+ if (!node)
2204
+ return false;
2205
+ switch (node.nodeType) {
2206
+ case NodeType.MacroInvocation:
2207
+ return false;
2208
+ case NodeType.ExpressionTypeCast:
2209
+ return isSimplePattern(node.typeCallee) && !hasComplexTypeArguments(node);
2210
+ case NodeType.ExpressionTypeSelector:
2211
+ return is_Identifier(node.typeTarget) && (!node.typeExpression || is_Identifier(node.typeExpression));
2212
+ case NodeType.ExpressionPath:
2213
+ return !node.namespace || isSimplePattern(node.namespace);
2214
+ case NodeType.RangePattern:
2215
+ return (!node.lower || isSimplePattern(node.lower)) && (!node.upper || isSimplePattern(node.upper));
2216
+ case NodeType.PatternVariableDeclaration:
2217
+ case NodeType.ReferencePattern:
2218
+ case NodeType.BoxPattern:
2219
+ case NodeType.MinusPattern:
2220
+ return isSimplePattern(node.pattern);
2221
+ case NodeType.Identifier:
2222
+ case NodeType.Literal:
2223
+ case NodeType.RestPattern:
2224
+ case NodeType.WildcardPattern:
2225
+ return true;
2226
+ default:
2227
+ return false;
2228
+ }
2229
+ }
2230
+ function printUnionPattern(print4, node) {
2231
+ if (node.patterns.length === 1)
2232
+ return print4.map("patterns");
2233
+ const parent = getParentNode();
2234
+ const prebreak = parent && (is_VariableDeclarationNode(parent) || is_LetScrutinee(parent)) && !needsParens(node);
2235
+ return group([
2236
+ prebreak ? softline : "",
2237
+ print4.map("patterns", (node2, i, arr) => [
2238
+ withComments(node2, [
2239
+ i === 0 ? ifBreak("| ") : "| ",
2240
+ align(2, print4())
2241
+ ]),
2242
+ i === arr.length - 1 ? "" : line
2243
+ ])
2244
+ ]);
2245
+ }
2246
+ function printArrayLike(print4, node) {
2247
+ const delims = getDelimChars(node.items);
2248
+ if (node.items.length === 0) {
2249
+ const comments = printDanglingCommentsForInline(node, "items" /* items */);
2250
+ return comments ? group([delims.left, comments, delims.right]) : delims.left + delims.right;
2251
+ }
2252
+ const groupId = Symbol("array");
2253
+ const shouldBreak = (
2254
+ // is_TupleStructDeclaration(node) ||
2255
+ !is_TupleNode(node) && node.items.length > 1 && node.items.every((item, i) => {
2256
+ const next = node.items[i + 1];
2257
+ return (hasProperties(item) && item.properties.length > 1 || hasItems(item) && item.items.length > 1) && (!next || item.nodeType === next.nodeType);
2258
+ })
2259
+ );
2260
+ const shouldUseConciseFormatting = isConciselyPrintedArray(node);
2261
+ const parent = getParentNode();
2262
+ const needsForcedTrailingComma = node.items.length === 1 ? is_TupleLiteral(node) ? is_RangeLiteral(node.items[0]) ? !(is_ReassignmentExpression(parent) && parent.left === node) : true : is_TuplePattern(node) ? !node.struct && !is_RangePattern(node.items[0]) && !is_RestPattern(node.items[0]) : is_TypeTuple(node) ? true : false : false;
2263
+ const trailingComma = needsForcedTrailingComma ? "," : shouldUseConciseFormatting ? ifBreak(",", "", { groupId }) : ifBreak(",");
2264
+ const printed = shouldUseConciseFormatting ? fill(
2265
+ print4.join(
2266
+ "items",
2267
+ (item, next) => isNextLineEmpty(item) ? [",", hardline, hardline] : hasComment(next, 2 /* Leading */, (comment) => is_LineCommentNode(comment) || comment.placement === "ownLine") ? [",", hardline] : [",", line],
2268
+ trailingComma
2269
+ )
2270
+ ) : print4.map_join(
2271
+ "items",
2272
+ () => group(print4()),
2273
+ (item) => isNextLineEmpty(item) ? [",", line, softline] : [",", line],
2274
+ trailingComma
2275
+ );
2276
+ return group([delims.left, indent([softline, printed]), printDanglingComments(node, true, "items" /* items */), softline, delims.right], {
2277
+ shouldBreak,
2278
+ id: groupId
2279
+ });
2280
+ }
2281
+ function printObject(print4, node) {
2282
+ if (hasSemiNoProperties(node)) {
2283
+ return ";";
2284
+ }
2285
+ if (!hasProperties(node)) {
2286
+ return [" {", printDanglingCommentsForInline(node, "properties" /* properties */) || emptyContent(node), "}"];
2287
+ }
2288
+ const firstProperty = node.properties[0];
2289
+ const parent = getParentNode();
2290
+ const shouldBreak = is_StructPattern(node) ? false : is_UnionDeclaration(node) || is_StructDeclaration(node) || is_EnumMemberStructDeclaration(node) || hasNewlineInRange(start(node), start(firstProperty));
2291
+ const content = [
2292
+ " {",
2293
+ indent([
2294
+ line,
2295
+ ...print4.join(
2296
+ "properties",
2297
+ //
2298
+ (node2) => isNextLineEmpty(node2) ? [",", hardline, hardline] : [",", line],
2299
+ (node2) => is_StructSpread(node2) ? "" : ifBreak(",")
2300
+ )
2301
+ ]),
2302
+ line,
2303
+ "}"
2304
+ ];
2305
+ const grandparent = getGrandParentNode();
2306
+ if (grandparent && (is_FunctionDeclaration(grandparent) || is_ClosureFunctionExpression(grandparent)) && getParameters(grandparent)[0] === parent) {
2307
+ return content;
2308
+ }
2309
+ if (is_StructLiteral(node) && is_ReassignmentNode(parent) && parent.left === node || is_StructPattern(node) && (is_VariableDeclarationNode(parent) || is_MatchExpressionCase(parent) || is_FunctionParameterDeclaration(parent)) && parent.pattern === node) {
2310
+ return content;
2311
+ }
2312
+ return group(content, { shouldBreak });
2313
+ }
2314
+ function printEnumBody(print4, node) {
2315
+ const printed = print4.join("members", (member) => [",", maybeEmptyLine(member)], ",");
2316
+ return [
2317
+ " {",
2318
+ printed.length === 0 ? printDanglingCommentsForInline(node, "members" /* members */) || emptyContent(node) : [indent([hardline, ...printed]), hardline],
2319
+ "}"
2320
+ ];
2321
+ }
2322
+
2323
+ // src/format/comments.ts
2324
+ function addCommentHelper(node, comment, leading = false, trailing = false) {
2325
+ (node.comments ?? (node.comments = [])).push(comment);
2326
+ comment.leading = leading, comment.trailing = trailing, comment.printed = false;
2327
+ }
2328
+ function addLeadingComment(node, comment) {
2329
+ addCommentHelper(node, comment, true);
2330
+ }
2331
+ function addDanglingComment(node, comment, marker) {
2332
+ addCommentHelper(node, comment);
2333
+ comment.marker = marker;
2334
+ }
2335
+ function addTrailingComment(node, comment) {
2336
+ addCommentHelper(node, comment, false, true);
2337
+ }
2338
+ function setPrettierIgnoreTarget(node, comment) {
2339
+ comment.unignore = true;
2340
+ node.prettierIgnore = true;
2341
+ }
2342
+ function hasComments(node) {
2343
+ return "comments" in node && node.comments.length > 0;
2344
+ }
2345
+ function printDanglingComments(enclosingNode, sameIndent, marker) {
2346
+ if (hasComments(enclosingNode)) {
2347
+ const printed = [];
2348
+ pathCallEach(enclosingNode, "comments", (comment) => {
2349
+ if (isDangling(comment) && (!marker || comment.marker === marker)) {
2350
+ printed.push(printComment(comment));
2351
+ }
2352
+ });
2353
+ if (printed.length > 0) {
2354
+ return sameIndent ? join(hardline, printed) : indent([hardline, join(hardline, printed)]);
2355
+ }
2356
+ }
2357
+ return "";
2358
+ }
2359
+ function setDidPrintComment(comment) {
2360
+ comment.printed = true;
2361
+ }
2362
+ function printComment(comment) {
2363
+ setDidPrintComment(comment);
2364
+ return getContext().options.printer.printComment(getContext().path, getOptions());
2365
+ }
2366
+ function isPreviousLineEmpty(node) {
2367
+ let index = start(node) - 1;
2368
+ index = skipSpaces(index, true);
2369
+ index = skipNewline(index, true);
2370
+ index = skipSpaces(index, true);
2371
+ return index !== skipNewline(index, true);
2372
+ }
2373
+ function hasBreaklineBefore(node) {
2374
+ return hasNewline(start(node) - 1, true);
2375
+ }
2376
+ function hasBreaklineAfter(node) {
2377
+ return hasNewline(end(node));
2378
+ }
2379
+ function printCommentsSeparately(ignored) {
2380
+ const node = getNode();
2381
+ const leading = [];
2382
+ const trailing = [];
2383
+ let hasTrailingLineComment = false;
2384
+ let hadLeadingBlockComment = false;
2385
+ if ("comments" in node) {
2386
+ pathCallEach(node, "comments", (comment) => {
2387
+ if (ignored?.has(comment)) {
2388
+ return;
2389
+ } else if (isLeading(comment)) {
2390
+ leading.push(printLeadingComment(comment));
2391
+ } else if (isTrailing(comment)) {
2392
+ trailing.push(printTrailingComment(comment));
2393
+ }
2394
+ });
2395
+ }
2396
+ return (leading.length | trailing.length) > 0 ? { leading, trailing } : { leading: "", trailing: "" };
2397
+ function printLeadingComment(comment) {
2398
+ if (is_Attribute(comment) && !comment.inner) {
2399
+ const printed = printComment(comment);
2400
+ return [printed, " "];
2401
+ }
2402
+ hadLeadingBlockComment || (hadLeadingBlockComment = is_BlockCommentKind(comment) && hasBreaklineBefore(comment));
2403
+ return [
2404
+ printComment(comment),
2405
+ is_BlockCommentKind(comment) ? hasBreaklineAfter(comment) ? hadLeadingBlockComment ? hardline : line : " " : hardline,
2406
+ hasNewline(skipNewline(skipSpaces(end(comment)))) ? hardline : ""
2407
+ ];
2408
+ }
2409
+ function printTrailingComment(comment) {
2410
+ const printed = printComment(comment);
2411
+ return hasBreaklineBefore(comment) ? lineSuffix([hardline, isPreviousLineEmpty(comment) ? hardline : "", printed]) : is_BlockCommentNode(comment) ? [" ", printed] : lineSuffix([" ", printed, hasTrailingLineComment === (hasTrailingLineComment = true) ? hardline : breakParent]);
2412
+ }
2413
+ }
2414
+ function getPostLeadingComment(comment) {
2415
+ return hasNewline(skipNewline(skipSpaces(end(comment)))) ? hardline : "";
2416
+ }
2417
+ function withComments(node, printed, ignored) {
2418
+ const { leading, trailing } = printCommentsSeparately(ignored);
2419
+ return leading || trailing ? [...leading, printed, ...trailing] : printed;
2420
+ }
2421
+ function getComments(node, ...args) {
2422
+ return node && node.comments ? args.length > 0 ? node.comments.filter(getCommentTestFunction(...args)) : node.comments : [];
2423
+ }
2424
+ function getFirstComment(node, flags, fn) {
2425
+ const r = getComments(node, flags | 128 /* First */, fn);
2426
+ return r.length === 0 ? void 0 : r[0];
2427
+ }
2428
+ function escapeComments(flags, fn) {
2429
+ const comments = getAllComments().filter(getCommentTestFunction(flags, fn));
2430
+ comments.forEach(setDidPrintComment);
2431
+ return new Set(comments);
2432
+ }
2433
+ function isPrettierIgnoreComment(comment) {
2434
+ return is_Comment(comment) && /^\s*prettier-ignore\s*/.test(comment.value) && !comment.unignore;
2435
+ }
2436
+ function isPrettierIgnoreAttribute(node) {
2437
+ return is_Attribute(node) && /^\s*rustfmt::skip\s*$/.test(node.value);
2438
+ }
2439
+ function getCommentTestFunction(flags, fn) {
2440
+ return function(comment, index, comments) {
2441
+ return !(flags & 2 /* Leading */ && !isLeading(comment) || flags & 4 /* Trailing */ && !isTrailing(comment) || flags & 8 /* Dangling */ && !isDangling(comment) || flags & 16 /* Block */ && !is_BlockCommentKind(comment) || flags & 32 /* Line */ && !is_LineCommentKind(comment) || flags & 128 /* First */ && index !== 0 || flags & 256 /* Last */ && !iLast(index, comments) || flags & 64 /* PrettierIgnore */ && !(isPrettierIgnoreComment(comment) || isPrettierIgnoreAttribute(comment)) || fn && !fn(comment));
2442
+ };
2443
+ }
2444
+ function hasComment(node, flags = 0, fn) {
2445
+ if ("comments" in node && node.comments.length > 0) {
2446
+ return flags || fn ? node.comments.some(getCommentTestFunction(flags, fn)) : true;
2447
+ }
2448
+ return false;
2449
+ }
2450
+ function hasNewlineInRange(leftIndex, rightIndex) {
2451
+ const text = getContext().options.originalText;
2452
+ for (var i = leftIndex; i < rightIndex; ++i)
2453
+ if (text.charCodeAt(i) === 10)
2454
+ return true;
2455
+ return false;
2456
+ }
2457
+ function isNextLineEmpty(node) {
2458
+ return isNextLineEmptyAfterIndex(end(node));
2459
+ }
2460
+ function isNextLineEmptyAfterIndex(index) {
2461
+ let oldIdx = -1;
2462
+ let idx = index;
2463
+ while (idx !== oldIdx) {
2464
+ oldIdx = idx;
2465
+ idx = skipToLineEnd(idx);
2466
+ idx = skipBlockComment(idx);
2467
+ idx = skipSpaces(idx);
2468
+ idx = skipParens(idx);
2469
+ }
2470
+ idx = skipLineComment(idx);
2471
+ idx = skipParens(idx);
2472
+ idx = skipNewline(idx);
2473
+ idx = skipParens(idx);
2474
+ return idx !== false && hasNewline(idx);
2475
+ }
2476
+ function hasNewline(index, backwards = false) {
2477
+ if (index === false)
2478
+ return false;
2479
+ const i = skipSpaces(index, backwards);
2480
+ return i !== false && i !== skipNewline(i, backwards);
2481
+ }
2482
+ function skipLineComment(index) {
2483
+ if (index === false)
2484
+ return false;
2485
+ const { commentSpans, originalText } = getContext().options;
2486
+ if (commentSpans.has(index) && originalText.charCodeAt(index + 1) === 47)
2487
+ return skipEverythingButNewLine(commentSpans.get(index));
2488
+ return index;
2489
+ }
2490
+ function skipBlockComment(index) {
2491
+ if (index === false)
2492
+ return false;
2493
+ const { commentSpans, originalText } = getContext().options;
2494
+ if (commentSpans.has(index) && originalText.charCodeAt(index + 1) === 42)
2495
+ return commentSpans.get(index);
2496
+ return index;
2497
+ }
2498
+ var [skipSpaces, skipToLineEnd, skipEverythingButNewLine] = [/[ \t]/, /[,; \t]/, /[^\r\n]/].map(function(re) {
2499
+ return function(index, backwards = false) {
2500
+ if (index === false)
2501
+ return false;
2502
+ const { originalText: text } = getContext().options;
2503
+ let cursor2 = index;
2504
+ while (cursor2 >= 0 && cursor2 < text.length) {
2505
+ if (re.test(text.charAt(cursor2)))
2506
+ backwards ? cursor2-- : cursor2++;
2507
+ else
2508
+ return cursor2;
2509
+ }
2510
+ return cursor2 === -1 || cursor2 === text.length ? cursor2 : false;
2511
+ };
2512
+ });
2513
+ function skipNewline(index, backwards = false) {
2514
+ if (index === false)
2515
+ return false;
2516
+ const { originalText } = getContext().options;
2517
+ const atIndex = originalText.charCodeAt(index);
2518
+ if (backwards) {
2519
+ if (originalText.charCodeAt(index - 1) === 13 && atIndex === 10)
2520
+ return index - 2;
2521
+ if (atIndex === 10)
2522
+ return index - 1;
2523
+ } else {
2524
+ if (atIndex === 13 && originalText.charCodeAt(index + 1) === 10)
2525
+ return index + 2;
2526
+ if (atIndex === 10)
2527
+ return index + 1;
2528
+ }
2529
+ return index;
2530
+ }
2531
+ function skipParens(index, backwards = false) {
2532
+ return index;
2533
+ }
2534
+ function getNextNonSpaceNonCommentCharacterIndex(node) {
2535
+ return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(end(node));
2536
+ }
2537
+ function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(i) {
2538
+ let oldIdx = -1;
2539
+ let nextIdx = i;
2540
+ while (nextIdx !== oldIdx) {
2541
+ oldIdx = nextIdx;
2542
+ nextIdx = skipSpaces(nextIdx);
2543
+ nextIdx = skipBlockComment(nextIdx);
2544
+ nextIdx = skipLineComment(nextIdx);
2545
+ nextIdx = skipNewline(nextIdx);
2546
+ nextIdx = skipParens(nextIdx);
2547
+ }
2548
+ return nextIdx;
2549
+ }
2550
+ function handled(comment) {
2551
+ return "printed" in comment;
2552
+ }
2553
+ function handleCommon(ctx2) {
2554
+ {
2555
+ const { comment: comment2, precedingNode: precedingNode2, enclosingNode, followingNode: followingNode2 } = ctx2;
2556
+ if (!enclosingNode) {
2557
+ ctx2.enclosingNode = ctx2.comment.loc.src.program;
2558
+ } else if (enclosingNode && is_NodeWithBodyOrCases(enclosingNode)) {
2559
+ const body = getBodyOrCases(enclosingNode);
2560
+ if (body) {
2561
+ if (is_ExpressionWithBodyOrCases(enclosingNode) && enclosingNode.label) {
2562
+ if (ctx2.precedingNode === enclosingNode.label) {
2563
+ ctx2.precedingNode = void 0;
2564
+ }
2565
+ if (followingNode2 === enclosingNode.label) {
2566
+ ctx2.followingNode = void 0;
2567
+ }
2568
+ }
2569
+ if (comment2.loc.isBefore(body)) {
2570
+ if (followingNode2 && body.loc.contains(followingNode2)) {
2571
+ ctx2.followingNode = void 0;
2572
+ }
2573
+ if (!ctx2.precedingNode && !ctx2.followingNode) {
2574
+ addLeadingComment(enclosingNode, comment2);
2575
+ return true;
2576
+ }
2577
+ } else if (comment2.loc.isAfter(body)) {
2578
+ if (precedingNode2 && body.loc.contains(precedingNode2)) {
2579
+ ctx2.precedingNode = void 0;
2580
+ }
2581
+ if (!ctx2.precedingNode && !ctx2.followingNode) {
2582
+ addTrailingComment(enclosingNode, comment2);
2583
+ return true;
2584
+ }
2585
+ } else if (body.loc.contains(comment2)) {
2586
+ if (precedingNode2 && !body.loc.contains(precedingNode2)) {
2587
+ ctx2.precedingNode = void 0;
2588
+ }
2589
+ if (followingNode2 && !body.loc.contains(followingNode2)) {
2590
+ ctx2.followingNode = void 0;
2591
+ }
2592
+ }
2593
+ }
2594
+ }
2595
+ }
2596
+ for (const fn of [
2597
+ handleMixedInOuterAttributeComments,
2598
+ handleAttributeComments,
2599
+ handleDanglingComments,
2600
+ handleFunctionComments,
2601
+ handleMacroRuleComments,
2602
+ handleStructLiteralComments,
2603
+ handleVariableDeclaratorComments,
2604
+ handleIfBlockExpressionComments,
2605
+ handleMemberExpressionComments,
2606
+ handleStatementComments,
2607
+ handleFlowControlComments,
2608
+ handleBadComments
2609
+ ]) {
2610
+ fn(ctx2);
2611
+ if (handled(ctx2.comment)) {
2612
+ return true;
2613
+ }
2614
+ }
2615
+ const { precedingNode, followingNode, comment } = ctx2;
2616
+ if (isStartOfLine(comment)) {
2617
+ if (followingNode) {
2618
+ addLeadingComment(followingNode, comment);
2619
+ } else if (precedingNode) {
2620
+ addTrailingComment(precedingNode, comment);
2621
+ } else {
2622
+ exit.never(ctx2);
2623
+ }
2624
+ } else if (isEndOfLine(comment)) {
2625
+ if (precedingNode) {
2626
+ addTrailingComment(precedingNode, comment);
2627
+ } else if (followingNode) {
2628
+ addLeadingComment(followingNode, comment);
2629
+ } else {
2630
+ exit.never(ctx2);
2631
+ }
2632
+ } else {
2633
+ if (precedingNode && followingNode) {
2634
+ return false;
2635
+ } else if (precedingNode) {
2636
+ addTrailingComment(precedingNode, comment);
2637
+ } else if (followingNode) {
2638
+ addLeadingComment(followingNode, comment);
2639
+ } else {
2640
+ exit.never(ctx2);
2641
+ }
2642
+ }
2643
+ return handled(ctx2.comment);
2644
+ }
2645
+ function handleOwnLineComment(ctx2) {
2646
+ return handleCommon(ctx2);
2647
+ }
2648
+ function handleEndOfLineComment(ctx2) {
2649
+ const { precedingNode, enclosingNode, comment } = ctx2;
2650
+ if (
2651
+ // handleCallExpressionComments
2652
+ precedingNode && enclosingNode && is_CallExpression_or_CallLikeMacroInvocation(enclosingNode) && enclosingNode.arguments.length > 0 && precedingNode === (enclosingNode.typeArguments ? last_of(enclosingNode.typeArguments) : enclosingNode.callee)
2653
+ ) {
2654
+ addLeadingComment(enclosingNode.arguments[0], comment);
2655
+ return true;
2656
+ } else if (
2657
+ // handlePropertyComments
2658
+ enclosingNode && is_StructLiteralProperty(enclosingNode)
2659
+ ) {
2660
+ addLeadingComment(enclosingNode, comment);
2661
+ return true;
2662
+ } else {
2663
+ return handleCommon(ctx2);
2664
+ }
2665
+ }
2666
+ function handleRemainingComment(ctx2) {
2667
+ return handleCommon(ctx2);
2668
+ }
2669
+ function handleStructLiteralComments({ enclosingNode, followingNode, comment }) {
2670
+ if (enclosingNode && is_StructLiteralPropertySpread(enclosingNode) && followingNode === enclosingNode.expression) {
2671
+ addLeadingComment(enclosingNode, comment);
2672
+ }
2673
+ }
2674
+ function handleVariableDeclaratorComments({ enclosingNode, followingNode, comment }) {
2675
+ if (enclosingNode && (is_xVariableEqualishLike(enclosingNode) || is_ReassignmentNode(enclosingNode)) && followingNode && (is_BlockCommentKind(comment) || nisAnyOf(followingNode, [
2676
+ NodeType.StructLiteral,
2677
+ NodeType.StructPattern,
2678
+ NodeType.TupleLiteral,
2679
+ NodeType.TypeTuple,
2680
+ NodeType.TuplePattern,
2681
+ NodeType.ArrayLiteral,
2682
+ NodeType.ArrayPattern,
2683
+ NodeType.SizedArrayLiteral,
2684
+ NodeType.TypeSizedArray
2685
+ ]))) {
2686
+ addLeadingComment(followingNode, comment);
2687
+ }
2688
+ }
2689
+ function handleMixedInOuterAttributeComments({ precedingNode, enclosingNode, followingNode, comment }) {
2690
+ if (enclosingNode && hasOuterAttributes(enclosingNode) && end(comment) <= ownStart(enclosingNode)) {
2691
+ if (isPrettierIgnoreComment(comment) || isPrettierIgnoreAttribute(comment)) {
2692
+ setPrettierIgnoreTarget(enclosingNode, comment);
2693
+ }
2694
+ if (isEndOfLine(comment)) {
2695
+ if (shouldPrintOuterAttributesAbove(enclosingNode)) {
2696
+ addTrailingComment(precedingNode, comment);
2697
+ } else {
2698
+ addLeadingComment(followingNode || enclosingNode, comment);
2699
+ }
2700
+ } else {
2701
+ if (followingNode && end(followingNode) <= ownStart(enclosingNode)) {
2702
+ addLeadingComment(followingNode, comment);
2703
+ } else if (precedingNode && enclosingNode.loc.contains(precedingNode)) {
2704
+ addTrailingComment(precedingNode, comment);
2705
+ } else {
2706
+ addLeadingComment(enclosingNode, comment);
2707
+ }
2708
+ }
2709
+ }
2710
+ }
2711
+ function handleAttributeComments({ precedingNode, enclosingNode, followingNode, comment, ast }) {
2712
+ if (is_AttributeOrDocComment(comment)) {
2713
+ if (comment.inner && enclosingNode && is_FunctionDeclaration(enclosingNode) && (!followingNode || !is_StatementNode(followingNode)) && (!precedingNode || !is_StatementNode(precedingNode))) {
2714
+ if (enclosingNode.body) {
2715
+ if (canAttachCommentInLocArray(enclosingNode.body)) {
2716
+ addDanglingComment(enclosingNode, comment, "body" /* body */);
2717
+ } else {
2718
+ addLeadingComment(enclosingNode.body[0], comment);
2719
+ }
2720
+ } else {
2721
+ addLeadingComment(enclosingNode, comment);
2722
+ }
2723
+ } else {
2724
+ if (followingNode) {
2725
+ addLeadingComment(followingNode, comment);
2726
+ } else if (enclosingNode) {
2727
+ for (var key in DCM)
2728
+ if (key in enclosingNode) {
2729
+ addDanglingComment(enclosingNode, comment, key);
2730
+ return;
2731
+ }
2732
+ } else {
2733
+ addDanglingComment(ast, comment, "body" /* body */);
2734
+ }
2735
+ }
2736
+ }
2737
+ }
2738
+ function handleBadComments({ precedingNode, enclosingNode, followingNode, ast, comment }) {
2739
+ if (!enclosingNode) {
2740
+ if (followingNode) {
2741
+ addLeadingComment(followingNode, comment);
2742
+ } else if (precedingNode) {
2743
+ addTrailingComment(precedingNode, comment);
2744
+ } else {
2745
+ addDanglingComment(enclosingNode || ast, comment, "body" /* body */);
2746
+ }
2747
+ } else if (!precedingNode && !followingNode) {
2748
+ if (enclosingNode && enclosingNode !== ast) {
2749
+ addLeadingComment(enclosingNode, comment);
2750
+ } else {
2751
+ addDanglingComment(ast, comment, "body" /* body */);
2752
+ }
2753
+ }
2754
+ }
2755
+ function is_ABI_Comment({ precedingNode, enclosingNode, comment }) {
2756
+ return is_CommentOrDocComment(comment) && (precedingNode && is_ExternSpecifier(precedingNode) || enclosingNode && is_ExternSpecifier(enclosingNode));
2757
+ }
2758
+ function handleFlowControlComments({ precedingNode, enclosingNode, followingNode, comment }) {
2759
+ if (enclosingNode && is_FlowControlExpression(enclosingNode)) {
2760
+ if (!precedingNode && (isOwnLine(comment) || isEndOfLine(comment)) && !followingNode) {
2761
+ addLeadingComment(enclosingNode, comment);
2762
+ }
2763
+ }
2764
+ }
2765
+ function handleFunctionComments(ctx2) {
2766
+ const { precedingNode, enclosingNode, followingNode, comment } = ctx2;
2767
+ if (enclosingNode && is_FunctionNode(enclosingNode)) {
2768
+ if (is_FunctionDeclaration(enclosingNode) && (!is_ABI_Comment(ctx2) && comment.loc.isBefore(enclosingNode.generics || enclosingNode.id) || enclosingNode.generics && comment.loc.isBetween(enclosingNode.generics, enclosingNode.parameters))) {
2769
+ addLeadingComment(enclosingNode, comment);
2770
+ } else if (!enclosingNode.returnType && comment.loc.isBetween(
2771
+ enclosingNode.parameters,
2772
+ is_FunctionDeclaration(enclosingNode) ? enclosingNode.body : enclosingNode.expression
2773
+ )) {
2774
+ if (is_FunctionDeclaration(enclosingNode)) {
2775
+ addCommentToBlock(enclosingNode, comment);
2776
+ } else {
2777
+ addLeadingComment(enclosingNode.expression, comment);
2778
+ }
2779
+ } else if (precedingNode && //
2780
+ enclosingNode.parameters.loc.contains(comment)) {
2781
+ if (precedingNode === getLastParameter(enclosingNode)) {
2782
+ addTrailingComment(precedingNode, comment);
2783
+ }
2784
+ } else if (followingNode && isStartOfLine(comment) && comment.loc.isAfter(enclosingNode.parameters) && (!is_FunctionDeclaration(enclosingNode) || !enclosingNode.whereBounds || comment.loc.isAfter(enclosingNode.whereBounds)) && (!enclosingNode.returnType || comment.loc.isAfter(enclosingNode.returnType)) && followingNode === (is_FunctionDeclaration(enclosingNode) ? enclosingNode.body?.[0] : enclosingNode.expression)) {
2785
+ addLeadingComment(followingNode, comment);
2786
+ }
2787
+ }
2788
+ }
2789
+ function handleMacroRuleComments(ctx2) {
2790
+ const { precedingNode, enclosingNode, followingNode, comment } = ctx2;
2791
+ if (enclosingNode && is_MacroRule(enclosingNode)) {
2792
+ if (enclosingNode.transform.loc.contains(comment)) {
2793
+ if (!precedingNode || !enclosingNode.transform.loc.contains(precedingNode)) {
2794
+ addLeadingComment(followingNode, comment);
2795
+ }
2796
+ } else if (enclosingNode.match.loc.contains(comment)) {
2797
+ if (!followingNode || !enclosingNode.match.loc.contains(followingNode)) {
2798
+ addTrailingComment(precedingNode, comment);
2799
+ }
2800
+ }
2801
+ }
2802
+ }
2803
+ function handleStatementComments(ctx2) {
2804
+ const { precedingNode, comment } = ctx2;
2805
+ if (isEndOfLine(comment) && precedingNode && (is_StatementNode(precedingNode) || precedingNode.loc.sliceText().endsWith(";"))) {
2806
+ addTrailingComment(precedingNode, comment);
2807
+ }
2808
+ }
2809
+ function addCommentToBlock(block, comment) {
2810
+ const body = getBodyOrCases(block);
2811
+ if (body.length > 0) {
2812
+ addLeadingComment(body[0], comment);
2813
+ } else {
2814
+ addDanglingComment(block, comment, "body" /* body */);
2815
+ }
2816
+ }
2817
+ function handleIfBlockExpressionComments(ctx2) {
2818
+ const { comment, enclosingNode } = ctx2;
2819
+ if (enclosingNode && is_IfBlockExpression(enclosingNode)) {
2820
+ const { condition, body, else: else_ } = enclosingNode;
2821
+ if (comment.loc.isBefore(condition)) {
2822
+ addLeadingComment(condition, comment);
2823
+ } else if (comment.loc.isBetween(condition, body)) {
2824
+ addTrailingComment(condition, comment);
2825
+ } else if (else_ && comment.loc.isBetween(body, else_)) {
2826
+ if (is_IfBlockExpression(else_)) {
2827
+ addLeadingComment(else_.condition, comment);
2828
+ } else {
2829
+ addCommentToBlock(else_, comment);
2830
+ }
2831
+ }
2832
+ }
2833
+ }
2834
+ function handleMemberExpressionComments({ comment, precedingNode, enclosingNode }) {
2835
+ if (enclosingNode && is_MemberAccessLike(enclosingNode)) {
2836
+ if (isStartOfLine(comment) || !precedingNode)
2837
+ addLeadingComment(enclosingNode, comment);
2838
+ else
2839
+ addTrailingComment(precedingNode, comment);
2840
+ return true;
2841
+ }
2842
+ return false;
2843
+ }
2844
+ function handleDanglingComments({ comment, enclosingNode }) {
2845
+ if (enclosingNode) {
2846
+ for (var key in DCM) {
2847
+ if (key in enclosingNode) {
2848
+ var arr = enclosingNode[key];
2849
+ if (is_LocArray(arr) && canAttachCommentInLocArray(arr) && arr.loc.contains(comment)) {
2850
+ addDanglingComment(enclosingNode, comment, key);
2851
+ return;
2852
+ }
2853
+ }
2854
+ }
2855
+ }
2856
+ }
2857
+ function canAttachCommentInLocArray(arr) {
2858
+ return arr.length === 0 || arr.every((node) => !canAttachComment(node));
2859
+ }
2860
+ function isOwnLine(comment) {
2861
+ return isStartOfLine(comment) && hasBreaklineAfter(comment);
2862
+ }
2863
+ function isStartOfLine(comment) {
2864
+ return comment.placement === "ownLine";
2865
+ }
2866
+ function isEndOfLine(comment) {
2867
+ return comment.placement === "endOfLine";
2868
+ }
2869
+ function isDangling(comment) {
2870
+ return !comment.leading && !comment.trailing;
2871
+ }
2872
+ function isLeading(comment) {
2873
+ return comment.leading && !comment.trailing;
2874
+ }
2875
+ function isTrailing(comment) {
2876
+ return !comment.leading && comment.trailing;
2877
+ }
2878
+ function print_comment(comment) {
2879
+ const doc = is_BlockCommentNode(comment) ? isIndentableBlockComment(comment.value) ? [
2880
+ (!handled(comment) || isTrailing(comment)) && !hasBreaklineBefore(comment) ? hardline : "",
2881
+ getCommentStart(comment),
2882
+ ...comment.value.split(/\n/g).map(
2883
+ (line2, i, a) => i === 0 ? [line2.trimEnd(), hardline] : !iLast(i, a) ? [" " + line2.trim(), hardline] : " " + line2.trimStart()
2884
+ ),
2885
+ "*/"
2886
+ ] : [
2887
+ getCommentStart(comment),
2888
+ //
2889
+ join(literalline, comment.value.split(/\n/g)),
2890
+ "*/"
2891
+ ] : [getCommentStart(comment), comment.value.trimEnd()];
2892
+ return handled(comment) && isDangling(comment) ? [doc, getPostLeadingComment(comment)] : doc;
2893
+ function getCommentStart(comment2) {
2894
+ return is_Comment(comment2) ? is_BlockCommentKind(comment2) ? "/*" : "//" : is_BlockCommentKind(comment2) ? isInner(comment2) ? "/*!" : "/**" : isInner(comment2) ? "//!" : "///";
2895
+ }
2896
+ function isIndentableBlockComment(value) {
2897
+ const lines = `*${value}*`.split(/\n/g);
2898
+ return lines.length > 1 && lines.every((line2) => /^\s*\*/.test(line2));
2899
+ }
2900
+ }
2901
+ function isIdent(node, name) {
2902
+ return !!node && is_Identifier(node) && (null == name || node.name === name);
2903
+ }
2904
+ function isToken(node, tk) {
2905
+ return !!node && (null == tk ? is_PunctuationToken(node) : isTK(node, tk));
2906
+ }
2907
+ function isGroup(node, dk) {
2908
+ return !!node && is_DelimGroup(node) && (null == dk || node.segments.dk === dk);
2909
+ }
2910
+
2911
+ // src/transform/custom/attribute.ts
2912
+ function transform_simpleAttrSyntax(segments) {
2913
+ assert(segments.length !== 0, segments.loc.url());
2914
+ return transform_segments(segments, false);
2915
+ function transform_segments(seq, nestedCall) {
2916
+ let i = 0;
2917
+ if (nestedCall) {
2918
+ const args = rs.createLocArray(DelimKind["()"], seq.loc.clone());
2919
+ while (i !== seq.length) {
2920
+ args.push(read(true));
2921
+ if (i === seq.length)
2922
+ break;
2923
+ assert(isTK(seq[i++], TK[","]));
2924
+ }
2925
+ return args;
2926
+ } else {
2927
+ const res = read(true);
2928
+ assert(i === seq.length, res.loc.url());
2929
+ return res;
2930
+ }
2931
+ function read(allowEq) {
2932
+ let lhs;
2933
+ switch (seq[i].nodeType) {
2934
+ case NodeType.Literal:
2935
+ return seq[i++];
2936
+ case NodeType.Identifier:
2937
+ lhs = seq[i++];
2938
+ break;
2939
+ case NodeType.PunctuationToken:
2940
+ assert(seq[i].tk === TK["::"], seq[i].loc.url());
2941
+ lhs = eatPathSegment(void 0);
2942
+ break;
2943
+ default:
2944
+ exit.never();
2945
+ }
2946
+ while (true) {
2947
+ if (i === seq.length)
2948
+ return lhs;
2949
+ const seg = seq[i];
2950
+ switch (seg.nodeType) {
2951
+ case NodeType.PunctuationToken:
2952
+ switch (seg.tk) {
2953
+ case TK[","]:
2954
+ assert(nestedCall);
2955
+ return lhs;
2956
+ case TK["="]: {
2957
+ assert(allowEq);
2958
+ const right = (i++, read(false));
2959
+ return rs.mockNode(NodeType.ReassignmentExpression, right.loc.cloneFrom(start(lhs)), {
2960
+ tk: TK["="],
2961
+ kind: DelimKind["="],
2962
+ left: lhs,
2963
+ right
2964
+ });
2965
+ }
2966
+ case TK["::"]:
2967
+ lhs = eatPathSegment(lhs);
2968
+ continue;
2969
+ default:
2970
+ exit.never();
2971
+ }
2972
+ case NodeType.DelimGroup:
2973
+ assert(seg.segments.dk === DelimKind["()"]);
2974
+ return rs.mockNode(NodeType.CallExpression, seq[i++].loc.cloneFrom(start(lhs)), {
2975
+ callee: lhs,
2976
+ typeArguments: void 0,
2977
+ method: void 0,
2978
+ arguments: transform_segments(seg.segments, true)
2979
+ });
2980
+ default:
2981
+ exit.never();
2982
+ }
2983
+ }
2984
+ }
2985
+ function eatPathSegment(left) {
2986
+ const segment = seq[i + 1];
2987
+ assert(isIdent(segment));
2988
+ const res = rs.mockNode(NodeType.ExpressionPath, segment.loc.cloneFrom(start(left ?? seq[i])), { namespace: left, segment });
2989
+ i += 2;
2990
+ return res;
2991
+ }
2992
+ }
2993
+ }
2994
+ function transform_macro_cfg_if(segments) {
2995
+ const danglingAttributes = [];
2996
+ const comments = [];
2997
+ const block = function create_if_block(i) {
2998
+ if (i >= segments.length)
2999
+ return void 0;
3000
+ const _if = segments[i];
3001
+ const pound = segments[i + 1];
3002
+ const grp = segments[i + 2];
3003
+ const block2 = segments[i + 3];
3004
+ const _else = segments[i + 4];
3005
+ assert(
3006
+ isIdent(_if, "if") && isToken(pound, TK["#"]) && isGroup(grp, DelimKind["[]"]) && isGroup(block2, DelimKind["{}"]) && (!_else || isIdent(_else, "else"))
3007
+ );
3008
+ return create_block(
3009
+ block2,
3010
+ (body) => rs.mockNode(NodeType.IfBlockExpression, block2.loc.cloneFrom(start(_if)), {
3011
+ label: void 0,
3012
+ condition: rs.mockNode(NodeType.Attribute, grp.loc.cloneFrom(start(pound)), {
3013
+ segments: grp.segments,
3014
+ value: grp.segments.loc.sliceText(),
3015
+ line: false,
3016
+ inner: false
3017
+ }),
3018
+ body,
3019
+ else: (_else && iLast(i + 5, segments) ? function create_else_block(i2) {
3020
+ const block3 = segments[i2];
3021
+ assert(isGroup(block3, DelimKind["{}"]));
3022
+ return create_block(
3023
+ block3,
3024
+ (body2) => rs.mockNode(NodeType.BlockExpression, body2.loc.clone(), {
3025
+ label: void 0,
3026
+ body: body2
3027
+ })
3028
+ );
3029
+ } : create_if_block)(i + 5)
3030
+ })
3031
+ );
3032
+ }(0);
3033
+ const ast = rs.createLocArray(
3034
+ segments.dk,
3035
+ segments.loc,
3036
+ block && [
3037
+ rs.mockNode(NodeType.ExpressionStatement, block.loc.clone(), {
3038
+ expression: block,
3039
+ semi: false
3040
+ })
3041
+ ]
3042
+ );
3043
+ return rs.mockNode(NodeType.Snippet, segments.loc.clone(), { ast, danglingAttributes, comments });
3044
+ function create_block(group2, fn) {
3045
+ const snippet = rs.toBlockBody(group2.segments);
3046
+ insertNodes(danglingAttributes, snippet.danglingAttributes);
3047
+ insertNodes(comments, snippet.comments);
3048
+ const block2 = fn(snippet.ast);
3049
+ transferAttributes(snippet, block2);
3050
+ return block2;
3051
+ }
3052
+ }
3053
+
3054
+ // src/transform/index.ts
3055
+ function is_CallLikeMacroInvocation(node) {
3056
+ return is_MacroInvocation(node) && "arguments" in node;
3057
+ }
3058
+ function is_BlockLikeMacroInvocation(node) {
3059
+ return is_MacroInvocation(node) && "body" in node;
3060
+ }
3061
+ function is_CallExpression_or_CallLikeMacroInvocation(node) {
3062
+ return is_CallExpression(node) || is_CallLikeMacroInvocation(node);
3063
+ }
3064
+ var IGNORED_MACROS = /* @__PURE__ */ new Set([
3065
+ // std
3066
+ // crates
3067
+ "quote"
3068
+ ]);
3069
+ var HARDCODED_MACRO_DELIMS = /* @__PURE__ */ new Map();
3070
+ each(
3071
+ {
3072
+ [DelimKind["{}"]]: [
3073
+ // std
3074
+ "thread_local",
3075
+ // crates
3076
+ "cfg_if"
3077
+ ],
3078
+ [DelimKind["()"]]: [
3079
+ // std
3080
+ "assert_eq",
3081
+ "assert_ne",
3082
+ "assert",
3083
+ "cfg",
3084
+ "concat_bytes",
3085
+ "concat_idents",
3086
+ "concat",
3087
+ "debug_assert_eq",
3088
+ "debug_assert_ne",
3089
+ "debug_assert",
3090
+ "eprint",
3091
+ "eprintln",
3092
+ "format_args_nl",
3093
+ "format_args",
3094
+ "format",
3095
+ "matches",
3096
+ "panic",
3097
+ "print",
3098
+ "println",
3099
+ "try",
3100
+ "unimplemented",
3101
+ "unreachable",
3102
+ "write",
3103
+ "writeln"
3104
+ // crates
3105
+ ],
3106
+ [DelimKind["[]"]]: [
3107
+ // std
3108
+ "vec"
3109
+ // crates
3110
+ ]
3111
+ },
3112
+ (names, tk) => each(names, (name) => {
3113
+ HARDCODED_MACRO_DELIMS.set(name, +tk);
3114
+ })
3115
+ );
3116
+ var _COMMENTS = void 0;
3117
+ var _DANGLING_ATTRIBUTES = void 0;
3118
+ function transform_ast(options2) {
3119
+ try {
3120
+ _COMMENTS = options2.comments;
3121
+ _DANGLING_ATTRIBUTES = options2.danglingAttributes;
3122
+ transformNode(options2.rsParsedFile);
3123
+ } finally {
3124
+ _depth = 0;
3125
+ _COMMENTS = void 0;
3126
+ _DANGLING_ATTRIBUTES = void 0;
3127
+ }
3128
+ }
3129
+ var _depth = 0;
3130
+ var isReadingSnippet = () => 0 !== _depth;
3131
+ function maybe_transform_node(node, read_snippet, fn) {
3132
+ const snippet = try_eval(read_snippet);
3133
+ if (snippet) {
3134
+ ++_depth;
3135
+ transformNode(snippet);
3136
+ --_depth;
3137
+ fn(node, snippet);
3138
+ transformed.add(node);
3139
+ return node;
3140
+ }
3141
+ }
3142
+ var transformed = /* @__PURE__ */ new WeakSet();
3143
+ function isTransformed(node) {
3144
+ return transformed.has(node);
3145
+ }
3146
+ var transform = {
3147
+ [NodeType.Attribute](node) {
3148
+ try_eval(() => {
3149
+ node.segments = rs.createLocArray(node.segments.dk, node.segments.loc.clone(), [
3150
+ transform_simpleAttrSyntax(node.segments)
3151
+ ]);
3152
+ transformed.add(node);
3153
+ });
3154
+ },
3155
+ [NodeType.MacroInlineRuleDeclaration](node) {
3156
+ node.match.dk = DelimKind["()"];
3157
+ node.transform.dk = DelimKind["{}"];
3158
+ },
3159
+ [NodeType.MacroInvocation](node) {
3160
+ const name = getMacroName(node);
3161
+ if (IGNORED_MACROS.has(name) || node.segments.length === 0 || node.segments.length === 1 && is_PunctuationToken(node.segments[0])) {
3162
+ return;
3163
+ }
3164
+ const tk = transformMacroDelim(name, node);
3165
+ if (name === "cfg_if") {
3166
+ transformBlockLike(() => transform_macro_cfg_if(node.segments));
3167
+ } else if (tk === DelimKind["{}"]) {
3168
+ transformBlockLike();
3169
+ } else {
3170
+ transformCallLike();
3171
+ }
3172
+ function transformBlockLike(transform2 = () => rs.toBlockBody(node.segments)) {
3173
+ return maybe_transform_node(node, transform2, (node2, snippet) => {
3174
+ const _body = snippet.ast;
3175
+ _body.dk = tk;
3176
+ node2.body = _body;
3177
+ node2.segments = _body;
3178
+ transferAttributes(snippet, node2);
3179
+ });
3180
+ }
3181
+ function transformCallLike() {
3182
+ return maybe_transform_node(
3183
+ node,
3184
+ () => rs.toCallExpressionArguments(node.segments),
3185
+ (node2, snippet) => {
3186
+ const _arguments = snippet.ast;
3187
+ _arguments.dk = tk;
3188
+ node2.method = void 0;
3189
+ node2.typeArguments = void 0;
3190
+ node2.arguments = _arguments;
3191
+ node2.segments = _arguments;
3192
+ }
3193
+ );
3194
+ }
3195
+ },
3196
+ [NodeType.CallExpression](node) {
3197
+ if (hasMethod(node)) {
3198
+ node.callee = rs.mockNode(NodeType.MemberExpression, node.method.loc.cloneFrom(start(node.callee)), {
3199
+ expression: node.callee,
3200
+ property: node.method,
3201
+ computed: false
3202
+ });
3203
+ node.method = void 0;
3204
+ getOptions().actuallyMethodNodes.add(node.callee);
3205
+ }
3206
+ },
3207
+ [NodeType.AutoTraitDeclaration](node) {
3208
+ mockBodyNoBody(node);
3209
+ },
3210
+ [NodeType.NegativeImplDeclaration](node) {
3211
+ mockBodyNoBody(node);
3212
+ },
3213
+ [NodeType.StructLiteral](node) {
3214
+ moveSpreadsToEnd(node);
3215
+ },
3216
+ [NodeType.StructPattern](node) {
3217
+ moveSpreadsToEnd(node);
3218
+ }
3219
+ };
3220
+ function moveSpreadsToEnd(node) {
3221
+ const props = node.properties;
3222
+ if (props.some((p, i, a) => is_StructSpread(p) && !iLast(i, a))) {
3223
+ const spreads = [];
3224
+ for (let i = 0; i < props.length; i++) {
3225
+ const prop = props[i];
3226
+ if (is_StructSpread(prop)) {
3227
+ Array_splice(props, prop, i--);
3228
+ spreads.push(prop);
3229
+ }
3230
+ }
3231
+ props.push(...spreads);
3232
+ }
3233
+ }
3234
+ function mockBodyNoBody(node) {
3235
+ node.body = rs.createLocArray(last_of(rs.toTokens(node).ast).loc.clone(), DelimKind["{}"]);
3236
+ }
3237
+ function transformMacroDelim(name, node) {
3238
+ if (HARDCODED_MACRO_DELIMS.has(name)) {
3239
+ return HARDCODED_MACRO_DELIMS.get(name);
3240
+ }
3241
+ if (node.segments.dk === DelimKind["{}"] && includesTK(node, TK[","])) {
3242
+ return DelimKind["()"];
3243
+ }
3244
+ if (node.segments.dk === DelimKind["()"] && includesTK(node, TK[";"])) {
3245
+ return DelimKind["{}"];
3246
+ }
3247
+ return node.segments.dk;
3248
+ }
3249
+ var seen = /* @__PURE__ */ new WeakSet();
3250
+ function transformNode(node, parent, key, index) {
3251
+ if (!seen.has(node)) {
3252
+ seen.add(node);
3253
+ if (is_Snippet(node) || is_Program(node)) {
3254
+ registerPogramLike(node);
3255
+ }
3256
+ each_childNode(node, transformNode);
3257
+ insert_blocks(node, parent, key, index);
3258
+ transform[node.nodeType]?.(node);
3259
+ flatten_typeBounds(node);
3260
+ transform_nodeAttributes(node);
3261
+ }
3262
+ return node;
3263
+ }
3264
+ function insert_blocks(node, parent, key, index) {
3265
+ if (parent && key) {
3266
+ if (!is_ExpressionStatement(parent) && (// "1 + break" -> "1 + { break; }"
3267
+ is_FlowControlExpression(node) || // "1 + a = b" -> "1 + { a = b; }"
3268
+ !isReadingSnippet() && is_ReassignmentNode(node) && !(is_ReassignmentNode(parent) && parent.left === node))) {
3269
+ reassignNodeProperty(blockify(node), parent, key, index);
3270
+ } else if (is_ClosureFunctionExpression(node) && (// "|| -> T x" -> "|| -> T { x }"
3271
+ !!node.returnType && !is_BlockExpression(node.expression) || // "|| match x {}" -> "|| { match x {} }"
3272
+ is_ExpressionWithBodyOrCases(node.expression) && !is_BlockExpression(node.expression) && !is_IfBlockExpression(node.expression))) {
3273
+ node.expression = blockify(node.expression);
3274
+ }
3275
+ }
3276
+ function blockify(node2) {
3277
+ const block = rs.mockNode(NodeType.BlockExpression, node2.loc.clone(), {
3278
+ label: void 0,
3279
+ body: rs.createLocArray(DelimKind["{}"], node2.loc.clone(), [
3280
+ rs.mockNode(NodeType.ExpressionStatement, node2.loc.clone(), { semi: false, expression: node2 })
3281
+ ])
3282
+ });
3283
+ transferAttributes(node2, block);
3284
+ return block;
3285
+ }
3286
+ }
3287
+ function flatten_typeBounds(topNode) {
3288
+ if (hasTypeBounds(topNode)) {
3289
+ const nestedBounds = topNode.typeBounds.filter(isBoundWithNestedBounds);
3290
+ const [first, ...subsequent] = nestedBounds;
3291
+ const flatten = (bound) => Array_replace(topNode.typeBounds, bound, ...bound.typeExpression.typeBounds);
3292
+ if (nestedBounds.every(isBareBoundWithNestedBoundsNoPrefix)) {
3293
+ each(nestedBounds, flatten);
3294
+ } else if (!hasDefinedPrefix(topNode) && first === topNode.typeBounds[0] && !isBareBoundWithNestedBoundsNoPrefix(first) && subsequent.every(isBareBoundWithNestedBoundsNoPrefix)) {
3295
+ if (is_TypeDynBounds(topNode)) {
3296
+ if (is_TypeImplBounds(first.typeExpression)) {
3297
+ unsafe_set_nodeType(topNode, NodeType.TypeImplBounds);
3298
+ } else {
3299
+ topNode.dyn = true;
3300
+ }
3301
+ each(nestedBounds, flatten);
3302
+ } else {
3303
+ each(subsequent, flatten);
3304
+ first.typeExpression.typeBounds.push(...topNode.typeBounds.slice(1));
3305
+ topNode.typeBounds.length = 1;
3306
+ }
3307
+ }
3308
+ }
3309
+ function isBoundWithNestedBounds(bound) {
3310
+ return is_TypeTraitBound(bound) && is_TypeBoundsStandaloneNode(bound.typeExpression);
3311
+ }
3312
+ function isBareBoundWithNestedBounds(bound) {
3313
+ return isBoundWithNestedBounds(bound) && is_BareTypeTraitBound(bound);
3314
+ }
3315
+ function isBareBoundWithNestedBoundsNoPrefix(bound) {
3316
+ return isBareBoundWithNestedBounds(bound) && !hasDefinedPrefix(bound.typeExpression);
3317
+ }
3318
+ function hasDefinedPrefix(node) {
3319
+ return is_TypeDynBounds(node) && node.dyn || is_TypeImplBounds(node);
3320
+ }
3321
+ }
3322
+ function transform_nodeAttributes(node) {
3323
+ if (hasAttributes(node)) {
3324
+ const attrs = node.attributes;
3325
+ for (let i = 0; i < attrs.length; i++) {
3326
+ const attr = attrs[i];
3327
+ if (isReadingSnippet() && is_DocCommentAttribute(attr)) {
3328
+ const index = binarySearchIn(_COMMENTS, start(attr), start);
3329
+ _COMMENTS.splice(index, 1);
3330
+ }
3331
+ if (attr.inner) {
3332
+ if (isPrettierIgnoreAttribute(attr)) {
3333
+ setPrettierIgnoreTarget(is_Program(node) ? node.loc.src : node, attr);
3334
+ }
3335
+ insertNode(is_Snippet(node) ? node.ast : getBodyOrCases(node), attr);
3336
+ Array_splice(attrs, attr, i--);
3337
+ }
3338
+ }
3339
+ if (attrs.length === 0) {
3340
+ deleteAttributes(node);
3341
+ }
3342
+ }
3343
+ }
3344
+ function registerPogramLike(program) {
3345
+ const comments = spliceAll(program.comments);
3346
+ const danglingAttributes = spliceAll(program.danglingAttributes);
3347
+ for (let i = 0; i < danglingAttributes.length; i++) {
3348
+ const attr = danglingAttributes[i];
3349
+ if (is_DocCommentAttribute(attr)) {
3350
+ if (isReadingSnippet()) {
3351
+ const index = binarySearchIn(_COMMENTS, start(attr), start);
3352
+ _COMMENTS.splice(index, 1);
3353
+ }
3354
+ } else {
3355
+ transformNode(danglingAttributes[i], program, "danglingAttributes", i);
3356
+ }
3357
+ }
3358
+ if (!isReadingSnippet())
3359
+ insertNodes(_COMMENTS, comments);
3360
+ insertNodes(_DANGLING_ATTRIBUTES, danglingAttributes);
3361
+ }
3362
+ var CommentChildNodes = /* @__PURE__ */ new WeakMap();
3363
+ function getVisitorKeys(node, nonTraversableKeys) {
3364
+ if (!is_Node(node))
3365
+ return [];
3366
+ const keys = [];
3367
+ for (const key of Object.keys(node)) {
3368
+ if (nonTraversableKeys.has(key))
3369
+ continue;
3370
+ const value = node[key];
3371
+ if (is_Node(value) || Array.isArray(value) && value.some(is_Node))
3372
+ keys.push(key);
3373
+ }
3374
+ return keys;
3375
+ }
3376
+ function getCommentChildNodes(n) {
3377
+ if (!is_Node(n))
3378
+ return [];
3379
+ const children = Map_get(CommentChildNodes, n, getTransformedNodeChildren);
3380
+ if (is_NodeWithBodyOrCases(n) || is_BlockLikeMacroInvocation(n)) {
3381
+ for (let i = 0; i < children.length; i++) {
3382
+ const attr = children[i];
3383
+ if (is_AttributeOrDocComment(attr)) {
3384
+ const target = children.find((n2) => start(n2) <= start(attr) && ownStart(n2) >= end(attr));
3385
+ if (target) {
3386
+ children.splice(i--, 1);
3387
+ insertNode(Map_get(CommentChildNodes, target, getTransformedNodeChildren), attr);
3388
+ }
3389
+ }
3390
+ }
3391
+ }
3392
+ return children;
3393
+ function getTransformedNodeChildren(node) {
3394
+ if (is_Program(node))
3395
+ node.comments ?? (node.comments = []);
3396
+ const children2 = getNodeChildren(node);
3397
+ if (is_NodeWithBodyNoBody(node)) {
3398
+ insertNodes(children2, node.body);
3399
+ }
3400
+ return children2;
3401
+ }
3402
+ }
3403
+ var printer = {
3404
+ [NodeType.MissingNode](print4, node) {
3405
+ return "";
3406
+ },
3407
+ [NodeType.SourceFile](print4, node) {
3408
+ return [
3409
+ print4.b("UTF8BOM", "\uFEFF"),
3410
+ //
3411
+ print4("shebang"),
3412
+ print4("program")
3413
+ ];
3414
+ },
3415
+ [NodeType.Shebang](print4, node) {
3416
+ return [`#!${node.value}`, hardline];
3417
+ },
3418
+ [NodeType.Program](print4, node) {
3419
+ return printBodyOrCases(print4, node);
3420
+ },
3421
+ [NodeType.Snippet](print4, node) {
3422
+ exit.never();
3423
+ },
3424
+ [NodeType.Identifier](print4, node) {
3425
+ return node.name;
3426
+ },
3427
+ [NodeType.Index](print4, node) {
3428
+ return node.name;
3429
+ },
3430
+ [NodeType.LbIdentifier](print4, node) {
3431
+ return node.name;
3432
+ },
3433
+ [NodeType.McIdentifier](print4, node) {
3434
+ return node.name;
3435
+ },
3436
+ [NodeType.LtIdentifier](print4, node) {
3437
+ return node.name;
3438
+ },
3439
+ [NodeType.PunctuationToken](print4, node) {
3440
+ return node.token;
3441
+ },
3442
+ [NodeType.DelimGroup](print4, node) {
3443
+ return node.loc.getOwnText();
3444
+ },
3445
+ [NodeType.Literal](print4, node) {
3446
+ let { value } = node;
3447
+ if (is_LiteralNumberLike(node))
3448
+ value = printNumber(value);
3449
+ return hasSuffix(node) ? [value, print4("suffix")] : value;
3450
+ },
3451
+ [NodeType.ItemPath](print4, node) {
3452
+ return [print4("namespace"), "::", print4("segment")];
3453
+ },
3454
+ [NodeType.ExpressionPath](print4, node) {
3455
+ return [print4("namespace"), "::", print4("segment")];
3456
+ },
3457
+ [NodeType.TypePath](print4, node) {
3458
+ return [print4("namespace"), "::", print4("segment")];
3459
+ },
3460
+ [NodeType.Comment](print4, node) {
3461
+ return print_comment(node);
3462
+ },
3463
+ [NodeType.DocCommentAttribute](print4, node) {
3464
+ return print_comment(node);
3465
+ },
3466
+ [NodeType.Attribute](print4, node) {
3467
+ return [
3468
+ node.inner ? "#![" : "#[",
3469
+ isTransformed(node) ? [print4("segments"), printDanglingCommentsForInline(node)] : node.segments.loc.sliceText(1, -1).trim(),
3470
+ "]"
3471
+ ];
3472
+ },
3473
+ [NodeType.MacroInvocation](print4, node) {
3474
+ const hasCurlyBrackets = node.segments.dk === DelimKind["{}"];
3475
+ const delim = getDelimChars(node.segments);
3476
+ if (node.segments.length === 0) {
3477
+ return [print4("callee"), "!", hasCurlyBrackets ? " " : "", delim.left, printDanglingCommentsForInline(node), delim.right];
3478
+ }
3479
+ if (isTransformed(node)) {
3480
+ if (is_CallLikeMacroInvocation(node)) {
3481
+ return [print4("callee"), "!", printCallArguments(print4, node)];
3482
+ }
3483
+ if (is_BlockLikeMacroInvocation(node)) {
3484
+ return [print4("callee"), "!", " ", printBlockBody(print4, node)];
3485
+ }
3486
+ }
3487
+ let content = node.segments.loc.sliceText(1, -1);
3488
+ if (content.trim().length === 0) {
3489
+ content = "";
3490
+ } else if (!content.includes("\n")) {
3491
+ content = content.trim();
3492
+ if (hasCurlyBrackets)
3493
+ content = " " + content + " ";
3494
+ }
3495
+ return [print4("callee"), "!", hasCurlyBrackets ? " " : "", delim.left, content, delim.right];
3496
+ },
3497
+ [NodeType.MacroRulesDeclaration](print4, node) {
3498
+ return ["macro_rules! ", print4("id"), printMacroRules(print4, node)];
3499
+ },
3500
+ [NodeType.MacroRuleDeclaration](print4, node) {
3501
+ return [printRuleMatch(print4, node), " => ", printRuleTransform(print4, node), ";"];
3502
+ },
3503
+ [NodeType.MacroDeclaration](print4, node) {
3504
+ return [print4("pub"), "macro ", print4("id"), printMacroRules(print4, node)];
3505
+ },
3506
+ [NodeType.MacroInlineRuleDeclaration](print4, node) {
3507
+ return [printRuleMatch(print4, node), " ", printRuleTransform(print4, node)];
3508
+ },
3509
+ [NodeType.MacroGroup](print4, node) {
3510
+ return node.loc.getOwnText();
3511
+ },
3512
+ [NodeType.MacroParameterDeclaration](print4, node) {
3513
+ return [print4("id"), ":", print4("ty")];
3514
+ },
3515
+ [NodeType.PubSpecifier](print4, node) {
3516
+ if (!node.location)
3517
+ return "pub ";
3518
+ if (is_Identifier(node.location)) {
3519
+ switch (node.location.name) {
3520
+ case "crate":
3521
+ if (start(node) === start(node.location)) {
3522
+ return "crate ";
3523
+ } else {
3524
+ return ["pub(", print4("location"), ") "];
3525
+ }
3526
+ case "self":
3527
+ case "super":
3528
+ return ["pub(", print4("location"), ") "];
3529
+ }
3530
+ }
3531
+ return ["pub(in ", print4("location"), ") "];
3532
+ },
3533
+ [NodeType.ExternSpecifier](print4, node) {
3534
+ return ["extern ", f`${print4("abi")} `];
3535
+ },
3536
+ [NodeType.ExpressionStatement](print4, node) {
3537
+ return [print4("expression"), stmtNeedsSemi(node) ? ";" : ""];
3538
+ },
3539
+ [NodeType.UseStatement](print4, node) {
3540
+ return [print4("pub"), "use ", print4("import"), ";"];
3541
+ },
3542
+ [NodeType.DestructuredImport](print4, node) {
3543
+ if (node.specifiers.length === 0)
3544
+ return [print4("source"), "::{", printDanglingCommentsForInline(node, "specifiers" /* specifiers */), "}"];
3545
+ return [
3546
+ print4("source"),
3547
+ group([
3548
+ "::{",
3549
+ indent([line , join([",", line], print4("specifiers")), ifBreak(",")]),
3550
+ line ,
3551
+ "}"
3552
+ ])
3553
+ ];
3554
+ },
3555
+ [NodeType.AmbientImport](print4, node) {
3556
+ return f`${print4("source")}::*` || "*";
3557
+ },
3558
+ [NodeType.AnonymousImport](print4, node) {
3559
+ return [print4("source"), " as ", "_"];
3560
+ },
3561
+ [NodeType.NamedImport](print4, node) {
3562
+ return [print4("source"), f` as ${print4("local")}`];
3563
+ },
3564
+ [NodeType.ExternCrateStatement](print4, node) {
3565
+ return [print4("pub"), "extern crate ", print4("import"), ";"];
3566
+ },
3567
+ [NodeType.TypeAliasDeclaration](print4, node) {
3568
+ return [
3569
+ print4("pub"),
3570
+ "type",
3571
+ printAssignment(
3572
+ printGenerics_x_whereBounds(print4, node, printDeclarationTypeBounds(print4, node, ":")),
3573
+ //
3574
+ " =",
3575
+ "typeExpression"
3576
+ ),
3577
+ ";"
3578
+ ];
3579
+ },
3580
+ [NodeType.LetVariableDeclaration](print4, node) {
3581
+ return [
3582
+ "let ",
3583
+ printAssignment(
3584
+ printAnnotatedPattern(print4, node),
3585
+ //
3586
+ " =",
3587
+ "expression"
3588
+ ),
3589
+ f` else ${print4("else")}`,
3590
+ ";"
3591
+ ];
3592
+ },
3593
+ [NodeType.ConstVariableDeclaration](print4, node) {
3594
+ return [
3595
+ print4("pub"),
3596
+ "const ",
3597
+ printAssignment(
3598
+ printAnnotatedPattern(print4, node),
3599
+ //
3600
+ " =",
3601
+ "expression"
3602
+ ),
3603
+ ";"
3604
+ ];
3605
+ },
3606
+ [NodeType.StaticVariableDeclaration](print4, node) {
3607
+ return [
3608
+ print4("pub"),
3609
+ "static ",
3610
+ printAssignment(
3611
+ printAnnotatedPattern(print4, node),
3612
+ //
3613
+ " =",
3614
+ "expression"
3615
+ ),
3616
+ ";"
3617
+ ];
3618
+ },
3619
+ [NodeType.ModuleDeclaration](print4, node) {
3620
+ return [
3621
+ print4("pub"),
3622
+ //
3623
+ print4.b("unsafe"),
3624
+ "mod ",
3625
+ print4("id"),
3626
+ printMaybeBlockBody(print4, node)
3627
+ ];
3628
+ },
3629
+ [NodeType.ExternBlockDeclaration](print4, node) {
3630
+ return [
3631
+ print4("pub"),
3632
+ //
3633
+ print4.b("unsafe"),
3634
+ "extern ",
3635
+ f`${print4("abi")} `,
3636
+ printBlockBody(print4, node)
3637
+ ];
3638
+ },
3639
+ [NodeType.FunctionDeclaration](print4, node) {
3640
+ return [
3641
+ print4("pub"),
3642
+ print4.b("const"),
3643
+ print4.b("async"),
3644
+ print4.b("unsafe"),
3645
+ print4("extern"),
3646
+ "fn",
3647
+ printGenerics_x_whereBounds(print4, node, printParametersAndReturnType(node)),
3648
+ printMaybeBlockBody(print4, node)
3649
+ ];
3650
+ },
3651
+ [NodeType.FunctionSelfParameterDeclaration](print4, node) {
3652
+ return group([print4.b("ref", "&"), f`${print4("lt")} `, print4.b("mut"), "self", printTypeAnnotation(print4, node)]);
3653
+ },
3654
+ [NodeType.FunctionParameterDeclaration](print4, node) {
3655
+ return group(printAnnotatedPattern(print4, node));
3656
+ },
3657
+ [NodeType.FunctionSpread](print4, node) {
3658
+ return "...";
3659
+ },
3660
+ [NodeType.StructDeclaration](print4, node) {
3661
+ return [print4("pub"), "struct", printGenerics_x_whereBounds(print4, node, ""), printObject(print4, node)];
3662
+ },
3663
+ [NodeType.StructPropertyDeclaration](print4, node) {
3664
+ return [print4("pub"), print4("id"), printTypeAnnotation(print4, node)];
3665
+ },
3666
+ [NodeType.TupleStructDeclaration](print4, node) {
3667
+ return [print4("pub"), "struct", printGenerics_x_whereBounds(print4, node, printArrayLike(print4, node)), ";"];
3668
+ },
3669
+ [NodeType.TupleStructItemDeclaration](print4, node) {
3670
+ return [print4("pub"), print4("typeAnnotation")];
3671
+ },
3672
+ [NodeType.UnionDeclaration](print4, node) {
3673
+ return [print4("pub"), "union", printGenerics_x_whereBounds(print4, node, ""), printObject(print4, node)];
3674
+ },
3675
+ [NodeType.EnumDeclaration](print4, node) {
3676
+ return [print4("pub"), "enum", printGenerics_x_whereBounds(print4, node, ""), printEnumBody(print4, node)];
3677
+ },
3678
+ [NodeType.EnumMemberDeclaration](print4, node) {
3679
+ return [
3680
+ print4("pub"),
3681
+ printAssignment(
3682
+ print4("id"),
3683
+ //
3684
+ " =",
3685
+ "value"
3686
+ )
3687
+ ];
3688
+ },
3689
+ [NodeType.EnumMemberTupleDeclaration](print4, node) {
3690
+ return [
3691
+ print4("pub"),
3692
+ printAssignment(
3693
+ [print4("id"), printArrayLike(print4, node)],
3694
+ //
3695
+ " =",
3696
+ "value"
3697
+ )
3698
+ ];
3699
+ },
3700
+ [NodeType.EnumMemberStructDeclaration](print4, node) {
3701
+ return [
3702
+ print4("pub"),
3703
+ printAssignment(
3704
+ [print4("id"), printObject(print4, node)],
3705
+ //
3706
+ " =",
3707
+ "value"
3708
+ )
3709
+ ];
3710
+ },
3711
+ [NodeType.TraitDeclaration](print4, node) {
3712
+ return [
3713
+ print4("pub"),
3714
+ print4.b("unsafe"),
3715
+ "trait",
3716
+ printGenerics_x_whereBounds(print4, node, printDeclarationTypeBounds(print4, node, ":")),
3717
+ adjustClause(node, printBlockBody(print4, node))
3718
+ ];
3719
+ },
3720
+ [NodeType.AutoTraitDeclaration](print4, node) {
3721
+ return [
3722
+ print4("pub"),
3723
+ print4.b("unsafe"),
3724
+ "auto trait ",
3725
+ print4("id"),
3726
+ " ",
3727
+ printBlockBody(print4, node)
3728
+ // see "transform.ts"
3729
+ ];
3730
+ },
3731
+ [NodeType.TraitAliasDeclaration](print4, node) {
3732
+ return [
3733
+ print4("pub"),
3734
+ print4.b("unsafe"),
3735
+ "trait",
3736
+ printGenerics_x_whereBounds(print4, node, printDeclarationTypeBounds(print4, node, " =")),
3737
+ ";"
3738
+ ];
3739
+ },
3740
+ [NodeType.ImplDeclaration](print4, node) {
3741
+ return [
3742
+ print4("pub"),
3743
+ print4.b("unsafe"),
3744
+ "impl",
3745
+ printGenerics_x_whereBounds(print4, node, [print4.b("const"), printImplTraitForType(print4, node)]),
3746
+ adjustClause(node, printBlockBody(print4, node))
3747
+ ];
3748
+ },
3749
+ [NodeType.NegativeImplDeclaration](print4, node) {
3750
+ return [
3751
+ print4("pub"),
3752
+ "impl",
3753
+ printGenerics_x_whereBounds(print4, node, ["!", printImplTraitForType(print4, node)]),
3754
+ " ",
3755
+ printBlockBody(print4, node)
3756
+ // see "transform.ts"
3757
+ ];
3758
+ },
3759
+ [NodeType.ExpressionTypeSelector](print4, node) {
3760
+ return group(["<", print4("typeTarget"), f` as ${print4("typeExpression")}`, ">"]);
3761
+ },
3762
+ [NodeType.ExpressionTypeCast](print4, node) {
3763
+ return [print4("typeCallee"), f`::${printTypeArguments(print4, node)}`];
3764
+ },
3765
+ [NodeType.ExpressionAsTypeCast](print4, node) {
3766
+ return [print4("expression"), " as ", print4("typeExpression")];
3767
+ },
3768
+ [NodeType.ReturnExpression](print4, node) {
3769
+ return ["return", printFlowControlExpression(print4, node)];
3770
+ },
3771
+ [NodeType.BreakExpression](print4, node) {
3772
+ return ["break", f` ${print4("label")}`, printFlowControlExpression(print4, node)];
3773
+ },
3774
+ [NodeType.ContinueExpression](print4, node) {
3775
+ return ["continue", f` ${print4("label")}`];
3776
+ },
3777
+ [NodeType.YieldExpression](print4, node) {
3778
+ return ["yield", printFlowControlExpression(print4, node)];
3779
+ },
3780
+ [NodeType.RangeLiteral](print4, node) {
3781
+ return [print4("lower"), "..", print4.b("last", "="), print4("upper")];
3782
+ },
3783
+ [NodeType.CallExpression](print4, node) {
3784
+ return printCallExpression(print4, node);
3785
+ },
3786
+ [NodeType.MemberExpression](print4, node) {
3787
+ return printMemberExpression(print4, node);
3788
+ },
3789
+ [NodeType.AwaitExpression](print4, node) {
3790
+ return [print4("expression"), ".await"];
3791
+ },
3792
+ [NodeType.UnwrapExpression](print4, node) {
3793
+ return [print4("expression"), "?"];
3794
+ },
3795
+ [NodeType.ParenthesizedExpression](print4, node) {
3796
+ exit.never();
3797
+ const shouldHug = !hasComment(node.expression) && (is_ArrayOrTupleLiteral(node.expression) || is_StructLiteral(node.expression));
3798
+ if (shouldHug)
3799
+ return ["(", print4("expression"), ")"];
3800
+ return group(["(", indent([softline, print4("expression")]), softline, ")"]);
3801
+ },
3802
+ [NodeType.MinusExpression](print4, node) {
3803
+ return printUnaryExpression("-");
3804
+ },
3805
+ [NodeType.NotExpression](print4, node) {
3806
+ return printUnaryExpression("!");
3807
+ },
3808
+ [NodeType.OrExpression](print4, node) {
3809
+ return printBinaryishExpression(print4, node);
3810
+ },
3811
+ [NodeType.AndExpression](print4, node) {
3812
+ return printBinaryishExpression(print4, node);
3813
+ },
3814
+ [NodeType.ReassignmentExpression](print4, node) {
3815
+ return printAssignment(print4("left"), " =", "right");
3816
+ },
3817
+ [NodeType.UnassignedExpression](print4, node) {
3818
+ return "_";
3819
+ },
3820
+ [NodeType.OperationExpression](print4, node) {
3821
+ return printBinaryishExpression(print4, node);
3822
+ },
3823
+ [NodeType.ReassignmentOperationExpression](print4, node) {
3824
+ return printAssignment(print4("left"), " " + node.kind, "right");
3825
+ },
3826
+ [NodeType.ComparisonExpression](print4, node) {
3827
+ return printBinaryishExpression(print4, node);
3828
+ },
3829
+ [NodeType.LetScrutinee](print4, node) {
3830
+ return ["let ", printAssignment(print4("pattern"), " =", "expression")];
3831
+ },
3832
+ [NodeType.ClosureFunctionExpression](print4, node) {
3833
+ return printArrowFunction(print4, node);
3834
+ },
3835
+ [NodeType.ClosureFunctionParameterDeclaration](print4, node) {
3836
+ return group(printAnnotatedPattern(print4, node));
3837
+ },
3838
+ [NodeType.BlockExpression](print4, node) {
3839
+ return [
3840
+ f`${print4("label")}: `,
3841
+ print4.b("const"),
3842
+ print4.b("async"),
3843
+ print4.b("move"),
3844
+ print4.b("unsafe"),
3845
+ printBlockBody(print4, node)
3846
+ ];
3847
+ },
3848
+ [NodeType.LoopBlockExpression](print4, node) {
3849
+ return [f`${print4("label")}: `, "loop ", printBlockBody(print4, node)];
3850
+ },
3851
+ [NodeType.WhileBlockExpression](print4, node) {
3852
+ return [f`${print4("label")}: `, "while ", printCondition(print4, node), printBlockBody(print4, node)];
3853
+ },
3854
+ [NodeType.ForInBlockExpression](print4, node) {
3855
+ return [f`${print4("label")}: `, "for ", print4("pattern"), " in ", print4("expression"), " ", printBlockBody(print4, node)];
3856
+ },
3857
+ [NodeType.IfBlockExpression](print4, node) {
3858
+ return [f`${print4("label")}: `, printIfBlock(print4, node)];
3859
+ },
3860
+ [NodeType.TryBlockExpression](print4, node) {
3861
+ return [f`${print4("label")}: `, "try ", printBlockBody(print4, node)];
3862
+ },
3863
+ [NodeType.MatchExpression](print4, node) {
3864
+ const id = Symbol("match");
3865
+ const expr = print4("expression");
3866
+ const needs_parens = pathCall(node, "expression", needsParens);
3867
+ let printed = [
3868
+ f`${print4("label")}: `,
3869
+ "match ",
3870
+ needs_parens ? expr : group([indent([softline, expr]), softline], { id }),
3871
+ needs_parens ? " " : !willBreak(expr) ? ifBreak("", " ", { groupId: id }) : "",
3872
+ printBlockBody(print4, node)
3873
+ ];
3874
+ const parent = getParentNode();
3875
+ if (is_ClosureFunctionExpression(parent) && parent.expression === node) {
3876
+ printed = parenthesize_if_break([indent([softline, printed]), softline]);
3877
+ }
3878
+ return printed;
3879
+ },
3880
+ [NodeType.MatchExpressionCase](print4, node) {
3881
+ return group([
3882
+ group(print4("pattern")),
3883
+ " ",
3884
+ printIfBlockCondition(print4, node),
3885
+ "=>",
3886
+ //
3887
+ (is_BlockExpression(node.expression) || is_IfBlockExpression(node.expression)) && !hasComment(node.expression, 0, (comment) => getOptions().danglingAttributes.includes(comment)) ? [" ", print4("expression")] : group(indent([line, print4("expression")]))
3888
+ ]);
3889
+ },
3890
+ [NodeType.StructLiteral](print4, node) {
3891
+ return [print4("struct"), printObject(print4, node)];
3892
+ },
3893
+ [NodeType.StructLiteralPropertyShorthand](print4, node) {
3894
+ return print4("value");
3895
+ },
3896
+ [NodeType.StructLiteralProperty](print4, node) {
3897
+ return [print4("key"), ": ", print4("value")];
3898
+ },
3899
+ [NodeType.StructLiteralPropertySpread](print4, node) {
3900
+ return ["..", print4("expression")];
3901
+ },
3902
+ [NodeType.StructLiteralRestUnassigned](print4, node) {
3903
+ return "..";
3904
+ },
3905
+ [NodeType.ArrayLiteral](print4, node) {
3906
+ return printArrayLike(print4, node);
3907
+ },
3908
+ [NodeType.SizedArrayLiteral](print4, node) {
3909
+ return sg_duo`[${print4("initExpression")};${print4("sizeExpression")}]`;
3910
+ },
3911
+ [NodeType.TupleLiteral](print4, node) {
3912
+ return printArrayLike(print4, node);
3913
+ },
3914
+ [NodeType.ReferenceExpression](print4, node) {
3915
+ return printUnaryExpression(["&", print4.b("mut")]);
3916
+ },
3917
+ [NodeType.RawReferenceExpression](print4, node) {
3918
+ return printUnaryExpression(`&raw ${node.kind} `);
3919
+ },
3920
+ [NodeType.DereferenceExpression](print4, node) {
3921
+ return printUnaryExpression("*");
3922
+ },
3923
+ [NodeType.BoxExpression](print4, node) {
3924
+ return printUnaryExpression("box ");
3925
+ },
3926
+ [NodeType.UnionPattern](print4, node) {
3927
+ return printUnionPattern(print4, node);
3928
+ },
3929
+ [NodeType.ParenthesizedPattern](print4, node) {
3930
+ exit.never();
3931
+ return sg_single`(${print4("pattern")})`;
3932
+ },
3933
+ [NodeType.RestPattern](print4, node) {
3934
+ return "..";
3935
+ },
3936
+ [NodeType.WildcardPattern](print4, node) {
3937
+ return "_";
3938
+ },
3939
+ [NodeType.PatternVariableDeclaration](print4, node) {
3940
+ return [print4.b("ref"), print4.b("mut"), printAssignment(print4("id"), " @", "pattern")];
3941
+ },
3942
+ [NodeType.StructPattern](print4, node) {
3943
+ return [print4("struct"), printObject(print4, node)];
3944
+ },
3945
+ [NodeType.StructPatternPropertyDestructured](print4, node) {
3946
+ return [print4("key"), ": ", print4("pattern")];
3947
+ },
3948
+ [NodeType.StructPatternPropertyShorthand](print4, node) {
3949
+ return [print4.b("box"), print4.b("ref"), print4.b("mut"), print4("id")];
3950
+ },
3951
+ [NodeType.TuplePattern](print4, node) {
3952
+ return [print4("struct"), printArrayLike(print4, node)];
3953
+ },
3954
+ [NodeType.ArrayPattern](print4, node) {
3955
+ return printArrayLike(print4, node);
3956
+ },
3957
+ [NodeType.ReferencePattern](print4, node) {
3958
+ return ["&", print4.b("mut"), print4("pattern")];
3959
+ },
3960
+ [NodeType.BoxPattern](print4, node) {
3961
+ return ["box ", print4("pattern")];
3962
+ },
3963
+ [NodeType.MinusPattern](print4, node) {
3964
+ return ["-", print4("pattern")];
3965
+ },
3966
+ [NodeType.RangePattern](print4, node) {
3967
+ return [print4("lower"), "..", print4.b("last", "="), print4("upper")];
3968
+ },
3969
+ [NodeType.TypeCall](print4, node) {
3970
+ return [print4("typeCallee"), printTypeArguments(print4, node)];
3971
+ },
3972
+ [NodeType.TypeCallNamedArgument](print4, node) {
3973
+ return printAssignment(print4("target"), " =", "typeExpression");
3974
+ },
3975
+ [NodeType.TypeCallNamedBound](print4, node) {
3976
+ return [print4("typeTarget"), printTypeBounds(":", print4, node)];
3977
+ },
3978
+ [NodeType.LtElided](print4, node) {
3979
+ return "'_";
3980
+ },
3981
+ [NodeType.LtStatic](print4, node) {
3982
+ return "'static";
3983
+ },
3984
+ [NodeType.TypeNever](print4, node) {
3985
+ return "!";
3986
+ },
3987
+ [NodeType.TypeInferred](print4, node) {
3988
+ return "_";
3989
+ },
3990
+ [NodeType.GenericTypeParameterDeclaration](print4, node) {
3991
+ return printAssignment(
3992
+ [print4("id"), printTypeBounds(":", print4, node)],
3993
+ //
3994
+ " =",
3995
+ "typeDefault"
3996
+ );
3997
+ },
3998
+ [NodeType.ConstTypeParameterDeclaration](print4, node) {
3999
+ return [
4000
+ "const ",
4001
+ printAssignment(
4002
+ [print4("id"), printTypeAnnotation(print4, node)],
4003
+ //
4004
+ " =",
4005
+ "typeDefault"
4006
+ )
4007
+ ];
4008
+ },
4009
+ [NodeType.GenericLtParameterDeclaration](print4, node) {
4010
+ return [print4("id"), printLtBounds(":", print4, node)];
4011
+ },
4012
+ [NodeType.WhereTypeBoundDeclaration](print4, node) {
4013
+ return [printLtParameters(print4, node), print4("typeTarget"), printTypeBounds(":", print4, node)];
4014
+ },
4015
+ [NodeType.WhereLtBoundDeclaration](print4, node) {
4016
+ return [print4("ltTarget"), printLtBounds(":", print4, node)];
4017
+ },
4018
+ [NodeType.TypeTraitBound](print4, node) {
4019
+ return [print4.b("maybeConst", "~const "), print4.b("optional", "?"), printLtParameters(print4, node), print4("typeExpression")];
4020
+ },
4021
+ [NodeType.TypeDynBounds](print4, node) {
4022
+ return printTypeBounds("dyn", print4, node);
4023
+ },
4024
+ [NodeType.TypeImplBounds](print4, node) {
4025
+ return printTypeBounds("impl", print4, node);
4026
+ },
4027
+ [NodeType.TypeFnPointer](print4, node) {
4028
+ return [printLtParameters(print4, node), print4.b("unsafe"), print4("extern"), "fn", printParametersAndReturnType(node)];
4029
+ },
4030
+ [NodeType.TypeFnPointerParameter](print4, node) {
4031
+ return [f`${print4("id")}: `, print4("typeAnnotation")];
4032
+ },
4033
+ [NodeType.TypeFunction](print4, node) {
4034
+ return [print4("callee"), printParametersAndReturnType(node)];
4035
+ },
4036
+ [NodeType.TypeTuple](print4, node) {
4037
+ return printArrayLike(print4, node);
4038
+ },
4039
+ [NodeType.TypeSizedArray](print4, node) {
4040
+ return sg_duo`[${print4("typeExpression")};${print4("sizeExpression")}]`;
4041
+ },
4042
+ [NodeType.TypeSlice](print4, node) {
4043
+ if (isSimpleType(node))
4044
+ return ["[", print4("typeExpression"), "]"];
4045
+ return sg_single`[${print4("typeExpression")}]`;
4046
+ },
4047
+ [NodeType.TypeReference](print4, node) {
4048
+ return ["&", f`${print4("lt")} `, print4.b("mut"), print4("typeExpression")];
4049
+ },
4050
+ [NodeType.TypeDereferenceConst](print4, node) {
4051
+ return ["*const ", print4("typeExpression")];
4052
+ },
4053
+ [NodeType.TypeDereferenceMut](print4, node) {
4054
+ return ["*mut ", print4("typeExpression")];
4055
+ },
4056
+ [NodeType.TypeParenthesized](print4, node) {
4057
+ exit.never();
4058
+ return sg_single`(${print4("typeExpression")})`;
4059
+ }
4060
+ };
4061
+
4062
+ // src/format/plugin.ts
4063
+ function is_printing_macro() {
4064
+ return getContext().path.stack.some((node) => is_Node(node) && (is_MacroInvocation(node) || is_Attribute(node)));
4065
+ }
4066
+ function f(...args) {
4067
+ let cancel = false;
4068
+ const res = map_tagged_template(args, (doc) => {
4069
+ cancel || (cancel = !doc || is_array(doc) && doc.length === 0);
4070
+ return doc;
4071
+ });
4072
+ return cancel ? "" : res;
4073
+ }
4074
+ function sg_single(s, v_0) {
4075
+ return group([s[0], indent([softline, v_0]), softline, s[1]]);
4076
+ }
4077
+ function sg_duo(s, v_0, v_1) {
4078
+ return group([s[0], indent([softline, v_0, s[1], line, v_1]), softline, s[2]]);
4079
+ }
4080
+ var ctx;
4081
+ var getNode = () => ctx.path.stack[ctx.path.stack.length - 1];
4082
+ var stackIncludes = (x) => ctx.path.stack.includes(x);
4083
+ var getContext = () => ctx;
4084
+ var getOptions = () => ctx.options;
4085
+ var getAllComments = () => ctx.options[Symbol_comments];
4086
+ var getParentNode = (child) => {
4087
+ return ctx.path.getParentNode();
4088
+ };
4089
+ var getGrandParentNode = () => ctx.path.getParentNode(1);
4090
+ var getPrintFn = (forNode) => {
4091
+ return print3;
4092
+ };
4093
+ var get = (property) => getNode()[property];
4094
+ var has = (property) => !!get(property);
4095
+ function pathCall(node, key, fn) {
4096
+ return ctx.path.call(() => fn(getNode()), key);
4097
+ }
4098
+ function pathCallEach(node, key, fn) {
4099
+ ctx.path.each((_, i) => fn(getNode(), i), key);
4100
+ }
4101
+ function pathCallAtParent(parent, fn) {
4102
+ return ctx.path.callParent(() => {
4103
+ return fn(parent);
4104
+ });
4105
+ }
4106
+ function pathCallParentOf(child, fn) {
4107
+ return ctx.path.callParent((p) => fn(getNode()));
4108
+ }
4109
+ function print3(property, args) {
4110
+ if (!property)
4111
+ return ctx.print(void 0, args);
4112
+ if (Array.isArray(property))
4113
+ return ctx.print(property, args);
4114
+ const value = get(property);
4115
+ return !!value ? Array.isArray(value) ? ctx.path.map(ctx.print, property) : ctx.print(property, args) : "";
4116
+ }
4117
+ ((print4) => {
4118
+ function b(property, res = `${property} `) {
4119
+ return has(property) ? res : "";
4120
+ }
4121
+ print4.b = b;
4122
+ function map(property, mapItem) {
4123
+ return !has(property) ? [] : ctx.path.map(mapItem ? (p, i, a) => mapItem(a[i], i, a) : () => ctx.print(), property);
4124
+ }
4125
+ print4.map = map;
4126
+ function join2(property, sep, trailingSep = "") {
4127
+ return map_join(property, () => ctx.print(), sep, trailingSep);
4128
+ }
4129
+ print4.join = join2;
4130
+ function map_join(property, mapFn, sep, sepTrailing = "") {
4131
+ const sepFn = typeof sep === "function" ? sep : () => sep;
4132
+ return map(property, (v, i, a) => [
4133
+ mapFn(v, i, a),
4134
+ iLast(i, a) ? typeof sepTrailing === "function" ? sepTrailing(v) : sepTrailing : sepFn(v, a[i + 1], i === 0 ? void 0 : a[i - 1])
4135
+ ]);
4136
+ }
4137
+ print4.map_join = map_join;
4138
+ })(print3 || (print3 = {}));
4139
+ function genericPrint() {
4140
+ return withCheckContext(() => {
4141
+ const node = getNode();
4142
+ let printed = hasPrettierIgnore(node) ? node.loc.getOwnText() : printer[node.nodeType](print3, node);
4143
+ const inner_parens = needsInnerParens(node);
4144
+ if (inner_parens) {
4145
+ printed = group(["(", printed, ")"]);
4146
+ }
4147
+ if (hasAttributes(node)) {
4148
+ const print_above = shouldPrintOuterAttributesAbove(node);
4149
+ printed = [
4150
+ ...print3.join(
4151
+ "attributes",
4152
+ (attr) => print_above ? maybeEmptyLine(attr) : is_LineCommentNode(attr) || is_BlockCommentNode(attr) && hasBreaklineAfter(attr) ? hardline : " ",
4153
+ (attr) => print_above && is_DocCommentAttribute(attr) ? maybeEmptyLine(attr) : print_above || is_LineCommentNode(attr) || is_BlockCommentNode(attr) && hasBreaklineAfter(attr) ? hardline : " "
4154
+ ),
4155
+ printed
4156
+ ];
4157
+ }
4158
+ printed = withComments(
4159
+ node,
4160
+ printed,
4161
+ hasPrettierIgnore(node) || (is_Attribute(node) || is_MacroInvocation(node)) && !isTransformed(node) ? escapeComments(0, (comment) => node.loc.ownContains(comment)) : is_MacroRule(node) ? escapeComments(0, (comment) => node.transform.loc.contains(comment)) : is_UnionPattern(getParentNode() ?? { nodeType: 0 }) ? new Set(getComments(node, 0, (comment) => !isDangling(comment))) : void 0
4162
+ );
4163
+ if (!inner_parens && needsOuterSoftbreakParens(node)) {
4164
+ printed = [group(["(", indent([softline, printed]), softline, ")"])];
4165
+ }
4166
+ return printed;
4167
+ });
4168
+ function hasPrettierIgnore(node) {
4169
+ return node.prettierIgnore || hasComment(node, 64 /* PrettierIgnore */) || hasAttributes(node) && node.attributes.some(isPrettierIgnoreAttribute);
4170
+ }
4171
+ }
4172
+ function canAttachComment(n) {
4173
+ return is_Node(n) && !is_Comment(n) && !isNoopExpressionStatement(n) && !is_MissingNode(n) && !is_PunctuationToken(n);
4174
+ }
4175
+ var rustParser = {
4176
+ astFormat: "jinx-rust",
4177
+ locStart: start,
4178
+ locEnd: end,
4179
+ parse(code, options2) {
4180
+ ctx = { options: options2 };
4181
+ options2.rsParsedFile = rs.parseFile(options2.originalText = code, { filepath: options2.filepath });
4182
+ options2.actuallyMethodNodes = /* @__PURE__ */ new WeakSet();
4183
+ options2.danglingAttributes = [];
4184
+ options2.comments = [];
4185
+ transform_ast(options2);
4186
+ const comments = [];
4187
+ insertNodes(comments, options2.comments);
4188
+ insertNodes(comments, options2.danglingAttributes);
4189
+ options2.rsParsedFile.program.comments = comments;
4190
+ options2.commentSpans = new Map(comments.map((n) => [start(n), end(n)]));
4191
+ return options2.rsParsedFile.program;
4192
+ }
4193
+ };
4194
+ var plugin = {
4195
+ languages: [
4196
+ {
4197
+ name: "Rust",
4198
+ aliases: ["rs"],
4199
+ parsers: ["jinx-rust", "rust"],
4200
+ extensions: [".rs", ".rs.in"],
4201
+ linguistLanguageId: 327,
4202
+ vscodeLanguageIds: ["rust"],
4203
+ tmScope: "source.rust",
4204
+ aceMode: "rust",
4205
+ codemirrorMode: "rust",
4206
+ codemirrorMimeType: "text/x-rustsrc"
4207
+ }
4208
+ ],
4209
+ parsers: {
4210
+ "jinx-rust": rustParser,
4211
+ rust: rustParser
4212
+ },
4213
+ printers: {
4214
+ "jinx-rust": {
4215
+ // Prettier v3 moved `handleComments.avoidAstMutation` to this feature flag.
4216
+ // @ts-expect-error internal printer feature, not part of the public typings
4217
+ features: { experimental_avoidAstMutation: true },
4218
+ preprocess: (node) => node.loc.src,
4219
+ print(path, options2, print4, args) {
4220
+ if (path.stack.length === 1) {
4221
+ ctx = { path, options: options2, print: print4, args };
4222
+ try {
4223
+ const printed = genericPrint();
4224
+ return printed;
4225
+ } finally {
4226
+ ctx = void 0;
4227
+ }
4228
+ } else if (args || ctx.args) {
4229
+ const prev_args = ctx.args;
4230
+ try {
4231
+ ctx.args = args;
4232
+ return genericPrint();
4233
+ } finally {
4234
+ ctx.args = prev_args;
4235
+ }
4236
+ } else {
4237
+ return genericPrint();
4238
+ }
4239
+ },
4240
+ hasPrettierIgnore: () => false,
4241
+ willPrintOwnComments: () => true,
4242
+ isBlockComment: is_BlockCommentKind,
4243
+ canAttachComment,
4244
+ getCommentChildNodes,
4245
+ getVisitorKeys,
4246
+ printComment: genericPrint,
4247
+ handleComments: {
4248
+ ownLine: handleOwnLineComment,
4249
+ endOfLine: handleEndOfLineComment,
4250
+ remaining: handleRemainingComment
4251
+ }
4252
+ }
4253
+ },
4254
+ options: {},
4255
+ defaultOptions: {
4256
+ // default prettier (2) -> rustfmt (4)
4257
+ tabWidth: 4,
4258
+ // default prettier (80) -> rustfmt (100)
4259
+ printWidth: 100
4260
+ }
4261
+ };
4262
+
4263
+ // src/index.ts
4264
+ var src_default = plugin;
4265
+ var languages = plugin.languages;
4266
+ var parsers = plugin.parsers;
4267
+ var printers = plugin.printers;
4268
+ var options = plugin.options;
4269
+ var defaultOptions = plugin.defaultOptions;
4270
+ //!is_LetScrutinee(condition); //!is_LetScrutinee(getLeftMostCondition(condition));
4271
+
4272
+ export { src_default as default, defaultOptions, languages, options, parsers, printers };