prettier-plugin-java 2.6.8 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/comments.d.ts +17 -0
  2. package/dist/comments.js +199 -0
  3. package/dist/index.d.ts +543 -0
  4. package/dist/index.js +26 -63
  5. package/dist/options.d.ts +23 -0
  6. package/dist/options.js +247 -239
  7. package/dist/parser.d.ts +9 -0
  8. package/dist/parser.js +24 -4
  9. package/dist/printer.d.ts +18 -0
  10. package/dist/printer.js +39 -5
  11. package/dist/printers/arrays.d.ts +9 -0
  12. package/dist/printers/arrays.js +8 -24
  13. package/dist/printers/blocks-and-statements.d.ts +117 -0
  14. package/dist/printers/blocks-and-statements.js +316 -412
  15. package/dist/printers/classes.d.ts +157 -0
  16. package/dist/printers/classes.js +422 -685
  17. package/dist/printers/expressions.d.ts +134 -0
  18. package/dist/printers/expressions.js +549 -555
  19. package/dist/printers/helpers.d.ts +71 -0
  20. package/dist/printers/helpers.js +233 -0
  21. package/dist/printers/index.d.ts +2 -0
  22. package/dist/printers/index.js +13 -0
  23. package/dist/printers/interfaces.d.ts +62 -0
  24. package/dist/printers/interfaces.js +146 -211
  25. package/dist/printers/lexical-structure.d.ts +14 -0
  26. package/dist/printers/lexical-structure.js +26 -28
  27. package/dist/printers/names.d.ts +12 -0
  28. package/dist/printers/names.js +11 -29
  29. package/dist/printers/packages-and-modules.d.ts +46 -0
  30. package/dist/printers/packages-and-modules.js +157 -159
  31. package/dist/printers/types-values-and-variables.d.ts +46 -0
  32. package/dist/printers/types-values-and-variables.js +86 -149
  33. package/package.json +5 -8
  34. package/dist/base-cst-printer.js +0 -55
  35. package/dist/cst-printer.js +0 -29
  36. package/dist/printers/comments/comments-utils.js +0 -21
  37. package/dist/printers/comments/format-comments.js +0 -171
  38. package/dist/printers/comments/handle-comments.js +0 -102
  39. package/dist/printers/prettier-builder.js +0 -45
  40. package/dist/printers/printer-utils.js +0 -598
  41. package/dist/types/utils.js +0 -20
  42. package/dist/utils/index.js +0 -2
  43. package/dist/utils/isEmptyDoc.js +0 -4
  44. package/dist/utils/printArgumentListWithBraces.js +0 -37
  45. package/index.d.ts +0 -4
@@ -1,591 +1,585 @@
1
- import forEach from "lodash/forEach.js";
2
1
  import { builders, utils } from "prettier/doc";
3
- import { BaseCstPrettierPrinter } from "../base-cst-printer.js";
4
- import { isAnnotationCstNode } from "../types/utils.js";
5
- import { printArgumentListWithBraces } from "../utils/index.js";
6
- import { hasLeadingComments } from "./comments/comments-utils.js";
7
- import { printTokenWithComments } from "./comments/format-comments.js";
8
- import { handleCommentsBinaryExpression, handleCommentsParameters } from "./comments/handle-comments.js";
9
- import { concat, dedent, group, indent, indentIfBreak } from "./prettier-builder.js";
10
- import { binary, findDeepElementInPartsArray, getOperators, isExplicitLambdaParameter, isUniqueMethodInvocation, putIntoBraces, rejectAndConcat, rejectAndJoin, rejectAndJoinSeps, sortAnnotationIdentifier, sortNodes, sortTokens } from "./printer-utils.js";
11
- const { breakParent, conditionalGroup, ifBreak, label, line, lineSuffixBoundary, softline } = builders;
2
+ import { call, definedKeys, each, findBaseIndent, flatMap, indentInParentheses, isBinaryExpression, isNonTerminal, isTerminal, map, onlyDefinedKey, printDanglingComments, printList, printName, printSingle } from "./helpers.js";
3
+ const { breakParent, conditionalGroup, group, hardline, ifBreak, indent, indentIfBreak, join, line, lineSuffixBoundary, softline } = builders;
12
4
  const { removeLines, willBreak } = utils;
13
- export class ExpressionsPrettierVisitor extends BaseCstPrettierPrinter {
14
- expression(ctx, params) {
15
- const expression = this.visitSingle(ctx, params);
16
- return (params === null || params === void 0 ? void 0 : params.hug) && expression.label !== undefined
17
- ? label(expression.label, expression)
18
- : expression;
19
- }
20
- lambdaExpression(ctx, params) {
21
- const lambdaParameters = group(this.visit(ctx.lambdaParameters));
22
- const lambdaBody = this.visit(ctx.lambdaBody);
23
- const isLambdaBodyABlock = ctx.lambdaBody[0].children.block !== undefined;
24
- const suffix = [
25
- " ",
26
- ctx.Arrow[0],
27
- ...(isLambdaBodyABlock
28
- ? [" ", lambdaBody]
29
- : [group([indent([line, lambdaBody]), (params === null || params === void 0 ? void 0 : params.hug) ? softline : ""])])
30
- ];
31
- if (params === null || params === void 0 ? void 0 : params.hug) {
32
- return willBreak(lambdaParameters)
33
- ? label({ huggable: false }, concat([lambdaParameters, ...suffix]))
34
- : concat([removeLines(lambdaParameters), ...suffix]);
35
- }
36
- return concat([lambdaParameters, ...suffix]);
37
- }
38
- lambdaParameters(ctx) {
39
- if (ctx.lambdaParametersWithBraces) {
40
- return this.visitSingle(ctx);
41
- }
42
- return printTokenWithComments(this.getSingle(ctx));
43
- }
44
- lambdaParametersWithBraces(ctx) {
45
- var _a, _b, _c, _d, _e, _f;
46
- const lambdaParameters = (_f = (_c = (_b = (_a = ctx.lambdaParameterList) === null || _a === void 0 ? void 0 : _a[0].children.normalLambdaParameterList) === null || _b === void 0 ? void 0 : _b[0].children.normalLambdaParameter) !== null && _c !== void 0 ? _c : (_e = (_d = ctx.lambdaParameterList) === null || _d === void 0 ? void 0 : _d[0].children.conciseLambdaParameterList) === null || _e === void 0 ? void 0 : _e[0].children.conciseLambdaParameter) !== null && _f !== void 0 ? _f : [];
47
- handleCommentsParameters(ctx.LBrace[0], lambdaParameters, ctx.RBrace[0]);
48
- const lambdaParameterList = this.visit(ctx.lambdaParameterList);
49
- if (findDeepElementInPartsArray(lambdaParameterList, ",")) {
50
- return concat([
51
- ctx.LBrace[0],
52
- indent([softline, lambdaParameterList]),
53
- softline,
54
- ctx.RBrace[0]
55
- ]);
5
+ export default {
6
+ expression: printSingle,
7
+ lambdaExpression(path, print, _, args = {}) {
8
+ var _a;
9
+ const hug = (_a = args.hug) !== null && _a !== void 0 ? _a : false;
10
+ const parameters = call(path, print, "lambdaParameters");
11
+ const expression = [hug ? removeLines(parameters) : parameters, " ->"];
12
+ const lambdaExpression = path.node.children.lambdaBody[0].children.expression;
13
+ const body = call(path, print, "lambdaBody");
14
+ if (lambdaExpression) {
15
+ const suffix = indent([line, body]);
16
+ expression.push(group(hug ? [suffix, softline] : suffix));
56
17
  }
57
- // removing braces when only no comments attached
58
- if ((ctx.LBrace &&
59
- ctx.RBrace &&
60
- (!lambdaParameterList || isExplicitLambdaParameter(ctx))) ||
61
- ctx.LBrace[0].leadingComments ||
62
- ctx.LBrace[0].trailingComments ||
63
- ctx.RBrace[0].leadingComments ||
64
- ctx.RBrace[0].trailingComments) {
65
- return rejectAndConcat([
66
- ctx.LBrace[0],
67
- lambdaParameterList,
68
- ctx.RBrace[0]
69
- ]);
18
+ else {
19
+ expression.push(" ", body);
70
20
  }
71
- return lambdaParameterList;
72
- }
73
- lambdaParameterList(ctx) {
74
- return this.visitSingle(ctx);
75
- }
76
- conciseLambdaParameterList(ctx) {
21
+ return expression;
22
+ },
23
+ lambdaParameters(path, print, options) {
24
+ const parameters = printSingle(path, print);
25
+ return !path.node.children.lambdaParametersWithBraces &&
26
+ options.arrowParens === "always"
27
+ ? ["(", parameters, ")"]
28
+ : parameters;
29
+ },
30
+ lambdaParametersWithBraces(path, print, options) {
77
31
  var _a;
78
- const conciseLambdaParameters = this.mapVisit(ctx.conciseLambdaParameter);
79
- const commas = (_a = ctx.Comma) === null || _a === void 0 ? void 0 : _a.map(comma => concat([comma, line]));
80
- return rejectAndJoinSeps(commas, conciseLambdaParameters);
81
- }
82
- normalLambdaParameterList(ctx) {
83
- var _a;
84
- const normalLambdaParameter = this.mapVisit(ctx.normalLambdaParameter);
85
- const commas = (_a = ctx.Comma) === null || _a === void 0 ? void 0 : _a.map(comma => concat([comma, line]));
86
- return rejectAndJoinSeps(commas, normalLambdaParameter);
87
- }
88
- normalLambdaParameter(ctx) {
89
- return this.visitSingle(ctx);
90
- }
91
- regularLambdaParameter(ctx) {
92
- const variableModifier = this.mapVisit(ctx.variableModifier);
93
- const lambdaParameterType = this.visit(ctx.lambdaParameterType);
94
- const variableDeclaratorId = this.visit(ctx.variableDeclaratorId);
95
- return rejectAndJoin(" ", [
96
- rejectAndJoin(" ", variableModifier),
97
- lambdaParameterType,
98
- variableDeclaratorId
99
- ]);
100
- }
101
- lambdaParameterType(ctx) {
102
- if (ctx.unannType) {
103
- return this.visitSingle(ctx);
32
+ const { lambdaParameterList } = path.node.children;
33
+ if (!lambdaParameterList) {
34
+ return "()";
104
35
  }
105
- return printTokenWithComments(this.getSingle(ctx));
106
- }
107
- conciseLambdaParameter(ctx) {
108
- return printTokenWithComments(this.getSingle(ctx));
109
- }
110
- lambdaBody(ctx) {
111
- return this.visitSingle(ctx);
112
- }
113
- conditionalExpression(ctx, params) {
114
- const binaryExpression = this.visit(ctx.binaryExpression, params);
115
- if (ctx.QuestionMark) {
116
- const expression1 = this.visit(ctx.expression[0]);
117
- const expression2 = this.visit(ctx.expression[1]);
118
- return indent(group(rejectAndConcat([
119
- rejectAndJoin(line, [
120
- binaryExpression,
121
- rejectAndJoin(" ", [ctx.QuestionMark[0], expression1]),
122
- rejectAndJoin(" ", [ctx.Colon[0], expression2])
123
- ])
124
- ])));
36
+ const { conciseLambdaParameterList, normalLambdaParameterList } = lambdaParameterList[0].children;
37
+ const parameterCount = ((_a = conciseLambdaParameterList === null || conciseLambdaParameterList === void 0 ? void 0 : conciseLambdaParameterList[0].children.conciseLambdaParameter) !== null && _a !== void 0 ? _a : normalLambdaParameterList === null || normalLambdaParameterList === void 0 ? void 0 : normalLambdaParameterList[0].children.normalLambdaParameter).length;
38
+ const parameters = call(path, print, "lambdaParameterList");
39
+ if (parameterCount > 1) {
40
+ return indentInParentheses(parameters);
125
41
  }
126
- return binaryExpression;
127
- }
128
- binaryExpression(ctx, params) {
129
- var _a, _b, _c, _d;
130
- handleCommentsBinaryExpression(ctx);
131
- const sortedNodes = sortNodes([
132
- ctx.pattern,
133
- ctx.referenceType,
134
- ctx.expression,
135
- ctx.unaryExpression
42
+ return conciseLambdaParameterList && options.arrowParens === "avoid"
43
+ ? parameters
44
+ : ["(", parameters, ")"];
45
+ },
46
+ lambdaParameterList: printSingle,
47
+ conciseLambdaParameterList(path, print) {
48
+ return printList(path, print, "conciseLambdaParameter");
49
+ },
50
+ normalLambdaParameterList(path, print) {
51
+ return printList(path, print, "normalLambdaParameter");
52
+ },
53
+ normalLambdaParameter: printSingle,
54
+ regularLambdaParameter(path, print) {
55
+ return join(" ", [
56
+ ...map(path, print, "variableModifier"),
57
+ call(path, print, "lambdaParameterType"),
58
+ call(path, print, "variableDeclaratorId")
136
59
  ]);
137
- const tokens = sortTokens(getOperators(ctx));
138
- const hasTokens = tokens.length > 0;
139
- const nodeParams = sortedNodes.length === 1 ? params : undefined;
140
- const nodes = [];
141
- for (let i = 0; i < sortedNodes.length; i++) {
142
- const node = this.visit(sortedNodes[i], nodeParams);
143
- const isAssignment = ((_b = (_a = tokens[i]) === null || _a === void 0 ? void 0 : _a.tokenType.CATEGORIES) === null || _b === void 0 ? void 0 : _b.find(({ name }) => name === "AssignmentOperator")) !== undefined;
144
- if (!isAssignment) {
145
- nodes.push(node);
146
- continue;
60
+ },
61
+ lambdaParameterType: printSingle,
62
+ conciseLambdaParameter: printSingle,
63
+ lambdaBody: printSingle,
64
+ conditionalExpression(path, print) {
65
+ const binaryExpression = call(path, print, "binaryExpression");
66
+ return path.node.children.QuestionMark
67
+ ? group(indent(join(line, [
68
+ binaryExpression,
69
+ ["? ", call(path, print, "expression", 0)],
70
+ [": ", call(path, print, "expression", 1)]
71
+ ])))
72
+ : binaryExpression;
73
+ },
74
+ binaryExpression(path, print, options) {
75
+ const { children } = path.node;
76
+ const operands = flatMap(path, print, definedKeys(children, [
77
+ "expression",
78
+ "pattern",
79
+ "referenceType",
80
+ "unaryExpression"
81
+ ]));
82
+ const operators = flatMap(path, operatorPath => {
83
+ const { node } = operatorPath;
84
+ let image;
85
+ if (isTerminal(node)) {
86
+ image = node.image;
87
+ }
88
+ else if (node.children.Less) {
89
+ image = "<<";
147
90
  }
148
- const [equals] = tokens.splice(i, 1);
149
- const expression = sortedNodes[++i];
150
- const nextNode = this.visit(expression);
151
- const conditionalExpression = (_c = expression.children.conditionalExpression) === null || _c === void 0 ? void 0 : _c[0].children;
152
- const binaryExpression = (_d = conditionalExpression === null || conditionalExpression === void 0 ? void 0 : conditionalExpression.binaryExpression) === null || _d === void 0 ? void 0 : _d[0].children;
153
- const breakAfterOperator = (conditionalExpression === null || conditionalExpression === void 0 ? void 0 : conditionalExpression.QuestionMark) === undefined &&
154
- binaryExpression !== undefined &&
155
- getOperators(binaryExpression).length > 0;
156
- if (breakAfterOperator) {
157
- nodes.push(concat([node, " ", equals, group(indent([line, nextNode]))]));
158
- continue;
91
+ else {
92
+ image = node.children.Greater.length === 2 ? ">>" : ">>>";
159
93
  }
160
- const groupId = Symbol("assignment");
161
- nodes.push(concat([
162
- node,
163
- " ",
164
- equals,
165
- indent(group(line, { id: groupId })),
166
- indentIfBreak(nextNode, { groupId })
167
- ]));
94
+ return { image, doc: print(operatorPath) };
95
+ }, definedKeys(children, [
96
+ "AssignmentOperator",
97
+ "BinaryOperator",
98
+ "Instanceof",
99
+ "shiftOperator"
100
+ ]));
101
+ const hasNonAssignmentOperators = (operators.length > 0 && !children.AssignmentOperator) ||
102
+ (children.expression !== undefined &&
103
+ isBinaryExpression(children.expression[0]));
104
+ return binary(operands, operators, {
105
+ hasNonAssignmentOperators,
106
+ isRoot: true,
107
+ operatorPosition: options.experimentalOperatorPosition
108
+ });
109
+ },
110
+ unaryExpression(path, print) {
111
+ return [
112
+ ...map(path, print, "UnaryPrefixOperator"),
113
+ call(path, print, "primary"),
114
+ ...map(path, print, "UnarySuffixOperator")
115
+ ];
116
+ },
117
+ unaryExpressionNotPlusMinus(path, print) {
118
+ const { children } = path.node;
119
+ const expression = [];
120
+ if (children.UnaryPrefixOperatorNotPlusMinus) {
121
+ expression.push(...map(path, print, "UnaryPrefixOperatorNotPlusMinus"));
168
122
  }
169
- const content = binary(nodes, tokens, true);
170
- return hasTokens && (params === null || params === void 0 ? void 0 : params.addParenthesisToWrapStatement)
171
- ? group(concat([
172
- ifBreak("("),
173
- indent(concat([softline, content])),
174
- softline,
175
- ifBreak(")")
176
- ]))
177
- : content;
178
- }
179
- unaryExpression(ctx, params) {
180
- const unaryPrefixOperator = ctx.UnaryPrefixOperator
181
- ? ctx.UnaryPrefixOperator
182
- : [];
183
- const primary = this.visit(ctx.primary, params);
184
- const unarySuffixOperator = ctx.UnarySuffixOperator
185
- ? ctx.UnarySuffixOperator
186
- : [];
187
- return rejectAndConcat([
188
- rejectAndConcat(unaryPrefixOperator),
189
- primary,
190
- rejectAndConcat(unarySuffixOperator)
191
- ]);
192
- }
193
- unaryExpressionNotPlusMinus(ctx) {
194
- const unaryPrefixOperatorNotPlusMinus = ctx.UnaryPrefixOperatorNotPlusMinus // changed when moved to TS
195
- ? rejectAndJoin(" ", ctx.UnaryPrefixOperatorNotPlusMinus) // changed when moved to TS
196
- : "";
197
- const primary = this.visit(ctx.primary);
198
- const unarySuffixOperator = ctx.UnarySuffixOperator // changed when moved to TS
199
- ? rejectAndJoin(" ", ctx.UnarySuffixOperator) // changed when moved to TS
200
- : "";
201
- return rejectAndJoin(" ", [
202
- unaryPrefixOperatorNotPlusMinus,
203
- primary,
204
- unarySuffixOperator
205
- ]);
206
- }
207
- primary(ctx, params) {
208
- var _a, _b, _c, _d;
209
- const countMethodInvocation = isUniqueMethodInvocation(ctx.primarySuffix);
210
- const newExpression = (_a = ctx.primaryPrefix[0].children.newExpression) === null || _a === void 0 ? void 0 : _a[0].children;
211
- const isBreakableNewExpression = countMethodInvocation <= 1 &&
212
- this.isBreakableNewExpression(newExpression);
213
- const firstMethodInvocation = (_b = ctx.primarySuffix) === null || _b === void 0 ? void 0 : _b.map(suffix => { var _a; return (_a = suffix.children.methodInvocationSuffix) === null || _a === void 0 ? void 0 : _a[0].children; }).find(methodInvocationSuffix => methodInvocationSuffix);
214
- const fqnOrRefType = (_c = ctx.primaryPrefix[0].children.fqnOrRefType) === null || _c === void 0 ? void 0 : _c[0].children;
215
- const hasFqnRefPart = (fqnOrRefType === null || fqnOrRefType === void 0 ? void 0 : fqnOrRefType.fqnOrRefTypePartRest) !== undefined;
216
- const isCapitalizedIdentifier = this.isCapitalizedIdentifier(fqnOrRefType);
217
- const shouldBreakBeforeFirstMethodInvocation = countMethodInvocation > 1 && hasFqnRefPart && !isCapitalizedIdentifier;
218
- const shouldBreakBeforeMethodInvocations = shouldBreakBeforeFirstMethodInvocation ||
219
- countMethodInvocation > 2 ||
220
- (countMethodInvocation > 1 && !!newExpression) ||
221
- !(firstMethodInvocation === null || firstMethodInvocation === void 0 ? void 0 : firstMethodInvocation.argumentList);
222
- const primaryPrefix = this.visit(ctx.primaryPrefix, Object.assign(Object.assign({}, params), { shouldBreakBeforeFirstMethodInvocation }));
223
- const suffixes = this.getPrimarySuffixes(ctx, newExpression, isBreakableNewExpression, shouldBreakBeforeMethodInvocations);
224
- if (!newExpression && countMethodInvocation === 1) {
225
- return group(rejectAndConcat([
226
- primaryPrefix,
227
- suffixes[0],
228
- indent(rejectAndConcat(suffixes.slice(1)))
229
- ]));
123
+ expression.push(call(path, print, "primary"));
124
+ if (children.UnarySuffixOperator) {
125
+ expression.push(...map(path, print, "UnarySuffixOperator"));
230
126
  }
231
- const methodInvocation = (_d = ctx.primarySuffix) === null || _d === void 0 ? void 0 : _d[0].children.methodInvocationSuffix;
232
- const isMethodInvocationWithArguments = (methodInvocation === null || methodInvocation === void 0 ? void 0 : methodInvocation[0].children.argumentList) !== undefined;
233
- const isUnqualifiedMethodInvocation = methodInvocation !== undefined && !(fqnOrRefType === null || fqnOrRefType === void 0 ? void 0 : fqnOrRefType.Dot);
234
- return group(rejectAndConcat([
235
- primaryPrefix,
236
- isCapitalizedIdentifier || isUnqualifiedMethodInvocation
237
- ? suffixes.shift()
238
- : "",
239
- !isBreakableNewExpression &&
240
- (shouldBreakBeforeMethodInvocations || !isMethodInvocationWithArguments)
241
- ? indent(concat(suffixes))
242
- : concat(suffixes)
243
- ]));
244
- }
245
- primaryPrefix(ctx, params) {
246
- if (ctx.This || ctx.Void) {
247
- return printTokenWithComments(this.getSingle(ctx));
127
+ return join(" ", expression);
128
+ },
129
+ primary(path, print) {
130
+ var _a, _b;
131
+ const { children } = path.node;
132
+ if (!children.primarySuffix) {
133
+ return call(path, print, "primaryPrefix");
248
134
  }
249
- return this.visitSingle(ctx, params);
250
- }
251
- primarySuffix(ctx, params) {
252
- var _a;
253
- if (ctx.Dot) {
254
- if (ctx.This) {
255
- return rejectAndConcat([ctx.Dot[0], ctx.This[0]]);
135
+ const methodInvocations = children.primarySuffix
136
+ .filter(({ children }) => children.methodInvocationSuffix)
137
+ .map(({ children }) => children.methodInvocationSuffix[0].children);
138
+ const hasLambdaMethodParameter = methodInvocations.some(({ argumentList }) => argumentList === null || argumentList === void 0 ? void 0 : argumentList[0].children.expression.some(({ children }) => children.lambdaExpression));
139
+ const prefixIsCallExpression = children.primaryPrefix[0].children.newExpression;
140
+ const callExpressionCount = methodInvocations.length +
141
+ (prefixIsCallExpression ? 1 : 0) +
142
+ children.primarySuffix.filter(({ children }) => children.unqualifiedClassInstanceCreationExpression).length;
143
+ const fqnOrRefType = (_a = children.primaryPrefix[0].children.fqnOrRefType) === null || _a === void 0 ? void 0 : _a[0].children;
144
+ const prefixIsMethodInvocation = (fqnOrRefType === null || fqnOrRefType === void 0 ? void 0 : fqnOrRefType.fqnOrRefTypePartRest) !== undefined &&
145
+ ((_b = children.primarySuffix) === null || _b === void 0 ? void 0 : _b[0].children.methodInvocationSuffix) !== undefined;
146
+ const prefixIsStaticMethodInvocation = prefixIsMethodInvocation && isCapitalizedIdentifier(fqnOrRefType);
147
+ const prefixIsInstanceMethodInvocation = prefixIsMethodInvocation && !prefixIsStaticMethodInvocation;
148
+ const mustBreakForCallExpressions = methodInvocations.length > 2 && hasLambdaMethodParameter;
149
+ const separator = mustBreakForCallExpressions ? hardline : softline;
150
+ const prefix = [
151
+ call(path, prefixPath => print(prefixPath, {
152
+ lastSeparator: prefixIsStaticMethodInvocation ||
153
+ (prefixIsInstanceMethodInvocation && callExpressionCount === 1)
154
+ ? ""
155
+ : separator
156
+ }), "primaryPrefix")
157
+ ];
158
+ const canBreakForCallExpressions = callExpressionCount > 2 ||
159
+ (callExpressionCount === 2 && prefixIsInstanceMethodInvocation) ||
160
+ willBreak(prefix);
161
+ const suffixes = [];
162
+ each(path, suffixPath => {
163
+ const { node, previous } = suffixPath;
164
+ const suffix = print(suffixPath);
165
+ if (node.children.Dot) {
166
+ if ((canBreakForCallExpressions &&
167
+ ((!previous && prefixIsCallExpression) ||
168
+ (previous === null || previous === void 0 ? void 0 : previous.children.methodInvocationSuffix) ||
169
+ (previous === null || previous === void 0 ? void 0 : previous.children.unqualifiedClassInstanceCreationExpression))) ||
170
+ (!node.children.templateArgument && willBreak(suffix))) {
171
+ suffixes.push(separator);
172
+ }
173
+ suffixes.push(suffix);
174
+ }
175
+ else if (previous) {
176
+ suffixes.push(suffix);
256
177
  }
257
- else if (ctx.Identifier) {
258
- const typeArguments = this.visit(ctx.typeArguments);
259
- return rejectAndConcat([ctx.Dot[0], typeArguments, ctx.Identifier[0]]);
178
+ else {
179
+ prefix.push(prefixIsInstanceMethodInvocation && callExpressionCount >= 2
180
+ ? indent(suffix)
181
+ : suffix);
260
182
  }
261
- const suffix = this.visit((_a = ctx.unqualifiedClassInstanceCreationExpression) !== null && _a !== void 0 ? _a : ctx.templateArgument);
262
- return rejectAndConcat([ctx.Dot[0], suffix]);
183
+ }, "primarySuffix");
184
+ return group(canBreakForCallExpressions || willBreak(suffixes)
185
+ ? [prefix, indent(suffixes)]
186
+ : [prefix, ...suffixes]);
187
+ },
188
+ primaryPrefix: printSingle,
189
+ primarySuffix(path, print) {
190
+ const { children } = path.node;
191
+ if (!children.Dot) {
192
+ return printSingle(path, print);
263
193
  }
264
- return this.visitSingle(ctx, params);
265
- }
266
- fqnOrRefType(ctx, params) {
267
- const fqnOrRefTypePartFirst = this.visit(ctx.fqnOrRefTypePartFirst);
268
- const fqnOrRefTypePartRest = this.mapVisit(ctx.fqnOrRefTypePartRest);
269
- const dims = this.visit(ctx.dims);
270
- const dots = ctx.Dot
271
- ? ctx.Dot.map(dot => {
272
- if (hasLeadingComments(dot)) {
273
- return concat([softline, dot]);
274
- }
275
- return dot;
276
- })
277
- : [];
278
- if ((params === null || params === void 0 ? void 0 : params.shouldBreakBeforeFirstMethodInvocation) === true &&
279
- ctx.Dot !== undefined) {
280
- dots[dots.length - 1] = concat([softline, ctx.Dot[ctx.Dot.length - 1]]);
194
+ const suffix = ["."];
195
+ if (children.This) {
196
+ suffix.push("this");
281
197
  }
282
- return indent(rejectAndConcat([
283
- rejectAndJoinSeps(dots, [
284
- fqnOrRefTypePartFirst,
285
- ...fqnOrRefTypePartRest
286
- ]),
287
- dims
288
- ]));
289
- }
290
- fqnOrRefTypePartFirst(ctx) {
291
- const annotation = this.mapVisit(ctx.annotation);
292
- const fqnOrRefTypeCommon = this.visit(ctx.fqnOrRefTypePartCommon);
293
- return rejectAndJoin(" ", [
294
- rejectAndJoin(" ", annotation),
295
- fqnOrRefTypeCommon
296
- ]);
297
- }
298
- fqnOrRefTypePartRest(ctx) {
299
- const annotation = this.mapVisit(ctx.annotation);
300
- const fqnOrRefTypeCommon = this.visit(ctx.fqnOrRefTypePartCommon);
301
- const typeArguments = this.visit(ctx.typeArguments);
302
- return rejectAndJoin(" ", [
303
- rejectAndJoin(" ", annotation),
304
- rejectAndConcat([typeArguments, fqnOrRefTypeCommon])
305
- ]);
306
- }
307
- fqnOrRefTypePartCommon(ctx) {
308
- let keyWord = null;
309
- if (ctx.Identifier) {
310
- keyWord = ctx.Identifier[0];
198
+ else if (children.Identifier) {
199
+ if (children.typeArguments) {
200
+ suffix.push(call(path, print, "typeArguments"));
201
+ }
202
+ suffix.push(call(path, print, "Identifier"));
311
203
  }
312
204
  else {
313
- keyWord = ctx.Super[0];
205
+ const suffixKey = onlyDefinedKey(children, [
206
+ "templateArgument",
207
+ "unqualifiedClassInstanceCreationExpression"
208
+ ]);
209
+ suffix.push(call(path, print, suffixKey));
314
210
  }
315
- const typeArguments = this.visit(ctx.typeArguments);
316
- return rejectAndConcat([keyWord, typeArguments]);
317
- }
318
- parenthesisExpression(ctx, params) {
319
- const expression = this.visit(ctx.expression);
320
- const separator = (params === null || params === void 0 ? void 0 : params.addParenthesisToWrapStatement) ? softline : "";
321
- return putIntoBraces(expression, separator, ctx.LBrace[0], ctx.RBrace[0]);
322
- }
323
- castExpression(ctx) {
324
- return this.visitSingle(ctx);
325
- }
326
- primitiveCastExpression(ctx) {
327
- const primitiveType = this.visit(ctx.primitiveType);
328
- const unaryExpression = this.visit(ctx.unaryExpression);
329
- return rejectAndJoin(" ", [
330
- rejectAndConcat([ctx.LBrace[0], primitiveType, ctx.RBrace[0]]),
331
- unaryExpression
332
- ]);
333
- }
334
- referenceTypeCastExpression(ctx) {
335
- const referenceType = this.visit(ctx.referenceType);
336
- const hasAdditionalBounds = ctx.additionalBound !== undefined;
337
- const additionalBounds = rejectAndJoin(line, this.mapVisit(ctx.additionalBound));
338
- const expression = ctx.lambdaExpression
339
- ? this.visit(ctx.lambdaExpression)
340
- : this.visit(ctx.unaryExpressionNotPlusMinus);
341
- return rejectAndJoin(" ", [
342
- putIntoBraces(rejectAndJoin(line, [referenceType, additionalBounds]), hasAdditionalBounds ? softline : "", ctx.LBrace[0], ctx.RBrace[0]),
343
- expression
344
- ]);
345
- }
346
- newExpression(ctx) {
347
- return this.visitSingle(ctx);
348
- }
349
- unqualifiedClassInstanceCreationExpression(ctx) {
350
- const typeArguments = this.visit(ctx.typeArguments);
351
- const classOrInterfaceTypeToInstantiate = this.visit(ctx.classOrInterfaceTypeToInstantiate);
352
- let content = printArgumentListWithBraces.call(this, ctx.argumentList, ctx.RBrace[0], ctx.LBrace[0]);
353
- const classBody = this.visit(ctx.classBody);
354
- return rejectAndJoin(" ", [
355
- ctx.New[0],
356
- rejectAndConcat([
357
- typeArguments,
358
- classOrInterfaceTypeToInstantiate,
359
- content
360
- ]),
361
- classBody
362
- ]);
363
- }
364
- classOrInterfaceTypeToInstantiate(ctx) {
365
- const tokens = sortAnnotationIdentifier(ctx.annotation, ctx.Identifier);
366
- const segments = [];
367
- let currentSegment = [];
368
- forEach(tokens, token => {
369
- if (isAnnotationCstNode(token)) {
370
- currentSegment.push(this.visit([token]));
371
- }
372
- else {
373
- currentSegment.push(token);
374
- segments.push(rejectAndJoin(" ", currentSegment));
375
- currentSegment = [];
376
- }
377
- });
378
- const typeArgumentsOrDiamond = this.visit(ctx.typeArgumentsOrDiamond);
379
- const dots = ctx.Dot ? ctx.Dot : [];
380
- return rejectAndConcat([
381
- rejectAndJoinSeps(dots, segments),
382
- typeArgumentsOrDiamond
211
+ return suffix;
212
+ },
213
+ fqnOrRefType(path, print, _, args) {
214
+ var _a;
215
+ const lastSeparator = (_a = args.lastSeparator) !== null && _a !== void 0 ? _a : "";
216
+ const fqnOrRefType = [
217
+ call(path, print, "fqnOrRefTypePartFirst"),
218
+ ...map(path, partPath => {
219
+ const part = print(partPath);
220
+ return partPath.isLast
221
+ ? [willBreak(part) ? hardline : lastSeparator, part]
222
+ : part;
223
+ }, "fqnOrRefTypePartRest")
224
+ ];
225
+ fqnOrRefType.push(indent(fqnOrRefType.pop()));
226
+ return path.node.children.dims
227
+ ? [fqnOrRefType, call(path, print, "dims")]
228
+ : fqnOrRefType;
229
+ },
230
+ fqnOrRefTypePartFirst(path, print) {
231
+ return join(" ", [
232
+ ...map(path, print, "annotation"),
233
+ call(path, print, "fqnOrRefTypePartCommon")
383
234
  ]);
384
- }
385
- typeArgumentsOrDiamond(ctx) {
386
- return this.visitSingle(ctx);
387
- }
388
- diamond(ctx) {
389
- return concat([ctx.Less[0], ctx.Greater[0]]);
390
- }
391
- methodInvocationSuffix(ctx) {
392
- return printArgumentListWithBraces.call(this, ctx.argumentList, ctx.RBrace[0], ctx.LBrace[0]);
393
- }
394
- argumentList(ctx) {
235
+ },
236
+ fqnOrRefTypePartRest(path, print) {
237
+ const common = call(path, print, "fqnOrRefTypePartCommon");
238
+ const type = path.node.children.typeArguments
239
+ ? [call(path, print, "typeArguments"), common]
240
+ : common;
241
+ return [".", ...join(" ", [...map(path, print, "annotation"), type])];
242
+ },
243
+ fqnOrRefTypePartCommon(path, print) {
244
+ const { children } = path.node;
245
+ const keywordKey = onlyDefinedKey(children, ["Identifier", "Super"]);
246
+ const keyword = call(path, print, keywordKey);
247
+ return children.typeArguments
248
+ ? [keyword, call(path, print, "typeArguments")]
249
+ : keyword;
250
+ },
251
+ parenthesisExpression(path, print) {
395
252
  var _a;
396
- const headArgs = this.mapVisit(ctx.expression.slice(0, -1)).map((expression, index) => concat([expression, ctx.Comma[index], line]));
397
- const lastExpression = ctx.expression.at(-1);
398
- const lastArg = this.visit(lastExpression);
399
- if (this.isArgumentListHuggable(ctx)) {
400
- const huggedLastArg = this.visit(lastExpression, { hug: true });
401
- const lastArgNotHuggable = typeof huggedLastArg === "object" &&
402
- !Array.isArray(huggedLastArg) &&
403
- huggedLastArg.type === "label" &&
404
- ((_a = huggedLastArg.label) === null || _a === void 0 ? void 0 : _a.huggable) === false;
405
- if (lastArgNotHuggable || headArgs.some(willBreak)) {
406
- return group([indent([line, ...headArgs, lastArg]), line], {
407
- shouldBreak: true
408
- });
409
- }
410
- const hugged = [...headArgs, group(huggedLastArg, { shouldBreak: true })];
411
- const expanded = group([indent([line, ...headArgs, lastArg]), line], {
412
- shouldBreak: true
413
- });
414
- return willBreak(huggedLastArg)
415
- ? [breakParent, conditionalGroup([hugged, expanded])]
416
- : conditionalGroup([[...headArgs, huggedLastArg], hugged, expanded]);
253
+ const expression = call(path, print, "expression");
254
+ const ancestorName = (_a = path.getNode(14)) === null || _a === void 0 ? void 0 : _a.name;
255
+ const binaryExpression = path.getNode(8);
256
+ return ancestorName &&
257
+ ["guard", "returnStatement"].includes(ancestorName) &&
258
+ binaryExpression &&
259
+ binaryExpression.name === "binaryExpression" &&
260
+ Object.keys(binaryExpression.children).length === 1
261
+ ? indentInParentheses(expression)
262
+ : ["(", indent(expression), ")"];
263
+ },
264
+ castExpression: printSingle,
265
+ primitiveCastExpression(path, print) {
266
+ return [
267
+ "(",
268
+ call(path, print, "primitiveType"),
269
+ ") ",
270
+ call(path, print, "unaryExpression")
271
+ ];
272
+ },
273
+ referenceTypeCastExpression(path, print) {
274
+ const { children } = path.node;
275
+ const type = call(path, print, "referenceType");
276
+ const cast = children.additionalBound
277
+ ? indentInParentheses(join(line, [type, ...map(path, print, "additionalBound")]))
278
+ : ["(", type, ")"];
279
+ const expressionKey = onlyDefinedKey(children, [
280
+ "lambdaExpression",
281
+ "unaryExpressionNotPlusMinus"
282
+ ]);
283
+ return [cast, " ", call(path, print, expressionKey)];
284
+ },
285
+ newExpression: printSingle,
286
+ unqualifiedClassInstanceCreationExpression(path, print) {
287
+ const { children } = path.node;
288
+ const expression = ["new "];
289
+ if (children.typeArguments) {
290
+ expression.push(call(path, print, "typeArguments"));
417
291
  }
418
- return group([indent([softline, ...headArgs, lastArg]), softline]);
419
- }
420
- arrayCreationExpression(ctx) {
421
- const type = ctx.primitiveType
422
- ? this.visit(ctx.primitiveType)
423
- : this.visit(ctx.classOrInterfaceType);
424
- const suffix = ctx.arrayCreationExpressionWithoutInitializerSuffix
425
- ? this.visit(ctx.arrayCreationExpressionWithoutInitializerSuffix)
426
- : this.visit(ctx.arrayCreationWithInitializerSuffix);
427
- return rejectAndConcat([concat([ctx.New[0], " "]), type, suffix]);
428
- }
429
- arrayCreationExpressionWithoutInitializerSuffix(ctx) {
430
- const dimExprs = this.visit(ctx.dimExprs);
431
- const dims = this.visit(ctx.dims);
432
- return rejectAndConcat([dimExprs, dims]);
433
- }
434
- arrayCreationWithInitializerSuffix(ctx) {
435
- const dims = this.visit(ctx.dims);
436
- const arrayInitializer = this.visit(ctx.arrayInitializer);
437
- return rejectAndJoin(" ", [dims, arrayInitializer]);
438
- }
439
- dimExprs(ctx) {
440
- const dimExpr = this.mapVisit(ctx.dimExpr);
441
- return rejectAndConcat(dimExpr);
442
- }
443
- dimExpr(ctx) {
444
- const annotations = this.mapVisit(ctx.annotation);
445
- const expression = this.visit(ctx.expression);
446
- return rejectAndJoin(" ", [
447
- rejectAndJoin(" ", annotations),
448
- rejectAndConcat([ctx.LSquare[0], expression, ctx.RSquare[0]])
292
+ expression.push(call(path, print, "classOrInterfaceTypeToInstantiate"), children.argumentList
293
+ ? group(["(", call(path, print, "argumentList"), ")"])
294
+ : "()");
295
+ if (children.classBody) {
296
+ expression.push(" ", call(path, print, "classBody"));
297
+ }
298
+ return expression;
299
+ },
300
+ classOrInterfaceTypeToInstantiate(path, print) {
301
+ const { children } = path.node;
302
+ const type = children.annotation
303
+ ? flatMap(path, childPath => [
304
+ print(childPath),
305
+ isNonTerminal(childPath.node) ? " " : "."
306
+ ], ["annotation", "Identifier"])
307
+ : printName(path, print);
308
+ if (children.typeArgumentsOrDiamond) {
309
+ type.push(call(path, print, "typeArgumentsOrDiamond"));
310
+ }
311
+ return type;
312
+ },
313
+ typeArgumentsOrDiamond: printSingle,
314
+ diamond() {
315
+ return "<>";
316
+ },
317
+ methodInvocationSuffix(path, print) {
318
+ return path.node.children.argumentList
319
+ ? group(["(", call(path, print, "argumentList"), ")"])
320
+ : indentInParentheses(printDanglingComments(path), { shouldBreak: true });
321
+ },
322
+ argumentList(path, print) {
323
+ var _a, _b, _c, _d;
324
+ const expressions = path.node.children.expression;
325
+ const lastExpression = expressions.at(-1);
326
+ const lastExpressionLambdaBodyExpression = (_b = (_a = lastExpression.children.lambdaExpression) === null || _a === void 0 ? void 0 : _a[0].children.lambdaBody[0].children.expression) === null || _b === void 0 ? void 0 : _b[0].children;
327
+ const lastExpressionLambdaBodyTernaryExpression = (_c = lastExpressionLambdaBodyExpression === null || lastExpressionLambdaBodyExpression === void 0 ? void 0 : lastExpressionLambdaBodyExpression.conditionalExpression) === null || _c === void 0 ? void 0 : _c[0].children;
328
+ const isHuggable = !lastExpression.comments &&
329
+ (!lastExpressionLambdaBodyExpression ||
330
+ (lastExpressionLambdaBodyTernaryExpression === null || lastExpressionLambdaBodyTernaryExpression === void 0 ? void 0 : lastExpressionLambdaBodyTernaryExpression.QuestionMark) !== undefined ||
331
+ ((_d = lastExpressionLambdaBodyTernaryExpression === null || lastExpressionLambdaBodyTernaryExpression === void 0 ? void 0 : lastExpressionLambdaBodyTernaryExpression.binaryExpression) === null || _d === void 0 ? void 0 : _d[0].children.unaryExpression.length) === 1) &&
332
+ expressions.findIndex(({ children }) => children.lambdaExpression) ===
333
+ expressions.length - 1;
334
+ const args = map(path, print, "expression");
335
+ const allArgsExpandable = [
336
+ indent([softline, ...join([",", line], args)]),
337
+ softline
338
+ ];
339
+ if (!isHuggable || willBreak(args.at(-1)[0])) {
340
+ return allArgsExpandable;
341
+ }
342
+ const headArgs = args.slice(0, -1);
343
+ const huggedLastArg = call(path, argPath => print(argPath, { hug: true }), "expression", args.length - 1);
344
+ const lastArgExpanded = join(", ", [
345
+ ...headArgs,
346
+ group(huggedLastArg, { shouldBreak: true })
449
347
  ]);
450
- }
451
- classLiteralSuffix(ctx) {
452
- const squares = [];
453
- if (ctx.LSquare) {
454
- for (let i = 0; i < ctx.LSquare.length; i++) {
455
- squares.push(concat([ctx.LSquare[i], ctx.RSquare[i]]));
456
- }
348
+ if (willBreak(huggedLastArg)) {
349
+ return [
350
+ breakParent,
351
+ conditionalGroup([lastArgExpanded, allArgsExpandable])
352
+ ];
457
353
  }
458
- return rejectAndConcat([...squares, ctx.Dot[0], ctx.Class[0]]);
459
- }
460
- arrayAccessSuffix(ctx) {
461
- const expression = this.visit(ctx.expression);
462
- return rejectAndConcat([ctx.LSquare[0], expression, ctx.RSquare[0]]);
463
- }
464
- methodReferenceSuffix(ctx) {
465
- const typeArguments = this.visit(ctx.typeArguments);
466
- const identifierOrNew = ctx.New ? ctx.New[0] : ctx.Identifier[0];
467
- return rejectAndConcat([ctx.ColonColon[0], typeArguments, identifierOrNew]);
468
- }
469
- templateArgument(ctx) {
470
- var _a;
471
- return ctx.template
472
- ? this.visit(ctx.template)
473
- : printTokenWithComments(((_a = ctx.StringLiteral) !== null && _a !== void 0 ? _a : ctx.TextBlock)[0]);
474
- }
475
- template(ctx) {
476
- return this.visitSingle(ctx);
477
- }
478
- stringTemplate(ctx) {
479
- const embeddedExpressions = this.mapVisit(ctx.embeddedExpression).flatMap(expression => group([softline, expression, lineSuffixBoundary, dedent(softline)]));
480
- return concat([
481
- ctx.StringTemplateBegin[0],
482
- rejectAndJoinSeps(ctx.StringTemplateMid, embeddedExpressions),
483
- ctx.StringTemplateEnd[0]
354
+ return conditionalGroup([
355
+ join(", ", [...headArgs, huggedLastArg]),
356
+ lastArgExpanded,
357
+ allArgsExpandable
484
358
  ]);
485
- }
486
- textBlockTemplate(ctx) {
487
- const embeddedExpressions = this.mapVisit(ctx.embeddedExpression).flatMap(expression => group([softline, expression, lineSuffixBoundary, dedent(softline)]));
488
- return concat([
489
- ctx.TextBlockTemplateBegin[0],
490
- rejectAndJoinSeps(ctx.TextBlockTemplateMid, embeddedExpressions),
491
- ctx.TextBlockTemplateEnd[0]
359
+ },
360
+ arrayCreationExpression(path, print) {
361
+ const { children } = path.node;
362
+ const typeKey = onlyDefinedKey(children, [
363
+ "classOrInterfaceType",
364
+ "primitiveType"
492
365
  ]);
493
- }
494
- embeddedExpression(ctx) {
495
- return this.visit(ctx.expression);
496
- }
497
- pattern(ctx) {
498
- return this.visitSingle(ctx);
499
- }
500
- typePattern(ctx) {
501
- return this.visitSingle(ctx);
502
- }
503
- recordPattern(ctx) {
504
- var _a, _b;
505
- const componentPatterns = (_b = (_a = ctx.componentPatternList) === null || _a === void 0 ? void 0 : _a[0].children.componentPattern) !== null && _b !== void 0 ? _b : [];
506
- handleCommentsParameters(ctx.LBrace[0], componentPatterns, ctx.RBrace[0]);
507
- const referenceType = this.visit(ctx.referenceType);
508
- const componentPatternList = this.visit(ctx.componentPatternList);
509
- return concat([
510
- referenceType,
511
- putIntoBraces(componentPatternList, softline, ctx.LBrace[0], ctx.RBrace[0])
366
+ const suffixKey = onlyDefinedKey(children, [
367
+ "arrayCreationExpressionWithoutInitializerSuffix",
368
+ "arrayCreationWithInitializerSuffix"
512
369
  ]);
513
- }
514
- componentPatternList(ctx) {
515
- var _a, _b;
516
- const componentPatterns = this.mapVisit(ctx.componentPattern);
517
- const commas = (_b = (_a = ctx.Comma) === null || _a === void 0 ? void 0 : _a.map(elt => concat([elt, line]))) !== null && _b !== void 0 ? _b : [];
518
- return rejectAndJoinSeps(commas, componentPatterns);
519
- }
520
- componentPattern(ctx) {
521
- return this.visitSingle(ctx);
522
- }
523
- matchAllPattern(ctx) {
524
- return printTokenWithComments(ctx.Underscore[0]);
525
- }
526
- guard(ctx) {
527
- const expression = this.visit(ctx.expression, {
528
- addParenthesisToWrapStatement: true
529
- });
530
- return concat([ctx.When[0], " ", expression]);
531
- }
532
- isRefTypeInMethodRef() {
533
- return "isRefTypeInMethodRef";
534
- }
535
- isArgumentListHuggable(argumentList) {
536
- var _a, _b, _c;
537
- const expressions = argumentList.expression;
538
- const lastArgument = expressions.at(-1);
539
- const lastArgumentLambdaBodyExpression = (_b = (_a = lastArgument === null || lastArgument === void 0 ? void 0 : lastArgument.children.lambdaExpression) === null || _a === void 0 ? void 0 : _a[0].children.lambdaBody[0].children.expression) === null || _b === void 0 ? void 0 : _b[0].children;
540
- const lastArgumentLambdaBodyTernaryExpression = (_c = lastArgumentLambdaBodyExpression === null || lastArgumentLambdaBodyExpression === void 0 ? void 0 : lastArgumentLambdaBodyExpression.conditionalExpression) === null || _c === void 0 ? void 0 : _c[0].children;
541
- return (!(lastArgument === null || lastArgument === void 0 ? void 0 : lastArgument.leadingComments) &&
542
- !(lastArgument === null || lastArgument === void 0 ? void 0 : lastArgument.trailingComments) &&
543
- (!lastArgumentLambdaBodyExpression ||
544
- (lastArgumentLambdaBodyTernaryExpression === null || lastArgumentLambdaBodyTernaryExpression === void 0 ? void 0 : lastArgumentLambdaBodyTernaryExpression.QuestionMark) !== undefined ||
545
- (lastArgumentLambdaBodyTernaryExpression === null || lastArgumentLambdaBodyTernaryExpression === void 0 ? void 0 : lastArgumentLambdaBodyTernaryExpression.binaryExpression[0].children.unaryExpression.length) === 1) &&
546
- expressions.findIndex(({ children }) => children.lambdaExpression) ===
547
- expressions.length - 1);
548
- }
549
- isBreakableNewExpression(newExpression) {
550
- var _a, _b, _c, _d, _e;
551
- const arrayCreationExpression = (_a = newExpression === null || newExpression === void 0 ? void 0 : newExpression.arrayCreationExpression) === null || _a === void 0 ? void 0 : _a[0].children;
552
- const classInstanceCreationExpression = (_b = newExpression === null || newExpression === void 0 ? void 0 : newExpression.unqualifiedClassInstanceCreationExpression) === null || _b === void 0 ? void 0 : _b[0].children;
370
+ return ["new ", call(path, print, typeKey), call(path, print, suffixKey)];
371
+ },
372
+ arrayCreationExpressionWithoutInitializerSuffix(path, print) {
373
+ const expressions = call(path, print, "dimExprs");
374
+ return path.node.children.dims
375
+ ? [expressions, call(path, print, "dims")]
376
+ : expressions;
377
+ },
378
+ arrayCreationWithInitializerSuffix(path, print) {
553
379
  return [
554
- (_c = arrayCreationExpression === null || arrayCreationExpression === void 0 ? void 0 : arrayCreationExpression.classOrInterfaceType) === null || _c === void 0 ? void 0 : _c[0].children.classType[0].children.typeArguments,
555
- (_d = arrayCreationExpression === null || arrayCreationExpression === void 0 ? void 0 : arrayCreationExpression.arrayCreationWithInitializerSuffix) === null || _d === void 0 ? void 0 : _d[0].children.arrayInitializer[0].children.variableInitializerList,
556
- (_e = classInstanceCreationExpression === null || classInstanceCreationExpression === void 0 ? void 0 : classInstanceCreationExpression.classOrInterfaceTypeToInstantiate[0].children.typeArgumentsOrDiamond) === null || _e === void 0 ? void 0 : _e[0].children.typeArguments,
557
- classInstanceCreationExpression === null || classInstanceCreationExpression === void 0 ? void 0 : classInstanceCreationExpression.argumentList
558
- ].some(breakablePart => breakablePart !== undefined);
559
- }
560
- isCapitalizedIdentifier(fqnOrRefType) {
561
- var _a, _b, _c;
562
- const fqnOrRefTypeParts = [
563
- fqnOrRefType === null || fqnOrRefType === void 0 ? void 0 : fqnOrRefType.fqnOrRefTypePartFirst[0],
564
- ...((_a = fqnOrRefType === null || fqnOrRefType === void 0 ? void 0 : fqnOrRefType.fqnOrRefTypePartRest) !== null && _a !== void 0 ? _a : [])
380
+ call(path, print, "dims"),
381
+ " ",
382
+ call(path, print, "arrayInitializer")
565
383
  ];
566
- const nextToLastIdentifier = (_c = (_b = fqnOrRefTypeParts[fqnOrRefTypeParts.length - 2]) === null || _b === void 0 ? void 0 : _b.children.fqnOrRefTypePartCommon[0].children.Identifier) === null || _c === void 0 ? void 0 : _c[0].image;
567
- return (!!nextToLastIdentifier &&
568
- /^\p{Uppercase_Letter}/u.test(nextToLastIdentifier));
569
- }
570
- getPrimarySuffixes(ctx, newExpression, isBreakableNewExpression, shouldBreakBeforeMethodInvocations) {
571
- if (ctx.primarySuffix === undefined) {
572
- return [];
384
+ },
385
+ dimExprs(path, print) {
386
+ return map(path, print, "dimExpr");
387
+ },
388
+ dimExpr(path, print) {
389
+ return join(" ", [
390
+ ...map(path, print, "annotation"),
391
+ ["[", call(path, print, "expression"), "]"]
392
+ ]);
393
+ },
394
+ classLiteralSuffix(path, print) {
395
+ const lSquares = map(path, print, "LSquare");
396
+ const rSquares = map(path, print, "RSquare");
397
+ return [
398
+ ...lSquares.flatMap((lSquare, index) => [lSquare, rSquares[index]]),
399
+ ".class"
400
+ ];
401
+ },
402
+ arrayAccessSuffix(path, print) {
403
+ return ["[", call(path, print, "expression"), "]"];
404
+ },
405
+ methodReferenceSuffix(path, print) {
406
+ const { children } = path.node;
407
+ const reference = ["::"];
408
+ if (children.typeArguments) {
409
+ reference.push(call(path, print, "typeArguments"));
573
410
  }
574
- const suffixes = [];
575
- if (newExpression &&
576
- !isBreakableNewExpression &&
577
- ctx.primarySuffix[0].children.Dot !== undefined) {
578
- suffixes.push(softline);
411
+ reference.push(call(path, print, onlyDefinedKey(children, ["Identifier", "New"])));
412
+ return reference;
413
+ },
414
+ templateArgument: printSingle,
415
+ template: printSingle,
416
+ stringTemplate(path, print) {
417
+ return printTemplate(path, print, "StringTemplateBegin", "StringTemplateMid", "StringTemplateEnd");
418
+ },
419
+ textBlockTemplate(path, print) {
420
+ return printTemplate(path, print, "TextBlockTemplateBegin", "TextBlockTemplateMid", "TextBlockTemplateEnd");
421
+ },
422
+ embeddedExpression: printSingle,
423
+ pattern: printSingle,
424
+ typePattern: printSingle,
425
+ recordPattern(path, print) {
426
+ const patterns = path.node.children.componentPatternList
427
+ ? indentInParentheses(call(path, print, "componentPatternList"))
428
+ : "()";
429
+ return [call(path, print, "referenceType"), patterns];
430
+ },
431
+ componentPatternList(path, print) {
432
+ return printList(path, print, "componentPattern");
433
+ },
434
+ componentPattern: printSingle,
435
+ matchAllPattern: printSingle,
436
+ guard(path, print) {
437
+ var _a;
438
+ const expression = call(path, print, "expression");
439
+ const hasParentheses = ((_a = path.node.children.expression[0].children.conditionalExpression) === null || _a === void 0 ? void 0 : _a[0].children.binaryExpression[0].children.unaryExpression[0].children.primary[0].children.primaryPrefix[0].children.parenthesisExpression) !==
440
+ undefined;
441
+ return [
442
+ "when ",
443
+ hasParentheses
444
+ ? expression
445
+ : group([
446
+ ifBreak("("),
447
+ indent([softline, expression]),
448
+ softline,
449
+ ifBreak(")")
450
+ ])
451
+ ];
452
+ }
453
+ };
454
+ function binary(operands, operators, { hasNonAssignmentOperators = false, isRoot = false, operatorPosition }) {
455
+ let levelOperator;
456
+ let levelPrecedence;
457
+ let level = [];
458
+ while (operators.length) {
459
+ const nextOperator = operators[0].image;
460
+ const nextPrecedence = getOperatorPrecedence(nextOperator);
461
+ if (levelPrecedence === undefined || nextPrecedence === levelPrecedence) {
462
+ const { image: operator, doc: operatorDoc } = operators.shift();
463
+ level.push(operands.shift());
464
+ if (levelOperator !== undefined &&
465
+ needsParentheses(levelOperator, operator)) {
466
+ level = [["(", group(indent(level)), ")"]];
467
+ }
468
+ const parts = [" ", operatorDoc, line];
469
+ if (operatorPosition === "start" && !isAssignmentOperator(operator)) {
470
+ parts.reverse();
471
+ }
472
+ level.push(parts);
473
+ levelOperator = operator;
474
+ levelPrecedence = nextPrecedence;
579
475
  }
580
- suffixes.push(this.visit(ctx.primarySuffix[0]));
581
- for (let i = 1; i < ctx.primarySuffix.length; i++) {
582
- if (shouldBreakBeforeMethodInvocations &&
583
- ctx.primarySuffix[i].children.Dot !== undefined &&
584
- ctx.primarySuffix[i - 1].children.methodInvocationSuffix !== undefined) {
585
- suffixes.push(softline);
476
+ else if (nextPrecedence < levelPrecedence) {
477
+ if (!isRoot) {
478
+ break;
586
479
  }
587
- suffixes.push(this.visit(ctx.primarySuffix[i]));
480
+ level.push(operands.shift());
481
+ const content = group(indent(level));
482
+ operands.unshift(levelOperator !== undefined &&
483
+ needsParentheses(levelOperator, nextOperator)
484
+ ? ["(", content, ")"]
485
+ : content);
486
+ level = [];
487
+ levelOperator = undefined;
488
+ levelPrecedence = undefined;
489
+ }
490
+ else {
491
+ const content = binary(operands, operators, { operatorPosition });
492
+ operands.unshift(levelOperator !== undefined &&
493
+ needsParentheses(nextOperator, levelOperator)
494
+ ? ["(", indent(content), ")"]
495
+ : content);
588
496
  }
589
- return suffixes;
590
497
  }
498
+ level.push(operands.shift());
499
+ if (!levelOperator || !isAssignmentOperator(levelOperator)) {
500
+ return group(level);
501
+ }
502
+ if (!isRoot || hasNonAssignmentOperators) {
503
+ return group(indent(level));
504
+ }
505
+ const groupId = Symbol("assignment");
506
+ return group([
507
+ level[0],
508
+ group(indent(level[1]), { id: groupId }),
509
+ indentIfBreak(level[2], { groupId })
510
+ ]);
511
+ }
512
+ const precedencesByOperator = new Map([
513
+ ["||"],
514
+ ["&&"],
515
+ ["|"],
516
+ ["^"],
517
+ ["&"],
518
+ ["==", "!="],
519
+ ["<", ">", "<=", ">=", "instanceof"],
520
+ ["<<", ">>", ">>>"],
521
+ ["+", "-"],
522
+ ["*", "/", "%"]
523
+ ].flatMap((operators, index) => operators.map(operator => [operator, index])));
524
+ function getOperatorPrecedence(operator) {
525
+ var _a;
526
+ return (_a = precedencesByOperator.get(operator)) !== null && _a !== void 0 ? _a : -1;
527
+ }
528
+ function needsParentheses(operator, parentOperator) {
529
+ return ((operator === "&&" && parentOperator === "||") ||
530
+ (["|", "^", "&", "<<", ">>", ">>>"].includes(parentOperator) &&
531
+ getOperatorPrecedence(operator) >
532
+ getOperatorPrecedence(parentOperator)) ||
533
+ [operator, parentOperator].every(o => ["==", "!="].includes(o)) ||
534
+ [operator, parentOperator].every(o => ["<<", ">>", ">>>"].includes(o)) ||
535
+ (operator === "*" && parentOperator === "/") ||
536
+ (operator === "/" && parentOperator === "*") ||
537
+ (operator === "%" && ["+", "-", "*", "/"].includes(parentOperator)) ||
538
+ (["*", "/"].includes(operator) && parentOperator === "%"));
539
+ }
540
+ const assignmentOperators = new Set([
541
+ "=",
542
+ "*=",
543
+ "/=",
544
+ "%=",
545
+ "+=",
546
+ "-=",
547
+ "<<=",
548
+ ">>=",
549
+ ">>>=",
550
+ "&=",
551
+ "^=",
552
+ "|="
553
+ ]);
554
+ function isAssignmentOperator(operator) {
555
+ return assignmentOperators.has(operator);
556
+ }
557
+ function isCapitalizedIdentifier(fqnOrRefType) {
558
+ var _a, _b, _c;
559
+ const nextToLastIdentifier = (_c = (_b = [
560
+ fqnOrRefType.fqnOrRefTypePartFirst[0],
561
+ ...((_a = fqnOrRefType.fqnOrRefTypePartRest) !== null && _a !== void 0 ? _a : [])
562
+ ].at(-2)) === null || _b === void 0 ? void 0 : _b.children.fqnOrRefTypePartCommon[0].children.Identifier) === null || _c === void 0 ? void 0 : _c[0].image;
563
+ return /^\p{Uppercase_Letter}/u.test(nextToLastIdentifier !== null && nextToLastIdentifier !== void 0 ? nextToLastIdentifier : "");
564
+ }
565
+ function printTemplate(path, print, beginKey, midKey, endKey) {
566
+ const { children } = path.node;
567
+ const begin = call(path, ({ node }) => node.image, beginKey);
568
+ const mids = map(path, ({ node }) => node.image, midKey);
569
+ const end = call(path, ({ node }) => node.image, endKey);
570
+ const lines = [begin, ...mids, end].join("").split("\n").slice(1);
571
+ const baseIndent = findBaseIndent(lines);
572
+ const prefix = "\n" + " ".repeat(baseIndent);
573
+ const parts = [begin, ...mids, end].map(image => join(hardline, image.split(prefix)));
574
+ return [
575
+ parts[0],
576
+ ...map(path, (expressionPath, index) => {
577
+ const expression = group([
578
+ indent([softline, print(expressionPath), lineSuffixBoundary]),
579
+ softline
580
+ ]);
581
+ return index === 0 ? expression : [parts[index], expression];
582
+ }, "embeddedExpression"),
583
+ parts.at(-1)
584
+ ];
591
585
  }