-
Notifications
You must be signed in to change notification settings - Fork 43
/
Java14InputAstVisitor.java
306 lines (289 loc) · 11.1 KB
/
Java14InputAstVisitor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.javaformat.java.java14;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.MoreCollectors.toOptional;
import static com.sun.source.tree.Tree.Kind.BLOCK;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;
import com.palantir.javaformat.Op;
import com.palantir.javaformat.OpsBuilder;
import com.palantir.javaformat.OpsBuilder.BlankLineWanted;
import com.palantir.javaformat.java.JavaInputAstVisitor;
import com.sun.source.tree.BindingPatternTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.ModuleTree;
import com.sun.source.tree.SwitchExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.YieldTree;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeInfo;
import java.util.List;
import java.util.Optional;
import javax.lang.model.element.Name;
/**
* Extends {@link JavaInputAstVisitor} with support for AST nodes that were added or modified for Java 14.
*/
public class Java14InputAstVisitor extends JavaInputAstVisitor {
public Java14InputAstVisitor(OpsBuilder builder, int indentMultiplier) {
super(builder, indentMultiplier);
}
@Override
protected void handleModule(boolean first, CompilationUnitTree node) {
try {
ModuleTree module = (ModuleTree)
CompilationUnitTree.class.getMethod("getModule").invoke(node);
if (module != null) {
if (!first) {
builder.blankLineWanted(BlankLineWanted.YES);
}
markForPartialFormat();
visitModule(module, null);
builder.forcedBreak();
}
} catch (ReflectiveOperationException e) {
// Java < 17, see https://bugs.openjdk.java.net/browse/JDK-8255464
}
}
@Override
public Void visitBindingPattern(BindingPatternTree node, Void unused) {
sync(node);
try {
VariableTree variableTree = (VariableTree)
BindingPatternTree.class.getMethod("getVariable").invoke(node);
visitBindingPattern(variableTree.getType(), variableTree.getName());
} catch (ReflectiveOperationException e1) {
try {
Tree type = (Tree) BindingPatternTree.class.getMethod("getType").invoke(node);
Name name = (Name) BindingPatternTree.class.getMethod("getName").invoke(node);
visitBindingPattern(type, name);
} catch (ReflectiveOperationException e2) {
e2.addSuppressed(e1);
throw new LinkageError(e2.getMessage(), e2);
}
}
return null;
}
private void visitBindingPattern(Tree type, Name name) {
scan(type, null);
builder.breakOp(" ");
visit(name);
}
@Override
public Void visitYield(YieldTree node, Void aVoid) {
sync(node);
token("yield");
builder.space();
scan(node.getValue(), null);
token(";");
return null;
}
@Override
public Void visitSwitchExpression(SwitchExpressionTree node, Void unused) {
sync(node);
visitSwitch(node.getExpression(), node.getCases());
return null;
}
@Override
public Void visitClass(ClassTree tree, Void unused) {
switch (tree.getKind()) {
case ANNOTATION_TYPE:
visitAnnotationType(tree);
break;
case CLASS:
case INTERFACE:
visitClassDeclaration(tree);
break;
case ENUM:
visitEnumDeclaration(tree);
break;
case RECORD:
visitRecordDeclaration(tree);
break;
default:
throw new AssertionError(tree.getKind());
}
return null;
}
public void visitRecordDeclaration(ClassTree node) {
sync(node);
List<Op> breaks = visitModifiers(
node.getModifiers(), Direction.VERTICAL, /* declarationAnnotationBreak= */ Optional.empty());
Verify.verify(node.getExtendsClause() == null);
boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty();
builder.addAll(breaks);
token("record");
builder.space();
visit(node.getSimpleName());
if (!node.getTypeParameters().isEmpty()) {
token("<");
}
builder.open(plusFour);
{
if (!node.getTypeParameters().isEmpty()) {
typeParametersRest(node.getTypeParameters(), hasSuperInterfaceTypes ? plusFour : ZERO);
}
ImmutableList<JCTree.JCVariableDecl> parameters = compactRecordConstructor(node)
.map(m -> ImmutableList.copyOf(m.getParameters()))
.orElseGet(() -> recordVariables(node));
token("(");
if (!parameters.isEmpty()) {
// Break before args.
builder.breakToFill("");
}
// record headers can't declare receiver parameters
visitFormals(/* receiver= */ Optional.empty(), parameters);
token(")");
if (hasSuperInterfaceTypes) {
builder.breakToFill(" ");
builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO);
token("implements");
builder.space();
boolean first = true;
for (Tree superInterfaceType : node.getImplementsClause()) {
if (!first) {
token(",");
builder.breakOp(" ");
}
scan(superInterfaceType, null);
first = false;
}
builder.close();
}
}
builder.close();
if (node.getMembers() == null) {
token(";");
} else {
List<Tree> members = node.getMembers().stream()
.filter(t -> (TreeInfo.flags((JCTree) t) & Flags.GENERATED_MEMBER) == 0)
.collect(toImmutableList());
addBodyDeclarations(members, BracesOrNot.YES, FirstDeclarationsOrNot.YES);
}
dropEmptyDeclarations();
}
private static Optional<JCTree.JCMethodDecl> compactRecordConstructor(ClassTree node) {
return node.getMembers().stream()
.filter(JCTree.JCMethodDecl.class::isInstance)
.map(JCTree.JCMethodDecl.class::cast)
.filter(m -> (m.mods.flags & COMPACT_RECORD_CONSTRUCTOR) == COMPACT_RECORD_CONSTRUCTOR)
.collect(toOptional());
}
private static ImmutableList<JCTree.JCVariableDecl> recordVariables(ClassTree node) {
return node.getMembers().stream()
.filter(JCTree.JCVariableDecl.class::isInstance)
.map(JCTree.JCVariableDecl.class::cast)
.filter(m -> (m.mods.flags & RECORD) == RECORD)
.collect(toImmutableList());
}
@Override
public Void visitInstanceOf(InstanceOfTree node, Void unused) {
sync(node);
builder.open(plusFour);
scan(node.getExpression(), null);
builder.breakOp(" ");
builder.open(ZERO);
token("instanceof");
builder.breakOp(" ");
if (node.getPattern() != null) {
scan(node.getPattern(), null);
} else {
scan(node.getType(), null);
}
builder.close();
builder.close();
return null;
}
@Override
public Void visitCase(CaseTree node, Void unused) {
sync(node);
markForPartialFormat();
builder.forcedBreak();
if (node.getExpressions().isEmpty()) {
token("default", plusTwo);
} else {
token("case", plusTwo);
builder.space();
builder.open(plusTwo);
boolean first = true;
for (ExpressionTree expression : node.getExpressions()) {
if (!first) {
token(",");
builder.breakOp(" ");
}
scan(expression, null);
first = false;
}
builder.close();
}
switch (node.getCaseKind()) {
case STATEMENT:
token(":");
boolean isBlock = node.getStatements().size() == 1
&& node.getStatements().get(0).getKind() == BLOCK;
builder.open(isBlock ? ZERO : plusTwo);
if (isBlock) {
builder.space();
}
visitStatements(node.getStatements(), isBlock);
builder.close();
break;
case RULE:
builder.space();
token("-");
token(">");
builder.space();
if (node.getBody().getKind() == BLOCK) {
// Explicit call with {@link CollapseEmptyOrNot.YES} to handle empty case blocks.
visitBlock(
(BlockTree) node.getBody(),
CollapseEmptyOrNot.YES,
AllowLeadingBlankLine.NO,
AllowTrailingBlankLine.NO);
} else {
scan(node.getBody(), null);
}
builder.guessToken(";");
break;
default:
throw new AssertionError(node.getCaseKind());
}
return null;
}
/**
* TODO(fwindheuser): Collapse with
* {@link JavaInputAstVisitor#visitLambdaExpression(LambdaExpressionTree, Void)}} after dropping Java 11
* compatibility.
*/
@Override
public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) {
sync(node);
// Also format switch expressions as statement body instead of inlining them
boolean statementBody = node.getBodyKind() == LambdaExpressionTree.BodyKind.STATEMENT
|| node.getBody().getKind() == Kind.SWITCH_EXPRESSION;
visitLambdaExpression(node, statementBody);
return null;
}
}