prettier-java-next-line 2.11.1 → 2.11.4

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/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  let web_tree_sitter = require("web-tree-sitter");
2
2
  let prettier = require("prettier");
3
3
  let prettier_doc = require("prettier/doc");
4
- //#region src/options.ts
4
+ // src/options.ts
5
5
  var options_default = {
6
6
  arrowParens: {
7
7
  type: "choice",
@@ -47,7 +47,7 @@ var options_default = {
47
47
  value: "end",
48
48
  description: ""
49
49
  }],
50
- description: "Where to print operators when binary expressions wrap lines."
50
+ description: "Where to print operators when binary and ternary expressions wrap lines."
51
51
  },
52
52
  braceStyle: {
53
53
  type: "choice",
@@ -95,8 +95,7 @@ var options_default = {
95
95
  description: "Import groups in Spotless's format, such as `java,javax,,#java|#javax,#`. Module imports always come first. Empty puts static imports next, then all others."
96
96
  }
97
97
  };
98
- //#endregion
99
- //#region src/node-types.ts
98
+ // src/node-types.ts
100
99
  const multiFieldsByType = {
101
100
  array_creation_expression: { dimensions: true },
102
101
  cast_expression: { type: true },
@@ -113,9 +112,9 @@ const multiFieldsByType = {
113
112
  requires_module_directive: { modifiers: true },
114
113
  spread_parameter: { annotations: true }
115
114
  };
116
- //#endregion
117
- //#region src/printers/helpers.ts
118
- const { group: group$7, hardline: hardline$7, ifBreak: ifBreak$2, indent: indent$7, indentIfBreak: indentIfBreak$2, join: join$7, line: line$7, lineSuffixBoundary: lineSuffixBoundary$1, softline: softline$4 } = prettier_doc.builders;
115
+ // src/printers/helpers.ts
116
+ const { hasNewline: hasNewline$2, isNextLineEmpty: isNextLineEmpty$1, skipInlineComment, skipTrailingComment } = prettier.util;
117
+ const { breakParent: breakParent$2, fill, group: group$7, hardline: hardline$7, ifBreak: ifBreak$2, indent: indent$7, indentIfBreak: indentIfBreak$2, join: join$7, line: line$7, lineSuffixBoundary: lineSuffixBoundary$1, softline: softline$3 } = prettier_doc.builders;
119
118
  const { mapDoc } = prettier_doc.utils;
120
119
  function hasType(path, type) {
121
120
  return path.node.type === type;
@@ -149,6 +148,10 @@ function printDanglingComments(path, danglingCommentsPrintOptions = {}) {
149
148
  const doc = join$7(hardline$7, parts);
150
149
  return shouldIndent ? indent$7([hardline$7, doc]) : doc;
151
150
  }
151
+ function printDanglingCommentsInList(path) {
152
+ const { node } = path;
153
+ return node.comments?.some(({ leading, trailing }) => !leading && !trailing) ? [indent$7([softline$3, printDanglingComments(path)]), node.comments?.some(({ type, leading, trailing }) => !leading && !trailing && type === "line_comment") ? hardline$7 : softline$3] : "";
154
+ }
152
155
  function printComment(comment) {
153
156
  comment.printed = true;
154
157
  const lines = comment.value.split("\n").map((line) => line.trim());
@@ -160,62 +163,152 @@ function hasLeadingComments(node) {
160
163
  function hasDanglingComments(node) {
161
164
  return node.comments?.some(({ leading, trailing }) => !leading && !trailing) ?? false;
162
165
  }
163
- function closingBracketLine(options, lineDoc = softline$4) {
166
+ function closingBracketLine(options, lineDoc = softline$3) {
164
167
  return options?.closingBracket === "same-line" ? "" : lineDoc;
165
168
  }
166
169
  function indentInParentheses(contents, options) {
167
170
  return contents && !Array.isArray(contents) || contents.length ? [
168
171
  "(",
169
- indent$7([softline$4, contents]),
172
+ indent$7([softline$3, contents]),
170
173
  closingBracketLine(options),
171
174
  ")"
172
175
  ] : "()";
173
176
  }
174
177
  function printArrayInitializer(path, print, options) {
175
- if (!path.node.namedChildren.length) {
176
- const danglingComments = printDanglingComments(path, { indent: true });
178
+ const { node } = path;
179
+ const elements = node.namedChildren;
180
+ const isNested = isNestedArray(path);
181
+ const nextLineLayout = options.braceStyle === "next-line" && node.type === "array_initializer" ? options.arrayInitializerLayout : void 0;
182
+ if (elements.length === 0) {
183
+ const danglingComments = printDanglingCommentsInList(path);
177
184
  if (!danglingComments) return "{}";
178
185
  const block = [
179
186
  "{",
180
187
  danglingComments,
181
- hardline$7,
182
188
  "}"
183
189
  ];
184
- return options.braceStyle === "next-line" && !isNestedArray(path) ? [hardline$7, ...block] : block;
190
+ if (isNested || nextLineLayout === void 0) return group$7(block);
191
+ return nextLineLayout === "fit" ? group$7([softline$3, ...block]) : [hardline$7, group$7(block)];
185
192
  }
186
- const list = join$7([",", line$7], path.map(print, "namedChildren"));
187
- if (list.length && options.trailingComma !== "none") list.push(ifBreak$2(","));
188
- if (options.braceStyle === "next-line" && path.node.type === "array_initializer") {
189
- if (options.arrayInitializerLayout === "fit") {
190
- const bracketLine = options.bracketSpacing ? line$7 : softline$4;
191
- const block = [
192
- "{",
193
- indent$7([bracketLine, ...list]),
194
- bracketLine,
195
- "}"
196
- ];
197
- return group$7(isNestedArray(path) ? block : [softline$4, ...block]);
198
- }
193
+ const groupId = Symbol("array");
194
+ const shouldBreak = node.comments?.some(({ type, leading, trailing }) => !leading && !trailing && type === "line_comment") || nextLineLayout !== "fit" && elements.length > 1 && elements.every((element, i, elements) => {
195
+ if (element.type !== "array_initializer") return false;
196
+ const elementType = element.type;
197
+ const nextElement = elements[i + 1];
198
+ if (nextElement && elementType !== nextElement.type) return false;
199
+ return element.namedChildren.length > 1;
200
+ });
201
+ const shouldUseConciseFormatting = nextLineLayout !== "always-break" && isConciselyPrintedArray(node, options);
202
+ const trailingComma = options.trailingComma === "none" ? "" : shouldUseConciseFormatting ? ifBreak$2(",", "", { groupId }) : ifBreak$2(",");
203
+ const contents = [shouldUseConciseFormatting ? printArrayElementsConcisely(path, options, print, trailingComma) : [printArrayElements(path, options, print), trailingComma], printDanglingComments(path)];
204
+ if (nextLineLayout === "fit") {
205
+ const bracketLine = options.bracketSpacing ? line$7 : softline$3;
206
+ const block = [
207
+ "{",
208
+ indent$7([bracketLine, contents]),
209
+ bracketLine,
210
+ "}"
211
+ ];
212
+ return group$7(isNested ? block : [softline$3, ...block], {
213
+ shouldBreak,
214
+ id: groupId
215
+ });
216
+ }
217
+ if (nextLineLayout === "always-break") {
199
218
  const block = [
200
219
  "{",
201
- indent$7([line$7, ...list]),
220
+ indent$7([line$7, contents]),
202
221
  line$7,
203
222
  "}"
204
223
  ];
205
- return isNestedArray(path) ? block : [hardline$7, ...block];
224
+ return isNested ? [breakParent$2, ...block] : [hardline$7, ...block];
206
225
  }
207
226
  return group$7([
208
227
  "{",
209
- indent$7([line$7, ...list]),
228
+ indent$7([line$7, contents]),
210
229
  line$7,
211
230
  "}"
212
- ]);
231
+ ], {
232
+ shouldBreak,
233
+ id: groupId
234
+ });
235
+ }
236
+ function isConciselyPrintedArray(node, options) {
237
+ return node.namedChildren.length > 0 && node.namedChildren.every((element) => element && (isNumericLiteral(element) || isSignedNumericLiteral(element) && !element.operandNode.comments) && !element.comments?.some((comment) => comment.trailing && comment.type === "line_comment" && !hasNewline$2(options.originalText, parser_default.locStart(comment), { backwards: true })));
238
+ }
239
+ const isNumericLiteral = createTypeCheckFunction([
240
+ "binary_integer_literal",
241
+ "decimal_floating_point_literal",
242
+ "decimal_integer_literal",
243
+ "hex_floating_point_literal",
244
+ "hex_integer_literal",
245
+ "octal_integer_literal"
246
+ ]);
247
+ function isSignedNumericLiteral(node) {
248
+ return node.type === "unary_expression" && (node.operatorNode.type === "+" || node.operatorNode.type === "-") && isNumericLiteral(node.operandNode);
249
+ }
250
+ function isLineAfterElementEmpty({ node }, { originalText: text }) {
251
+ let currentIdx = parser_default.locEnd(node);
252
+ if (currentIdx === parser_default.locStart(node)) return false;
253
+ const { length } = text;
254
+ while (currentIdx < length) {
255
+ if (text[currentIdx] === ",") break;
256
+ currentIdx = skipInlineComment(text, skipTrailingComment(text, currentIdx + 1));
257
+ }
258
+ return isNextLineEmpty$1(text, currentIdx);
259
+ }
260
+ function printArrayElements(path, options, print) {
261
+ const parts = [];
262
+ path.each((element) => {
263
+ parts.push(group$7(print(element)));
264
+ if (!element.isLast) parts.push([
265
+ ",",
266
+ line$7,
267
+ isLineAfterElementEmpty(path, options) ? softline$3 : ""
268
+ ]);
269
+ }, "namedChildren");
270
+ return parts;
271
+ }
272
+ function printArrayElementsConcisely(path, options, print, trailingComma) {
273
+ const parts = [];
274
+ path.each((element) => {
275
+ const { next } = element;
276
+ parts.push([print(element), !next ? trailingComma : ","]);
277
+ if (next) parts.push(isLineAfterElementEmpty(path, options) ? [hardline$7, hardline$7] : next.comments?.some(({ type, leading }) => leading && type === "line_comment") ? hardline$7 : line$7);
278
+ }, "namedChildren");
279
+ return fill(parts);
213
280
  }
214
281
  function isNestedArray(path) {
215
282
  return path.parent?.type === "array_initializer" || path.parent?.type === "element_value_array_initializer";
216
283
  }
284
+ /**
285
+ * Separates a header such as `void m()`, `try` or `class A` from the `{` of
286
+ * the block that follows it. Blocks never add their own leading separator.
287
+ */
288
+ function printBlockSeparator(options) {
289
+ return options.braceStyle === "next-line" ? hardline$7 : " ";
290
+ }
291
+ /**
292
+ * Separators between a declaration header and its body. With same-line braces,
293
+ * a non-empty body's `{` moves onto its own line when the `extends`,
294
+ * `implements` or `permits` clauses break, so that separator sits inside the
295
+ * clause group. With next-line braces, `{` always follows the whole header on
296
+ * its own line.
297
+ */
298
+ function printDeclarationBodySeparators(hasClauses, hasBody, options) {
299
+ if (options.braceStyle === "next-line") return {
300
+ afterClauses: "",
301
+ afterHeader: hardline$7
302
+ };
303
+ return hasClauses ? {
304
+ afterClauses: hasBody ? line$7 : " ",
305
+ afterHeader: ""
306
+ } : {
307
+ afterClauses: "",
308
+ afterHeader: " "
309
+ };
310
+ }
217
311
  function printBlock(path, contents, options) {
218
- if (options?.braceStyle === "next-line") return printBlockNextLine(path, contents);
219
312
  if (contents.length) return group$7([
220
313
  "{",
221
314
  indent$7([hardline$7, ...join$7(hardline$7, contents)]),
@@ -229,6 +322,11 @@ function printBlock(path, contents, options) {
229
322
  hardline$7,
230
323
  "}"
231
324
  ];
325
+ if (options?.braceStyle === "next-line") return [
326
+ "{",
327
+ hardline$7,
328
+ "}"
329
+ ];
232
330
  const parent = path.parent;
233
331
  const grandparent = path.grandparent;
234
332
  return parent?.type === "catch_clause" && (grandparent?.type === "try_statement" || grandparent?.type === "try_with_resources_statement") && grandparent.namedChildren.filter(({ type }) => type === "catch_clause").length === 1 && !grandparent.namedChildren.some(({ type }) => type === "finally_clause") || parent && [
@@ -256,42 +354,6 @@ function printBlock(path, contents, options) {
256
354
  "}"
257
355
  ];
258
356
  }
259
- function printBlockNextLine(path, contents) {
260
- const parentType = path.parent?.type;
261
- const isChildOfBodyDeclaration = parentType != null && [
262
- "annotation_type_body",
263
- "class_body",
264
- "enum_body",
265
- "interface_body"
266
- ].includes(parentType);
267
- const isBlockStatement = parentType != null && [
268
- "block",
269
- "constructor_body",
270
- "switch_block_statement_group"
271
- ].includes(parentType);
272
- const prefix = isChildOfBodyDeclaration || isBlockStatement ? [] : [hardline$7];
273
- if (contents.length) return [
274
- ...prefix,
275
- "{",
276
- indent$7([hardline$7, ...join$7(hardline$7, contents)]),
277
- hardline$7,
278
- "}"
279
- ];
280
- const danglingComments = printDanglingComments(path, { indent: true });
281
- if (danglingComments) return [
282
- ...prefix,
283
- "{",
284
- danglingComments,
285
- hardline$7,
286
- "}"
287
- ];
288
- return [
289
- ...prefix,
290
- "{",
291
- hardline$7,
292
- "}"
293
- ];
294
- }
295
357
  function printBlockStatements(path, print) {
296
358
  const parts = [];
297
359
  path.each((child) => {
@@ -306,7 +368,7 @@ function printBlockStatements(path, print) {
306
368
  function printBodyDeclarations(path, print, padFirst = false) {
307
369
  const isInterfaceBody = path.node.type === "interface_body";
308
370
  const isFormalParameters = path.node.type === "formal_parameters";
309
- const separator = isFormalParameters ? softline$4 : hardline$7;
371
+ const separator = isFormalParameters ? softline$3 : hardline$7;
310
372
  let previousRequiresPadding = padFirst;
311
373
  return path.map((child) => {
312
374
  const { node, previous } = child;
@@ -329,14 +391,14 @@ function printTypeParameters(path, print, options) {
329
391
  ];
330
392
  const parts = [
331
393
  "<",
332
- indent$7([softline$4, join$7([",", line$7], path.map(print, "namedChildren"))]),
394
+ indent$7([softline$3, join$7([",", line$7], path.map(print, "namedChildren"))]),
333
395
  closingBracketLine(options),
334
396
  ">"
335
397
  ];
336
398
  return path.node.type === "type_arguments" ? group$7(parts) : parts;
337
399
  }
338
400
  function printVariableDeclaration(path, print) {
339
- const declaration = printModifiers(path, print);
401
+ const declaration = printModifiers(path, print, path.parent?.type === "for_statement" ? "noBreak" : void 0);
340
402
  declaration.push(path.call(print, "typeNode"), " ");
341
403
  const declarators = path.map(print, "declaratorNodes");
342
404
  if (declarators.length > 1 && path.node.declaratorNodes.some(({ valueNode }) => valueNode)) declaration.push(group$7(indent$7(join$7([",", line$7], declarators)), { shouldBreak: path.parent?.type !== "for_statement" }));
@@ -346,7 +408,7 @@ function printVariableDeclaration(path, print) {
346
408
  }
347
409
  function printAssignment(leftDoc, operator, rightDoc, rightNode) {
348
410
  if (!rightDoc || !rightNode) return leftDoc;
349
- if (rightNode.type === "binary_expression" || rightNode.type === "instanceof_expression" || rightNode.type === "ternary_expression" && (rightNode.conditionNode.type === "binary_expression" || rightNode.conditionNode.type === "instanceof_expression") || isMember(rightNode) && hasDanglingComments(rightNode) || !isMember(rightNode) && hasLeadingComments(rightNode)) return group$7([
411
+ if (rightNode.type === "binary_expression" || rightNode.type === "instanceof_expression" || rightNode.type === "ternary_expression" && (rightNode.conditionNode.type === "binary_expression" || rightNode.conditionNode.type === "instanceof_expression") || hasLeadingComments(rightNode)) return group$7([
350
412
  leftDoc,
351
413
  operator,
352
414
  group$7(indent$7([line$7, rightDoc]))
@@ -367,22 +429,28 @@ function inferParser(options, language) {
367
429
  return getLanguageByLanguageName(options.plugins?.filter((plugin) => typeof plugin !== "string" && !(plugin instanceof URL)).reverse().flatMap((plugin) => plugin.languages ?? []) ?? [], language)?.parsers[0];
368
430
  }
369
431
  function printTextBlock(contents) {
370
- return [
371
- "\"\"\"",
432
+ return ["\"\"\"", indent$7([
372
433
  hardline$7,
373
434
  contents,
374
435
  "\"\"\""
375
- ];
436
+ ])];
437
+ }
438
+ function isTextBlock(node) {
439
+ return node.type === "string_literal" && node.children[0].value === "\"\"\"";
376
440
  }
377
441
  function embedTextBlock(path, options) {
378
- if (path.node.namedChildren.some(({ type }) => type === "string_interpolation") || path.node.children[0].value === "\"") return null;
442
+ if (path.node.namedChildren.some(({ type }) => type === "string_interpolation") || !isTextBlock(path.node)) return null;
379
443
  const language = findEmbeddedLanguage(path);
380
444
  if (!language) return null;
381
445
  const parser = inferParser(options, language);
382
446
  if (!parser) return null;
383
- const text = unescapeTextBlockContents(textBlockContents(path.node));
447
+ const contents = textBlockContents(path.node);
448
+ if (/[\uE000-\uF8FF]/.test(contents)) return null;
449
+ const preservedEscapes = [];
450
+ const text = unescapeTextBlockContents(contents, preservedEscapes);
451
+ if (preservedEscapes.length > 6400) return null;
384
452
  return async (textToDoc) => {
385
- return printTextBlock([escapeDocForTextBlock(await textToDoc(text, { parser })), hardline$7]);
453
+ return printTextBlock([escapeDocForTextBlock(await textToDoc(text, { parser }), preservedEscapes), hardline$7]);
386
454
  };
387
455
  }
388
456
  function textBlockContents(node) {
@@ -553,11 +621,19 @@ function findBaseIndent(lines) {
553
621
  function findEmbeddedLanguage(path) {
554
622
  return [path.node, ...path.ancestors].find(({ type, comments }) => type === "block" || comments?.some(({ leading }) => leading))?.comments?.filter(({ leading }) => leading).map(({ value }) => value.match(/^(?:\/\/|\/\*)\s*language\s*=\s*(\S+)/)?.[1]).findLast((language) => language)?.toLowerCase();
555
623
  }
556
- function escapeDocForTextBlock(doc) {
557
- return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" ? currentDoc.replace(/\\|"""/g, (match) => match === "\\" ? "\\\\" : "\"\"\\\"") : currentDoc);
624
+ function escapeDocForTextBlock(doc, preservedEscapes) {
625
+ return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" ? currentDoc.replace(/\\|"""|[\uE000-\uF8FF]/g, (match) => match === "\\" ? "\\\\" : match === "\"\"\"" ? "\"\"\\\"" : preservedEscapes[match.charCodeAt(0) - 57344] ?? match) : currentDoc);
558
626
  }
559
- function unescapeTextBlockContents(text) {
560
- return text.replace(/\\(?:([stnr"'\\])|\n|\r\n?)/g, (_, escaped) => {
627
+ /**
628
+ * Escapes with no safe unescaped form (\b, \f and octal) are swapped for
629
+ * private-use placeholders and restored verbatim by escapeDocForTextBlock.
630
+ */
631
+ function unescapeTextBlockContents(text, preservedEscapes) {
632
+ return text.replace(/\\(?:([stnr"'\\])|([bf]|[0-3][0-7]{0,2}|[4-7][0-7]?)|\n|\r\n?)/g, (match, escaped, preserved) => {
633
+ if (preserved) {
634
+ preservedEscapes.push(match);
635
+ return String.fromCharCode(57344 + preservedEscapes.length - 1);
636
+ }
561
637
  switch (escaped) {
562
638
  case "s": return " ";
563
639
  case "t": return " ";
@@ -567,2085 +643,2141 @@ function unescapeTextBlockContents(text) {
567
643
  }
568
644
  });
569
645
  }
570
- //#endregion
571
- //#region src/printers/arrays.ts
572
- var arrays_default = { array_initializer: printArrayInitializer };
573
- //#endregion
574
- //#region src/printers/blocks-and-statements.ts
575
- const { group: group$6, hardline: hardline$6, ifBreak: ifBreak$1, indent: indent$6, indentIfBreak: indentIfBreak$1, join: join$6, line: line$6, softline: softline$3 } = prettier_doc.builders;
576
- var blocks_and_statements_default = {
577
- block(path, print, options) {
578
- return printBlock(path, printBlockStatements(path, print), options);
579
- },
580
- local_variable_declaration: printVariableDeclaration,
581
- labeled_statement(path, print) {
582
- return join$6(": ", path.map(print, "namedChildren"));
583
- },
584
- expression_statement(path, print) {
585
- const parentType = path.parent?.type;
586
- const expressionType = path.node.namedChildren[0].type;
587
- const expression = path.call(print, "namedChildren", 0);
588
- return expressionType === "switch_expression" && parentType !== "assignment_expression" && parentType !== "switch_rule" ? expression : [expression, ";"];
589
- },
590
- if_statement(path, print, options) {
591
- const statement = ["if ", path.call(print, "conditionNode")];
592
- if (path.node.consequenceNode.type === ";") statement.push(";");
593
- else statement.push(" ", path.call(print, "consequenceNode"));
594
- if (!hasChild(path, "alternativeNode")) return statement;
595
- const danglingComments = printDanglingComments(path);
596
- if (danglingComments) statement.push(hardline$6, danglingComments, hardline$6);
597
- else if (options?.braceStyle === "next-line") statement.push(hardline$6);
598
- else {
599
- const ifHasBlock = path.node.consequenceNode.type === "block";
600
- statement.push(ifHasBlock ? " " : hardline$6);
646
+ // src/comments.ts
647
+ const { hasNewline: hasNewline$1, isPreviousLineEmpty, skipNewline, skipSpaces } = prettier.util;
648
+ const { breakParent: breakParent$1, hardline: hardline$6, line: line$6, lineSuffix } = prettier_doc.builders;
649
+ const prettierIgnoreRangesByTree = /* @__PURE__ */ new WeakMap();
650
+ function determinePrettierIgnoreRanges(tree) {
651
+ const { comments } = tree;
652
+ if (!comments) return;
653
+ const ranges = comments.filter(({ value }) => /^\/(?:\/\s*(?:prettier-ignore-(?:start|end)|@formatter:(?:off|on))\s*|\*\s*(?:prettier-ignore-(?:start|end)|@formatter:(?:off|on))\s*\*\/)$/.test(value)).reduce((ranges, { value, start }) => {
654
+ const previous = ranges.at(-1);
655
+ if (value.includes("start") || value.includes("off")) {
656
+ if (previous?.end !== Infinity) ranges.push({
657
+ start: start.index,
658
+ end: Infinity
659
+ });
660
+ } else if (previous?.end === Infinity) previous.end = start.index;
661
+ return ranges;
662
+ }, new Array());
663
+ prettierIgnoreRangesByTree.set(tree, ranges);
664
+ }
665
+ function isFullyBetweenPrettierIgnore(path) {
666
+ const { node, root } = path;
667
+ const start = parser_default.locStart(node);
668
+ const end = parser_default.locEnd(node);
669
+ return prettierIgnoreRangesByTree.get(root)?.some((range) => range.start < start && end < range.end) === true;
670
+ }
671
+ function isPrettierIgnore(comment) {
672
+ return /^(\/\/\s*prettier-ignore|\/\*\s*prettier-ignore\s*\*\/)$/.test(comment.value);
673
+ }
674
+ function canAttachComment(node, ancestors) {
675
+ if (!node.isNamed) return isBinaryOperator(node);
676
+ switch (node.type) {
677
+ case "enum_body_declarations":
678
+ case "escape_sequence":
679
+ case "modifier":
680
+ case "multiline_string_fragment":
681
+ case "program":
682
+ case "string_fragment":
683
+ case "visibility": return false;
684
+ case "parenthesized_expression": {
685
+ const [parent] = ancestors;
686
+ return !(parent.isNamed && [
687
+ "do_statement",
688
+ "if_statement",
689
+ "switch_expression",
690
+ "synchronized_statement",
691
+ "try_statement",
692
+ "try_with_resources_statement",
693
+ "while_statement"
694
+ ].includes(parent.type));
601
695
  }
602
- statement.push("else");
603
- if (path.node.alternativeNode.type === ";") statement.push(";");
604
- else statement.push(" ", path.call(print, "alternativeNode"));
605
- return statement;
606
- },
607
- assert_statement(path, print) {
608
- return [
609
- "assert ",
610
- ...join$6(" : ", path.map(print, "namedChildren")),
611
- ";"
612
- ];
613
- },
614
- switch_expression(path, print) {
615
- return join$6(" ", [
616
- "switch",
617
- path.call(print, "conditionNode"),
618
- path.call(print, "bodyNode")
619
- ]);
620
- },
621
- switch_block(path, print, options) {
622
- return printBlock(path, path.map(print, "namedChildren"), options);
623
- },
624
- switch_block_statement_group(path, print) {
625
- const parts = [];
626
- path.each((child) => {
627
- if (child.node.type === "switch_label") parts.push(print(child), ":");
628
- }, "namedChildren");
629
- const firstStatementIndex = path.node.namedChildren.findIndex(({ type }) => type !== "switch_label");
630
- if (firstStatementIndex === path.node.namedChildren.length - 1 && path.node.namedChildren[firstStatementIndex].type === "block") parts.push(" ", path.call(print, "namedChildren", firstStatementIndex));
631
- else if (firstStatementIndex !== -1) parts.push(indent$6([hardline$6, ...join$6(hardline$6, printBlockStatements(path, print))]));
632
- return parts;
633
- },
634
- switch_label(path, print) {
635
- if (!path.node.children.some(({ type }) => type === "case")) return "default";
636
- const values = [];
637
- path.each((child) => {
638
- if (child.node.type !== "guard") values.push(print(child));
639
- }, "namedChildren");
640
- const hasMultipleValues = values.length > 1;
641
- const label = hasMultipleValues ? ["case", indent$6([line$6, ...join$6([",", line$6], values)])] : ["case ", values[0]];
642
- const guardIndex = path.node.namedChildren.findIndex(({ type }) => type === "guard");
643
- return guardIndex !== -1 ? [group$6([...label, hasMultipleValues ? line$6 : " "]), path.call(print, "namedChildren", guardIndex)] : group$6(label);
644
- },
645
- switch_rule(path, print) {
646
- const bodyIndex = path.node.namedChildren.findIndex(({ type }) => type === "block" || type === "expression_statement" || type === "throw_statement");
647
- const body = path.call(print, "namedChildren", bodyIndex);
648
- const switchLabelIndex = path.node.namedChildren.findIndex(({ type }) => type === "switch_label");
649
- const parts = [path.call(print, "namedChildren", switchLabelIndex), " ->"];
650
- const bodyNode = path.node.namedChildren[bodyIndex];
651
- if (bodyNode.type !== "block" && hasLeadingComments(bodyNode)) parts.push(indent$6([hardline$6, body]));
652
- else parts.push(" ", body);
653
- return parts;
654
- },
655
- while_statement(path, print) {
656
- const parts = ["while ", path.call(print, "conditionNode")];
657
- const body = path.call(print, "bodyNode");
658
- const bodyType = path.node.bodyNode.type;
659
- if (bodyType === "block") {
660
- parts.push(" ", body);
661
- return parts;
662
- } else if (bodyType === ";") {
663
- parts.push(";");
664
- return parts;
665
- } else {
666
- parts.push(line$6, body);
667
- return group$6(indent$6(parts));
696
+ default: return true;
697
+ }
698
+ }
699
+ function handleLineComment(commentNode, _, options) {
700
+ return [
701
+ handleBinaryExpressionComments,
702
+ handleFormalParametersComments,
703
+ handleFqnOrRefTypeComments,
704
+ handleIfStatementComments,
705
+ handleJumpStatementComments,
706
+ handleLabeledStatementComments,
707
+ handleLambdaExpressionComments,
708
+ handleMemberChainComments,
709
+ handleMethodHeaderComments,
710
+ handleModifiersComments,
711
+ handleNameComments,
712
+ handleTernaryExpressionComments,
713
+ handleTryStatementComments
714
+ ].some((fn) => fn(commentNode, options));
715
+ }
716
+ function handleRemainingComment(commentNode) {
717
+ return [
718
+ handleFqnOrRefTypeComments,
719
+ handleNameComments,
720
+ handleJumpStatementComments
721
+ ].some((fn) => fn(commentNode));
722
+ }
723
+ function handleBinaryExpressionComments(commentNode, options) {
724
+ const { enclosingNode, precedingNode, followingNode } = commentNode;
725
+ if (enclosingNode?.type === "binary_expression") {
726
+ if (isBinaryOperator(followingNode)) {
727
+ if (options.experimentalOperatorPosition === "start") prettier.util.addLeadingComment(followingNode, commentNode);
728
+ else prettier.util.addTrailingComment(followingNode, commentNode);
729
+ return true;
730
+ } else if (options.experimentalOperatorPosition === "start" && isBinaryOperator(precedingNode)) {
731
+ prettier.util.addLeadingComment(precedingNode, commentNode);
732
+ return true;
668
733
  }
669
- },
670
- do_statement(path, print, options) {
671
- const hasEmptyStatement = path.node.bodyNode.type === ";";
672
- const isNextLine = options?.braceStyle === "next-line";
673
- const whilePrefix = isNextLine ? [hardline$6, "while "] : " while ";
674
- return [
675
- "do",
676
- hasEmptyStatement ? ";" : isNextLine ? path.call(print, "bodyNode") : [" ", path.call(print, "bodyNode")],
677
- whilePrefix,
678
- path.call(print, "conditionNode"),
679
- ";"
680
- ];
681
- },
682
- for_statement(path, print, options) {
683
- const danglingComments = printDanglingComments(path);
684
- const hasInit = path.node.initNodes.length > 0;
685
- const hasCondition = hasChild(path, "conditionNode");
686
- const hasUpdate = path.node.updateNodes.length > 0;
687
- const expressions = [
688
- !hasInit ? ";" : path.node.initNodes[0].type === "local_variable_declaration" ? path.call(print, "initNodes", 0) : [printExpressionList(path.map(print, "initNodes")), ";"],
689
- hasCondition ? [path.call(print, "conditionNode"), ";"] : ";",
690
- hasUpdate ? [line$6, printExpressionList(path.map(print, "updateNodes"))] : ifBreak$1("", " ")
691
- ];
692
- const hasEmptyStatement = path.node.bodyNode.type === ";";
693
- return [
694
- danglingComments && [danglingComments, hardline$6],
695
- "for ",
696
- hasInit || hasCondition || hasUpdate ? group$6(indentInParentheses([join$6(line$6, expressions.slice(0, 2)), expressions[2]], options)) : "(;;)",
697
- hasEmptyStatement ? ";" : [" ", path.call(print, "bodyNode")]
698
- ];
699
- },
700
- update_expression(path, print) {
701
- return path.map(print, "children");
702
- },
703
- enhanced_for_statement(path, print) {
704
- const danglingComments = printDanglingComments(path);
705
- const forStatement = [
706
- danglingComments && [danglingComments, hardline$6],
707
- "for (",
708
- ...printModifiers(path, print),
709
- path.call(print, "typeNode"),
710
- " ",
711
- path.call(print, "nameNode")
712
- ];
713
- if (hasChild(path, "dimensionsNode")) forStatement.push(path.call(print, "dimensionsNode"));
714
- forStatement.push(" : ", path.call(print, "valueNode"), ")");
715
- const bodyType = path.node.bodyNode.type;
716
- if (bodyType === ";") forStatement.push(";");
717
- else {
718
- const body = path.call(print, "bodyNode");
719
- forStatement.push(bodyType === "block" ? [" ", body] : indent$6([line$6, body]));
734
+ }
735
+ return false;
736
+ }
737
+ function handleFormalParametersComments(commentNode) {
738
+ const { enclosingNode, precedingNode, followingNode } = commentNode;
739
+ if (enclosingNode?.type === "formal_parameters" && !precedingNode && !followingNode) {
740
+ prettier.util.addDanglingComment(enclosingNode, commentNode, void 0);
741
+ return true;
742
+ }
743
+ return false;
744
+ }
745
+ function handleFqnOrRefTypeComments(commentNode) {
746
+ const { enclosingNode, followingNode } = commentNode;
747
+ if (enclosingNode?.type === "scoped_type_identifier" && followingNode) {
748
+ prettier.util.addLeadingComment(followingNode, commentNode);
749
+ return true;
750
+ }
751
+ return false;
752
+ }
753
+ function handleIfStatementComments(commentNode) {
754
+ const { enclosingNode, precedingNode } = commentNode;
755
+ if (enclosingNode?.type === "if_statement" && precedingNode?.fieldName === "consequence") {
756
+ prettier.util.addDanglingComment(enclosingNode, commentNode, void 0);
757
+ return true;
758
+ }
759
+ return false;
760
+ }
761
+ function handleJumpStatementComments(commentNode) {
762
+ const { enclosingNode, precedingNode, followingNode } = commentNode;
763
+ if (enclosingNode && !precedingNode && !followingNode && (enclosingNode.type === "break_statement" || enclosingNode.type === "continue_statement" || enclosingNode.type === "return_statement")) {
764
+ prettier.util.addTrailingComment(enclosingNode, commentNode);
765
+ return true;
766
+ }
767
+ return false;
768
+ }
769
+ function handleLabeledStatementComments(commentNode) {
770
+ const { enclosingNode, precedingNode } = commentNode;
771
+ if (enclosingNode?.type === "labeled_statement" && precedingNode?.type === "identifier") {
772
+ prettier.util.addLeadingComment(precedingNode, commentNode);
773
+ return true;
774
+ }
775
+ return false;
776
+ }
777
+ function handleLambdaExpressionComments(commentNode) {
778
+ const { enclosingNode, precedingNode, followingNode } = commentNode;
779
+ if (enclosingNode?.type === "lambda_expression" && precedingNode && followingNode && enclosingNode.children.find(({ type }) => type === "->").end.index < commentNode.start.index) {
780
+ if (followingNode.type === "block") {
781
+ if (followingNode.namedChildren.length) prettier.util.addLeadingComment(followingNode.namedChildren[0], commentNode);
782
+ else prettier.util.addDanglingComment(followingNode, commentNode, void 0);
783
+ } else prettier.util.addLeadingComment(followingNode, commentNode);
784
+ return true;
785
+ }
786
+ }
787
+ function handleMemberChainComments(commentNode) {
788
+ const { enclosingNode, precedingNode } = commentNode;
789
+ if (isMember(enclosingNode)) {
790
+ if (commentNode.end.index <= enclosingNode.start.index) {
791
+ const memberChainRoot = getMemberChainRoot(enclosingNode);
792
+ prettier.util.addLeadingComment(memberChainRoot, commentNode);
793
+ return true;
720
794
  }
721
- return group$6(forStatement);
722
- },
723
- break_statement(path, print) {
724
- const parts = ["break"];
725
- const identifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier");
726
- if (identifierIndex !== -1) parts.push(" ", path.call(print, "namedChildren", identifierIndex));
727
- parts.push(";");
728
- return parts;
729
- },
730
- continue_statement(path, print) {
731
- const identifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier");
732
- return identifierIndex !== -1 ? [
733
- "continue ",
734
- path.call(print, "namedChildren", identifierIndex),
735
- ";"
736
- ] : "continue;";
737
- },
738
- return_statement: printReturnOrThrowStatement,
739
- throw_statement: printReturnOrThrowStatement,
740
- synchronized_statement(path, print) {
741
- const parenthesizedExpressionIndex = path.node.namedChildren.findIndex(({ type }) => type === "parenthesized_expression");
742
- return [
743
- "synchronized ",
744
- path.call(print, "namedChildren", parenthesizedExpressionIndex),
745
- " ",
746
- path.call(print, "bodyNode")
747
- ];
748
- },
749
- try_statement(path, print, options) {
750
- const parts = ["try", path.call(print, "bodyNode")];
751
- path.each((child) => {
752
- if (child.node.type === "catch_clause" || child.node.type === "finally_clause") parts.push(print(child));
753
- }, "namedChildren");
754
- if (options?.braceStyle === "next-line") return parts;
755
- return join$6(" ", parts);
756
- },
757
- catch_clause(path, print, options) {
758
- const catchFormalParameterIndex = path.node.namedChildren.findIndex(({ type }) => type === "catch_formal_parameter");
759
- const params = group$6(indentInParentheses(path.call(print, "namedChildren", catchFormalParameterIndex), options));
760
- const body = path.call(print, "bodyNode");
761
- if (options?.braceStyle === "next-line") return [
762
- hardline$6,
763
- "catch ",
764
- params,
765
- body
766
- ];
767
- return [
768
- "catch ",
769
- params,
770
- " ",
771
- body
772
- ];
773
- },
774
- catch_formal_parameter(path, print) {
775
- const parts = printModifiers(path, print, "noBreak");
776
- const catchTypeIndex = path.node.namedChildren.findIndex(({ type }) => type === "catch_type");
777
- parts.push(path.call(print, "namedChildren", catchTypeIndex), " ", path.call(print, "nameNode"));
778
- if (hasChild(path, "dimensionsNode")) parts.push(path.call(print, "dimensionsNode"));
779
- return parts;
780
- },
781
- catch_type(path, print) {
782
- return join$6([line$6, "| "], path.map(print, "namedChildren"));
783
- },
784
- finally_clause(path, print, options) {
785
- if (options?.braceStyle === "next-line") return [
786
- hardline$6,
787
- "finally",
788
- path.call(print, "namedChildren", 0)
789
- ];
790
- return ["finally ", path.call(print, "namedChildren", 0)];
791
- },
792
- try_with_resources_statement(path, print, options) {
793
- const resources = path.call(print, "resourcesNode");
794
- const body = path.call(print, "bodyNode");
795
- const clauses = [];
796
- path.each((child) => {
797
- if (child.node.type === "catch_clause" || child.node.type === "finally_clause") clauses.push(print(child));
798
- }, "namedChildren");
799
- if (options?.braceStyle === "next-line") return [
800
- "try ",
801
- resources,
802
- body,
803
- ...clauses
804
- ];
805
- return join$6(" ", [
806
- "try",
807
- resources,
808
- body,
809
- ...clauses
810
- ]);
811
- },
812
- resource_specification(path, print, options) {
813
- const resources = [];
814
- let hasTrailingSemicolon = false;
815
- path.each((child) => {
816
- if (child.node.type === "resource") {
817
- resources.push(print(child));
818
- hasTrailingSemicolon = false;
819
- } else if (child.node.type === ";") hasTrailingSemicolon = true;
820
- }, "children");
821
- const parts = join$6([";", line$6], resources);
822
- if (hasTrailingSemicolon) parts.push(ifBreak$1(";"));
823
- return group$6(indentInParentheses(parts, options));
824
- },
825
- resource(path, print) {
826
- if (hasChild(path, "typeNode") && hasChild(path, "nameNode") && hasChild(path, "valueNode")) {
827
- const parts = printModifiers(path, print);
828
- parts.push(path.call(print, "typeNode"), " ", path.call(print, "nameNode"));
829
- if (hasChild(path, "dimensionsNode")) parts.push(path.call(print, "dimensionsNode"));
830
- parts.push(" =");
831
- const value = path.call(print, "valueNode");
832
- if (path.node.valueNode.type === "binary_expression" || hasLeadingComments(path.node.valueNode)) parts.push(group$6(indent$6([line$6, value])));
833
- else {
834
- const groupId = Symbol("assignment");
835
- parts.push(group$6(indent$6(line$6), { id: groupId }), indentIfBreak$1(value, { groupId }));
836
- }
837
- return parts;
795
+ if (precedingNode && (enclosingNode.type === "field_access" || precedingNode.end.row < commentNode.start.row) && precedingNode === getMemberObject(enclosingNode)) {
796
+ prettier.util.addLeadingComment(enclosingNode, commentNode);
797
+ return true;
838
798
  }
839
- const resourceIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier" || type === "field_access");
840
- return path.call(print, "namedChildren", resourceIndex);
841
- },
842
- yield_statement(path, print) {
843
- return [
844
- "yield ",
845
- path.call(print, "namedChildren", 0),
846
- ";"
847
- ];
848
799
  }
849
- };
850
- function printExpressionList(expressions) {
851
- return group$6(expressions.map((expression, index) => index === 0 ? expression : [",", indent$6([line$6, expression])]));
800
+ return false;
852
801
  }
853
- function printReturnOrThrowArgument(path, print, options) {
854
- const { node } = path;
855
- const argumentDoc = print(path);
856
- if (returnArgumentHasLeadingComment(node)) return [
857
- "(",
858
- indent$6([hardline$6, argumentDoc]),
859
- closingBracketLine(options, hardline$6),
860
- ")"
861
- ];
862
- if (node.type === "binary_expression") return group$6([
863
- ifBreak$1("("),
864
- indent$6([softline$3, argumentDoc]),
865
- closingBracketLine(options),
866
- ifBreak$1(")")
867
- ]);
868
- return argumentDoc;
802
+ function getMemberChainRoot(node) {
803
+ let current = node;
804
+ while (isMember(current)) {
805
+ const next = getMemberObject(current);
806
+ if (!next) return current;
807
+ else current = next;
808
+ }
809
+ return current;
869
810
  }
870
- function printReturnOrThrowStatement(path, print, options) {
871
- const { node } = path;
872
- return [
873
- node.type === "throw_statement" ? "throw" : "return",
874
- node.namedChildren.length ? [" ", path.call(() => printReturnOrThrowArgument(path, print, options), "namedChildren", 0)] : "",
875
- ";"
876
- ];
811
+ /**
812
+ * With same-line braces, `{` follows the method header on the same line, so a
813
+ * comment between the header and the block moves into the block.
814
+ */
815
+ function handleMethodHeaderComments(commentNode, options) {
816
+ const { enclosingNode, followingNode } = commentNode;
817
+ if (options.braceStyle !== "same-line" || enclosingNode?.type !== "method_declaration" || followingNode?.type !== "block" || followingNode !== enclosingNode.bodyNode) return false;
818
+ const firstStatement = followingNode.namedChildren.at(0);
819
+ if (firstStatement) prettier.util.addLeadingComment(firstStatement, commentNode);
820
+ else prettier.util.addDanglingComment(followingNode, commentNode, void 0);
821
+ return true;
877
822
  }
878
- //#endregion
879
- //#region src/printers/classes.ts
880
- const { group: group$5, hardline: hardline$5, indent: indent$5, join: join$5, line: line$5, softline: softline$2 } = prettier_doc.builders;
881
- var classes_default = {
882
- class_declaration(path, print, options) {
883
- const parts = ["class ", path.call(print, "nameNode")];
884
- const definedClauses = definedKeys(path.node, [
885
- "superclassNode",
886
- "interfacesNode",
887
- "permitsNode"
888
- ]);
889
- const hasMultipleClauses = definedClauses.length > 1;
890
- if (hasChild(path, "type_parametersNode")) {
891
- const typeParameters = path.call(print, "type_parametersNode");
892
- parts.push(hasMultipleClauses ? group$5(indent$5(typeParameters)) : options?.braceStyle === "next-line" ? group$5(typeParameters) : typeParameters);
893
- }
894
- if (definedClauses.length) {
895
- const clauses = definedClauses.flatMap((clause) => {
896
- if (!hasChild(path, clause)) return [];
897
- return [clause === "superclassNode" || clause === "interfacesNode" ? hardline$5 : line$5, path.call(print, clause)];
898
- });
899
- const hasBody = path.node.bodyNode.namedChildren.length > 0;
900
- const afterClauses = options?.braceStyle === "next-line" ? "" : hasBody ? line$5 : " ";
901
- const clauseGroup = [indent$5(clauses), afterClauses];
902
- parts.push(hasMultipleClauses ? clauseGroup : group$5(clauseGroup));
903
- } else if (options?.braceStyle !== "next-line") parts.push(" ");
904
- return [
905
- ...printModifiers(path, print, "declarationOnly"),
906
- group$5(parts),
907
- path.call(print, "bodyNode")
908
- ];
909
- },
910
- type_parameters: printTypeParameters,
911
- superclass(path, print) {
912
- return ["extends ", path.call(print, "namedChildren", 0)];
913
- },
914
- super_interfaces(path, print) {
915
- return group$5(["implements", indent$5([line$5, path.call(print, "namedChildren", 0)])]);
916
- },
917
- permits(path, print) {
918
- return group$5(["permits", indent$5([line$5, path.call(print, "namedChildren", 0)])]);
919
- },
920
- type_list(path, print) {
921
- return join$5([",", line$5], path.map(print, "namedChildren"));
922
- },
923
- class_body(path, print, options) {
924
- return printBlock(path, printBodyDeclarations(path, print, path.parent?.type === "class_declaration" && options?.braceStyle !== "next-line"), options);
925
- },
926
- field_declaration: printVariableDeclaration,
927
- variable_declarator(path, print) {
928
- const leftDoc = [path.call(print, "nameNode")];
929
- if (hasChild(path, "dimensionsNode")) leftDoc.push(path.call(print, "dimensionsNode"));
930
- return printAssignment(leftDoc, " =", hasChild(path, "valueNode") ? path.call(print, "valueNode") : void 0, path.node.valueNode);
931
- },
932
- method_declaration(path, print) {
933
- const modifiers = printModifiers(path, print);
934
- const declaration = [];
935
- if (hasChild(path, "type_parametersNode")) declaration.push(group$5(path.call(print, "type_parametersNode")), " ");
936
- path.each((child) => {
937
- if (child.node.type === "annotation" || child.node.type === "marker_annotation") declaration.push(print(child), " ");
938
- }, "children");
939
- declaration.push(path.call(print, "typeNode"));
940
- if (hasChild(path, "dimensionsNode")) declaration.push(path.call(print, "dimensionsNode"));
941
- declaration.push(" ", path.call(print, "nameNode"), group$5(path.call(print, "parametersNode")));
942
- const throwsIndex = path.node.namedChildren.findIndex(({ type }) => type === "throws");
943
- if (throwsIndex !== -1) declaration.push(group$5(indent$5([hardline$5, path.call(print, "namedChildren", throwsIndex)])));
944
- return hasChild(path, "bodyNode") ? [
945
- modifiers,
946
- group$5(declaration),
947
- " ",
948
- path.call(print, "bodyNode")
949
- ] : [
950
- modifiers,
951
- group$5(declaration),
952
- ";"
953
- ];
954
- },
955
- receiver_parameter(path, print) {
956
- return path.map((child) => child.isLast ? print(child) : [print(child), child.node.type === "identifier" ? "." : " "], "namedChildren");
957
- },
958
- formal_parameters(path, print, options) {
959
- const parameters = path.parent?.type === "record_declaration" ? printBodyDeclarations(path, print) : path.map(print, "namedChildren");
960
- if (parameters.length === 0) return [
961
- "(",
962
- printDanglingCommentsInList(path),
963
- ")"
964
- ];
965
- return indentInParentheses(join$5([",", line$5], parameters), options);
966
- },
967
- formal_parameter(path, print) {
968
- const parameter = printModifiers(path, print, path.grandparent?.type === "record_declaration" ? "avoidBreak" : "noBreak");
969
- parameter.push(path.call(print, "typeNode"));
970
- if (hasChild(path, "dimensionsNode")) parameter.push(path.call(print, "dimensionsNode"));
971
- parameter.push(" ", path.call(print, "nameNode"));
972
- return group$5(parameter);
973
- },
974
- spread_parameter(path, print) {
975
- const parts = printModifiers(path, print, "noBreak");
976
- parts.push(path.call(print, "typeNode"));
977
- if (hasChild(path, "annotationsNodes")) parts.push(...path.map((annotation) => [" ", print(annotation)], "annotationsNodes"));
978
- parts.push("... ", path.call(print, "namedChildren", path.node.namedChildren.length - 1));
979
- return parts;
980
- },
981
- throws(path, print) {
982
- return ["throws ", ...join$5(", ", path.map(print, "namedChildren"))];
983
- },
984
- static_initializer(path, print) {
985
- return ["static ", path.call(print, "namedChildren", 0)];
986
- },
987
- constructor_declaration(path, print) {
988
- const modifiers = printModifiers(path, print, "declarationOnly");
989
- const declaration = [];
990
- if (hasChild(path, "type_parametersNode")) declaration.push(group$5(path.call(print, "type_parametersNode")), " ");
991
- declaration.push(path.call(print, "nameNode"), group$5(path.call(print, "parametersNode")));
992
- const throwsIndex = path.node.namedChildren.findIndex(({ type }) => type === "throws");
993
- if (throwsIndex !== -1) declaration.push(group$5(indent$5([hardline$5, path.call(print, "namedChildren", throwsIndex)])));
994
- return [
995
- modifiers,
996
- group$5(declaration),
997
- " ",
998
- path.call(print, "bodyNode")
999
- ];
1000
- },
1001
- constructor_body(path, print, options) {
1002
- return printBlock(path, printBlockStatements(path, print), options);
1003
- },
1004
- explicit_constructor_invocation(path, print) {
1005
- const invocation = [];
1006
- if (hasChild(path, "objectNode")) invocation.push(path.call(print, "objectNode"), ".");
1007
- if (hasChild(path, "type_argumentsNode")) invocation.push(path.call(print, "type_argumentsNode"));
1008
- invocation.push(path.call(print, "constructorNode"), path.call(print, "argumentsNode"), ";");
1009
- return invocation;
1010
- },
1011
- visibility: printValue,
1012
- modifier: printValue,
1013
- modifiers(path, print, _, args) {
1014
- const parts = [];
1015
- const modifiers = [];
1016
- const typeAnnotations = [];
1017
- path.each((child) => {
1018
- if (child.node.type === "annotation" || child.node.type === "marker_annotation") (modifiers.length ? typeAnnotations : parts).push(print(child));
1019
- else {
1020
- modifiers.push(child.node.value);
1021
- parts.push(...typeAnnotations);
1022
- typeAnnotations.length = 0;
1023
- }
1024
- }, "namedChildren");
1025
- const annotationMode = args && typeof args === "object" && "annotationMode" in args ? args.annotationMode : null;
1026
- if (annotationMode === "declarationOnly") {
1027
- parts.push(...typeAnnotations);
1028
- typeAnnotations.length = 0;
1029
- }
1030
- modifiers.sort((a, b) => (indexByModifier.get(a) ?? -1) - (indexByModifier.get(b) ?? -1));
1031
- if (modifiers.length || typeAnnotations.length) parts.push(join$5(" ", [...modifiers, ...typeAnnotations]));
1032
- return join$5(annotationMode === "avoidBreak" ? line$5 : annotationMode === "noBreak" ? " " : hardline$5, parts);
1033
- },
1034
- enum_declaration(path, print, options) {
1035
- const modifiers = printModifiers(path, print, "declarationOnly");
1036
- const parts = ["enum ", path.call(print, "nameNode")];
1037
- if (hasChild(path, "interfacesNode")) {
1038
- const hasBody = path.node.bodyNode.namedChildren.length > 0;
1039
- parts.push(indent$5([hardline$5, path.call(print, "interfacesNode")]), options?.braceStyle === "next-line" ? "" : hasBody ? line$5 : " ");
1040
- } else parts.push(" ");
1041
- return [
1042
- ...modifiers,
1043
- group$5(parts),
1044
- path.call(print, "bodyNode")
1045
- ];
1046
- },
1047
- enum_body(path, print, options) {
1048
- const parts = printBodyDeclarations(path, print);
1049
- const enumBodyDeclarationsIndex = path.node.namedChildren.findIndex(({ type }) => type === "enum_body_declarations");
1050
- const declarations = [];
1051
- if (enumBodyDeclarationsIndex !== -1) {
1052
- const hasDeclarations = path.node.namedChildren[enumBodyDeclarationsIndex].namedChildren.length > 0;
1053
- const enumBodyDeclarations = parts.pop();
1054
- if (hasDeclarations) {
1055
- if (!parts.length) declarations.push(hardline$5);
1056
- declarations.push(enumBodyDeclarations);
1057
- }
823
+ function handleModifiersComments(commentNode) {
824
+ const { precedingNode } = commentNode;
825
+ if (precedingNode?.type === "annotation" || precedingNode?.type === "marker_annotation" || precedingNode?.type === "modifiers") {
826
+ prettier.util.addTrailingComment(precedingNode, commentNode);
827
+ return true;
828
+ }
829
+ return false;
830
+ }
831
+ function handleNameComments(commentNode) {
832
+ const { enclosingNode, precedingNode } = commentNode;
833
+ if (enclosingNode && precedingNode?.type === "identifier" && (enclosingNode.type === "scoped_identifier" || enclosingNode.type === "module_declaration" || enclosingNode.type === "package_declaration" || enclosingNode.type === "scoped_type_identifier")) {
834
+ prettier.util.addTrailingComment(precedingNode, commentNode);
835
+ return true;
836
+ }
837
+ return false;
838
+ }
839
+ function handleTernaryExpressionComments(commentNode) {
840
+ const { enclosingNode, precedingNode, followingNode } = commentNode;
841
+ if (enclosingNode?.type === "ternary_expression" && precedingNode?.isNamed && followingNode?.isNamed && precedingNode.end.row < commentNode.start.row && commentNode.end.row < followingNode.start.row) {
842
+ prettier.util.addLeadingComment(followingNode, commentNode);
843
+ return true;
844
+ }
845
+ return false;
846
+ }
847
+ function handleTryStatementComments(commentNode) {
848
+ const { enclosingNode, followingNode } = commentNode;
849
+ if (enclosingNode && (enclosingNode.type === "catch_clause" || enclosingNode.type === "try_statement" || enclosingNode.type === "try_with_resources_statement") && followingNode?.isNamed) {
850
+ const block = followingNode.type === "catch_clause" ? followingNode.bodyNode : followingNode.type === "finally_clause" ? followingNode.namedChildren[0] : null;
851
+ if (!block) return false;
852
+ const blockStatement = block.namedChildren.at(0);
853
+ if (blockStatement) prettier.util.addLeadingComment(blockStatement, commentNode);
854
+ else prettier.util.addDanglingComment(block, commentNode, void 0);
855
+ return true;
856
+ }
857
+ return false;
858
+ }
859
+ function getMemberObject(node) {
860
+ return node.type === "array_access" ? node.arrayNode : node.objectNode;
861
+ }
862
+ const binaryOperators = /* @__PURE__ */ new Set([
863
+ "<<",
864
+ ">>",
865
+ ">>>",
866
+ "instanceof",
867
+ "<=",
868
+ ">=",
869
+ "==",
870
+ "-",
871
+ "+",
872
+ "&&",
873
+ "&",
874
+ "^",
875
+ "!=",
876
+ "||",
877
+ "|",
878
+ "*",
879
+ "/",
880
+ "%"
881
+ ]);
882
+ function isBinaryOperator(node) {
883
+ return node !== void 0 && binaryOperators.has(node.type);
884
+ }
885
+ function printLeadingComment(path) {
886
+ const comment = path.node;
887
+ const parts = [printComment(comment)];
888
+ const originalText = path.root.value;
889
+ if (comment.type === "block_comment") {
890
+ let lineBreak = " ";
891
+ if (hasNewline$1(originalText, parser_default.locEnd(comment))) {
892
+ if (hasNewline$1(originalText, parser_default.locStart(comment), { backwards: true })) lineBreak = hardline$6;
893
+ else lineBreak = line$6;
1058
894
  }
1059
- const contents = [];
1060
- if (parts.length) {
1061
- contents.push(join$5([",", hardline$5], parts));
1062
- if (!declarations.length && options.trailingComma !== "none") contents.push(",");
895
+ parts.push(lineBreak);
896
+ } else parts.push(hardline$6);
897
+ const index = skipNewline(originalText, skipSpaces(originalText, parser_default.locEnd(comment)));
898
+ if (index !== false && hasNewline$1(originalText, index)) parts.push(hardline$6);
899
+ return parts;
900
+ }
901
+ function printTrailingComment(path, previousComment) {
902
+ const comment = path.node;
903
+ const printed = printComment(comment);
904
+ const originalText = path.root.value;
905
+ const isBlock = comment.type === "block_comment";
906
+ if (previousComment?.hasLineSuffix && !previousComment?.isBlock || hasNewline$1(originalText, parser_default.locStart(comment), { backwards: true })) {
907
+ const isLineBeforeEmpty = isPreviousLineEmpty(originalText, parser_default.locStart(comment));
908
+ return {
909
+ doc: lineSuffix([
910
+ hardline$6,
911
+ isLineBeforeEmpty ? hardline$6 : "",
912
+ printed
913
+ ]),
914
+ isBlock,
915
+ hasLineSuffix: true
916
+ };
917
+ }
918
+ if (!isBlock || previousComment?.hasLineSuffix) return {
919
+ doc: [lineSuffix([" ", printed]), breakParent$1],
920
+ isBlock,
921
+ hasLineSuffix: true
922
+ };
923
+ return {
924
+ doc: [" ", printed],
925
+ isBlock,
926
+ hasLineSuffix: false
927
+ };
928
+ }
929
+ function printLeadingComments(path) {
930
+ if (!hasChild(path, "comments")) return [];
931
+ const docs = [];
932
+ path.each((path) => {
933
+ const { node: comment } = path;
934
+ if (!comment.leading) return;
935
+ docs.push(printLeadingComment(path));
936
+ }, "comments");
937
+ return docs;
938
+ }
939
+ function printTrailingComments(path) {
940
+ if (!hasChild(path, "comments")) return [];
941
+ const docs = [];
942
+ let printedTrailingComment;
943
+ path.each((path) => {
944
+ const { node: comment } = path;
945
+ if (!comment.trailing) return;
946
+ printedTrailingComment = printTrailingComment(path, printedTrailingComment);
947
+ docs.push(printedTrailingComment.doc);
948
+ }, "comments");
949
+ return docs;
950
+ }
951
+ function printCommentsSeparately(path) {
952
+ return {
953
+ leading: printLeadingComments(path),
954
+ trailing: printTrailingComments(path)
955
+ };
956
+ }
957
+ function printComments(path, doc) {
958
+ const leading = printLeadingComments(path);
959
+ const trailing = printTrailingComments(path);
960
+ return leading.length || trailing.length ? [
961
+ leading,
962
+ doc,
963
+ trailing
964
+ ] : doc;
965
+ }
966
+ // src/parser.ts
967
+ var parser_default = {
968
+ async parse(text) {
969
+ const tree = (await parser).parse(text);
970
+ try {
971
+ const { rootNode } = tree;
972
+ if (rootNode.hasError) throw new Error("Failed to parse: " + rootNode);
973
+ const ast = processTree(rootNode);
974
+ determinePrettierIgnoreRanges(ast);
975
+ return ast;
976
+ } finally {
977
+ tree.delete();
1063
978
  }
1064
- if (declarations.length) contents.push(";", hardline$5, ...declarations);
1065
- return printBlock(path, contents.length ? [contents] : [], options);
1066
979
  },
1067
- enum_constant(path, print) {
1068
- const initializer = printModifiers(path, print);
1069
- initializer.push(path.call(print, "nameNode"));
1070
- if (hasChild(path, "argumentsNode")) initializer.push(path.call(print, "argumentsNode"));
1071
- if (hasChild(path, "bodyNode")) initializer.push(" ", path.call(print, "bodyNode"));
1072
- return initializer;
1073
- },
1074
- enum_body_declarations(path, print) {
1075
- return join$5(hardline$5, printBodyDeclarations(path, print));
980
+ astFormat: "java",
981
+ hasPragma(text) {
982
+ return /^\/\*\*\n\s+\*\s@(format|prettier)\n\s+\*\//.test(text);
1076
983
  },
1077
- record_declaration(path, print) {
1078
- const modifiers = printModifiers(path, print, "declarationOnly");
1079
- const parts = ["record ", path.call(print, "nameNode")];
1080
- if (hasChild(path, "type_parametersNode")) parts.push(group$5(path.call(print, "type_parametersNode")));
1081
- parts.push(group$5(path.call(print, "parametersNode")));
1082
- if (hasChild(path, "interfacesNode")) {
1083
- const hasBody = path.node.bodyNode.namedChildren.length > 0;
1084
- const interfaces = [hardline$5, path.call(print, "interfacesNode")];
1085
- parts.push(group$5([indent$5(interfaces), hasBody ? line$5 : " "]));
1086
- } else parts.push(" ");
1087
- return [
1088
- ...modifiers,
1089
- group$5(parts),
1090
- path.call(print, "bodyNode")
1091
- ];
984
+ locStart(node) {
985
+ return node.start.index;
1092
986
  },
1093
- compact_constructor_declaration(path, print) {
1094
- const parts = printModifiers(path, print, "declarationOnly");
1095
- parts.push(path.call(print, "nameNode"), " ", path.call(print, "bodyNode"));
1096
- return parts;
987
+ locEnd(node) {
988
+ return node.end.index;
1097
989
  }
1098
990
  };
1099
- const indexByModifier = [
1100
- "public",
1101
- "protected",
1102
- "private",
1103
- "abstract",
1104
- "default",
1105
- "static",
1106
- "final",
1107
- "transient",
1108
- "volatile",
1109
- "synchronized",
1110
- "native",
1111
- "sealed",
1112
- "non-sealed",
1113
- "strictfp"
1114
- ].reduce((map, name, index) => map.set(name, index), /* @__PURE__ */ new Map());
1115
- function printDanglingCommentsInList(path) {
1116
- const { node } = path;
1117
- return node.comments?.some((comment) => !(comment.leading || comment.trailing)) ? [indent$5([softline$2, printDanglingComments(path)]), node.comments.some(({ type, leading, trailing }) => !(leading || trailing) && type === "line_comment") ? hardline$5 : softline$2] : "";
1118
- }
1119
- //#endregion
1120
- //#region src/printers/expressions.ts
1121
- const { align, breakParent: breakParent$1, conditionalGroup, dedent, group: group$4, hardline: hardline$4, ifBreak, indent: indent$4, indentIfBreak, join: join$4, line: line$4, lineSuffixBoundary, softline: softline$1 } = prettier_doc.builders;
1122
- const { getNextNonSpaceNonCommentCharacterIndex, hasNewline: hasNewline$1, isNextLineEmpty } = prettier.util;
1123
- const { removeLines, willBreak } = prettier_doc.utils;
1124
- var expressions_default = {
1125
- lambda_expression(path, print, options, args) {
1126
- const signatureDocs = [];
1127
- let bodyDoc;
1128
- const bodyComments = [];
1129
- const shouldPrintAsChain = !(args && typeof args === "object" && "expandLastArg" in args && args.expandLastArg) && path.node.bodyNode.type === "lambda_expression";
1130
- let functionBody;
1131
- (function rec() {
1132
- const { node } = path;
1133
- const signatureDoc = printLambdaExpressionSignature(path, options, print, args);
1134
- if (signatureDocs.length === 0) signatureDocs.push(signatureDoc);
991
+ const parser = (async () => {
992
+ await web_tree_sitter.Parser.init();
993
+ const parser = new web_tree_sitter.Parser();
994
+ const Java = await web_tree_sitter.Language.load(new URL("./tree-sitter-java_orchard.wasm", require("url").pathToFileURL(__filename).href));
995
+ parser.setLanguage(Java);
996
+ return parser;
997
+ })();
998
+ const isParenthesizedParent = createTypeCheckFunction([
999
+ "do_statement",
1000
+ "if_statement",
1001
+ "switch_expression",
1002
+ "synchronized_statement",
1003
+ "try_statement",
1004
+ "try_with_resources_statement",
1005
+ "while_statement"
1006
+ ]);
1007
+ function processTree(node, fieldName = null, comments) {
1008
+ const { type, isNamed, text: value, startPosition, endPosition } = node;
1009
+ const javaNode = {
1010
+ type,
1011
+ isNamed,
1012
+ value,
1013
+ start: {
1014
+ index: node.startIndex,
1015
+ row: startPosition.row,
1016
+ column: startPosition.column
1017
+ },
1018
+ end: {
1019
+ index: node.endIndex,
1020
+ row: endPosition.row,
1021
+ column: endPosition.column
1022
+ },
1023
+ children: [],
1024
+ namedChildren: [],
1025
+ fieldName
1026
+ };
1027
+ if (!comments) comments = javaNode.comments = [];
1028
+ if (!javaNode.isNamed) return javaNode;
1029
+ const multiFields = multiFieldsByType[node.type];
1030
+ if (multiFields) Object.keys(multiFields).forEach((name) => javaNode[`${name}Nodes`] = []);
1031
+ node.children.forEach((child, index) => {
1032
+ const fieldName = node.fieldNameForChild(index);
1033
+ (child.type === "parenthesized_expression" && !isParenthesizedParent(javaNode) ? child.namedChildren : [child]).forEach((child) => {
1034
+ const { type, text: value, startPosition, endPosition } = child;
1035
+ if (type === "block_comment" || type === "line_comment") comments.push({
1036
+ type,
1037
+ value,
1038
+ start: {
1039
+ index: child.startIndex,
1040
+ row: startPosition.row,
1041
+ column: startPosition.column
1042
+ },
1043
+ end: {
1044
+ index: child.endIndex,
1045
+ row: endPosition.row,
1046
+ column: endPosition.column
1047
+ },
1048
+ leading: false,
1049
+ trailing: false,
1050
+ printed: false
1051
+ });
1135
1052
  else {
1136
- const { leading, trailing } = printCommentsSeparately(path);
1137
- signatureDocs.push([leading, signatureDoc]);
1138
- bodyComments.unshift(trailing);
1053
+ const javaChild = processTree(child, fieldName, comments);
1054
+ javaNode.children.push(javaChild);
1055
+ if (javaChild.isNamed) javaNode.namedChildren.push(javaChild);
1056
+ if (fieldName) {
1057
+ if (multiFields?.[fieldName]) javaNode[`${fieldName}Nodes`].push(javaChild);
1058
+ else javaNode[`${fieldName}Node`] = javaChild;
1059
+ }
1139
1060
  }
1140
- if (!shouldPrintAsChain || node.bodyNode.type !== "lambda_expression") {
1141
- bodyDoc = path.call((child) => print(child, args), "bodyNode");
1142
- functionBody = node.bodyNode;
1143
- } else path.call(rec, "bodyNode");
1144
- })();
1145
- const shouldPutBodyOnSameLine = !functionBody.comments?.some((comment) => comment.leading && hasNewline$1(options.originalText, comment.end.index)) && mayBreakAfterShortPrefix(functionBody);
1146
- const chainGroupId = Symbol("arrow-chain");
1147
- const signaturesDoc = printArrowFunctionSignatures(path, { signatureDocs });
1148
- bodyDoc = printArrowFunctionBody(path, args, options, {
1149
- bodyDoc,
1150
- bodyComments,
1151
- shouldPutBodyOnSameLine
1152
1061
  });
1153
- return group$4([
1154
- group$4(signaturesDoc, { id: chainGroupId }),
1155
- " ->",
1156
- shouldPrintAsChain ? indentIfBreak(bodyDoc, { groupId: chainGroupId }) : group$4(bodyDoc)
1157
- ]);
1062
+ });
1063
+ return javaNode;
1064
+ }
1065
+ // src/printers/arrays.ts
1066
+ var arrays_default = { array_initializer: printArrayInitializer };
1067
+ // src/printers/blocks-and-statements.ts
1068
+ const { group: group$6, hardline: hardline$5, ifBreak: ifBreak$1, indent: indent$6, indentIfBreak: indentIfBreak$1, join: join$6, line: line$5, softline: softline$2 } = prettier_doc.builders;
1069
+ var blocks_and_statements_default = {
1070
+ block(path, print, options) {
1071
+ return printBlock(path, printBlockStatements(path, print), options);
1158
1072
  },
1159
- inferred_parameters(path, print, options) {
1160
- const identifiers = [];
1161
- path.each((child) => {
1162
- if (child.node.type === "identifier") identifiers.push(print(child));
1163
- }, "namedChildren");
1164
- if (!identifiers.length) return "()";
1165
- const parameters = join$4([",", line$4], identifiers);
1166
- if (identifiers.length > 1 || willBreak(identifiers)) return group$4(indentInParentheses(parameters, options));
1167
- return options.arrowParens === "avoid" ? parameters : [
1168
- "(",
1169
- ...parameters,
1170
- ")"
1073
+ local_variable_declaration: printVariableDeclaration,
1074
+ labeled_statement(path, print, options) {
1075
+ const [label, statement] = path.map(print, "namedChildren");
1076
+ return [
1077
+ label,
1078
+ ":",
1079
+ printStatementSeparator(path.node.namedChildren[1].type, options),
1080
+ statement
1171
1081
  ];
1172
1082
  },
1173
- ternary_expression(path, print, options) {
1174
- const { node } = path;
1175
- const consequentNode = node.consequenceNode;
1176
- const parts = [];
1177
- const parent = path.parent;
1178
- const isParentTest = parent.type === node.type && parent.conditionNode === node;
1179
- const forceNoIndent = parent.type === node.type && !isParentTest;
1180
- let currentParent;
1181
- let previousParent;
1182
- let i = 0;
1183
- do {
1184
- previousParent = currentParent || node;
1185
- currentParent = path.getParentNode(i);
1186
- i++;
1187
- } while (currentParent && currentParent.type === node.type && currentParent.conditionNode !== previousParent);
1188
- const firstNonConditionalParent = currentParent || parent;
1189
- const printBranch = (nodePropertyName) => options.useTabs ? indent$4(path.call(print, nodePropertyName)) : align(2, path.call(print, nodePropertyName));
1190
- const part = [
1191
- line$4,
1192
- "? ",
1193
- consequentNode.type === node.type ? ifBreak("", "(") : "",
1194
- printBranch("consequenceNode"),
1195
- consequentNode.type === node.type ? ifBreak("", ")") : "",
1196
- line$4,
1197
- ": ",
1198
- printBranch("alternativeNode")
1083
+ expression_statement(path, print) {
1084
+ const parentType = path.parent?.type;
1085
+ const expressionType = path.node.namedChildren[0].type;
1086
+ const expression = path.call(print, "namedChildren", 0);
1087
+ return expressionType === "switch_expression" && parentType !== "assignment_expression" && parentType !== "switch_rule" ? expression : [expression, ";"];
1088
+ },
1089
+ if_statement(path, print, options) {
1090
+ const statement = ["if ", path.call(print, "conditionNode")];
1091
+ if (path.node.consequenceNode.type === ";") statement.push(";");
1092
+ else statement.push(printStatementSeparator(path.node.consequenceNode.type, options), path.call(print, "consequenceNode"));
1093
+ if (!hasChild(path, "alternativeNode")) return statement;
1094
+ const danglingComments = printDanglingComments(path);
1095
+ if (danglingComments) statement.push(hardline$5, danglingComments, hardline$5);
1096
+ else if (options?.braceStyle === "next-line") statement.push(hardline$5);
1097
+ else {
1098
+ const ifHasBlock = path.node.consequenceNode.type === "block";
1099
+ statement.push(ifHasBlock ? " " : hardline$5);
1100
+ }
1101
+ statement.push("else");
1102
+ if (path.node.alternativeNode.type === ";") statement.push(";");
1103
+ else statement.push(printStatementSeparator(path.node.alternativeNode.type, options), path.call(print, "alternativeNode"));
1104
+ return statement;
1105
+ },
1106
+ assert_statement(path, print) {
1107
+ return [
1108
+ "assert ",
1109
+ ...join$6(" : ", path.map(print, "namedChildren")),
1110
+ ";"
1199
1111
  ];
1200
- parts.push(parent.type !== node.type || parent.alternativeNode === node || isParentTest ? part : options.useTabs ? dedent(indent$4(part)) : align(Math.max(0, options.tabWidth - 2), part));
1201
- const maybeGroup = (doc) => parent === firstNonConditionalParent ? group$4(doc) : doc;
1202
- const breakClosingParen = parent.type === "explicit_constructor_invocation" || parent.type === "field_access" || parent.type === "method_invocation" || parent.type === "method_reference" || parent.type === "object_creation_expression";
1203
- const shouldExtraIndent = shouldExtraIndentForTernaryExpression(path);
1204
- const result = maybeGroup([
1205
- printTernaryTest(path, print),
1206
- forceNoIndent ? parts : indent$4(parts),
1207
- breakClosingParen && !shouldExtraIndent ? closingBracketLine(options) : ""
1208
- ]);
1209
- return isParentTest || shouldExtraIndent ? group$4([indent$4([softline$1, result]), closingBracketLine(options)]) : result;
1210
1112
  },
1211
- assignment_expression(path, print) {
1212
- const { node } = path;
1213
- return printAssignment(path.call(print, "leftNode"), [" ", node.operatorNode.type], path.call(print, "rightNode"), node.rightNode);
1113
+ switch_expression(path, print, options) {
1114
+ return [
1115
+ "switch ",
1116
+ path.call(print, "conditionNode"),
1117
+ printBlockSeparator(options),
1118
+ path.call(print, "bodyNode")
1119
+ ];
1214
1120
  },
1215
- binary_expression(path, print, options) {
1216
- const { node } = path;
1217
- const parent = path.parent;
1218
- const grandparent = path.grandparent;
1219
- const isInsideParentheses = (grandparent?.type === "if_statement" || grandparent?.type === "while_statement" || grandparent?.type === "switch_expression" || grandparent?.type === "do_statement") && grandparent.conditionNode === parent || grandparent?.type === "synchronized_statement" && grandparent.bodyNode !== parent;
1220
- const parts = printBinaryExpressions(path, print, options, isInsideParentheses);
1221
- if (isInsideParentheses) return parts;
1222
- if (parent?.type === "unary_expression" && !node.comments || (parent?.type === "explicit_constructor_invocation" || parent?.type === "field_access" || parent?.type === "method_invocation") && parent.objectNode === node || parent?.type === "method_reference" || parent?.type === "object_creation_expression") return group$4([indent$4([softline$1, ...parts]), closingBracketLine(options)]);
1223
- if (isReturnOrThrowStatement(parent) || parent?.type === "assignment_expression" || parent?.type === "variable_declarator" || parent?.type === "guard" || parent?.type === "lambda_expression" && parent.bodyNode === node || parent?.type === "for_statement" && parent.conditionNode === node || parent?.type === "ternary_expression" && !isReturnOrThrowStatement(grandparent) && grandparent?.type !== "parenthesized_expression" && grandparent?.type !== "argument_list" || parent?.type === "unary_expression" && parent.operandNode === node) return group$4(parts);
1224
- if (parts.length === 0) return "";
1225
- const firstGroupIndex = parts.findIndex((part) => typeof part !== "string" && !Array.isArray(part) && part.type === "group");
1226
- const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1);
1227
- const rest = parts.slice(headParts.length);
1228
- return group$4([...headParts, indent$4(rest)]);
1121
+ switch_block(path, print, options) {
1122
+ return printBlock(path, path.map(print, "namedChildren"), options);
1229
1123
  },
1230
- instanceof_expression(path, print, options) {
1231
- return group$4(indent$4(path.map((child) => {
1232
- const doc = print(child, { annotationMode: "noBreak" });
1233
- if (!child.previous) return doc;
1234
- return [(options.experimentalOperatorPosition === "start" ? child.node.type === "instanceof" : child.previous.type === "instanceof") ? line$4 : " ", doc];
1235
- }, "children")));
1124
+ switch_block_statement_group(path, print, options) {
1125
+ const parts = [];
1126
+ path.each((child) => {
1127
+ if (child.node.type === "switch_label") parts.push(print(child), ":");
1128
+ }, "namedChildren");
1129
+ const firstStatementIndex = path.node.namedChildren.findIndex(({ type }) => type !== "switch_label");
1130
+ if (firstStatementIndex === path.node.namedChildren.length - 1 && path.node.namedChildren[firstStatementIndex].type === "block") parts.push(printBlockSeparator(options), path.call(print, "namedChildren", firstStatementIndex));
1131
+ else if (firstStatementIndex !== -1) parts.push(indent$6([hardline$5, ...join$6(hardline$5, printBlockStatements(path, print))]));
1132
+ return parts;
1236
1133
  },
1237
- unary_expression(path, print, options) {
1238
- const parts = [path.call(print, "operatorNode")];
1239
- const operandDoc = path.call(print, "operandNode");
1240
- if (path.node.operandNode.comments) parts.push(group$4(indentInParentheses(operandDoc, options)));
1241
- else parts.push(operandDoc);
1134
+ switch_label(path, print) {
1135
+ if (!path.node.children.some(({ type }) => type === "case")) return "default";
1136
+ const values = [];
1137
+ path.each((child) => {
1138
+ if (child.node.type !== "guard") values.push(print(child));
1139
+ }, "namedChildren");
1140
+ const hasMultipleValues = values.length > 1;
1141
+ const label = hasMultipleValues ? ["case", indent$6([line$5, ...join$6([",", line$5], values)])] : ["case ", values[0]];
1142
+ const guardIndex = path.node.namedChildren.findIndex(({ type }) => type === "guard");
1143
+ return guardIndex !== -1 ? [group$6([...label, hasMultipleValues ? line$5 : " "]), path.call(print, "namedChildren", guardIndex)] : group$6(label);
1144
+ },
1145
+ switch_rule(path, print, options) {
1146
+ const bodyIndex = path.node.namedChildren.findIndex(({ type }) => type === "block" || type === "expression_statement" || type === "throw_statement");
1147
+ const body = path.call(print, "namedChildren", bodyIndex);
1148
+ const switchLabelIndex = path.node.namedChildren.findIndex(({ type }) => type === "switch_label");
1149
+ const parts = [path.call(print, "namedChildren", switchLabelIndex), " ->"];
1150
+ const bodyNode = path.node.namedChildren[bodyIndex];
1151
+ if (bodyNode.type !== "block" && hasLeadingComments(bodyNode)) parts.push(indent$6([hardline$5, body]));
1152
+ else parts.push(printStatementSeparator(bodyNode.type, options), body);
1242
1153
  return parts;
1243
1154
  },
1244
- field_access: printMemberChain,
1245
- generic_type(path, print) {
1246
- const typeIdentifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "scoped_type_identifier" || type === "type_identifier");
1247
- const typeArgumentsIndex = path.node.namedChildren.findIndex(({ type }) => type === "type_arguments");
1248
- return [path.call(print, "namedChildren", typeIdentifierIndex), path.call(print, "namedChildren", typeArgumentsIndex)];
1155
+ while_statement(path, print, options) {
1156
+ const parts = ["while ", path.call(print, "conditionNode")];
1157
+ const body = path.call(print, "bodyNode");
1158
+ const bodyType = path.node.bodyNode.type;
1159
+ if (bodyType === "block") {
1160
+ parts.push(printBlockSeparator(options), body);
1161
+ return parts;
1162
+ } else if (bodyType === ";") {
1163
+ parts.push(";");
1164
+ return parts;
1165
+ } else {
1166
+ parts.push(line$5, body);
1167
+ return group$6(indent$6(parts));
1168
+ }
1249
1169
  },
1250
- parenthesized_expression(path, print, options) {
1251
- const expression = path.call(print, "namedChildren", 0);
1252
- const parentType = path.parent?.type;
1253
- const grandparentType = path.grandparent?.type;
1254
- const expressionType = path.node.namedChildren[0].type;
1255
- const hasLambda = expressionType === "lambda_expression";
1256
- const hasTernary = expressionType === "ternary_expression";
1257
- const hasSuffix = parentType && (parentType === "array_access" || parentType === "explicit_constructor_invocation" || parentType === "field_access" || parentType === "method_invocation" || parentType === "method_reference" || parentType === "object_creation_expression");
1258
- const isAssignment = parentType && (parentType === "assignment_expression" || parentType === "variable_declarator") || hasSuffix && (grandparentType === "assignment_expression" || grandparentType === "variable_declarator");
1259
- if (!hasLambda && hasSuffix && (!hasTernary || isAssignment)) return group$4(indentInParentheses(hasTernary ? group$4(expression) : expression, options));
1260
- else if (parentType && (parentType === "guard" || parentType === "return_statement" || parentType === "unary_expression" && grandparentType === "return_statement" || path.node.fieldName === "condition" && (parentType === "do_statement" || parentType === "if_statement" || parentType === "switch_expression" || parentType === "while_statement") || path.node.fieldName !== "body" && parentType === "synchronized_statement")) return group$4(indentInParentheses(group$4(expression), options));
1261
- else if (hasTernary && hasSuffix && !isAssignment) return group$4([
1262
- "(",
1263
- expression,
1264
- closingBracketLine(options),
1265
- ")"
1266
- ]);
1267
- else return group$4([
1268
- "(",
1269
- hasLambda || hasTernary ? expression : indent$4(expression),
1270
- ")"
1271
- ]);
1170
+ do_statement(path, print, options) {
1171
+ const hasEmptyStatement = path.node.bodyNode.type === ";";
1172
+ const whilePrefix = options?.braceStyle === "next-line" ? [hardline$5, "while "] : " while ";
1173
+ return [
1174
+ "do",
1175
+ hasEmptyStatement ? ";" : [printStatementSeparator(path.node.bodyNode.type, options), path.call(print, "bodyNode")],
1176
+ whilePrefix,
1177
+ path.call(print, "conditionNode"),
1178
+ ";"
1179
+ ];
1272
1180
  },
1273
- cast_expression(path, print) {
1274
- const { node } = path;
1275
- const parts = [
1276
- group$4(node.typeNodes.length === 1 ? [
1277
- "(",
1278
- path.call(print, "typeNodes", 0),
1279
- ")"
1280
- ] : [
1281
- "(",
1282
- indent$4([softline$1, join$4([" &", line$4], path.map(print, "typeNodes"))]),
1283
- softline$1,
1284
- ")"
1285
- ]),
1286
- " ",
1287
- path.call(print, "valueNode")
1181
+ for_statement(path, print, options) {
1182
+ const danglingComments = printDanglingComments(path);
1183
+ const hasInit = path.node.initNodes.length > 0;
1184
+ const hasCondition = hasChild(path, "conditionNode");
1185
+ const hasUpdate = path.node.updateNodes.length > 0;
1186
+ const expressions = [
1187
+ !hasInit ? ";" : path.node.initNodes[0].type === "local_variable_declaration" ? path.call(print, "initNodes", 0) : [printExpressionList(path.map(print, "initNodes")), ";"],
1188
+ hasCondition ? [path.call(print, "conditionNode"), ";"] : ";",
1189
+ hasUpdate ? [line$5, printExpressionList(path.map(print, "updateNodes"))] : ifBreak$1("", " ")
1190
+ ];
1191
+ const hasEmptyStatement = path.node.bodyNode.type === ";";
1192
+ return [
1193
+ danglingComments && [danglingComments, hardline$5],
1194
+ "for ",
1195
+ hasInit || hasCondition || hasUpdate ? group$6(indentInParentheses([join$6(line$5, expressions.slice(0, 2)), expressions[2]], options)) : "(;;)",
1196
+ hasEmptyStatement ? ";" : [printStatementSeparator(path.node.bodyNode.type, options), path.call(print, "bodyNode")]
1288
1197
  ];
1289
- const parent = path.parent;
1290
- if (parent?.type === "unary_expression" && !node.comments || parent?.type === "array_access" && parent.arrayNode === node || (parent?.type === "explicit_constructor_invocation" || parent?.type === "field_access" || parent?.type === "method_invocation") && parent.objectNode === node || parent?.type === "method_reference" || parent?.type === "object_creation_expression") return group$4([indent$4([softline$1, ...parts]), softline$1]);
1291
- return parts;
1292
1198
  },
1293
- object_creation_expression(path, print) {
1294
- const expression = [];
1295
- path.each((child) => {
1296
- if (child.node.type === "class_body") expression.push(" ");
1297
- expression.push(print(child));
1298
- if (child.node.type === "annotation" || child.node.type === "marker_annotation" || child.node.type === "new") expression.push(" ");
1299
- }, "children");
1300
- return expression;
1199
+ update_expression(path, print) {
1200
+ return path.map(print, "children");
1301
1201
  },
1302
- method_invocation: printMemberChain,
1303
- argument_list(path, print, options) {
1304
- const args = path.node.namedChildren;
1305
- if (args.length === 0) {
1306
- const shouldBreak = path.node.comments?.some(({ type, leading, trailing }) => !leading && !trailing && type === "line_comment");
1307
- return group$4(indentInParentheses(printDanglingComments(path), options), { shouldBreak });
1308
- }
1309
- const lastArgIndex = args.length - 1;
1310
- let anyArgEmptyLine = false;
1311
- const printedArguments = [];
1312
- path.each((arg, index) => {
1313
- let argDoc = print(arg);
1314
- if (index === lastArgIndex) {} else if (isNextLineEmpty(options.originalText, arg.node.end.index)) {
1315
- anyArgEmptyLine = true;
1316
- argDoc = [
1317
- argDoc,
1318
- ",",
1319
- hardline$4,
1320
- hardline$4
1321
- ];
1322
- } else argDoc = [
1323
- argDoc,
1324
- ",",
1325
- line$4
1326
- ];
1327
- printedArguments.push(argDoc);
1328
- }, "namedChildren");
1329
- function allArgsBrokenOut() {
1330
- return group$4([
1331
- "(",
1332
- indent$4([line$4, ...printedArguments]),
1333
- closingBracketLine(options, line$4),
1334
- ")"
1335
- ], { shouldBreak: true });
1336
- }
1337
- if (anyArgEmptyLine) return allArgsBrokenOut();
1338
- if (shouldExpandFirstArg(args)) {
1339
- const tailArgs = printedArguments.slice(1);
1340
- if (tailArgs.some(willBreak)) return allArgsBrokenOut();
1341
- let firstArg;
1342
- try {
1343
- firstArg = path.call((arg) => print(arg, { expandFirstArg: true }), "namedChildren", 0);
1344
- } catch (caught) {
1345
- if (caught instanceof ArgExpansionBailout) return allArgsBrokenOut();
1346
- throw caught;
1347
- }
1348
- if (willBreak(firstArg)) return [breakParent$1, conditionalGroup([[
1349
- "(",
1350
- group$4(firstArg, { shouldBreak: true }),
1351
- ", ",
1352
- ...tailArgs,
1353
- ")"
1354
- ], allArgsBrokenOut()])];
1355
- return conditionalGroup([
1356
- [
1357
- "(",
1358
- firstArg,
1359
- ", ",
1360
- ...tailArgs,
1361
- ")"
1362
- ],
1363
- [
1364
- "(",
1365
- group$4(firstArg, { shouldBreak: true }),
1366
- ", ",
1367
- ...tailArgs,
1368
- ")"
1369
- ],
1370
- allArgsBrokenOut()
1371
- ]);
1372
- }
1373
- if (shouldExpandLastArg(args)) {
1374
- const headArgs = printedArguments.slice(0, -1);
1375
- if (headArgs.some(willBreak)) return allArgsBrokenOut();
1376
- let lastArg;
1377
- try {
1378
- lastArg = path.call((arg) => print(arg, { expandLastArg: true }), "namedChildren", lastArgIndex);
1379
- } catch (caught) {
1380
- if (caught instanceof ArgExpansionBailout) return allArgsBrokenOut();
1381
- throw caught;
1382
- }
1383
- if (willBreak(lastArg)) return [breakParent$1, conditionalGroup([[
1384
- "(",
1385
- ...headArgs,
1386
- group$4(lastArg, { shouldBreak: true }),
1387
- ")"
1388
- ], allArgsBrokenOut()])];
1389
- return conditionalGroup([
1390
- [
1391
- "(",
1392
- ...headArgs,
1393
- lastArg,
1394
- ")"
1395
- ],
1396
- [
1397
- "(",
1398
- ...headArgs,
1399
- group$4(lastArg, { shouldBreak: true }),
1400
- ")"
1401
- ],
1402
- allArgsBrokenOut()
1403
- ]);
1202
+ enhanced_for_statement(path, print, options) {
1203
+ const danglingComments = printDanglingComments(path);
1204
+ const forStatement = [
1205
+ danglingComments && [danglingComments, hardline$5],
1206
+ "for (",
1207
+ ...printModifiers(path, print, "noBreak"),
1208
+ path.call(print, "typeNode"),
1209
+ " ",
1210
+ path.call(print, "nameNode")
1211
+ ];
1212
+ if (hasChild(path, "dimensionsNode")) forStatement.push(path.call(print, "dimensionsNode"));
1213
+ forStatement.push(" : ", path.call(print, "valueNode"), ")");
1214
+ const bodyType = path.node.bodyNode.type;
1215
+ if (bodyType === ";") forStatement.push(";");
1216
+ else {
1217
+ const body = path.call(print, "bodyNode");
1218
+ forStatement.push(bodyType === "block" ? [printBlockSeparator(options), body] : indent$6([line$5, body]));
1404
1219
  }
1405
- return group$4(indentInParentheses(printedArguments, options), { shouldBreak: printedArguments.some(willBreak) || anyArgEmptyLine });
1220
+ return group$6(forStatement);
1406
1221
  },
1407
- array_creation_expression(path, print) {
1408
- const parts = ["new "];
1409
- path.each((child) => {
1410
- if (child.node.type === "annotation" || child.node.type === "marker_annotation") parts.push(print(child), " ");
1411
- }, "namedChildren");
1412
- parts.push(path.call(print, "typeNode"), ...path.map(print, "dimensionsNodes"));
1413
- if (hasChild(path, "valueNode")) parts.push(" ", path.call(print, "valueNode"));
1222
+ break_statement(path, print) {
1223
+ const parts = ["break"];
1224
+ const identifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier");
1225
+ if (identifierIndex !== -1) parts.push(" ", path.call(print, "namedChildren", identifierIndex));
1226
+ parts.push(";");
1414
1227
  return parts;
1415
1228
  },
1416
- dimensions_expr(path, print) {
1417
- return path.map((child) => child.node.type === "annotation" || child.node.type === "marker_annotation" ? [print(child), " "] : [
1418
- "[",
1419
- print(child),
1420
- "]"
1421
- ], "namedChildren");
1229
+ continue_statement(path, print) {
1230
+ const identifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier");
1231
+ return identifierIndex !== -1 ? [
1232
+ "continue ",
1233
+ path.call(print, "namedChildren", identifierIndex),
1234
+ ";"
1235
+ ] : "continue;";
1422
1236
  },
1423
- class_literal(path, print) {
1424
- return [path.call(print, "namedChildren", 0), ".class"];
1237
+ return_statement: printReturnOrThrowStatement,
1238
+ throw_statement: printReturnOrThrowStatement,
1239
+ synchronized_statement(path, print, options) {
1240
+ const parenthesizedExpressionIndex = path.node.namedChildren.findIndex(({ type }) => type === "parenthesized_expression");
1241
+ return [
1242
+ "synchronized ",
1243
+ path.call(print, "namedChildren", parenthesizedExpressionIndex),
1244
+ printBlockSeparator(options),
1245
+ path.call(print, "bodyNode")
1246
+ ];
1425
1247
  },
1426
- array_access: printMemberChain,
1427
- method_reference(path, print) {
1428
- return group$4(path.map(print, "children"));
1248
+ try_statement(path, print, options) {
1249
+ return [
1250
+ "try",
1251
+ printBlockSeparator(options),
1252
+ path.call(print, "bodyNode"),
1253
+ ...printCatchAndFinallyClauses(path, print, options)
1254
+ ];
1429
1255
  },
1430
- template_expression(path, print) {
1256
+ catch_clause(path, print, options) {
1257
+ const catchFormalParameterIndex = path.node.namedChildren.findIndex(({ type }) => type === "catch_formal_parameter");
1431
1258
  return [
1432
- path.call(print, "template_processorNode"),
1433
- ".",
1434
- path.call(print, "template_argumentNode")
1259
+ "catch ",
1260
+ group$6(indentInParentheses(path.call(print, "namedChildren", catchFormalParameterIndex), options)),
1261
+ printBlockSeparator(options),
1262
+ path.call(print, "bodyNode")
1435
1263
  ];
1436
1264
  },
1437
- pattern(path, print) {
1438
- return path.call(print, "namedChildren", 0);
1265
+ catch_formal_parameter(path, print) {
1266
+ const parts = printModifiers(path, print, "noBreak");
1267
+ const catchTypeIndex = path.node.namedChildren.findIndex(({ type }) => type === "catch_type");
1268
+ parts.push(path.call(print, "namedChildren", catchTypeIndex), " ", path.call(print, "nameNode"));
1269
+ if (hasChild(path, "dimensionsNode")) parts.push(path.call(print, "dimensionsNode"));
1270
+ return parts;
1439
1271
  },
1440
- type_pattern(path, print) {
1441
- return join$4(" ", path.map(print, "children"));
1272
+ catch_type(path, print) {
1273
+ return join$6([line$5, "| "], path.map(print, "namedChildren"));
1442
1274
  },
1443
- record_pattern(path, print) {
1444
- return path.map(print, "children");
1275
+ finally_clause(path, print, options) {
1276
+ return [
1277
+ "finally",
1278
+ printBlockSeparator(options),
1279
+ path.call(print, "namedChildren", 0)
1280
+ ];
1445
1281
  },
1446
- record_pattern_body(path, print, options) {
1447
- return group$4(indentInParentheses(join$4([",", line$4], path.map(print, "namedChildren")), options));
1282
+ try_with_resources_statement(path, print, options) {
1283
+ return [
1284
+ "try ",
1285
+ path.call(print, "resourcesNode"),
1286
+ printBlockSeparator(options),
1287
+ path.call(print, "bodyNode"),
1288
+ ...printCatchAndFinallyClauses(path, print, options)
1289
+ ];
1448
1290
  },
1449
- record_pattern_component(path, print) {
1450
- return join$4(" ", path.map(print, "children"));
1291
+ resource_specification(path, print, options) {
1292
+ const resources = [];
1293
+ let hasTrailingSemicolon = false;
1294
+ path.each((child) => {
1295
+ if (child.node.type === "resource") {
1296
+ resources.push(print(child));
1297
+ hasTrailingSemicolon = false;
1298
+ } else if (child.node.type === ";") hasTrailingSemicolon = true;
1299
+ }, "children");
1300
+ const parts = join$6([";", line$5], resources);
1301
+ if (hasTrailingSemicolon) parts.push(ifBreak$1(";"));
1302
+ return group$6(indentInParentheses(parts, options));
1451
1303
  },
1452
- guard(path, print) {
1453
- return ["when ", group$4([
1454
- ifBreak("("),
1455
- indent$4([softline$1, path.call(print, "namedChildren", 0)]),
1456
- softline$1,
1457
- ifBreak(")")
1458
- ])];
1459
- }
1460
- };
1461
- function printLambdaExpressionSignature(path, options, print, args) {
1462
- const parts = [];
1463
- const parameters = path.call(print, "parametersNode");
1464
- if (shouldPrintParamsWithoutParens(path, options)) parts.push(parameters);
1465
- else {
1466
- if (args != null && typeof args === "object" && ("expandLastArg" in args && args.expandLastArg === true || "expandFirstArg" in args && args.expandFirstArg === true)) {
1467
- if (willBreak(parameters)) throw new ArgExpansionBailout();
1468
- parts.push(group$4(removeLines(parameters)));
1469
- } else parts.push(parameters);
1470
- if (path.node.parametersNode.type === "identifier") return path.node.parametersNode.comments ? group$4([
1471
- "(",
1472
- indent$4([softline$1, ...parts]),
1473
- lineSuffixBoundary,
1474
- ")"
1475
- ]) : [
1476
- "(",
1477
- ...parts,
1478
- ")"
1304
+ resource(path, print) {
1305
+ if (hasChild(path, "typeNode") && hasChild(path, "nameNode") && hasChild(path, "valueNode")) {
1306
+ const parts = printModifiers(path, print, "noBreak");
1307
+ parts.push(path.call(print, "typeNode"), " ", path.call(print, "nameNode"));
1308
+ if (hasChild(path, "dimensionsNode")) parts.push(path.call(print, "dimensionsNode"));
1309
+ parts.push(" =");
1310
+ const value = path.call(print, "valueNode");
1311
+ if (path.node.valueNode.type === "binary_expression" || hasLeadingComments(path.node.valueNode)) parts.push(group$6(indent$6([line$5, value])));
1312
+ else {
1313
+ const groupId = Symbol("assignment");
1314
+ parts.push(group$6(indent$6(line$5), { id: groupId }), indentIfBreak$1(value, { groupId }));
1315
+ }
1316
+ return parts;
1317
+ }
1318
+ const resourceIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier" || type === "field_access");
1319
+ return path.call(print, "namedChildren", resourceIndex);
1320
+ },
1321
+ yield_statement(path, print) {
1322
+ return [
1323
+ "yield ",
1324
+ path.call(print, "namedChildren", 0),
1325
+ ";"
1479
1326
  ];
1480
1327
  }
1481
- const dangling = printDanglingComments(path);
1482
- if (dangling) parts.push(" ", dangling);
1483
- return parts;
1484
- }
1485
- function mayBreakAfterShortPrefix(functionBody) {
1486
- return functionBody.type === "array_creation_expression" || functionBody.type === "lambda_expression" || functionBody.type === "block";
1328
+ };
1329
+ function printExpressionList(expressions) {
1330
+ return group$6(expressions.map((expression, index) => index === 0 ? expression : [",", indent$6([line$5, expression])]));
1487
1331
  }
1488
- function printArrowFunctionSignatures(path, { signatureDocs }) {
1489
- if (signatureDocs.length === 1) return signatureDocs[0];
1490
- const { node, parent } = path;
1491
- if (node.fieldName !== "object" && parent?.type === "method_invocation" || parent?.type === "binary_expression") return group$4([
1492
- signatureDocs[0],
1493
- " ->",
1494
- indent$4([line$4, join$4([" ->", line$4], signatureDocs.slice(1))])
1332
+ function printReturnOrThrowArgument(path, print, options) {
1333
+ const { node } = path;
1334
+ const argumentDoc = print(path);
1335
+ if (returnArgumentHasLeadingComment(node)) return [
1336
+ "(",
1337
+ indent$6([hardline$5, argumentDoc]),
1338
+ closingBracketLine(options, hardline$5),
1339
+ ")"
1340
+ ];
1341
+ if (node.type === "binary_expression") return group$6([
1342
+ ifBreak$1("("),
1343
+ indent$6([softline$2, argumentDoc]),
1344
+ closingBracketLine(options),
1345
+ ifBreak$1(")")
1495
1346
  ]);
1496
- if (node.fieldName === "object" && parent?.type === "method_invocation") return group$4(join$4([" ->", line$4], signatureDocs));
1497
- return group$4(indent$4(join$4([" ->", line$4], signatureDocs)));
1498
- }
1499
- function printArrowFunctionBody(path, args, options, { bodyDoc, bodyComments, shouldPutBodyOnSameLine }) {
1500
- const trailingSpace = args && typeof args === "object" && "expandLastArg" in args && args.expandLastArg && !path.node.comments ? closingBracketLine(options) : "";
1501
- return shouldPutBodyOnSameLine ? [
1502
- " ",
1503
- bodyDoc,
1504
- bodyComments
1505
- ] : [indent$4([
1506
- line$4,
1507
- bodyDoc,
1508
- bodyComments
1509
- ]), trailingSpace];
1510
- }
1511
- function shouldPrintParamsWithoutParens(path, options) {
1512
- if (options.arrowParens === "always") return false;
1513
- if (options.arrowParens === "avoid") {
1514
- const { node } = path;
1515
- return canPrintParamsWithoutParens(node);
1516
- }
1517
- return false;
1518
- }
1519
- function canPrintParamsWithoutParens(node) {
1520
- return node.parametersNode.type === "identifier" && !hasDanglingComments(node) && !node.parametersNode.comments;
1347
+ return argumentDoc;
1521
1348
  }
1522
- function printMemberChain(path, print, options) {
1523
- const isExpressionStatement = path.parent?.type === "expression_statement";
1524
- const printedNodes = [];
1525
- function shouldInsertEmptyLineAfter(node) {
1526
- const { originalText } = options;
1527
- const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex(originalText, node.end.index);
1528
- if ((nextCharIndex ? originalText.charAt(nextCharIndex) : "") === ")") return nextCharIndex !== false && isNextLineEmpty(originalText, nextCharIndex + 1);
1529
- return isNextLineEmpty(originalText, node.end.index);
1530
- }
1531
- function rec(path) {
1532
- const { node } = path;
1533
- if (hasType(path, "method_invocation") && hasChild(path, "objectNode")) {
1534
- const hasTrailingEmptyLine = shouldInsertEmptyLineAfter(node);
1535
- printedNodes.unshift({
1536
- node,
1537
- hasTrailingEmptyLine,
1538
- printed: [printComments(path, printMethodInvocation(path, print)), hasTrailingEmptyLine ? hardline$4 : ""]
1539
- });
1540
- path.call(rec, "objectNode");
1541
- } else if (hasType(path, "array_access")) {
1542
- printedNodes.unshift({
1543
- node,
1544
- printed: printComments(path, printArrayAccess(path, print))
1545
- });
1546
- path.call(rec, "arrayNode");
1547
- } else if (hasType(path, "field_access")) {
1548
- printedNodes.unshift({
1549
- node,
1550
- printed: printComments(path, printFieldAccess(path, print))
1551
- });
1552
- path.call(rec, "objectNode");
1553
- } else printedNodes.unshift({
1554
- node,
1555
- printed: print(path)
1556
- });
1557
- }
1349
+ function printReturnOrThrowStatement(path, print, options) {
1558
1350
  const { node } = path;
1559
- if (hasType(path, "method_invocation")) {
1560
- printedNodes.unshift({
1561
- node,
1562
- printed: printComments(path, printMethodInvocation(path, print))
1563
- });
1564
- if (hasChild(path, "objectNode")) path.call(rec, "objectNode");
1565
- } else if (hasType(path, "array_access")) {
1566
- printedNodes.unshift({
1567
- node,
1568
- printed: printComments(path, printArrayAccess(path, print))
1569
- });
1570
- if (hasChild(path, "arrayNode")) path.call(rec, "arrayNode");
1571
- } else if (hasType(path, "field_access")) {
1572
- printedNodes.unshift({
1573
- node,
1574
- printed: printComments(path, printFieldAccess(path, print))
1575
- });
1576
- if (hasChild(path, "objectNode")) path.call(rec, "objectNode");
1577
- }
1578
- const danglingComments = printDanglingComments(path);
1579
- if (danglingComments) printedNodes[0].printed = [
1580
- danglingComments,
1581
- hardline$4,
1582
- printedNodes[0].printed
1583
- ];
1584
- const groups = [];
1585
- let currentGroup = [printedNodes[0]];
1586
- let i = 1;
1587
- for (; i < printedNodes.length; ++i) if (printedNodes[i].node.type === "array_access") currentGroup.push(printedNodes[i]);
1588
- else break;
1589
- if (printedNodes[0].node.type !== "method_invocation") for (; i + 1 < printedNodes.length; ++i) if (printedNodes[i].node.type !== "method_invocation") currentGroup.push(printedNodes[i]);
1590
- else break;
1591
- groups.push(currentGroup);
1592
- currentGroup = [];
1593
- let hasSeenMethodInvocation = false;
1594
- for (; i < printedNodes.length; ++i) {
1595
- if (hasSeenMethodInvocation) {
1596
- if (printedNodes[i].node.type === "array_access") {
1597
- currentGroup.push(printedNodes[i]);
1598
- continue;
1599
- }
1600
- groups.push(currentGroup);
1601
- currentGroup = [];
1602
- hasSeenMethodInvocation = false;
1603
- }
1604
- if (printedNodes[i].node.type === "method_invocation") hasSeenMethodInvocation = true;
1605
- currentGroup.push(printedNodes[i]);
1606
- if (printedNodes[i].node.comments?.some(({ trailing }) => trailing)) {
1607
- groups.push(currentGroup);
1608
- currentGroup = [];
1609
- hasSeenMethodInvocation = false;
1610
- }
1611
- }
1612
- if (currentGroup.length > 0) groups.push(currentGroup);
1613
- function isFactory(name) {
1614
- return /^[A-Z]|^[$_]+$/.test(name);
1615
- }
1616
- function isShort(name) {
1617
- return name.length <= options.tabWidth;
1618
- }
1619
- function shouldNotWrap(groups) {
1620
- const hasArrayAccess = groups[1][0]?.node.type === "array_access";
1621
- if (groups[0].length === 1) {
1622
- const firstNode = groups[0][0].node;
1623
- return firstNode.type === "this" || firstNode.type === "identifier" && (isFactory(firstNode.value) || isExpressionStatement && isShort(firstNode.value) || hasArrayAccess);
1624
- }
1625
- const lastNode = groups[0].at(-1).node;
1626
- return lastNode.type === "field_access" && lastNode.fieldNode.type === "identifier" && (isFactory(lastNode.fieldNode.value) || hasArrayAccess);
1627
- }
1628
- const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments?.length && shouldNotWrap(groups);
1629
- function printGroup(printedGroup) {
1630
- return printedGroup.map((tuple) => tuple.printed);
1631
- }
1632
- function printIndentedGroup(groups) {
1633
- if (groups.length === 0) return "";
1634
- return indent$4([hardline$4, join$4(hardline$4, groups.map(printGroup))]);
1635
- }
1636
- const printedGroups = groups.map(printGroup);
1637
- const oneLine = printedGroups;
1638
- const cutoff = shouldMerge ? 3 : 2;
1639
- const flatGroups = groups.flat();
1640
- const nodeHasComment = flatGroups.some((node) => node.node.comments?.some(({ leading }) => leading)) || flatGroups.slice(0, -1).some((node) => node.node.comments?.some(({ trailing }) => trailing));
1641
- if (groups.length <= cutoff && !nodeHasComment && !groups.some((g) => g.at(-1).hasTrailingEmptyLine)) return group$4(oneLine);
1642
- const lastNodeBeforeIndent = groups[shouldMerge ? 1 : 0].at(-1).node;
1643
- const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "method_invocation" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
1644
- const expanded = [
1645
- printGroup(groups[0]),
1646
- shouldMerge ? groups.slice(1, 2).map(printGroup) : "",
1647
- shouldHaveEmptyLineBeforeIndent ? hardline$4 : "",
1648
- printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))
1351
+ return [
1352
+ node.type === "throw_statement" ? "throw" : "return",
1353
+ node.namedChildren.length ? [" ", path.call(() => printReturnOrThrowArgument(path, print, options), "namedChildren", 0)] : "",
1354
+ ";"
1649
1355
  ];
1650
- const methodInvocations = printedNodes.map(({ node }) => node).filter((node) => node.type === "method_invocation");
1651
- function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
1652
- const lastGroupNode = groups.at(-1).at(-1).node;
1653
- const lastGroupDoc = printedGroups.at(-1);
1654
- return lastGroupNode.type === "method_invocation" && willBreak(lastGroupDoc) && methodInvocations.slice(0, -1).some((node) => node.argumentsNode.namedChildren.some(({ type }) => type === "lambda_expression"));
1655
- }
1656
- let result;
1657
- if (nodeHasComment || methodInvocations.length > 2 && methodInvocations.some((inv) => !inv.argumentsNode.namedChildren.every((arg) => isSimpleCallArgument(arg))) || printedGroups.slice(0, -1).some(willBreak) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) result = group$4(expanded);
1658
- else result = [willBreak(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$1 : "", conditionalGroup([oneLine, expanded])];
1659
- return result;
1660
- }
1661
- function printMethodInvocation(path, print) {
1662
- const parts = [];
1663
- if (hasChild(path, "objectNode")) parts.push(".");
1664
- if (path.node.children.filter(({ type }) => type === ".").length === 2) parts.push("super", ".");
1665
- if (hasChild(path, "type_argumentsNode")) parts.push(path.call(print, "type_argumentsNode"));
1666
- parts.push(path.call(print, "nameNode"), path.call(print, "argumentsNode"));
1667
- return parts;
1668
1356
  }
1669
- function printArrayAccess(path, print) {
1670
- const index = path.call(print, "indexNode");
1671
- return path.node.indexNode.type === "decimal_integer_literal" ? [
1672
- "[",
1673
- index,
1674
- "]"
1675
- ] : group$4([
1676
- "[",
1677
- indent$4([softline$1, index]),
1678
- softline$1,
1679
- "]"
1680
- ]);
1357
+ function printStatementSeparator(statementType, options) {
1358
+ return statementType === "block" ? printBlockSeparator(options) : " ";
1681
1359
  }
1682
- function printFieldAccess(path, print) {
1683
- const parts = ["."];
1684
- if (path.node.children.filter(({ type }) => type === ".").length === 2) parts.push("super.");
1685
- parts.push(path.call(print, "fieldNode"));
1686
- return parts;
1360
+ function printCatchAndFinallyClauses(path, print, options) {
1361
+ const clauses = [];
1362
+ path.each((child) => {
1363
+ if (child.node.type === "catch_clause" || child.node.type === "finally_clause") clauses.push(printBlockSeparator(options), print(child));
1364
+ }, "namedChildren");
1365
+ return clauses;
1687
1366
  }
1688
- /**
1689
- * For binary expressions to be consistent, we need to group
1690
- * subsequent operators with the same precedence level under a single
1691
- * group. Otherwise they will be nested such that some of them break
1692
- * onto new lines but not all. Operators with the same precedence
1693
- * level should either all break or not. Because we group them by
1694
- * precedence level and the AST is structured based on precedence
1695
- * level, things are naturally broken up correctly, i.e. `&&` is
1696
- * broken before `+`.
1697
- */
1698
- function printBinaryExpressions(path, print, options, isInsideParentheses) {
1699
- if (!hasType(path, "binary_expression")) return [group$4(print(path))];
1700
- const { node } = path;
1701
- let parts = [];
1702
- if (node.leftNode.type === "binary_expression" && shouldFlatten(node.operatorNode.type, node.leftNode.operatorNode.type)) parts = path.call(() => printBinaryExpressions(path, print, options, isInsideParentheses), "leftNode");
1703
- else parts.push(group$4(path.call(print, "leftNode")));
1704
- const operator = node.operatorNode.type;
1705
- const operatorDoc = path.call(print, "operatorNode");
1706
- const rightContent = path.call(print, "rightNode");
1707
- let right = options.experimentalOperatorPosition === "start" ? [
1708
- line$4,
1709
- operatorDoc,
1710
- " ",
1711
- rightContent
1712
- ] : [
1713
- " ",
1714
- operatorDoc,
1715
- line$4,
1716
- rightContent
1717
- ];
1718
- const { parent } = path;
1719
- const shouldBreak = node.leftNode.comments?.some(({ trailing, type }) => trailing && type === "line_comment") ?? false;
1720
- if (shouldBreak || !(isInsideParentheses && logicalOperators.has(operator)) && (parent?.type !== node.type || logicalOperators.has(parent.operatorNode.value) !== logicalOperators.has(operator)) && node.leftNode.type !== node.type && node.rightNode.type !== node.type) right = group$4(right, { shouldBreak });
1721
- parts.push(right);
1722
- return parts;
1723
- }
1724
- const logicalOperators = /* @__PURE__ */ new Set(["||", "&&"]);
1725
- function isSimpleCallArgument(node, depth = 2) {
1726
- if (depth <= 0) return false;
1727
- const isChildSimple = (child) => isSimpleCallArgument(child, depth - 1);
1728
- if (isLiteral(node) || isSingleWordType(node) || node.type === "class_literal") return true;
1729
- if (node.type === "object_creation_expression" || node.type === "method_invocation") {
1730
- if (node.type === "object_creation_expression" || !node.objectNode || isSimpleCallArgument(node.objectNode, depth)) {
1731
- const args = node.argumentsNode.namedChildren;
1732
- return args.length <= depth && args.every(isChildSimple);
1733
- }
1734
- return false;
1735
- }
1736
- if (node.type === "array_access") return isSimpleCallArgument(node.arrayNode, depth) && isSimpleCallArgument(node.indexNode, depth);
1737
- if (node.type === "field_access") return isSimpleCallArgument(node.objectNode, depth) && isSimpleCallArgument(node.fieldNode, depth);
1738
- if (node.type === "unary_expression") return isSimpleCallArgument(node.operandNode, depth);
1739
- if (node.type === "method_reference" || node.type === "update_expression") return isSimpleCallArgument(node.namedChildren[0], depth);
1740
- return false;
1741
- }
1742
- function isLiteral(node) {
1743
- return [
1744
- "true",
1745
- "false",
1746
- "null_literal",
1747
- "binary_integer_literal",
1748
- "decimal_floating_point_literal",
1749
- "decimal_integer_literal",
1750
- "hex_floating_point_literal",
1751
- "hex_integer_literal",
1752
- "octal_integer_literal",
1753
- "character_literal"
1754
- ].includes(node.type) || isStringLiteral(node);
1755
- }
1756
- function isSingleWordType(node) {
1757
- return [
1758
- "identifier",
1759
- "this",
1760
- "super"
1761
- ].includes(node.type);
1762
- }
1763
- function couldExpandArg(arg, lambdaChainRecursion = false) {
1764
- if (arg.type === "array_creation_expression" && arg.valueNode && (arg.valueNode.namedChildren.length > 0 || arg.valueNode.comments)) return true;
1765
- if (arg.type === "lambda_expression") {
1766
- const { bodyNode: body } = arg;
1767
- if (body.type === "block" || body.type === "array_creation_expression") return true;
1768
- if (body.type === "lambda_expression" && couldExpandArg(body, true)) return true;
1769
- if (!lambdaChainRecursion) {
1770
- if (body.type === "ternary_expression") return true;
1771
- if (body.type === "method_invocation" || body.type === "object_creation_expression") return true;
1772
- }
1773
- }
1774
- return false;
1775
- }
1776
- function shouldExpandLastArg(args) {
1777
- const lastArg = args.at(-1);
1778
- const penultimateArg = args.at(-2);
1779
- return !lastArg.comments?.some(({ leading }) => leading) && !lastArg.comments?.some(({ trailing }) => trailing) && couldExpandArg(lastArg) && (!penultimateArg || penultimateArg.type !== lastArg.type) && (args.length !== 2 || penultimateArg.type !== "lambda_expression");
1780
- }
1781
- function shouldExpandFirstArg(args) {
1782
- if (args.length !== 2) return false;
1783
- const [firstArg, secondArg] = args;
1784
- return !firstArg.comments && firstArg.type === "lambda_expression" && firstArg.bodyNode.type === "block" && secondArg.type !== "lambda_expression" && secondArg.type !== "ternary_expression" && isHopefullyShortCallArgument(secondArg) && !couldExpandArg(secondArg);
1785
- }
1786
- function isHopefullyShortCallArgument(node) {
1787
- if ((node.type === "method_invocation" || node.type === "object_creation_expression") && node.argumentsNode.namedChildren.length > 1) return false;
1788
- if (node.type === "binary_expression") return isSimpleCallArgument(node.leftNode, 1) && isSimpleCallArgument(node.rightNode, 1);
1789
- return isSimpleCallArgument(node);
1790
- }
1791
- function printTernaryTest(path, print) {
1792
- const { node, parent } = path;
1793
- const printed = path.call(print, "conditionNode");
1794
- /**
1795
- * a
1796
- * ? b
1797
- * : multiline
1798
- * test
1799
- * node
1800
- * ^^ align(2)
1801
- * ? d
1802
- * : e
1803
- */
1804
- if (parent?.type === node.type && parent.alternativeNode === node) return align(2, printed);
1805
- return printed;
1806
- }
1807
- function getExpressionChild(node) {
1808
- switch (node.type) {
1809
- case "assignment_expression": return node.rightNode;
1810
- case "variable_declarator": return node.valueNode;
1811
- case "unary_expression": return node.operandNode;
1812
- case "return_statement":
1813
- case "throw_statement":
1814
- case "yield_statement": return node.namedChildren[0];
1815
- default: return null;
1816
- }
1817
- }
1818
- function shouldExtraIndentForTernaryExpression(path) {
1819
- const { node } = path;
1820
- let parent;
1821
- let child = node;
1822
- for (let ancestorCount = 0; !parent; ancestorCount++) {
1823
- const node = path.getParentNode(ancestorCount);
1824
- if (node.type === "array_access" && node.arrayNode === child || (node.type === "explicit_constructor_invocation" || node.type === "field_access" || node.type === "method_invocation") && node.objectNode === child || node.type === "method_reference" || node.type === "object_creation_expression") {
1825
- child = node;
1826
- continue;
1827
- }
1828
- if (node.type === "cast_expression" && node.valueNode === child) {
1829
- parent = path.getParentNode(ancestorCount + 1);
1830
- child = node;
1831
- } else parent = node;
1832
- }
1833
- if (child === node) return false;
1834
- return getExpressionChild(parent) === child;
1835
- }
1836
- function isStringLiteral(node) {
1837
- return node.type === "string_literal" && node.children[0].value === "\"";
1838
- }
1839
- var ArgExpansionBailout = class extends Error {
1840
- constructor(..._args) {
1841
- super(..._args);
1842
- this.name = "ArgExpansionBailout";
1843
- }
1844
- };
1845
- //#endregion
1846
- //#region src/printers/interfaces.ts
1847
- const { group: group$3, hardline: hardline$3, indent: indent$3, join: join$3, line: line$3 } = prettier_doc.builders;
1848
- var interfaces_default = {
1849
- interface_declaration(path, print, options) {
1850
- const parts = ["interface ", path.call(print, "nameNode")];
1851
- const extendsInterfacesIndex = path.node.namedChildren.findIndex(({ type }) => type === "extends_interfaces");
1852
- const hasExtendsInterfaces = extendsInterfacesIndex !== -1;
1853
- const hasPermits = hasChild(path, "permitsNode");
1854
- const hasMultipleClauses = hasExtendsInterfaces && hasPermits;
1367
+ // src/printers/classes.ts
1368
+ const { group: group$5, hardline: hardline$4, indent: indent$5, join: join$5, line: line$4 } = prettier_doc.builders;
1369
+ var classes_default = {
1370
+ class_declaration(path, print, options) {
1371
+ const parts = ["class ", path.call(print, "nameNode")];
1372
+ const definedClauses = definedKeys(path.node, [
1373
+ "superclassNode",
1374
+ "interfacesNode",
1375
+ "permitsNode"
1376
+ ]);
1377
+ const hasMultipleClauses = definedClauses.length > 1;
1855
1378
  if (hasChild(path, "type_parametersNode")) {
1856
1379
  const typeParameters = path.call(print, "type_parametersNode");
1857
- parts.push(hasMultipleClauses ? group$3(indent$3(typeParameters)) : options?.braceStyle === "next-line" ? group$3(typeParameters) : typeParameters);
1380
+ parts.push(hasMultipleClauses ? group$5(indent$5(typeParameters)) : group$5(typeParameters));
1381
+ }
1382
+ const separators = printDeclarationBodySeparators(definedClauses.length > 0, path.node.bodyNode.namedChildren.length > 0, options);
1383
+ if (definedClauses.length) {
1384
+ const clauses = definedClauses.flatMap((clause) => {
1385
+ if (!hasChild(path, clause)) return [];
1386
+ return [clause === "superclassNode" || clause === "interfacesNode" ? hardline$4 : line$4, path.call(print, clause)];
1387
+ });
1388
+ const clauseGroup = [indent$5(clauses), separators.afterClauses];
1389
+ parts.push(hasMultipleClauses ? clauseGroup : group$5(clauseGroup));
1858
1390
  }
1859
- if (hasExtendsInterfaces || hasPermits) {
1860
- const clauses = [];
1861
- if (hasExtendsInterfaces) clauses.push(hardline$3, path.call(print, "namedChildren", extendsInterfacesIndex));
1862
- if (hasPermits) clauses.push(line$3, path.call(print, "permitsNode"));
1863
- const hasBody = path.node.bodyNode.namedChildren.length > 0;
1864
- const clauseGroup = [indent$3(clauses), options?.braceStyle === "next-line" ? "" : hasBody ? line$3 : " "];
1865
- parts.push(hasMultipleClauses ? clauseGroup : group$3(clauseGroup));
1866
- } else parts.push(" ");
1867
1391
  return [
1868
1392
  ...printModifiers(path, print, "declarationOnly"),
1869
- group$3(parts),
1393
+ group$5(parts),
1394
+ separators.afterHeader,
1870
1395
  path.call(print, "bodyNode")
1871
1396
  ];
1872
1397
  },
1873
- extends_interfaces(path, print) {
1874
- const typeListIndex = path.node.namedChildren.findIndex(({ type }) => type === "type_list");
1875
- return group$3(["extends", indent$3([line$3, path.call(print, "namedChildren", typeListIndex)])]);
1398
+ type_parameters: printTypeParameters,
1399
+ superclass(path, print) {
1400
+ return ["extends ", path.call(print, "namedChildren", 0)];
1876
1401
  },
1877
- interface_body(path, print, options) {
1878
- return printBlock(path, printBodyDeclarations(path, print), options);
1402
+ super_interfaces(path, print) {
1403
+ return group$5(["implements", indent$5([line$4, path.call(print, "namedChildren", 0)])]);
1879
1404
  },
1880
- constant_declaration: printVariableDeclaration,
1881
- annotation_type_declaration(path, print) {
1882
- const parts = printModifiers(path, print);
1883
- parts.push("@interface ", path.call(print, "nameNode"), " ", path.call(print, "bodyNode"));
1884
- return parts;
1405
+ permits(path, print) {
1406
+ return group$5(["permits", indent$5([line$4, path.call(print, "namedChildren", 0)])]);
1885
1407
  },
1886
- annotation_type_body(path, print, options) {
1887
- return printBlock(path, printBodyDeclarations(path, print), options);
1408
+ type_list(path, print) {
1409
+ return join$5([",", line$4], path.map(print, "namedChildren"));
1888
1410
  },
1889
- annotation_type_element_declaration(path, print) {
1890
- const parts = printModifiers(path, print);
1891
- parts.push(path.call(print, "typeNode"), " ", path.call(print, "nameNode"), "()");
1892
- if (hasChild(path, "dimensionsNode")) parts.push(path.call(print, "dimensionsNode"));
1893
- if (hasChild(path, "valueNode")) parts.push(" default ", path.call(print, "valueNode"));
1894
- parts.push(";");
1895
- return parts;
1411
+ class_body(path, print, options) {
1412
+ return printBlock(path, printBodyDeclarations(path, print, path.parent?.type === "class_declaration" && options?.braceStyle !== "next-line"), options);
1896
1413
  },
1897
- annotation(path, print) {
1898
- return [
1899
- "@",
1900
- path.call(print, "nameNode"),
1901
- path.call(print, "argumentsNode")
1414
+ field_declaration: printVariableDeclaration,
1415
+ variable_declarator(path, print) {
1416
+ const leftDoc = [path.call(print, "nameNode")];
1417
+ if (hasChild(path, "dimensionsNode")) leftDoc.push(path.call(print, "dimensionsNode"));
1418
+ return printAssignment(leftDoc, " =", hasChild(path, "valueNode") ? path.call(print, "valueNode") : void 0, path.node.valueNode);
1419
+ },
1420
+ method_declaration(path, print, options) {
1421
+ const modifiers = printModifiers(path, print);
1422
+ const declaration = [];
1423
+ if (hasChild(path, "type_parametersNode")) declaration.push(group$5(path.call(print, "type_parametersNode")), " ");
1424
+ path.each((child) => {
1425
+ if (child.node.type === "annotation" || child.node.type === "marker_annotation") declaration.push(print(child), " ");
1426
+ }, "children");
1427
+ declaration.push(path.call(print, "typeNode"));
1428
+ if (hasChild(path, "dimensionsNode")) declaration.push(path.call(print, "dimensionsNode"));
1429
+ declaration.push(" ", path.call(print, "nameNode"), group$5(path.call(print, "parametersNode")));
1430
+ const throwsIndex = path.node.namedChildren.findIndex(({ type }) => type === "throws");
1431
+ if (throwsIndex !== -1) declaration.push(group$5(indent$5([hardline$4, path.call(print, "namedChildren", throwsIndex)])));
1432
+ return hasChild(path, "bodyNode") ? [
1433
+ modifiers,
1434
+ group$5(declaration),
1435
+ printBlockSeparator(options),
1436
+ path.call(print, "bodyNode")
1437
+ ] : [
1438
+ modifiers,
1439
+ group$5(declaration),
1440
+ ";"
1902
1441
  ];
1903
1442
  },
1904
- marker_annotation(path, print) {
1905
- return ["@", path.call(print, "nameNode")];
1443
+ receiver_parameter(path, print) {
1444
+ return path.map((child) => child.isLast ? print(child) : [print(child), child.node.type === "identifier" ? "." : " "], "namedChildren");
1906
1445
  },
1907
- annotation_argument_list(path, print, options) {
1908
- const args = path.map(print, "namedChildren");
1909
- return args.length === 1 && path.node.namedChildren[0].type === "element_value_array_initializer" ? [
1446
+ formal_parameters(path, print, options) {
1447
+ const parameters = path.parent?.type === "record_declaration" ? printBodyDeclarations(path, print) : path.map(print, "namedChildren");
1448
+ if (parameters.length === 0) return [
1910
1449
  "(",
1911
- args[0],
1450
+ printDanglingCommentsInList(path),
1912
1451
  ")"
1913
- ] : group$3(indentInParentheses(join$3([",", line$3], args), options));
1452
+ ];
1453
+ return indentInParentheses(join$5([",", line$4], parameters), options);
1914
1454
  },
1915
- element_value_pair(path, print) {
1916
- return group$3([
1917
- path.call(print, "keyNode"),
1918
- " = ",
1919
- path.call(print, "valueNode")
1920
- ]);
1455
+ formal_parameter(path, print) {
1456
+ const parameter = printModifiers(path, print, path.grandparent?.type === "record_declaration" ? "avoidBreak" : "noBreak");
1457
+ parameter.push(path.call(print, "typeNode"));
1458
+ if (hasChild(path, "dimensionsNode")) parameter.push(path.call(print, "dimensionsNode"));
1459
+ parameter.push(" ", path.call(print, "nameNode"));
1460
+ return group$5(parameter);
1921
1461
  },
1922
- element_value_array_initializer: printArrayInitializer
1923
- };
1924
- //#endregion
1925
- //#region src/printers/lexical-structure.ts
1926
- const { group: group$2, hardline: hardline$2, indent: indent$2, join: join$2, softline } = prettier_doc.builders;
1927
- var lexical_structure_default = {
1928
- string_literal(path, print) {
1929
- if (path.node.namedChildren.some(({ type }) => type === "string_interpolation") || path.node.children[0].value === "\"") return path.map(print, "children");
1930
- return printTextBlock(join$2(hardline$2, textBlockContents(path.node).split("\n")));
1462
+ spread_parameter(path, print) {
1463
+ const parts = printModifiers(path, print, "noBreak");
1464
+ parts.push(path.call(print, "typeNode"));
1465
+ if (hasChild(path, "annotationsNodes")) parts.push(...path.map((annotation) => [" ", print(annotation)], "annotationsNodes"));
1466
+ parts.push("... ", path.call(print, "namedChildren", path.node.namedChildren.length - 1));
1467
+ return parts;
1931
1468
  },
1932
- string_fragment: printValue,
1933
- multiline_string_fragment: printValue,
1934
- string_interpolation(path, print) {
1935
- const expressionType = path.node.namedChildren[0].type;
1936
- const expression = path.call(print, "namedChildren", 0);
1937
- return expressionType === "binary_expression" || expressionType === "ternary_expression" ? group$2([
1938
- "\\{",
1939
- indent$2([softline, expression]),
1940
- softline,
1941
- "}"
1942
- ]) : [
1943
- "\\{",
1944
- expression,
1945
- "}"
1469
+ throws(path, print) {
1470
+ const exceptions = path.map(print, "namedChildren");
1471
+ return exceptions.length === 1 ? ["throws ", exceptions[0]] : ["throws", group$5(indent$5([line$4, ...join$5([",", line$4], exceptions)]))];
1472
+ },
1473
+ static_initializer(path, print, options) {
1474
+ return [
1475
+ "static",
1476
+ printBlockSeparator(options),
1477
+ path.call(print, "namedChildren", 0)
1946
1478
  ];
1947
1479
  },
1948
- escape_sequence: printValue,
1949
- character_literal: printValue,
1950
- binary_integer_literal: printValue,
1951
- decimal_integer_literal: printValue,
1952
- hex_integer_literal: printValue,
1953
- octal_integer_literal: printValue,
1954
- decimal_floating_point_literal: printValue,
1955
- hex_floating_point_literal: printValue,
1956
- null_literal: printValue,
1957
- true: printValue,
1958
- false: printValue,
1959
- this: printValue,
1960
- super: printValue,
1961
- underscore_pattern: printValue,
1962
- asterisk: printValue
1963
- };
1964
- //#endregion
1965
- //#region src/printers/names.ts
1966
- var names_default = {
1967
- identifier: printValue,
1968
- type_identifier: printValue,
1969
- scoped_identifier(path, print) {
1480
+ constructor_declaration(path, print, options) {
1481
+ const modifiers = printModifiers(path, print, "declarationOnly");
1482
+ const declaration = [];
1483
+ if (hasChild(path, "type_parametersNode")) declaration.push(group$5(path.call(print, "type_parametersNode")), " ");
1484
+ declaration.push(path.call(print, "nameNode"), group$5(path.call(print, "parametersNode")));
1485
+ const throwsIndex = path.node.namedChildren.findIndex(({ type }) => type === "throws");
1486
+ if (throwsIndex !== -1) declaration.push(group$5(indent$5([hardline$4, path.call(print, "namedChildren", throwsIndex)])));
1970
1487
  return [
1971
- path.call(print, "scopeNode"),
1972
- ".",
1973
- path.call(print, "nameNode")
1488
+ modifiers,
1489
+ group$5(declaration),
1490
+ printBlockSeparator(options),
1491
+ path.call(print, "bodyNode")
1974
1492
  ];
1975
1493
  },
1976
- scoped_type_identifier(path, print) {
1977
- return path.map((child) => child.node.type === "annotation" || child.node.type === "marker_annotation" ? [print(child), " "] : print(child), "children");
1978
- }
1979
- };
1980
- //#endregion
1981
- //#region src/printers/packages-and-modules.ts
1982
- const { group: group$1, hardline: hardline$1, indent: indent$1, join: join$1, line: line$2 } = prettier_doc.builders;
1983
- var packages_and_modules_default = {
1984
- program(path, print, options) {
1985
- if (!path.node.namedChildren.length) return [printDanglingComments(path), hardline$1];
1986
- const parts = [];
1987
- if (path.node.namedChildren[0].type !== "import_declaration") parts.push(path.call(print, "namedChildren", 0));
1988
- const moduleImports = [];
1989
- const imports = [];
1990
- const otherDeclarations = [];
1991
- path.each((child) => {
1992
- const doc = print(child);
1993
- if (child.node.type === "import_declaration") {
1994
- const names = extractNames(child.node.namedChildren[0]);
1995
- if (child.node.namedChildren.some(({ type }) => type === "asterisk")) names.push("*");
1996
- const modifier = child.node.children[1].type;
1997
- (modifier === "module" ? moduleImports : imports).push({
1998
- doc,
1999
- names,
2000
- isStatic: modifier === "static"
2001
- });
2002
- } else if (!child.isFirst) otherDeclarations.push(doc);
2003
- }, "namedChildren");
2004
- parts.push(...[moduleImports.sort(compareFqn), ...groupImports(imports, options.importOrder)].filter((group) => group.length).map((group) => join$1(hardline$1, group.map(({ doc }) => doc))), ...otherDeclarations);
2005
- return [...join$1([hardline$1, hardline$1], parts), hardline$1];
1494
+ constructor_body(path, print, options) {
1495
+ return printBlock(path, printBlockStatements(path, print), options);
2006
1496
  },
2007
- package_declaration(path, print) {
2008
- const annotations = [];
2009
- const identifier = [];
1497
+ explicit_constructor_invocation(path, print) {
1498
+ const invocation = [];
1499
+ if (hasChild(path, "objectNode")) invocation.push(path.call(print, "objectNode"), ".");
1500
+ if (hasChild(path, "type_argumentsNode")) invocation.push(path.call(print, "type_argumentsNode"));
1501
+ invocation.push(path.call(print, "constructorNode"), path.call(print, "argumentsNode"), ";");
1502
+ return invocation;
1503
+ },
1504
+ visibility: printValue,
1505
+ modifier: printValue,
1506
+ modifiers(path, print, _, args) {
1507
+ const parts = [];
1508
+ const modifiers = [];
1509
+ const typeAnnotations = [];
2010
1510
  path.each((child) => {
2011
- switch (child.node.type) {
2012
- case "annotation":
2013
- case "marker_annotation":
2014
- annotations.push(print(child));
2015
- break;
2016
- case "identifier":
2017
- case "scoped_identifier": identifier.push(print(child));
1511
+ if (child.node.type === "annotation" || child.node.type === "marker_annotation") (modifiers.length ? typeAnnotations : parts).push(print(child));
1512
+ else {
1513
+ modifiers.push(child.node.value);
1514
+ parts.push(...typeAnnotations);
1515
+ typeAnnotations.length = 0;
2018
1516
  }
2019
1517
  }, "namedChildren");
2020
- return join$1(hardline$1, [...annotations, [
2021
- "package ",
2022
- ...identifier,
2023
- ";"
2024
- ]]);
1518
+ const annotationMode = args && typeof args === "object" && "annotationMode" in args ? args.annotationMode : null;
1519
+ if (annotationMode === "declarationOnly") {
1520
+ parts.push(...typeAnnotations);
1521
+ typeAnnotations.length = 0;
1522
+ }
1523
+ modifiers.sort((a, b) => (indexByModifier.get(a) ?? -1) - (indexByModifier.get(b) ?? -1));
1524
+ if (modifiers.length || typeAnnotations.length) parts.push(join$5(" ", [...modifiers, ...typeAnnotations]));
1525
+ return join$5(annotationMode === "avoidBreak" ? line$4 : annotationMode === "noBreak" ? " " : hardline$4, parts);
2025
1526
  },
2026
- import_declaration(path, print) {
2027
- const declaration = ["import "];
2028
- const modifier = path.node.children[1].type;
2029
- if (modifier === "module" || modifier === "static") declaration.push(modifier, " ");
2030
- const identifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier" || type === "scoped_identifier");
2031
- declaration.push(path.call(print, "namedChildren", identifierIndex));
2032
- if (path.node.namedChildren.some(({ type }) => type === "asterisk")) declaration.push(".*");
2033
- declaration.push(";");
2034
- return declaration;
1527
+ enum_declaration(path, print, options) {
1528
+ const modifiers = printModifiers(path, print, "declarationOnly");
1529
+ const parts = ["enum ", path.call(print, "nameNode")];
1530
+ const hasInterfaces = hasChild(path, "interfacesNode");
1531
+ const separators = printDeclarationBodySeparators(hasInterfaces, path.node.bodyNode.namedChildren.length > 0, options);
1532
+ if (hasInterfaces) parts.push(indent$5([hardline$4, path.call(print, "interfacesNode")]), separators.afterClauses);
1533
+ return [
1534
+ ...modifiers,
1535
+ group$5(parts),
1536
+ separators.afterHeader,
1537
+ path.call(print, "bodyNode")
1538
+ ];
2035
1539
  },
2036
- module_declaration(path, print) {
2037
- const parts = [];
2038
- path.each((child) => {
2039
- if (child.node.type === "annotation" || child.node.type === "marker_annotation") parts.push(print(child));
2040
- }, "namedChildren");
2041
- if (path.node.children.some(({ type }) => type === "open")) parts.push("open");
2042
- parts.push("module", path.call(print, "nameNode"), path.call(print, "bodyNode"));
2043
- return join$1(" ", parts);
1540
+ enum_body(path, print, options) {
1541
+ const parts = printBodyDeclarations(path, print);
1542
+ const enumBodyDeclarationsIndex = path.node.namedChildren.findIndex(({ type }) => type === "enum_body_declarations");
1543
+ const declarations = [];
1544
+ if (enumBodyDeclarationsIndex !== -1) {
1545
+ const hasDeclarations = path.node.namedChildren[enumBodyDeclarationsIndex].namedChildren.length > 0;
1546
+ const enumBodyDeclarations = parts.pop();
1547
+ if (hasDeclarations) {
1548
+ if (!parts.length) declarations.push(hardline$4);
1549
+ declarations.push(enumBodyDeclarations);
1550
+ }
1551
+ }
1552
+ const contents = [];
1553
+ if (parts.length) {
1554
+ contents.push(join$5([",", hardline$4], parts));
1555
+ if (!declarations.length && options.trailingComma !== "none") contents.push(",");
1556
+ }
1557
+ if (declarations.length) contents.push(";", hardline$4, ...declarations);
1558
+ return printBlock(path, contents.length ? [contents] : [], options);
2044
1559
  },
2045
- module_body(path, print, options) {
2046
- return printBlock(path, path.map((child) => child.previous && child.node.start.row > child.previous.end.row + 1 ? [hardline$1, print(child)] : print(child), "namedChildren"), options);
1560
+ enum_constant(path, print, options) {
1561
+ const initializer = printModifiers(path, print);
1562
+ initializer.push(path.call(print, "nameNode"));
1563
+ if (hasChild(path, "argumentsNode")) initializer.push(path.call(print, "argumentsNode"));
1564
+ if (hasChild(path, "bodyNode")) initializer.push(printBlockSeparator(options), path.call(print, "bodyNode"));
1565
+ return initializer;
2047
1566
  },
2048
- requires_module_directive(path, print) {
2049
- const parts = ["requires"];
2050
- path.each((child) => {
2051
- if (child.node.type === "requires_modifier") parts.push(print(child));
2052
- }, "namedChildren");
2053
- parts.push(path.call(print, "moduleNode"));
2054
- return [...join$1(" ", parts), ";"];
1567
+ enum_body_declarations(path, print) {
1568
+ return join$5(hardline$4, printBodyDeclarations(path, print));
2055
1569
  },
2056
- exports_module_directive: printToModuleNamesDirective,
2057
- opens_module_directive: printToModuleNamesDirective,
2058
- uses_module_directive(path, print) {
1570
+ record_declaration(path, print, options) {
1571
+ const modifiers = printModifiers(path, print, "declarationOnly");
1572
+ const parts = ["record ", path.call(print, "nameNode")];
1573
+ if (hasChild(path, "type_parametersNode")) parts.push(group$5(path.call(print, "type_parametersNode")));
1574
+ parts.push(group$5(path.call(print, "parametersNode")));
1575
+ const hasInterfaces = hasChild(path, "interfacesNode");
1576
+ const separators = printDeclarationBodySeparators(hasInterfaces, path.node.bodyNode.namedChildren.length > 0, options);
1577
+ if (hasInterfaces) {
1578
+ const interfaces = [hardline$4, path.call(print, "interfacesNode")];
1579
+ parts.push(group$5([indent$5(interfaces), separators.afterClauses]));
1580
+ }
2059
1581
  return [
2060
- "uses ",
2061
- path.call(print, "typeNode"),
2062
- ";"
1582
+ ...modifiers,
1583
+ group$5(parts),
1584
+ separators.afterHeader,
1585
+ path.call(print, "bodyNode")
2063
1586
  ];
2064
1587
  },
2065
- provides_module_directive(path, print) {
2066
- const [provided, ...providers] = path.map(print, "namedChildren");
2067
- return [
2068
- "provides ",
2069
- provided,
2070
- group$1(indent$1([line$2, group$1(indent$1([
2071
- "with",
2072
- line$2,
2073
- ...join$1([",", line$2], providers)
2074
- ]))])),
2075
- ";"
1588
+ compact_constructor_declaration(path, print, options) {
1589
+ const parts = printModifiers(path, print, "declarationOnly");
1590
+ parts.push(path.call(print, "nameNode"), printBlockSeparator(options), path.call(print, "bodyNode"));
1591
+ return parts;
1592
+ }
1593
+ };
1594
+ const indexByModifier = [
1595
+ "public",
1596
+ "protected",
1597
+ "private",
1598
+ "abstract",
1599
+ "default",
1600
+ "static",
1601
+ "final",
1602
+ "transient",
1603
+ "volatile",
1604
+ "synchronized",
1605
+ "native",
1606
+ "sealed",
1607
+ "non-sealed",
1608
+ "strictfp"
1609
+ ].reduce((map, name, index) => map.set(name, index), /* @__PURE__ */ new Map());
1610
+ // src/printers/expressions.ts
1611
+ const { align, breakParent, conditionalGroup, dedent, group: group$4, hardline: hardline$3, ifBreak, indent: indent$4, indentIfBreak, join: join$4, line: line$3, lineSuffixBoundary, softline: softline$1 } = prettier_doc.builders;
1612
+ const { getNextNonSpaceNonCommentCharacterIndex, hasNewline, isNextLineEmpty } = prettier.util;
1613
+ const { removeLines, willBreak } = prettier_doc.utils;
1614
+ var expressions_default = {
1615
+ lambda_expression(path, print, options, args) {
1616
+ const signatureDocs = [];
1617
+ let bodyDoc;
1618
+ const bodyComments = [];
1619
+ const shouldPrintAsChain = !(args && typeof args === "object" && "expandLastArg" in args && args.expandLastArg) && path.node.bodyNode.type === "lambda_expression";
1620
+ let functionBody;
1621
+ (function rec() {
1622
+ const { node } = path;
1623
+ const signatureDoc = printLambdaExpressionSignature(path, options, print, args);
1624
+ if (signatureDocs.length === 0) signatureDocs.push(signatureDoc);
1625
+ else {
1626
+ const { leading, trailing } = printCommentsSeparately(path);
1627
+ signatureDocs.push([leading, signatureDoc]);
1628
+ bodyComments.unshift(trailing);
1629
+ }
1630
+ if (!shouldPrintAsChain || node.bodyNode.type !== "lambda_expression") {
1631
+ bodyDoc = path.call((child) => print(child, args), "bodyNode");
1632
+ functionBody = node.bodyNode;
1633
+ } else path.call(rec, "bodyNode");
1634
+ })();
1635
+ const shouldPutBodyOnSameLine = !functionBody.comments?.some((comment) => comment.leading && hasNewline(options.originalText, comment.end.index)) && mayBreakAfterShortPrefix(functionBody);
1636
+ const chainGroupId = Symbol("arrow-chain");
1637
+ const signaturesDoc = printArrowFunctionSignatures(path, { signatureDocs });
1638
+ bodyDoc = printArrowFunctionBody(path, args, options, {
1639
+ bodyDoc,
1640
+ bodyComments,
1641
+ bodySeparator: functionBody.type === "block" ? printBlockSeparator(options) : " ",
1642
+ shouldPutBodyOnSameLine
1643
+ });
1644
+ return group$4([
1645
+ group$4(signaturesDoc, { id: chainGroupId }),
1646
+ " ->",
1647
+ shouldPrintAsChain ? indentIfBreak(bodyDoc, { groupId: chainGroupId }) : group$4(bodyDoc)
1648
+ ]);
1649
+ },
1650
+ inferred_parameters(path, print, options) {
1651
+ const identifiers = [];
1652
+ path.each((child) => {
1653
+ if (child.node.type === "identifier") identifiers.push(print(child));
1654
+ }, "namedChildren");
1655
+ if (!identifiers.length) return "()";
1656
+ const parameters = join$4([",", line$3], identifiers);
1657
+ if (identifiers.length > 1 || willBreak(identifiers)) return group$4(indentInParentheses(parameters, options));
1658
+ return options.arrowParens === "avoid" ? parameters : [
1659
+ "(",
1660
+ ...parameters,
1661
+ ")"
2076
1662
  ];
2077
1663
  },
2078
- requires_modifier: printValue
2079
- };
2080
- function extractNames(node) {
2081
- return node.type === "identifier" ? [node.value] : [...extractNames(node.scopeNode), node.nameNode.value];
2082
- }
2083
- const STATIC_PREFIX = "static ";
2084
- const CATCH_ALL_PREFIX = "";
2085
- function groupImports(imports, importOrder) {
2086
- if (!importOrder) return [imports.filter(({ isStatic }) => isStatic), imports.filter(({ isStatic }) => !isStatic)].filter((group) => group.length).map((group) => group.sort(compareFqn));
2087
- const groups = parseImportOrder(importOrder);
2088
- const prefixes = groups.flat();
2089
- const importsByPrefix = /* @__PURE__ */ new Map();
2090
- for (const entry of imports) {
2091
- const key = importKey(entry);
2092
- const prefix = prefixes.filter((candidate) => key.startsWith(candidate)).reduce((best, candidate) => candidate.length > best.length ? candidate : best);
2093
- importsByPrefix.set(prefix, [...importsByPrefix.get(prefix) ?? [], {
2094
- key,
2095
- entry
2096
- }]);
2097
- }
2098
- return groups.map((group) => group.flatMap((prefix) => (importsByPrefix.get(prefix) ?? []).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0).map(({ entry }) => entry))).filter((group) => group.length);
2099
- }
2100
- /**
2101
- * Parses an import order in Spotless's format: groups separated by `,` are
2102
- * printed with blank lines between them, prefixes joined by `|` share a group,
2103
- * `#` marks a static prefix, and an empty prefix catches everything else.
2104
- * Each import belongs to its longest matching prefix.
2105
- */
2106
- function parseImportOrder(importOrder) {
2107
- const knownPrefixes = /* @__PURE__ */ new Set();
2108
- const groups = importOrder.split(",").map((group) => group.split("|").map((prefix) => prefix.startsWith("#") ? STATIC_PREFIX + prefix.slice(1) : prefix).filter((prefix) => {
2109
- if (knownPrefixes.has(prefix)) return false;
2110
- knownPrefixes.add(prefix);
2111
- return true;
2112
- }));
2113
- if (!knownPrefixes.has(STATIC_PREFIX)) {
2114
- const lastStaticGroupIndex = groups.findLastIndex((group) => group.some((prefix) => prefix.startsWith(STATIC_PREFIX)));
2115
- groups.splice(Math.max(lastStaticGroupIndex, 0), 0, [STATIC_PREFIX]);
2116
- }
2117
- if (!knownPrefixes.has(CATCH_ALL_PREFIX)) groups.push([CATCH_ALL_PREFIX]);
2118
- return groups;
2119
- }
2120
- function importKey({ names, isStatic }) {
2121
- return (isStatic ? STATIC_PREFIX : "") + names.join(".");
2122
- }
2123
- function compareFqn({ names: a }, { names: b }) {
2124
- const minParts = Math.min(a.length, b.length);
2125
- for (let i = 0; i < minParts; i++) {
2126
- const imageA = a[i];
2127
- const imageB = b[i];
2128
- if (imageA < imageB) return -1;
2129
- else if (imageA > imageB) return 1;
2130
- }
2131
- return a.length - b.length;
2132
- }
2133
- function printToModuleNamesDirective(path, print) {
2134
- const directive = [
2135
- path.node.type === "exports_module_directive" ? "exports" : "opens",
2136
- " ",
2137
- path.call(print, "packageNode")
2138
- ];
2139
- if (path.node.modulesNodes.length) {
2140
- const moduleNames = join$1([",", line$2], path.map(print, "modulesNodes"));
2141
- directive.push(group$1(indent$1([line$2, group$1(indent$1([
2142
- "to",
2143
- line$2,
2144
- ...moduleNames
2145
- ]))])));
2146
- }
2147
- directive.push(";");
2148
- return directive;
2149
- }
2150
- //#endregion
2151
- //#region src/printers/types-values-and-variables.ts
2152
- const { group, indent, join, line: line$1 } = prettier_doc.builders;
2153
- var types_values_and_variables_default = {
2154
- boolean_type: printValue,
2155
- integral_type: printValue,
2156
- floating_point_type: printValue,
2157
- void_type: printValue,
2158
- array_type(path, print) {
2159
- return [path.call(print, "elementNode"), path.call(print, "dimensionsNode")];
1664
+ ternary_expression(path, print, options) {
1665
+ const { node } = path;
1666
+ const consequentNode = node.consequenceNode;
1667
+ const parts = [];
1668
+ const parent = path.parent;
1669
+ const isParentTest = parent.type === node.type && parent.conditionNode === node;
1670
+ const forceNoIndent = parent.type === node.type && !isParentTest;
1671
+ let currentParent;
1672
+ let previousParent;
1673
+ let i = 0;
1674
+ do {
1675
+ previousParent = currentParent || node;
1676
+ currentParent = path.getParentNode(i);
1677
+ i++;
1678
+ } while (currentParent && currentParent.type === node.type && currentParent.conditionNode !== previousParent);
1679
+ const firstNonConditionalParent = currentParent || parent;
1680
+ const operatorAtEnd = options.experimentalOperatorPosition === "end";
1681
+ const printBranch = (nodePropertyName) => operatorAtEnd || isTextBlock(node[nodePropertyName]) ? path.call(print, nodePropertyName) : options.useTabs ? indent$4(path.call(print, nodePropertyName)) : align(2, path.call(print, nodePropertyName));
1682
+ const openParen = consequentNode.type === node.type ? ifBreak("", "(") : "";
1683
+ const closeParen = consequentNode.type === node.type ? ifBreak("", ")") : "";
1684
+ const part = operatorAtEnd ? [
1685
+ " ?",
1686
+ line$3,
1687
+ openParen,
1688
+ printBranch("consequenceNode"),
1689
+ closeParen,
1690
+ " :",
1691
+ line$3,
1692
+ printBranch("alternativeNode")
1693
+ ] : [
1694
+ line$3,
1695
+ "? ",
1696
+ openParen,
1697
+ printBranch("consequenceNode"),
1698
+ closeParen,
1699
+ line$3,
1700
+ ": ",
1701
+ printBranch("alternativeNode")
1702
+ ];
1703
+ parts.push(operatorAtEnd || parent.type !== node.type || parent.alternativeNode === node || isParentTest ? part : options.useTabs ? dedent(indent$4(part)) : align(Math.max(0, options.tabWidth - 2), part));
1704
+ const maybeGroup = (doc) => parent === firstNonConditionalParent ? group$4(doc) : doc;
1705
+ const breakClosingParen = parent.type === "explicit_constructor_invocation" || parent.type === "field_access" || parent.type === "method_invocation" || parent.type === "method_reference" || parent.type === "object_creation_expression";
1706
+ const shouldExtraIndent = shouldExtraIndentForTernaryExpression(path);
1707
+ const result = maybeGroup([
1708
+ printTernaryTest(path, print, operatorAtEnd),
1709
+ forceNoIndent && !operatorAtEnd ? parts : indent$4(parts),
1710
+ breakClosingParen && !shouldExtraIndent ? closingBracketLine(options) : ""
1711
+ ]);
1712
+ return isParentTest || shouldExtraIndent ? group$4([indent$4([softline$1, result]), closingBracketLine(options)]) : result;
2160
1713
  },
2161
- annotated_type(path, print) {
2162
- return join(" ", path.map(print, "children"));
1714
+ assignment_expression(path, print) {
1715
+ const { node } = path;
1716
+ return printAssignment(path.call(print, "leftNode"), [" ", node.operatorNode.type], path.call(print, "rightNode"), node.rightNode);
2163
1717
  },
2164
- dimensions(path, print) {
2165
- return path.map((child) => {
2166
- if (child.node.isNamed) return [
2167
- ...child.isFirst ? [" "] : [],
2168
- print(child),
2169
- " "
2170
- ];
2171
- return child.node.value;
2172
- }, "children");
1718
+ binary_expression(path, print, options) {
1719
+ const { node } = path;
1720
+ const parent = path.parent;
1721
+ const grandparent = path.grandparent;
1722
+ const isInsideParentheses = (grandparent?.type === "if_statement" || grandparent?.type === "while_statement" || grandparent?.type === "switch_expression" || grandparent?.type === "do_statement") && grandparent.conditionNode === parent || grandparent?.type === "synchronized_statement" && grandparent.bodyNode !== parent;
1723
+ const parts = printBinaryExpressions(path, print, options, isInsideParentheses);
1724
+ if (isInsideParentheses) return parts;
1725
+ if (parent?.type === "unary_expression" && !node.comments || (parent?.type === "explicit_constructor_invocation" || parent?.type === "field_access" || parent?.type === "method_invocation") && parent.objectNode === node || parent?.type === "method_reference" || parent?.type === "object_creation_expression") return group$4([indent$4([softline$1, ...parts]), closingBracketLine(options)]);
1726
+ if (isReturnOrThrowStatement(parent) || parent?.type === "assignment_expression" || parent?.type === "variable_declarator" || parent?.type === "guard" || parent?.type === "lambda_expression" && parent.bodyNode === node || parent?.type === "for_statement" && parent.conditionNode === node || parent?.type === "ternary_expression" && !isReturnOrThrowStatement(grandparent) && grandparent?.type !== "parenthesized_expression" && grandparent?.type !== "argument_list" || parent?.type === "unary_expression" && parent.operandNode === node) return group$4(parts);
1727
+ if (parts.length === 0) return "";
1728
+ const firstGroupIndex = parts.findIndex((part) => typeof part !== "string" && !Array.isArray(part) && part.type === "group");
1729
+ const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1);
1730
+ const rest = parts.slice(headParts.length);
1731
+ return group$4([...headParts, indent$4(rest)]);
2173
1732
  },
2174
- type_parameter(path, print) {
2175
- return join(" ", path.map(print, "children"));
1733
+ instanceof_expression(path, print, options) {
1734
+ return group$4(indent$4(path.map((child) => {
1735
+ const doc = print(child, { annotationMode: "noBreak" });
1736
+ if (!child.previous) return doc;
1737
+ return [(options.experimentalOperatorPosition === "start" ? child.node.type === "instanceof" : child.previous.type === "instanceof") ? line$3 : " ", doc];
1738
+ }, "children")));
2176
1739
  },
2177
- type_bound(path, print) {
2178
- const [firstType, ...restTypes] = path.map(print, "namedChildren");
2179
- const bound = ["extends ", firstType];
2180
- if (restTypes.length) bound.push(group(indent([
2181
- line$1,
2182
- "& ",
2183
- ...join([line$1, "& "], restTypes)
2184
- ])));
2185
- return bound;
1740
+ unary_expression(path, print, options) {
1741
+ const parts = [path.call(print, "operatorNode")];
1742
+ const operandDoc = path.call(print, "operandNode");
1743
+ if (path.node.operandNode.comments) parts.push(group$4(indentInParentheses(operandDoc, options)));
1744
+ else parts.push(operandDoc);
1745
+ return parts;
2186
1746
  },
2187
- type_arguments: printTypeParameters,
2188
- wildcard(path, print) {
2189
- return join(" ", path.map(print, "children"));
2190
- }
2191
- };
2192
- //#endregion
2193
- //#region src/printers/index.ts
2194
- const printersByNodeType = {
2195
- ERROR(path) {
2196
- throw new Error(`Failed to parse: "${printValue(path)}"`);
1747
+ field_access: printMemberChain,
1748
+ generic_type(path, print) {
1749
+ const typeIdentifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "scoped_type_identifier" || type === "type_identifier");
1750
+ const typeArgumentsIndex = path.node.namedChildren.findIndex(({ type }) => type === "type_arguments");
1751
+ return [path.call(print, "namedChildren", typeIdentifierIndex), path.call(print, "namedChildren", typeArgumentsIndex)];
2197
1752
  },
2198
- ...arrays_default,
2199
- ...blocks_and_statements_default,
2200
- ...classes_default,
2201
- ...expressions_default,
2202
- ...interfaces_default,
2203
- ...lexical_structure_default,
2204
- ...names_default,
2205
- ...packages_and_modules_default,
2206
- ...types_values_and_variables_default
2207
- };
2208
- function printerForNodeType(type) {
2209
- return printersByNodeType[type];
2210
- }
2211
- //#endregion
2212
- //#region src/printer.ts
2213
- var printer_default = {
2214
- print(path, options, print, args) {
2215
- if (!hasNamedNode(path)) return printValue(path);
2216
- const doc = printerForNodeType(path.node.type)(path, print, options, args);
2217
- return needsParentheses(path) ? [
1753
+ parenthesized_expression(path, print, options) {
1754
+ const expression = path.call(print, "namedChildren", 0);
1755
+ const parentType = path.parent?.type;
1756
+ const grandparentType = path.grandparent?.type;
1757
+ const expressionType = path.node.namedChildren[0].type;
1758
+ const hasLambda = expressionType === "lambda_expression";
1759
+ const hasTernary = expressionType === "ternary_expression";
1760
+ const hasSuffix = parentType && (parentType === "array_access" || parentType === "explicit_constructor_invocation" || parentType === "field_access" || parentType === "method_invocation" || parentType === "method_reference" || parentType === "object_creation_expression");
1761
+ const isAssignment = parentType && (parentType === "assignment_expression" || parentType === "variable_declarator") || hasSuffix && (grandparentType === "assignment_expression" || grandparentType === "variable_declarator");
1762
+ if (!hasLambda && hasSuffix && (!hasTernary || isAssignment)) return group$4(indentInParentheses(hasTernary ? group$4(expression) : expression, options));
1763
+ else if (parentType && (parentType === "guard" || parentType === "return_statement" || parentType === "unary_expression" && grandparentType === "return_statement" || path.node.fieldName === "condition" && (parentType === "do_statement" || parentType === "if_statement" || parentType === "switch_expression" || parentType === "while_statement") || path.node.fieldName !== "body" && parentType === "synchronized_statement")) return group$4(indentInParentheses(group$4(expression), options));
1764
+ else if (hasTernary && hasSuffix && !isAssignment) return group$4([
2218
1765
  "(",
2219
- doc,
1766
+ expression,
1767
+ closingBracketLine(options),
2220
1768
  ")"
2221
- ] : doc;
2222
- },
2223
- embed(path, options) {
2224
- return hasType(path, "string_literal") ? embedTextBlock(path, options) : null;
2225
- },
2226
- hasPrettierIgnore(path) {
2227
- return path.node.comments?.some(isPrettierIgnore) === true || canAttachComment(path.node, path.parent ? [path.parent] : []) && isFullyBetweenPrettierIgnore(path);
2228
- },
2229
- canAttachComment,
2230
- isBlockComment(node) {
2231
- return node.type === "block_comment";
2232
- },
2233
- willPrintOwnComments,
2234
- printComment(commentPath) {
2235
- return printComment(commentPath.node);
1769
+ ]);
1770
+ else return group$4([
1771
+ "(",
1772
+ hasLambda || hasTernary ? expression : indent$4(expression),
1773
+ ")"
1774
+ ]);
2236
1775
  },
2237
- getCommentChildNodes(node) {
2238
- return node.isNamed ? node.children : [];
1776
+ cast_expression(path, print, options) {
1777
+ const { node } = path;
1778
+ const parts = [
1779
+ group$4(node.typeNodes.length === 1 ? [
1780
+ "(",
1781
+ path.call(print, "typeNodes", 0),
1782
+ ")"
1783
+ ] : [
1784
+ "(",
1785
+ indent$4([softline$1, join$4([" &", line$3], path.map(print, "typeNodes"))]),
1786
+ closingBracketLine(options),
1787
+ ")"
1788
+ ]),
1789
+ " ",
1790
+ path.call(print, "valueNode")
1791
+ ];
1792
+ const parent = path.parent;
1793
+ if (parent?.type === "unary_expression" && !node.comments || parent?.type === "array_access" && parent.arrayNode === node || (parent?.type === "explicit_constructor_invocation" || parent?.type === "field_access" || parent?.type === "method_invocation") && parent.objectNode === node || parent?.type === "method_reference" || parent?.type === "object_creation_expression") return group$4([indent$4([softline$1, ...parts]), closingBracketLine(options)]);
1794
+ return parts;
2239
1795
  },
2240
- handleComments: {
2241
- ownLine: handleLineComment,
2242
- endOfLine: handleLineComment,
2243
- remaining: handleRemainingComment
1796
+ object_creation_expression(path, print, options) {
1797
+ const expression = [];
1798
+ path.each((child) => {
1799
+ if (child.node.type === "class_body") expression.push(printBlockSeparator(options));
1800
+ expression.push(print(child));
1801
+ if (child.node.type === "annotation" || child.node.type === "marker_annotation" || child.node.type === "new") expression.push(" ");
1802
+ }, "children");
1803
+ return expression;
2244
1804
  },
2245
- getVisitorKeys() {
2246
- return ["namedChildren"];
2247
- }
2248
- };
2249
- function hasNamedNode(path) {
2250
- return path.node.isNamed;
2251
- }
2252
- //#endregion
2253
- //#region src/comments.ts
2254
- const { hasNewline, isPreviousLineEmpty, skipNewline, skipSpaces } = prettier.util;
2255
- const { breakParent, hardline, line, lineSuffix } = prettier_doc.builders;
2256
- const prettierIgnoreRangesByTree = /* @__PURE__ */ new WeakMap();
2257
- function determinePrettierIgnoreRanges(tree) {
2258
- const { comments } = tree;
2259
- if (!comments) return;
2260
- const ranges = comments.filter(({ value }) => /^\/(?:\/\s*(?:prettier-ignore-(?:start|end)|@formatter:(?:off|on))\s*|\*\s*(?:prettier-ignore-(?:start|end)|@formatter:(?:off|on))\s*\*\/)$/.test(value)).reduce((ranges, { value, start }) => {
2261
- const previous = ranges.at(-1);
2262
- if (value.includes("start") || value.includes("off")) {
2263
- if (previous?.end !== Infinity) ranges.push({
2264
- start: start.index,
2265
- end: Infinity
2266
- });
2267
- } else if (previous?.end === Infinity) previous.end = start.index;
2268
- return ranges;
2269
- }, new Array());
2270
- prettierIgnoreRangesByTree.set(tree, ranges);
1805
+ method_invocation: printMemberChain,
1806
+ argument_list(path, print, options) {
1807
+ const args = path.node.namedChildren;
1808
+ if (args.length === 0) {
1809
+ const shouldBreak = path.node.comments?.some(({ type, leading, trailing }) => !leading && !trailing && type === "line_comment");
1810
+ return group$4([
1811
+ "(",
1812
+ printDanglingCommentsInList(path),
1813
+ ")"
1814
+ ], { shouldBreak });
1815
+ }
1816
+ const lastArgIndex = args.length - 1;
1817
+ let anyArgEmptyLine = false;
1818
+ const printedArguments = [];
1819
+ path.each((arg, index) => {
1820
+ let argDoc = print(arg);
1821
+ if (index === lastArgIndex) {} else if (isNextLineEmpty(options.originalText, arg.node.end.index)) {
1822
+ anyArgEmptyLine = true;
1823
+ argDoc = [
1824
+ argDoc,
1825
+ ",",
1826
+ hardline$3,
1827
+ hardline$3
1828
+ ];
1829
+ } else argDoc = [
1830
+ argDoc,
1831
+ ",",
1832
+ line$3
1833
+ ];
1834
+ printedArguments.push(argDoc);
1835
+ }, "namedChildren");
1836
+ function allArgsBrokenOut() {
1837
+ return group$4([
1838
+ "(",
1839
+ indent$4([line$3, ...printedArguments]),
1840
+ closingBracketLine(options, line$3),
1841
+ ")"
1842
+ ], { shouldBreak: true });
1843
+ }
1844
+ if (anyArgEmptyLine) return allArgsBrokenOut();
1845
+ if (shouldExpandFirstArg(args)) {
1846
+ const tailArgs = printedArguments.slice(1);
1847
+ if (tailArgs.some(willBreak)) return allArgsBrokenOut();
1848
+ let firstArg;
1849
+ try {
1850
+ firstArg = path.call((arg) => print(arg, { expandFirstArg: true }), "namedChildren", 0);
1851
+ } catch (caught) {
1852
+ if (caught instanceof ArgExpansionBailout) return allArgsBrokenOut();
1853
+ throw caught;
1854
+ }
1855
+ if (willBreak(firstArg)) return [breakParent, conditionalGroup([[
1856
+ "(",
1857
+ group$4(firstArg, { shouldBreak: true }),
1858
+ ", ",
1859
+ ...tailArgs,
1860
+ ")"
1861
+ ], allArgsBrokenOut()])];
1862
+ return conditionalGroup([
1863
+ [
1864
+ "(",
1865
+ firstArg,
1866
+ ", ",
1867
+ ...tailArgs,
1868
+ ")"
1869
+ ],
1870
+ [
1871
+ "(",
1872
+ group$4(firstArg, { shouldBreak: true }),
1873
+ ", ",
1874
+ ...tailArgs,
1875
+ ")"
1876
+ ],
1877
+ allArgsBrokenOut()
1878
+ ]);
1879
+ }
1880
+ if (shouldExpandLastArg(args, options)) {
1881
+ const headArgs = printedArguments.slice(0, -1);
1882
+ if (headArgs.some(willBreak)) return allArgsBrokenOut();
1883
+ let lastArg;
1884
+ try {
1885
+ lastArg = path.call((arg) => print(arg, { expandLastArg: true }), "namedChildren", lastArgIndex);
1886
+ } catch (caught) {
1887
+ if (caught instanceof ArgExpansionBailout) return allArgsBrokenOut();
1888
+ throw caught;
1889
+ }
1890
+ if (willBreak(lastArg)) return [breakParent, conditionalGroup([[
1891
+ "(",
1892
+ ...headArgs,
1893
+ group$4(lastArg, { shouldBreak: true }),
1894
+ ")"
1895
+ ], allArgsBrokenOut()])];
1896
+ return conditionalGroup([
1897
+ [
1898
+ "(",
1899
+ ...headArgs,
1900
+ lastArg,
1901
+ ")"
1902
+ ],
1903
+ [
1904
+ "(",
1905
+ ...headArgs,
1906
+ group$4(lastArg, { shouldBreak: true }),
1907
+ ")"
1908
+ ],
1909
+ allArgsBrokenOut()
1910
+ ]);
1911
+ }
1912
+ return group$4(indentInParentheses(printedArguments, options), { shouldBreak: printedArguments.some(willBreak) || anyArgEmptyLine });
1913
+ },
1914
+ array_creation_expression(path, print) {
1915
+ const parts = ["new "];
1916
+ path.each((child) => {
1917
+ if (child.node.type === "annotation" || child.node.type === "marker_annotation") parts.push(print(child), " ");
1918
+ }, "namedChildren");
1919
+ parts.push(path.call(print, "typeNode"), ...path.map(print, "dimensionsNodes"));
1920
+ if (hasChild(path, "valueNode")) parts.push(" ", path.call(print, "valueNode"));
1921
+ return parts;
1922
+ },
1923
+ dimensions_expr(path, print) {
1924
+ return path.map((child) => child.node.type === "annotation" || child.node.type === "marker_annotation" ? [print(child), " "] : [
1925
+ "[",
1926
+ print(child),
1927
+ "]"
1928
+ ], "namedChildren");
1929
+ },
1930
+ class_literal(path, print) {
1931
+ return [path.call(print, "namedChildren", 0), ".class"];
1932
+ },
1933
+ array_access: printMemberChain,
1934
+ method_reference(path, print) {
1935
+ return group$4(path.map(print, "children"));
1936
+ },
1937
+ template_expression(path, print) {
1938
+ return [
1939
+ path.call(print, "template_processorNode"),
1940
+ ".",
1941
+ path.call(print, "template_argumentNode")
1942
+ ];
1943
+ },
1944
+ pattern(path, print) {
1945
+ return path.call(print, "namedChildren", 0);
1946
+ },
1947
+ type_pattern(path, print) {
1948
+ return join$4(" ", path.map(print, "children"));
1949
+ },
1950
+ record_pattern(path, print) {
1951
+ return path.map(print, "children");
1952
+ },
1953
+ record_pattern_body(path, print, options) {
1954
+ return group$4(indentInParentheses(join$4([",", line$3], path.map(print, "namedChildren")), options));
1955
+ },
1956
+ record_pattern_component(path, print) {
1957
+ return join$4(" ", path.map(print, "children"));
1958
+ },
1959
+ guard(path, print, options) {
1960
+ return ["when ", group$4([
1961
+ ifBreak("("),
1962
+ indent$4([softline$1, path.call(print, "namedChildren", 0)]),
1963
+ closingBracketLine(options),
1964
+ ifBreak(")")
1965
+ ])];
1966
+ }
1967
+ };
1968
+ function printLambdaExpressionSignature(path, options, print, args) {
1969
+ const parts = [];
1970
+ const parameters = path.call(print, "parametersNode");
1971
+ if (shouldPrintParamsWithoutParens(path, options)) parts.push(parameters);
1972
+ else {
1973
+ if (args != null && typeof args === "object" && ("expandLastArg" in args && args.expandLastArg === true || "expandFirstArg" in args && args.expandFirstArg === true)) {
1974
+ if (willBreak(parameters)) throw new ArgExpansionBailout();
1975
+ parts.push(group$4(removeLines(parameters)));
1976
+ } else parts.push(parameters);
1977
+ if (path.node.parametersNode.type === "identifier") return path.node.parametersNode.comments ? group$4([
1978
+ "(",
1979
+ indent$4([softline$1, ...parts]),
1980
+ lineSuffixBoundary,
1981
+ ")"
1982
+ ]) : [
1983
+ "(",
1984
+ ...parts,
1985
+ ")"
1986
+ ];
1987
+ }
1988
+ const dangling = printDanglingComments(path);
1989
+ if (dangling) parts.push(" ", dangling);
1990
+ return parts;
2271
1991
  }
2272
- function isFullyBetweenPrettierIgnore(path) {
2273
- const { node, root } = path;
2274
- const start = parser_default.locStart(node);
2275
- const end = parser_default.locEnd(node);
2276
- return prettierIgnoreRangesByTree.get(root)?.some((range) => range.start < start && end < range.end) === true;
1992
+ function mayBreakAfterShortPrefix(functionBody) {
1993
+ return functionBody.type === "array_creation_expression" || functionBody.type === "lambda_expression" || functionBody.type === "block";
2277
1994
  }
2278
- function isPrettierIgnore(comment) {
2279
- return /^(\/\/\s*prettier-ignore|\/\*\s*prettier-ignore\s*\*\/)$/.test(comment.value);
1995
+ function printArrowFunctionSignatures(path, { signatureDocs }) {
1996
+ if (signatureDocs.length === 1) return signatureDocs[0];
1997
+ const { node, parent } = path;
1998
+ if (node.fieldName !== "object" && parent?.type === "method_invocation" || parent?.type === "binary_expression") return group$4([
1999
+ signatureDocs[0],
2000
+ " ->",
2001
+ indent$4([line$3, join$4([" ->", line$3], signatureDocs.slice(1))])
2002
+ ]);
2003
+ if (node.fieldName === "object" && parent?.type === "method_invocation") return group$4(join$4([" ->", line$3], signatureDocs));
2004
+ return group$4(indent$4(join$4([" ->", line$3], signatureDocs)));
2280
2005
  }
2281
- function willPrintOwnComments(path) {
2282
- return isMember(path.node) && !printer_default.hasPrettierIgnore(path);
2006
+ function printArrowFunctionBody(path, args, options, { bodyDoc, bodyComments, bodySeparator, shouldPutBodyOnSameLine }) {
2007
+ const trailingSpace = args && typeof args === "object" && "expandLastArg" in args && args.expandLastArg && !path.node.comments ? closingBracketLine(options) : "";
2008
+ return shouldPutBodyOnSameLine ? [
2009
+ bodySeparator,
2010
+ bodyDoc,
2011
+ bodyComments
2012
+ ] : [indent$4([
2013
+ line$3,
2014
+ bodyDoc,
2015
+ bodyComments
2016
+ ]), trailingSpace];
2283
2017
  }
2284
- function canAttachComment(node, ancestors) {
2285
- if (!node.isNamed) return isBinaryOperator(node);
2286
- switch (node.type) {
2287
- case "enum_body_declarations":
2288
- case "escape_sequence":
2289
- case "modifier":
2290
- case "multiline_string_fragment":
2291
- case "program":
2292
- case "string_fragment":
2293
- case "visibility": return false;
2294
- case "parenthesized_expression": {
2295
- const [parent] = ancestors;
2296
- return !(parent.isNamed && [
2297
- "do_statement",
2298
- "if_statement",
2299
- "switch_expression",
2300
- "synchronized_statement",
2301
- "try_statement",
2302
- "try_with_resources_statement",
2303
- "while_statement"
2304
- ].includes(parent.type));
2305
- }
2306
- default: return true;
2018
+ function shouldPrintParamsWithoutParens(path, options) {
2019
+ if (options.arrowParens === "always") return false;
2020
+ if (options.arrowParens === "avoid") {
2021
+ const { node } = path;
2022
+ return canPrintParamsWithoutParens(node);
2307
2023
  }
2024
+ return false;
2308
2025
  }
2309
- function handleLineComment(commentNode, _, options) {
2310
- return [
2311
- handleBinaryExpressionComments,
2312
- handleFormalParametersComments,
2313
- handleFqnOrRefTypeComments,
2314
- handleIfStatementComments,
2315
- handleJumpStatementComments,
2316
- handleLabeledStatementComments,
2317
- handleLambdaExpressionComments,
2318
- handleMemberChainComments,
2319
- handleModifiersComments,
2320
- handleNameComments,
2321
- handleTernaryExpressionComments,
2322
- handleTryStatementComments
2323
- ].some((fn) => fn(commentNode, options));
2324
- }
2325
- function handleRemainingComment(commentNode) {
2326
- return [
2327
- handleFqnOrRefTypeComments,
2328
- handleNameComments,
2329
- handleJumpStatementComments
2330
- ].some((fn) => fn(commentNode));
2026
+ function canPrintParamsWithoutParens(node) {
2027
+ return node.parametersNode.type === "identifier" && !hasDanglingComments(node) && !node.parametersNode.comments;
2331
2028
  }
2332
- function handleBinaryExpressionComments(commentNode, options) {
2333
- const { enclosingNode, precedingNode, followingNode } = commentNode;
2334
- if (enclosingNode?.type === "binary_expression") {
2335
- if (isBinaryOperator(followingNode)) {
2336
- if (options.experimentalOperatorPosition === "start") prettier.util.addLeadingComment(followingNode, commentNode);
2337
- else prettier.util.addTrailingComment(followingNode, commentNode);
2338
- return true;
2339
- } else if (options.experimentalOperatorPosition === "start" && isBinaryOperator(precedingNode)) {
2340
- prettier.util.addLeadingComment(precedingNode, commentNode);
2341
- return true;
2342
- }
2029
+ function printMemberChain(path, print, options) {
2030
+ const isExpressionStatement = path.parent?.type === "expression_statement";
2031
+ const printedNodes = [];
2032
+ function shouldInsertEmptyLineAfter(node) {
2033
+ const { originalText } = options;
2034
+ const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex(originalText, node.end.index);
2035
+ if ((nextCharIndex ? originalText.charAt(nextCharIndex) : "") === ")") return nextCharIndex !== false && isNextLineEmpty(originalText, nextCharIndex + 1);
2036
+ return isNextLineEmpty(originalText, node.end.index);
2343
2037
  }
2344
- return false;
2345
- }
2346
- function handleFormalParametersComments(commentNode) {
2347
- const { enclosingNode, precedingNode, followingNode } = commentNode;
2348
- if (enclosingNode?.type === "formal_parameters" && !precedingNode && !followingNode) {
2349
- prettier.util.addDanglingComment(enclosingNode, commentNode, void 0);
2350
- return true;
2038
+ function rec(path) {
2039
+ const { node } = path;
2040
+ if (hasType(path, "method_invocation") && hasChild(path, "objectNode")) {
2041
+ const hasTrailingEmptyLine = shouldInsertEmptyLineAfter(node);
2042
+ printedNodes.unshift({
2043
+ node,
2044
+ hasTrailingEmptyLine,
2045
+ printed: [printComments(path, printMethodInvocation(path, print)), hasTrailingEmptyLine ? hardline$3 : ""]
2046
+ });
2047
+ path.call(rec, "objectNode");
2048
+ } else if (hasType(path, "array_access")) {
2049
+ printedNodes.unshift({
2050
+ node,
2051
+ printed: printComments(path, printArrayAccess(path, print))
2052
+ });
2053
+ path.call(rec, "arrayNode");
2054
+ } else if (hasType(path, "field_access")) {
2055
+ printedNodes.unshift({
2056
+ node,
2057
+ printed: printComments(path, printFieldAccess(path, print))
2058
+ });
2059
+ path.call(rec, "objectNode");
2060
+ } else printedNodes.unshift({
2061
+ node,
2062
+ printed: print(path)
2063
+ });
2351
2064
  }
2352
- return false;
2353
- }
2354
- function handleFqnOrRefTypeComments(commentNode) {
2355
- const { enclosingNode, followingNode } = commentNode;
2356
- if (enclosingNode?.type === "scoped_type_identifier" && followingNode) {
2357
- prettier.util.addLeadingComment(followingNode, commentNode);
2358
- return true;
2065
+ const { node } = path;
2066
+ if (hasType(path, "method_invocation")) {
2067
+ printedNodes.unshift({
2068
+ node,
2069
+ printed: printMethodInvocation(path, print)
2070
+ });
2071
+ if (hasChild(path, "objectNode")) path.call(rec, "objectNode");
2072
+ } else if (hasType(path, "array_access")) {
2073
+ printedNodes.unshift({
2074
+ node,
2075
+ printed: printArrayAccess(path, print)
2076
+ });
2077
+ if (hasChild(path, "arrayNode")) path.call(rec, "arrayNode");
2078
+ } else if (hasType(path, "field_access")) {
2079
+ printedNodes.unshift({
2080
+ node,
2081
+ printed: printFieldAccess(path, print)
2082
+ });
2083
+ if (hasChild(path, "objectNode")) path.call(rec, "objectNode");
2359
2084
  }
2360
- return false;
2361
- }
2362
- function handleIfStatementComments(commentNode) {
2363
- const { enclosingNode, precedingNode } = commentNode;
2364
- if (enclosingNode?.type === "if_statement" && precedingNode?.fieldName === "consequence") {
2365
- prettier.util.addDanglingComment(enclosingNode, commentNode, void 0);
2366
- return true;
2085
+ node.comments?.filter(({ leading }) => leading).filter(({ start }) => start.index >= node.start.index).filter(({ end }) => end.index <= node.end.index).map((comment) => comment.leading = false);
2086
+ const danglingComments = printDanglingComments(path);
2087
+ if (danglingComments) {
2088
+ const lastNode = printedNodes.at(-1);
2089
+ lastNode.printed = [
2090
+ danglingComments,
2091
+ hardline$3,
2092
+ lastNode.printed
2093
+ ];
2367
2094
  }
2368
- return false;
2369
- }
2370
- function handleJumpStatementComments(commentNode) {
2371
- const { enclosingNode, precedingNode, followingNode } = commentNode;
2372
- if (enclosingNode && !precedingNode && !followingNode && (enclosingNode.type === "break_statement" || enclosingNode.type === "continue_statement" || enclosingNode.type === "return_statement")) {
2373
- prettier.util.addTrailingComment(enclosingNode, commentNode);
2374
- return true;
2095
+ const groups = [];
2096
+ let currentGroup = [printedNodes[0]];
2097
+ let i = 1;
2098
+ for (; i < printedNodes.length; ++i) if (printedNodes[i].node.type === "array_access") currentGroup.push(printedNodes[i]);
2099
+ else break;
2100
+ if (printedNodes[0].node.type !== "method_invocation") for (; i + 1 < printedNodes.length; ++i) if (printedNodes[i].node.type !== "method_invocation") currentGroup.push(printedNodes[i]);
2101
+ else break;
2102
+ groups.push(currentGroup);
2103
+ currentGroup = [];
2104
+ let hasSeenMethodInvocation = false;
2105
+ for (; i < printedNodes.length; ++i) {
2106
+ if (hasSeenMethodInvocation) {
2107
+ if (printedNodes[i].node.type === "array_access") {
2108
+ currentGroup.push(printedNodes[i]);
2109
+ continue;
2110
+ }
2111
+ groups.push(currentGroup);
2112
+ currentGroup = [];
2113
+ hasSeenMethodInvocation = false;
2114
+ }
2115
+ if (printedNodes[i].node.type === "method_invocation") hasSeenMethodInvocation = true;
2116
+ currentGroup.push(printedNodes[i]);
2117
+ if (printedNodes[i].node.comments?.some(({ trailing }) => trailing)) {
2118
+ groups.push(currentGroup);
2119
+ currentGroup = [];
2120
+ hasSeenMethodInvocation = false;
2121
+ }
2375
2122
  }
2376
- return false;
2377
- }
2378
- function handleLabeledStatementComments(commentNode) {
2379
- const { enclosingNode, precedingNode } = commentNode;
2380
- if (enclosingNode?.type === "labeled_statement" && precedingNode?.type === "identifier") {
2381
- prettier.util.addLeadingComment(precedingNode, commentNode);
2382
- return true;
2123
+ if (currentGroup.length > 0) groups.push(currentGroup);
2124
+ function isFactory(name) {
2125
+ return /^[A-Z]|^[$_]+$/.test(name);
2383
2126
  }
2384
- return false;
2385
- }
2386
- function handleLambdaExpressionComments(commentNode) {
2387
- const { enclosingNode, precedingNode, followingNode } = commentNode;
2388
- if (enclosingNode?.type === "lambda_expression" && precedingNode && followingNode && enclosingNode.children.find(({ type }) => type === "->").end.index < commentNode.start.index) {
2389
- if (followingNode.type === "block") {
2390
- if (followingNode.namedChildren.length) prettier.util.addLeadingComment(followingNode.namedChildren[0], commentNode);
2391
- else prettier.util.addDanglingComment(followingNode, commentNode, void 0);
2392
- } else prettier.util.addLeadingComment(followingNode, commentNode);
2393
- return true;
2127
+ function isShort(name) {
2128
+ return name.length <= options.tabWidth;
2394
2129
  }
2395
- }
2396
- function handleMemberChainComments(commentNode) {
2397
- const { enclosingNode, precedingNode, followingNode } = commentNode;
2398
- if (precedingNode && (enclosingNode?.type === "field_access" || enclosingNode?.type === "method_invocation" && precedingNode.end.row < commentNode.start.row) && precedingNode === enclosingNode.objectNode) {
2399
- prettier.util.addLeadingComment(enclosingNode, commentNode);
2400
- return true;
2401
- } else if (isMember(followingNode) && (!precedingNode || precedingNode !== getMemberObject(followingNode) && precedingNode.end.row < commentNode.start.row) && !isPrettierIgnore(commentNode)) {
2402
- prettier.util.addDanglingComment(followingNode, commentNode, void 0);
2403
- return true;
2130
+ function shouldNotWrap(groups) {
2131
+ const hasArrayAccess = groups[1][0]?.node.type === "array_access";
2132
+ if (groups[0].length === 1) {
2133
+ const firstNode = groups[0][0].node;
2134
+ return firstNode.type === "this" || firstNode.type === "identifier" && (isFactory(firstNode.value) || isExpressionStatement && isShort(firstNode.value) || hasArrayAccess);
2135
+ }
2136
+ const lastNode = groups[0].at(-1).node;
2137
+ return lastNode.type === "field_access" && lastNode.fieldNode.type === "identifier" && (isFactory(lastNode.fieldNode.value) || hasArrayAccess);
2404
2138
  }
2405
- return false;
2406
- }
2407
- function handleModifiersComments(commentNode) {
2408
- const { precedingNode } = commentNode;
2409
- if (precedingNode?.type === "annotation" || precedingNode?.type === "marker_annotation" || precedingNode?.type === "modifiers") {
2410
- prettier.util.addTrailingComment(precedingNode, commentNode);
2411
- return true;
2139
+ const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments?.length && shouldNotWrap(groups);
2140
+ function printGroup(printedGroup) {
2141
+ return printedGroup.map((tuple) => tuple.printed);
2412
2142
  }
2413
- return false;
2414
- }
2415
- function handleNameComments(commentNode) {
2416
- const { enclosingNode, precedingNode } = commentNode;
2417
- if (enclosingNode && precedingNode?.type === "identifier" && (enclosingNode.type === "scoped_identifier" || enclosingNode.type === "module_declaration" || enclosingNode.type === "package_declaration" || enclosingNode.type === "scoped_type_identifier")) {
2418
- prettier.util.addTrailingComment(precedingNode, commentNode);
2419
- return true;
2143
+ function printIndentedGroup(groups) {
2144
+ if (groups.length === 0) return "";
2145
+ return indent$4([hardline$3, join$4(hardline$3, groups.map(printGroup))]);
2420
2146
  }
2421
- return false;
2422
- }
2423
- function handleTernaryExpressionComments(commentNode) {
2424
- const { enclosingNode, precedingNode, followingNode } = commentNode;
2425
- if (enclosingNode?.type === "ternary_expression" && precedingNode?.isNamed && followingNode?.isNamed && precedingNode.end.row < commentNode.start.row && commentNode.end.row < followingNode.start.row) {
2426
- prettier.util.addLeadingComment(followingNode, commentNode);
2427
- return true;
2147
+ const printedGroups = groups.map(printGroup);
2148
+ const oneLine = printedGroups;
2149
+ const cutoff = shouldMerge ? 3 : 2;
2150
+ const flatGroups = groups.flat();
2151
+ const nodeHasComment = flatGroups.at(-1).node.comments?.some(({ leading, trailing }) => !leading && !trailing) || flatGroups.slice(1, -1).some((node) => node.node.comments?.some(({ leading }) => leading)) || flatGroups.slice(0, -1).some((node) => node.node.comments?.some(({ trailing }) => trailing));
2152
+ if (groups.length <= cutoff && !nodeHasComment && !groups.some((g) => g.at(-1).hasTrailingEmptyLine)) return group$4(oneLine);
2153
+ const lastNodeBeforeIndent = groups[shouldMerge ? 1 : 0].at(-1).node;
2154
+ const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "method_invocation" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
2155
+ const expanded = [
2156
+ printGroup(groups[0]),
2157
+ shouldMerge ? groups.slice(1, 2).map(printGroup) : "",
2158
+ shouldHaveEmptyLineBeforeIndent ? hardline$3 : "",
2159
+ printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))
2160
+ ];
2161
+ const methodInvocations = printedNodes.map(({ node }) => node).filter((node) => node.type === "method_invocation");
2162
+ function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
2163
+ const lastGroupNode = groups.at(-1).at(-1).node;
2164
+ const lastGroupDoc = printedGroups.at(-1);
2165
+ return lastGroupNode.type === "method_invocation" && willBreak(lastGroupDoc) && methodInvocations.slice(0, -1).some((node) => node.argumentsNode.namedChildren.some(({ type }) => type === "lambda_expression"));
2428
2166
  }
2429
- return false;
2167
+ let result;
2168
+ if (nodeHasComment || methodInvocations.length > 2 && methodInvocations.some((inv) => !inv.argumentsNode.namedChildren.every((arg) => isSimpleCallArgument(arg))) || printedGroups.slice(0, -1).some(willBreak) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) result = group$4(expanded);
2169
+ else result = [willBreak(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent : "", conditionalGroup([oneLine, expanded])];
2170
+ return result;
2430
2171
  }
2431
- function handleTryStatementComments(commentNode) {
2432
- const { enclosingNode, followingNode } = commentNode;
2433
- if (enclosingNode && (enclosingNode.type === "catch_clause" || enclosingNode.type === "try_statement" || enclosingNode.type === "try_with_resources_statement") && followingNode?.isNamed) {
2434
- const block = followingNode.type === "catch_clause" ? followingNode.bodyNode : followingNode.type === "finally_clause" ? followingNode.namedChildren[0] : null;
2435
- if (!block) return false;
2436
- const blockStatement = block.namedChildren.at(0);
2437
- if (blockStatement) prettier.util.addLeadingComment(blockStatement, commentNode);
2438
- else prettier.util.addDanglingComment(block, commentNode, void 0);
2439
- return true;
2440
- }
2441
- return false;
2172
+ function printMethodInvocation(path, print) {
2173
+ const parts = [];
2174
+ if (hasChild(path, "objectNode")) parts.push(".");
2175
+ if (path.node.children.filter(({ type }) => type === ".").length === 2) parts.push("super", ".");
2176
+ if (hasChild(path, "type_argumentsNode")) parts.push(path.call(print, "type_argumentsNode"));
2177
+ parts.push(path.call(print, "nameNode"), path.call(print, "argumentsNode"));
2178
+ return parts;
2442
2179
  }
2443
- function getMemberObject(node) {
2444
- return node.type === "array_access" ? node.arrayNode : node.objectNode;
2180
+ function printArrayAccess(path, print) {
2181
+ const index = path.call(print, "indexNode");
2182
+ return path.node.indexNode.type === "decimal_integer_literal" ? [
2183
+ "[",
2184
+ index,
2185
+ "]"
2186
+ ] : group$4([
2187
+ "[",
2188
+ indent$4([softline$1, index]),
2189
+ softline$1,
2190
+ "]"
2191
+ ]);
2445
2192
  }
2446
- const binaryOperators = /* @__PURE__ */ new Set([
2447
- "<<",
2448
- ">>",
2449
- ">>>",
2450
- "instanceof",
2451
- "<=",
2452
- ">=",
2453
- "==",
2454
- "-",
2455
- "+",
2456
- "&&",
2457
- "&",
2458
- "^",
2459
- "!=",
2460
- "||",
2461
- "|",
2462
- "*",
2463
- "/",
2464
- "%"
2465
- ]);
2466
- function isBinaryOperator(node) {
2467
- return node !== void 0 && binaryOperators.has(node.type);
2193
+ function printFieldAccess(path, print) {
2194
+ const parts = ["."];
2195
+ if (path.node.children.filter(({ type }) => type === ".").length === 2) parts.push("super.");
2196
+ parts.push(path.call(print, "fieldNode"));
2197
+ return parts;
2468
2198
  }
2469
- function printLeadingComment(path) {
2470
- const comment = path.node;
2471
- const parts = [printComment(comment)];
2472
- const originalText = path.root.value;
2473
- if (comment.type === "block_comment") {
2474
- let lineBreak = " ";
2475
- if (hasNewline(originalText, parser_default.locEnd(comment))) {
2476
- if (hasNewline(originalText, parser_default.locStart(comment), { backwards: true })) lineBreak = hardline;
2477
- else lineBreak = line;
2478
- }
2479
- parts.push(lineBreak);
2480
- } else parts.push(hardline);
2481
- const index = skipNewline(originalText, skipSpaces(originalText, parser_default.locEnd(comment)));
2482
- if (index !== false && hasNewline(originalText, index)) parts.push(hardline);
2199
+ /**
2200
+ * For binary expressions to be consistent, we need to group
2201
+ * subsequent operators with the same precedence level under a single
2202
+ * group. Otherwise they will be nested such that some of them break
2203
+ * onto new lines but not all. Operators with the same precedence
2204
+ * level should either all break or not. Because we group them by
2205
+ * precedence level and the AST is structured based on precedence
2206
+ * level, things are naturally broken up correctly, i.e. `&&` is
2207
+ * broken before `+`.
2208
+ */
2209
+ function printBinaryExpressions(path, print, options, isInsideParentheses) {
2210
+ if (!hasType(path, "binary_expression")) return [group$4(print(path))];
2211
+ const { node } = path;
2212
+ let parts = [];
2213
+ if (node.leftNode.type === "binary_expression" && shouldFlatten(node.operatorNode.type, node.leftNode.operatorNode.type)) parts = path.call(() => printBinaryExpressions(path, print, options, isInsideParentheses), "leftNode");
2214
+ else parts.push(group$4(path.call(print, "leftNode")));
2215
+ const operator = node.operatorNode.type;
2216
+ const operatorDoc = path.call(print, "operatorNode");
2217
+ const rightContent = path.call(print, "rightNode");
2218
+ let right = options.experimentalOperatorPosition === "start" ? [
2219
+ line$3,
2220
+ operatorDoc,
2221
+ " ",
2222
+ rightContent
2223
+ ] : [
2224
+ " ",
2225
+ operatorDoc,
2226
+ line$3,
2227
+ rightContent
2228
+ ];
2229
+ const { parent } = path;
2230
+ const shouldBreak = node.leftNode.comments?.some(({ trailing, type }) => trailing && type === "line_comment") ?? false;
2231
+ if (shouldBreak || !(isInsideParentheses && logicalOperators.has(operator)) && (parent?.type !== node.type || logicalOperators.has(parent.operatorNode.value) !== logicalOperators.has(operator)) && node.leftNode.type !== node.type && node.rightNode.type !== node.type) right = group$4(right, { shouldBreak });
2232
+ parts.push(right);
2483
2233
  return parts;
2484
2234
  }
2485
- function printTrailingComment(path, previousComment) {
2486
- const comment = path.node;
2487
- const printed = printComment(comment);
2488
- const originalText = path.root.value;
2489
- const isBlock = comment.type === "block_comment";
2490
- if (previousComment?.hasLineSuffix && !previousComment?.isBlock || hasNewline(originalText, parser_default.locStart(comment), { backwards: true })) {
2491
- const isLineBeforeEmpty = isPreviousLineEmpty(originalText, parser_default.locStart(comment));
2492
- return {
2493
- doc: lineSuffix([
2494
- hardline,
2495
- isLineBeforeEmpty ? hardline : "",
2496
- printed
2497
- ]),
2498
- isBlock,
2499
- hasLineSuffix: true
2500
- };
2235
+ const logicalOperators = /* @__PURE__ */ new Set(["||", "&&"]);
2236
+ const isType = createTypeCheckFunction([
2237
+ "void_type",
2238
+ "integral_type",
2239
+ "floating_point_type",
2240
+ "floating_point_type",
2241
+ "boolean_type",
2242
+ "type_identifier",
2243
+ "scoped_type_identifier",
2244
+ "generic_type",
2245
+ "array_type",
2246
+ "annotated_type"
2247
+ ]);
2248
+ function isSimpleCallArgument(node, depth = 2) {
2249
+ if (depth <= 0) return false;
2250
+ const isChildSimple = (child) => isSimpleCallArgument(child, depth - 1);
2251
+ if (isLiteral(node) || isSingleWordType(node) || node.type === "class_literal") return true;
2252
+ if (node.type === "object_creation_expression" || node.type === "method_invocation") {
2253
+ if (node.type === "object_creation_expression" || !node.objectNode || isSimpleCallArgument(node.objectNode, depth)) {
2254
+ const args = node.argumentsNode.namedChildren;
2255
+ return args.length <= depth && args.every(isChildSimple);
2256
+ }
2257
+ return false;
2258
+ }
2259
+ if (node.type === "array_access") return isSimpleCallArgument(node.arrayNode, depth) && isSimpleCallArgument(node.indexNode, depth);
2260
+ if (node.type === "field_access") return isSimpleCallArgument(node.objectNode, depth) && isSimpleCallArgument(node.fieldNode, depth);
2261
+ if (node.type === "unary_expression") return isSimpleCallArgument(node.operandNode, depth);
2262
+ if (node.type === "method_reference" || node.type === "update_expression") {
2263
+ const [qualifierNode] = node.namedChildren;
2264
+ return isType(qualifierNode) || isSimpleCallArgument(qualifierNode, depth);
2265
+ }
2266
+ return false;
2267
+ }
2268
+ function isLiteral(node) {
2269
+ return [
2270
+ "true",
2271
+ "false",
2272
+ "null_literal",
2273
+ "binary_integer_literal",
2274
+ "decimal_floating_point_literal",
2275
+ "decimal_integer_literal",
2276
+ "hex_floating_point_literal",
2277
+ "hex_integer_literal",
2278
+ "octal_integer_literal",
2279
+ "character_literal"
2280
+ ].includes(node.type) || isStringLiteral(node);
2281
+ }
2282
+ const isSingleWordType = createTypeCheckFunction([
2283
+ "identifier",
2284
+ "this",
2285
+ "super"
2286
+ ]);
2287
+ function couldExpandArg(arg, lambdaChainRecursion = false) {
2288
+ if (arg.type === "array_creation_expression" && arg.valueNode && (arg.valueNode.namedChildren.length > 0 || arg.valueNode.comments)) return true;
2289
+ if (arg.type === "lambda_expression") {
2290
+ const { bodyNode: body } = arg;
2291
+ if (body.type === "block" || body.type === "array_creation_expression") return true;
2292
+ if (body.type === "lambda_expression" && couldExpandArg(body, true)) return true;
2293
+ if (!lambdaChainRecursion) {
2294
+ if (body.type === "ternary_expression") return true;
2295
+ if (body.type === "method_invocation" || body.type === "object_creation_expression") return true;
2296
+ }
2297
+ }
2298
+ return false;
2299
+ }
2300
+ function shouldExpandLastArg(args, options) {
2301
+ const lastArg = args.at(-1);
2302
+ const penultimateArg = args.at(-2);
2303
+ return !lastArg.comments?.some(({ leading, trailing }) => leading || trailing) && couldExpandArg(lastArg) && (!penultimateArg || penultimateArg.type !== lastArg.type) && (args.length !== 2 || penultimateArg.type !== "lambda_expression" || lastArg.type !== "array_creation_expression") && !(args.length > 1 && lastArg.type === "array_creation_expression" && lastArg.valueNode && isConciselyPrintedArray(lastArg.valueNode, options));
2304
+ }
2305
+ function shouldExpandFirstArg(args) {
2306
+ if (args.length !== 2) return false;
2307
+ const [firstArg, secondArg] = args;
2308
+ return !firstArg.comments && firstArg.type === "lambda_expression" && firstArg.bodyNode.type === "block" && secondArg.type !== "lambda_expression" && secondArg.type !== "ternary_expression" && isHopefullyShortCallArgument(secondArg) && !couldExpandArg(secondArg);
2309
+ }
2310
+ function isHopefullyShortCallArgument(node) {
2311
+ if ((node.type === "method_invocation" || node.type === "object_creation_expression") && node.argumentsNode.namedChildren.length > 1) return false;
2312
+ if (node.type === "binary_expression") return isSimpleCallArgument(node.leftNode, 1) && isSimpleCallArgument(node.rightNode, 1);
2313
+ return isSimpleCallArgument(node);
2314
+ }
2315
+ function printTernaryTest(path, print, operatorAtEnd) {
2316
+ const { node, parent } = path;
2317
+ const printed = path.call(print, "conditionNode");
2318
+ /**
2319
+ * a
2320
+ * ? b
2321
+ * : multiline
2322
+ * test
2323
+ * node
2324
+ * ^^ align(2)
2325
+ * ? d
2326
+ * : e
2327
+ *
2328
+ * With operators at the end there is no `: ` prefix to align under.
2329
+ */
2330
+ if (!operatorAtEnd && parent?.type === node.type && parent.alternativeNode === node) return align(2, printed);
2331
+ return printed;
2332
+ }
2333
+ function getExpressionChild(node) {
2334
+ switch (node.type) {
2335
+ case "assignment_expression": return node.rightNode;
2336
+ case "variable_declarator": return node.valueNode;
2337
+ case "unary_expression": return node.operandNode;
2338
+ case "return_statement":
2339
+ case "throw_statement":
2340
+ case "yield_statement": return node.namedChildren[0];
2341
+ default: return null;
2342
+ }
2343
+ }
2344
+ function shouldExtraIndentForTernaryExpression(path) {
2345
+ const { node } = path;
2346
+ let parent;
2347
+ let child = node;
2348
+ for (let ancestorCount = 0; !parent; ancestorCount++) {
2349
+ const node = path.getParentNode(ancestorCount);
2350
+ if (node.type === "array_access" && node.arrayNode === child || (node.type === "explicit_constructor_invocation" || node.type === "field_access" || node.type === "method_invocation") && node.objectNode === child || node.type === "method_reference" || node.type === "object_creation_expression") {
2351
+ child = node;
2352
+ continue;
2353
+ }
2354
+ if (node.type === "cast_expression" && node.valueNode === child) {
2355
+ parent = path.getParentNode(ancestorCount + 1);
2356
+ child = node;
2357
+ } else parent = node;
2358
+ }
2359
+ if (child === node) return false;
2360
+ return getExpressionChild(parent) === child;
2361
+ }
2362
+ function isStringLiteral(node) {
2363
+ return node.type === "string_literal" && !isTextBlock(node);
2364
+ }
2365
+ var ArgExpansionBailout = class extends Error {
2366
+ constructor(..._args) {
2367
+ super(..._args);
2368
+ this.name = "ArgExpansionBailout";
2369
+ }
2370
+ };
2371
+ // src/printers/interfaces.ts
2372
+ const { group: group$3, hardline: hardline$2, indent: indent$3, join: join$3, line: line$2 } = prettier_doc.builders;
2373
+ var interfaces_default = {
2374
+ interface_declaration(path, print, options) {
2375
+ const parts = ["interface ", path.call(print, "nameNode")];
2376
+ const extendsInterfacesIndex = path.node.namedChildren.findIndex(({ type }) => type === "extends_interfaces");
2377
+ const hasExtendsInterfaces = extendsInterfacesIndex !== -1;
2378
+ const hasPermits = hasChild(path, "permitsNode");
2379
+ const hasMultipleClauses = hasExtendsInterfaces && hasPermits;
2380
+ if (hasChild(path, "type_parametersNode")) {
2381
+ const typeParameters = path.call(print, "type_parametersNode");
2382
+ parts.push(hasMultipleClauses ? group$3(indent$3(typeParameters)) : group$3(typeParameters));
2383
+ }
2384
+ const separators = printDeclarationBodySeparators(hasExtendsInterfaces || hasPermits, path.node.bodyNode.namedChildren.length > 0, options);
2385
+ if (hasExtendsInterfaces || hasPermits) {
2386
+ const clauses = [];
2387
+ if (hasExtendsInterfaces) clauses.push(hardline$2, path.call(print, "namedChildren", extendsInterfacesIndex));
2388
+ if (hasPermits) clauses.push(line$2, path.call(print, "permitsNode"));
2389
+ const clauseGroup = [indent$3(clauses), separators.afterClauses];
2390
+ parts.push(hasMultipleClauses ? clauseGroup : group$3(clauseGroup));
2391
+ }
2392
+ return [
2393
+ ...printModifiers(path, print, "declarationOnly"),
2394
+ group$3(parts),
2395
+ separators.afterHeader,
2396
+ path.call(print, "bodyNode")
2397
+ ];
2398
+ },
2399
+ extends_interfaces(path, print) {
2400
+ const typeListIndex = path.node.namedChildren.findIndex(({ type }) => type === "type_list");
2401
+ return group$3(["extends", indent$3([line$2, path.call(print, "namedChildren", typeListIndex)])]);
2402
+ },
2403
+ interface_body(path, print, options) {
2404
+ return printBlock(path, printBodyDeclarations(path, print), options);
2405
+ },
2406
+ constant_declaration: printVariableDeclaration,
2407
+ annotation_type_declaration(path, print, options) {
2408
+ const parts = printModifiers(path, print);
2409
+ parts.push("@interface ", path.call(print, "nameNode"), printBlockSeparator(options), path.call(print, "bodyNode"));
2410
+ return parts;
2411
+ },
2412
+ annotation_type_body(path, print, options) {
2413
+ return printBlock(path, printBodyDeclarations(path, print), options);
2414
+ },
2415
+ annotation_type_element_declaration(path, print) {
2416
+ const parts = printModifiers(path, print);
2417
+ parts.push(path.call(print, "typeNode"), " ", path.call(print, "nameNode"), "()");
2418
+ if (hasChild(path, "dimensionsNode")) parts.push(path.call(print, "dimensionsNode"));
2419
+ if (hasChild(path, "valueNode")) parts.push(" default ", path.call(print, "valueNode"));
2420
+ parts.push(";");
2421
+ return parts;
2422
+ },
2423
+ annotation(path, print) {
2424
+ return [
2425
+ "@",
2426
+ path.call(print, "nameNode"),
2427
+ path.call(print, "argumentsNode")
2428
+ ];
2429
+ },
2430
+ marker_annotation(path, print) {
2431
+ return ["@", path.call(print, "nameNode")];
2432
+ },
2433
+ annotation_argument_list(path, print, options) {
2434
+ const args = path.map(print, "namedChildren");
2435
+ return args.length === 1 && path.node.namedChildren[0].type === "element_value_array_initializer" ? [
2436
+ "(",
2437
+ args[0],
2438
+ ")"
2439
+ ] : group$3(indentInParentheses(join$3([",", line$2], args), options));
2440
+ },
2441
+ element_value_pair(path, print) {
2442
+ return group$3([
2443
+ path.call(print, "keyNode"),
2444
+ " = ",
2445
+ path.call(print, "valueNode")
2446
+ ]);
2447
+ },
2448
+ element_value_array_initializer: printArrayInitializer
2449
+ };
2450
+ // src/printers/lexical-structure.ts
2451
+ const { group: group$2, hardline: hardline$1, indent: indent$2, join: join$2, softline } = prettier_doc.builders;
2452
+ var lexical_structure_default = {
2453
+ string_literal(path, print) {
2454
+ if (path.node.namedChildren.some(({ type }) => type === "string_interpolation") || !isTextBlock(path.node)) return path.map(print, "children");
2455
+ return printTextBlock(join$2(hardline$1, textBlockContents(path.node).split("\n")));
2456
+ },
2457
+ string_fragment: printValue,
2458
+ multiline_string_fragment: printValue,
2459
+ string_interpolation(path, print) {
2460
+ const expressionType = path.node.namedChildren[0].type;
2461
+ const expression = path.call(print, "namedChildren", 0);
2462
+ return expressionType === "binary_expression" || expressionType === "ternary_expression" ? group$2([
2463
+ "\\{",
2464
+ indent$2([softline, expression]),
2465
+ softline,
2466
+ "}"
2467
+ ]) : [
2468
+ "\\{",
2469
+ expression,
2470
+ "}"
2471
+ ];
2472
+ },
2473
+ escape_sequence: printValue,
2474
+ character_literal: printValue,
2475
+ binary_integer_literal: printValue,
2476
+ decimal_integer_literal: printValue,
2477
+ hex_integer_literal: printValue,
2478
+ octal_integer_literal: printValue,
2479
+ decimal_floating_point_literal: printValue,
2480
+ hex_floating_point_literal: printValue,
2481
+ null_literal: printValue,
2482
+ true: printValue,
2483
+ false: printValue,
2484
+ this: printValue,
2485
+ super: printValue,
2486
+ underscore_pattern: printValue,
2487
+ asterisk: printValue
2488
+ };
2489
+ // src/printers/names.ts
2490
+ var names_default = {
2491
+ identifier: printValue,
2492
+ type_identifier: printValue,
2493
+ scoped_identifier(path, print) {
2494
+ return [
2495
+ path.call(print, "scopeNode"),
2496
+ ".",
2497
+ path.call(print, "nameNode")
2498
+ ];
2499
+ },
2500
+ scoped_type_identifier(path, print) {
2501
+ return path.map((child) => child.node.type === "annotation" || child.node.type === "marker_annotation" ? [print(child), " "] : print(child), "children");
2502
+ }
2503
+ };
2504
+ // src/printers/packages-and-modules.ts
2505
+ const { group: group$1, hardline, indent: indent$1, join: join$1, line: line$1 } = prettier_doc.builders;
2506
+ var packages_and_modules_default = {
2507
+ program(path, print, options) {
2508
+ if (!path.node.namedChildren.length) return [printDanglingComments(path), hardline];
2509
+ const parts = [];
2510
+ if (path.node.namedChildren[0].type !== "import_declaration") parts.push(path.call(print, "namedChildren", 0));
2511
+ const moduleImports = [];
2512
+ const imports = [];
2513
+ const otherDeclarations = [];
2514
+ path.each((child) => {
2515
+ const doc = print(child);
2516
+ if (child.node.type === "import_declaration") {
2517
+ const names = extractNames(child.node.namedChildren[0]);
2518
+ if (child.node.namedChildren.some(({ type }) => type === "asterisk")) names.push("*");
2519
+ const modifier = child.node.children[1].type;
2520
+ (modifier === "module" ? moduleImports : imports).push({
2521
+ doc,
2522
+ names,
2523
+ isStatic: modifier === "static"
2524
+ });
2525
+ } else if (!child.isFirst) otherDeclarations.push(doc);
2526
+ }, "namedChildren");
2527
+ parts.push(...[moduleImports.sort(compareFqn), ...groupImports(imports, options.importOrder)].filter((group) => group.length).map((group) => join$1(hardline, group.map(({ doc }) => doc))), ...otherDeclarations);
2528
+ return [...join$1([hardline, hardline], parts), hardline];
2529
+ },
2530
+ package_declaration(path, print) {
2531
+ const annotations = [];
2532
+ const identifier = [];
2533
+ path.each((child) => {
2534
+ switch (child.node.type) {
2535
+ case "annotation":
2536
+ case "marker_annotation":
2537
+ annotations.push(print(child));
2538
+ break;
2539
+ case "identifier":
2540
+ case "scoped_identifier": identifier.push(print(child));
2541
+ }
2542
+ }, "namedChildren");
2543
+ return join$1(hardline, [...annotations, [
2544
+ "package ",
2545
+ ...identifier,
2546
+ ";"
2547
+ ]]);
2548
+ },
2549
+ import_declaration(path, print) {
2550
+ const declaration = ["import "];
2551
+ const modifier = path.node.children[1].type;
2552
+ if (modifier === "module" || modifier === "static") declaration.push(modifier, " ");
2553
+ const identifierIndex = path.node.namedChildren.findIndex(({ type }) => type === "identifier" || type === "scoped_identifier");
2554
+ declaration.push(path.call(print, "namedChildren", identifierIndex));
2555
+ if (path.node.namedChildren.some(({ type }) => type === "asterisk")) declaration.push(".*");
2556
+ declaration.push(";");
2557
+ return declaration;
2558
+ },
2559
+ module_declaration(path, print, options) {
2560
+ const parts = [];
2561
+ path.each((child) => {
2562
+ if (child.node.type === "annotation" || child.node.type === "marker_annotation") parts.push(print(child));
2563
+ }, "namedChildren");
2564
+ if (path.node.children.some(({ type }) => type === "open")) parts.push("open");
2565
+ parts.push("module", path.call(print, "nameNode"));
2566
+ return [
2567
+ join$1(" ", parts),
2568
+ printBlockSeparator(options),
2569
+ path.call(print, "bodyNode")
2570
+ ];
2571
+ },
2572
+ module_body(path, print, options) {
2573
+ return printBlock(path, path.map((child) => child.previous && child.node.start.row > child.previous.end.row + 1 ? [hardline, print(child)] : print(child), "namedChildren"), options);
2574
+ },
2575
+ requires_module_directive(path, print) {
2576
+ const parts = ["requires"];
2577
+ path.each((child) => {
2578
+ if (child.node.type === "requires_modifier") parts.push(print(child));
2579
+ }, "namedChildren");
2580
+ parts.push(path.call(print, "moduleNode"));
2581
+ return [...join$1(" ", parts), ";"];
2582
+ },
2583
+ exports_module_directive: printToModuleNamesDirective,
2584
+ opens_module_directive: printToModuleNamesDirective,
2585
+ uses_module_directive(path, print) {
2586
+ return [
2587
+ "uses ",
2588
+ path.call(print, "typeNode"),
2589
+ ";"
2590
+ ];
2591
+ },
2592
+ provides_module_directive(path, print) {
2593
+ const [provided, ...providers] = path.map(print, "namedChildren");
2594
+ return [
2595
+ "provides ",
2596
+ provided,
2597
+ group$1(indent$1([line$1, group$1(indent$1([
2598
+ "with",
2599
+ line$1,
2600
+ ...join$1([",", line$1], providers)
2601
+ ]))])),
2602
+ ";"
2603
+ ];
2604
+ },
2605
+ requires_modifier: printValue
2606
+ };
2607
+ function extractNames(node) {
2608
+ return node.type === "identifier" ? [node.value] : [...extractNames(node.scopeNode), node.nameNode.value];
2609
+ }
2610
+ const STATIC_PREFIX = "static ";
2611
+ const CATCH_ALL_PREFIX = "";
2612
+ function groupImports(imports, importOrder) {
2613
+ if (!importOrder) return [imports.filter(({ isStatic }) => isStatic), imports.filter(({ isStatic }) => !isStatic)].filter((group) => group.length).map((group) => group.sort(compareFqn));
2614
+ const groups = parseImportOrder(importOrder);
2615
+ const prefixes = groups.flat();
2616
+ const importsByPrefix = /* @__PURE__ */ new Map();
2617
+ for (const entry of imports) {
2618
+ const key = importKey(entry);
2619
+ const prefix = prefixes.filter((candidate) => key.startsWith(candidate)).reduce((best, candidate) => candidate.length > best.length ? candidate : best);
2620
+ const bucket = importsByPrefix.get(prefix);
2621
+ if (bucket) bucket.push({
2622
+ key,
2623
+ entry
2624
+ });
2625
+ else importsByPrefix.set(prefix, [{
2626
+ key,
2627
+ entry
2628
+ }]);
2501
2629
  }
2502
- if (!isBlock || previousComment?.hasLineSuffix) return {
2503
- doc: [lineSuffix([" ", printed]), breakParent],
2504
- isBlock,
2505
- hasLineSuffix: true
2506
- };
2507
- return {
2508
- doc: [" ", printed],
2509
- isBlock,
2510
- hasLineSuffix: false
2511
- };
2630
+ return groups.map((group) => group.flatMap((prefix) => (importsByPrefix.get(prefix) ?? []).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0).map(({ entry }) => entry))).filter((group) => group.length);
2512
2631
  }
2513
- function printLeadingComments(path) {
2514
- if (!hasChild(path, "comments")) return [];
2515
- const docs = [];
2516
- path.each((path) => {
2517
- const { node: comment } = path;
2518
- if (!comment.leading) return;
2519
- docs.push(printLeadingComment(path));
2520
- }, "comments");
2521
- return docs;
2632
+ /**
2633
+ * Parses an import order in Spotless's format: groups separated by `,` are
2634
+ * printed with blank lines between them, prefixes joined by `|` share a group,
2635
+ * `#` marks a static prefix, and an empty prefix catches everything else.
2636
+ * Each import belongs to its longest matching prefix.
2637
+ */
2638
+ function parseImportOrder(importOrder) {
2639
+ const knownPrefixes = /* @__PURE__ */ new Set();
2640
+ const groups = importOrder.split(",").map((group) => group.split("|").map((prefix) => prefix.startsWith("#") ? STATIC_PREFIX + prefix.slice(1) : prefix).filter((prefix) => {
2641
+ if (knownPrefixes.has(prefix)) return false;
2642
+ knownPrefixes.add(prefix);
2643
+ return true;
2644
+ }));
2645
+ if (!knownPrefixes.has(STATIC_PREFIX)) {
2646
+ const lastStaticGroupIndex = groups.findLastIndex((group) => group.some((prefix) => prefix.startsWith(STATIC_PREFIX)));
2647
+ groups.splice(Math.max(lastStaticGroupIndex, 0), 0, [STATIC_PREFIX]);
2648
+ }
2649
+ if (!knownPrefixes.has(CATCH_ALL_PREFIX)) groups.push([CATCH_ALL_PREFIX]);
2650
+ return groups;
2522
2651
  }
2523
- function printTrailingComments(path) {
2524
- if (!hasChild(path, "comments")) return [];
2525
- const docs = [];
2526
- let printedTrailingComment;
2527
- path.each((path) => {
2528
- const { node: comment } = path;
2529
- if (!comment.trailing) return;
2530
- printedTrailingComment = printTrailingComment(path, printedTrailingComment);
2531
- docs.push(printedTrailingComment.doc);
2532
- }, "comments");
2533
- return docs;
2652
+ function importKey({ names, isStatic }) {
2653
+ return (isStatic ? STATIC_PREFIX : "") + names.join(".");
2534
2654
  }
2535
- function printCommentsSeparately(path) {
2536
- return {
2537
- leading: printLeadingComments(path),
2538
- trailing: printTrailingComments(path)
2539
- };
2655
+ function compareFqn({ names: a }, { names: b }) {
2656
+ const minParts = Math.min(a.length, b.length);
2657
+ for (let i = 0; i < minParts; i++) {
2658
+ const imageA = a[i];
2659
+ const imageB = b[i];
2660
+ if (imageA < imageB) return -1;
2661
+ else if (imageA > imageB) return 1;
2662
+ }
2663
+ return a.length - b.length;
2540
2664
  }
2541
- function printComments(path, doc) {
2542
- const leading = printLeadingComments(path);
2543
- const trailing = printTrailingComments(path);
2544
- return leading.length || trailing.length ? [
2545
- leading,
2546
- doc,
2547
- trailing
2548
- ] : doc;
2665
+ function printToModuleNamesDirective(path, print) {
2666
+ const directive = [
2667
+ path.node.type === "exports_module_directive" ? "exports" : "opens",
2668
+ " ",
2669
+ path.call(print, "packageNode")
2670
+ ];
2671
+ if (path.node.modulesNodes.length) {
2672
+ const moduleNames = join$1([",", line$1], path.map(print, "modulesNodes"));
2673
+ directive.push(group$1(indent$1([line$1, group$1(indent$1([
2674
+ "to",
2675
+ line$1,
2676
+ ...moduleNames
2677
+ ]))])));
2678
+ }
2679
+ directive.push(";");
2680
+ return directive;
2549
2681
  }
2550
- //#endregion
2551
- //#region src/parser.ts
2552
- var parser_default = {
2553
- async parse(text) {
2554
- const tree = (await parser).parse(text);
2555
- const { rootNode } = tree;
2556
- if (rootNode.hasError) throw new Error("Failed to parse: " + rootNode);
2557
- const ast = processTree(rootNode);
2558
- determinePrettierIgnoreRanges(ast);
2559
- tree.delete();
2560
- return ast;
2682
+ // src/printers/types-values-and-variables.ts
2683
+ const { group, indent, join, line } = prettier_doc.builders;
2684
+ var types_values_and_variables_default = {
2685
+ boolean_type: printValue,
2686
+ integral_type: printValue,
2687
+ floating_point_type: printValue,
2688
+ void_type: printValue,
2689
+ array_type(path, print) {
2690
+ return [path.call(print, "elementNode"), path.call(print, "dimensionsNode")];
2561
2691
  },
2562
- astFormat: "java",
2563
- hasPragma(text) {
2564
- return /^\/\*\*\n\s+\*\s@(format|prettier)\n\s+\*\//.test(text);
2692
+ annotated_type(path, print) {
2693
+ return join(" ", path.map(print, "children"));
2565
2694
  },
2566
- locStart(node) {
2567
- return node.start.index;
2695
+ dimensions(path, print) {
2696
+ return path.map((child) => {
2697
+ if (child.node.isNamed) return [
2698
+ ...child.isFirst ? [" "] : [],
2699
+ print(child),
2700
+ " "
2701
+ ];
2702
+ return child.node.value;
2703
+ }, "children");
2568
2704
  },
2569
- locEnd(node) {
2570
- return node.end.index;
2705
+ type_parameter(path, print) {
2706
+ return join(" ", path.map(print, "children"));
2707
+ },
2708
+ type_bound(path, print) {
2709
+ const [firstType, ...restTypes] = path.map(print, "namedChildren");
2710
+ const bound = ["extends ", firstType];
2711
+ if (restTypes.length) bound.push(group(indent([
2712
+ line,
2713
+ "& ",
2714
+ ...join([line, "& "], restTypes)
2715
+ ])));
2716
+ return bound;
2717
+ },
2718
+ type_arguments: printTypeParameters,
2719
+ wildcard(path, print) {
2720
+ return join(" ", path.map(print, "children"));
2571
2721
  }
2572
2722
  };
2573
- const parser = (async () => {
2574
- await web_tree_sitter.Parser.init();
2575
- const parser = new web_tree_sitter.Parser();
2576
- const Java = await web_tree_sitter.Language.load(new URL("./tree-sitter-java_orchard.wasm", require("url").pathToFileURL(__filename).href));
2577
- parser.setLanguage(Java);
2578
- return parser;
2579
- })();
2580
- const isParenthesizedParent = createTypeCheckFunction([
2581
- "do_statement",
2582
- "if_statement",
2583
- "switch_expression",
2584
- "synchronized_statement",
2585
- "try_statement",
2586
- "try_with_resources_statement",
2587
- "while_statement"
2588
- ]);
2589
- function processTree(node, fieldName = null, comments) {
2590
- const { type, isNamed, text: value, startPosition, endPosition } = node;
2591
- const javaNode = {
2592
- type,
2593
- isNamed,
2594
- value,
2595
- start: {
2596
- index: node.startIndex,
2597
- row: startPosition.row,
2598
- column: startPosition.column
2599
- },
2600
- end: {
2601
- index: node.endIndex,
2602
- row: endPosition.row,
2603
- column: endPosition.column
2604
- },
2605
- children: [],
2606
- namedChildren: [],
2607
- fieldName
2608
- };
2609
- if (!comments) comments = javaNode.comments = [];
2610
- if (!javaNode.isNamed) return javaNode;
2611
- const multiFields = multiFieldsByType[node.type];
2612
- if (multiFields) Object.keys(multiFields).forEach((name) => javaNode[`${name}Nodes`] = []);
2613
- node.children.forEach((child, index) => {
2614
- const fieldName = node.fieldNameForChild(index);
2615
- (child.type === "parenthesized_expression" && !isParenthesizedParent(javaNode) ? child.namedChildren : [child]).forEach((child) => {
2616
- const { type, text: value, startPosition, endPosition } = child;
2617
- if (type === "block_comment" || type === "line_comment") comments.push({
2618
- type,
2619
- value,
2620
- start: {
2621
- index: child.startIndex,
2622
- row: startPosition.row,
2623
- column: startPosition.column
2624
- },
2625
- end: {
2626
- index: child.endIndex,
2627
- row: endPosition.row,
2628
- column: endPosition.column
2629
- },
2630
- leading: false,
2631
- trailing: false,
2632
- printed: false
2633
- });
2634
- else {
2635
- const javaChild = processTree(child, fieldName, comments);
2636
- javaNode.children.push(javaChild);
2637
- if (javaChild.isNamed) javaNode.namedChildren.push(javaChild);
2638
- if (fieldName) {
2639
- if (multiFields?.[fieldName]) javaNode[`${fieldName}Nodes`].push(javaChild);
2640
- else javaNode[`${fieldName}Node`] = javaChild;
2641
- }
2642
- }
2643
- });
2644
- });
2645
- return javaNode;
2723
+ // src/printers/index.ts
2724
+ const printersByNodeType = {
2725
+ ERROR(path) {
2726
+ throw new Error(`Failed to parse: "${printValue(path)}"`);
2727
+ },
2728
+ ...arrays_default,
2729
+ ...blocks_and_statements_default,
2730
+ ...classes_default,
2731
+ ...expressions_default,
2732
+ ...interfaces_default,
2733
+ ...lexical_structure_default,
2734
+ ...names_default,
2735
+ ...packages_and_modules_default,
2736
+ ...types_values_and_variables_default
2737
+ };
2738
+ function printerForNodeType(type) {
2739
+ return printersByNodeType[type];
2740
+ }
2741
+ // src/printer.ts
2742
+ var printer_default = {
2743
+ print(path, options, print, args) {
2744
+ if (!hasNamedNode(path)) return printValue(path);
2745
+ const doc = printerForNodeType(path.node.type)(path, print, options, args);
2746
+ return needsParentheses(path) ? [
2747
+ "(",
2748
+ doc,
2749
+ ")"
2750
+ ] : doc;
2751
+ },
2752
+ embed(path, options) {
2753
+ return hasType(path, "string_literal") ? embedTextBlock(path, options) : null;
2754
+ },
2755
+ hasPrettierIgnore(path) {
2756
+ return path.node.comments?.some(isPrettierIgnore) === true || canAttachComment(path.node, path.parent ? [path.parent] : []) && isFullyBetweenPrettierIgnore(path);
2757
+ },
2758
+ canAttachComment,
2759
+ isBlockComment(node) {
2760
+ return node.type === "block_comment";
2761
+ },
2762
+ printComment(commentPath) {
2763
+ return printComment(commentPath.node);
2764
+ },
2765
+ getCommentChildNodes(node) {
2766
+ return node.isNamed ? node.children : [];
2767
+ },
2768
+ handleComments: {
2769
+ ownLine: handleLineComment,
2770
+ endOfLine: handleLineComment,
2771
+ remaining: handleRemainingComment
2772
+ },
2773
+ getVisitorKeys() {
2774
+ return ["namedChildren"];
2775
+ }
2776
+ };
2777
+ function hasNamedNode(path) {
2778
+ return path.node.isNamed;
2646
2779
  }
2647
- //#endregion
2648
- //#region src/index.ts
2780
+ // src/index.ts
2649
2781
  var src_default = {
2650
2782
  languages: [{
2651
2783
  name: "Java",
@@ -2664,5 +2796,4 @@ var src_default = {
2664
2796
  options: options_default,
2665
2797
  defaultOptions: { arrowParens: "avoid" }
2666
2798
  };
2667
- //#endregion
2668
2799
  module.exports = src_default;