Skip to content

Commit a4cd6ae

Browse files
committed
Bind instanceof matches to pattern variables
error-prone's PatternMatchingInstanceof warned at 33 places in the formatter and the SPI where an instanceof check is followed by a cast of the same value. The check now declares the variable itself, and the cast goes. Names follow error-prone's suggestions, except classDecl, space and methodInvocation, which read better than jCClassDecl, nonBreakingSpace and methodInvocationTree. Nothing else changes: ./gradlew test passes, and so does :open-java-format:test on JDK 25, which also runs the import module tests that JDK 21 skips.
1 parent 1a01c3b commit a4cd6ae

8 files changed

Lines changed: 49 additions & 62 deletions

File tree

‎open-java-format-spi/src/main/java/com/palantir/javaformat/java/Replacement.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ public boolean equals(Object o) {
5757
if (o == this) {
5858
return true;
5959
}
60-
if (o instanceof Replacement) {
61-
Replacement that = (Replacement) o;
60+
if (o instanceof Replacement that) {
6261
return replaceRange.equals(that.getReplaceRange()) && replacementString.equals(that.getReplacementString());
6362
}
6463
return false;

‎open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,10 @@ public Optional<Boolean> wanted(State state) {
149149

150150
@Override
151151
public BlankLineWanted merge(BlankLineWanted other) {
152-
if (!(other instanceof ConditionalBlankLine)) {
152+
if (!(other instanceof ConditionalBlankLine conditionalBlankLine)) {
153153
return other;
154154
}
155-
return new ConditionalBlankLine(Iterables.concat(this.tags, ((ConditionalBlankLine) other).tags));
155+
return new ConditionalBlankLine(Iterables.concat(this.tags, conditionalBlankLine.tags));
156156
}
157157
}
158158
}
@@ -522,13 +522,12 @@ public OpsOutput build() {
522522
int opsN = ops.size();
523523
for (int i = 0; i < opsN; i++) {
524524
Op op = ops.get(i);
525-
if (op instanceof Token) {
525+
if (op instanceof Token tokenOp) {
526526
/*
527527
* Token ops can have associated non-tokens, including comments, which we need to insert.
528528
* They can also cause line breaks, so we insert them before or after the current level,
529529
* when possible.
530530
*/
531-
Token tokenOp = (Token) op;
532531
Input.Token token = tokenOp.getToken();
533532
int j = i; // Where to insert toksBefore before.
534533
while (0 < j && ops.get(j - 1) instanceof OpenOp) {
@@ -654,9 +653,9 @@ public OpsOutput build() {
654653
Op op = ops.get(i);
655654
if (afterForcedBreak
656655
&& (op instanceof NonBreakingSpace
657-
|| (op instanceof Break
658-
&& ((Break) op).evalPlusIndent(State.startingState()) == 0
659-
&& " ".equals(((Doc) op).getFlat())))) {
656+
|| (op instanceof Break b
657+
&& b.evalPlusIndent(State.startingState()) == 0
658+
&& " ".equals(b.getFlat())))) {
660659
continue;
661660
}
662661
newOps.add(op);
@@ -681,7 +680,7 @@ private static boolean isNonNlsComment(Input.Tok tokAfter) {
681680
}
682681

683682
private static boolean isForcedBreak(Op op) {
684-
return op instanceof Break && ((Break) op).isForced();
683+
return op instanceof Break b && b.isForced();
685684
}
686685

687686
private static List<Op> makeComment(Input.Tok comment) {

‎open-java-format/src/main/java/com/palantir/javaformat/doc/DocVisitor.java‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,16 @@
1818

1919
public interface DocVisitor<T> {
2020
default T visit(Doc doc) {
21-
if (doc instanceof Level) {
22-
return visitLevel((Level) doc);
23-
} else if (doc instanceof Break) {
24-
return visitBreak((Break) doc);
25-
} else if (doc instanceof Token) {
26-
return visitToken((Token) doc);
27-
} else if (doc instanceof Comment) {
28-
return visitComment((Comment) doc);
29-
} else if (doc instanceof NonBreakingSpace) {
30-
return visitSpace((NonBreakingSpace) doc);
21+
if (doc instanceof Level level) {
22+
return visitLevel(level);
23+
} else if (doc instanceof Break b) {
24+
return visitBreak(b);
25+
} else if (doc instanceof Token token) {
26+
return visitToken(token);
27+
} else if (doc instanceof Comment comment) {
28+
return visitComment(comment);
29+
} else if (doc instanceof NonBreakingSpace space) {
30+
return visitSpace(space);
3131
}
3232
throw new RuntimeException();
3333
}

‎open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,12 +148,11 @@ private Optional<Integer> tryToFitOnOneLine(int maxWidth, State state, Iterable<
148148
int column = state.column();
149149
int columnBeforeLastBreak = 0; // Not activated by default
150150
for (Doc doc : docs) {
151-
if (doc instanceof Break && ((Break) doc).hasColumnLimit()) {
151+
if (doc instanceof Break b && b.hasColumnLimit()) {
152152
columnBeforeLastBreak = column;
153-
} else if (doc instanceof Level) {
153+
} else if (doc instanceof Level innerLevel) {
154154
// Levels might have nested levels that have a 'columnLimitBeforeLastBreak' set, so recurse.
155155
State newState = state.withColumn(column);
156-
Level innerLevel = (Level) doc;
157156
Optional<Integer> newWidth = innerLevel.tryToFitOnOneLine(maxWidth, newState, innerLevel.getDocs());
158157
if (!newWidth.isPresent()) {
159158
return Optional.empty();
@@ -633,10 +632,10 @@ private static SplitsBreaks splitByBreaks(List<Doc> docs) {
633632
ImmutableSplitsBreaks.Builder builder = ImmutableSplitsBreaks.builder();
634633
ImmutableList.Builder<Doc> currentSplit = ImmutableList.builder();
635634
for (Doc doc : docs) {
636-
if (doc instanceof Break) {
635+
if (doc instanceof Break b) {
637636
builder.addSplits(currentSplit.build());
638637
currentSplit = ImmutableList.builder();
639-
builder.addBreaks((Break) doc);
638+
builder.addBreaks(b);
640639
} else {
641640
currentSplit.add(doc);
642641
}
@@ -790,8 +789,7 @@ private int getMaxDepth() {
790789
private int computeMaxDepth(Iterable<Doc> docs) {
791790
int maxChildDepth = 0;
792791
for (Doc doc : docs) {
793-
if (doc instanceof Level) {
794-
Level childLevel = (Level) doc;
792+
if (doc instanceof Level childLevel) {
795793
maxChildDepth = Math.max(maxChildDepth, childLevel.getMaxDepth());
796794
}
797795
}

‎open-java-format/src/main/java/com/palantir/javaformat/java/DebugRenderer.java‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,7 @@ private static String opsJson(OpsOutput opsOutput) {
9090

9191
ImmutableList<Op> ops = opsOutput.ops();
9292
for (Op op : ops) {
93-
if (op instanceof Token) {
94-
Token token = (Token) op;
93+
if (op instanceof Token token) {
9594
Input.Token inputToken = token.getToken();
9695

9796
ObjectNode json = arrayNode.addObject();
@@ -109,9 +108,7 @@ private static String opsJson(OpsOutput opsOutput) {
109108
.collect(Collectors.joining()));
110109
json.put("hue", computeHue(token));
111110
}
112-
if (op instanceof Break) {
113-
Break breakOp = (Break) op;
114-
111+
if (op instanceof Break breakOp) {
115112
ObjectNode json = arrayNode.addObject();
116113
json.put("type", "break");
117114
json.put("fillMode", breakOp.fillMode().toString());

‎open-java-format/src/main/java/com/palantir/javaformat/java/JavaInputAstVisitor.java‎

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -866,8 +866,7 @@ public boolean visitEnumDeclaration(ClassTree node) {
866866
ArrayList<VariableTree> enumConstants = new ArrayList<>();
867867
ArrayList<Tree> members = new ArrayList<>();
868868
for (Tree member : node.getMembers()) {
869-
if (member instanceof JCTree.JCVariableDecl) {
870-
JCTree.JCVariableDecl variableDecl = (JCTree.JCVariableDecl) member;
869+
if (member instanceof JCTree.JCVariableDecl variableDecl) {
871870
if ((variableDecl.mods.flags & Flags.ENUM) == Flags.ENUM) {
872871
enumConstants.add(variableDecl);
873872
continue;
@@ -1332,8 +1331,8 @@ public Void visitAnnotation(AnnotationTree node, Void unused) {
13321331
builder.breakOp(" ");
13331332
}
13341333
}
1335-
if (argument instanceof AssignmentTree) {
1336-
visitAnnotationArgument((AssignmentTree) argument);
1334+
if (argument instanceof AssignmentTree assignmentTree) {
1335+
visitAnnotationArgument(assignmentTree);
13371336
} else {
13381337
scan(argument, null);
13391338
}
@@ -1353,11 +1352,11 @@ public Void visitAnnotation(AnnotationTree node, Void unused) {
13531352
}
13541353

13551354
private static boolean isArrayValue(ExpressionTree argument) {
1356-
if (!(argument instanceof AssignmentTree)) {
1355+
if (!(argument instanceof AssignmentTree assignmentTree)) {
13571356
return false;
13581357
}
1359-
ExpressionTree expression = ((AssignmentTree) argument).getExpression();
1360-
return expression instanceof NewArrayTree && ((NewArrayTree) expression).getType() == null;
1358+
ExpressionTree expression = assignmentTree.getExpression();
1359+
return expression instanceof NewArrayTree newArrayTree && newArrayTree.getType() == null;
13611360
}
13621361

13631362
public void visitAnnotationArgument(AssignmentTree node) {
@@ -1383,8 +1382,7 @@ public void visitAnnotationArgument(AssignmentTree node) {
13831382
public Void visitAnnotatedType(AnnotatedTypeTree node, Void unused) {
13841383
sync(node);
13851384
ExpressionTree base = node.getUnderlyingType();
1386-
if (base instanceof MemberSelectTree) {
1387-
MemberSelectTree selectTree = (MemberSelectTree) base;
1385+
if (base instanceof MemberSelectTree selectTree) {
13881386
scan(selectTree.getExpression(), null);
13891387
token(".");
13901388
visitAnnotations(node.getAnnotations(), BreakOrNot.NO, BreakOrNot.NO);
@@ -1411,8 +1409,8 @@ public Void visitAnnotatedType(AnnotatedTypeTree node, Void unused) {
14111409

14121410
/** Is {@code type} the implicit wrapper class javac synthesizes for a compact source file? */
14131411
private static boolean isCompactSourceFile(Tree type) {
1414-
return type instanceof JCTree.JCClassDecl
1415-
&& (((JCTree.JCClassDecl) type).mods.flags & IMPLICIT_CLASS) == IMPLICIT_CLASS;
1412+
return type instanceof JCTree.JCClassDecl classDecl
1413+
&& (classDecl.mods.flags & IMPLICIT_CLASS) == IMPLICIT_CLASS;
14161414
}
14171415

14181416
@SuppressWarnings("for-rollout:NullAway")
@@ -1646,10 +1644,10 @@ private boolean handleLogStatement(MethodInvocationTree node) {
16461644

16471645
private static List<Long> handleStream(List<ExpressionTree> parts) {
16481646
return indexes(parts.stream(), p -> {
1649-
if (!(p instanceof MethodInvocationTree)) {
1647+
if (!(p instanceof MethodInvocationTree methodInvocation)) {
16501648
return false;
16511649
}
1652-
Name name = getMethodName((MethodInvocationTree) p);
1650+
Name name = getMethodName(methodInvocation);
16531651
return Stream.of("stream", "parallelStream", "toBuilder").anyMatch(name::contentEquals);
16541652
})
16551653
.collect(toList());
@@ -1976,8 +1974,7 @@ public Void visitTry(TryTree node, Void unused) {
19761974
if (!first) {
19771975
builder.forcedBreak();
19781976
}
1979-
if (resource instanceof VariableTree) {
1980-
VariableTree variableTree = (VariableTree) resource;
1977+
if (resource instanceof VariableTree variableTree) {
19811978
declareOne(
19821979
DeclarationKind.PARAMETER,
19831980
inlineAnnotationDirection(variableTree.getModifiers()),
@@ -2446,8 +2443,7 @@ private void visitUnionType(VariableTree declaration) {
24462443
/** Accumulate the operands and operators. */
24472444
private static void walkInfix(
24482445
int precedence, ExpressionTree expression, List<ExpressionTree> operands, List<String> operators) {
2449-
if (expression instanceof BinaryTree) {
2450-
BinaryTree binaryTree = (BinaryTree) expression;
2446+
if (expression instanceof BinaryTree binaryTree) {
24512447
if (precedence(binaryTree) == precedence) {
24522448
walkInfix(precedence, binaryTree.getLeftOperand(), operands, operators);
24532449
operators.add(operatorName(expression));
@@ -2958,10 +2954,9 @@ private boolean fillFirstArgument(ExpressionTree e, List<ExpressionTree> items,
29582954
return false;
29592955
}
29602956
// don't special-case calls nested inside expressions
2961-
if (!(e instanceof MethodInvocationTree)) {
2957+
if (!(e instanceof MethodInvocationTree methodInvocation)) {
29622958
return false;
29632959
}
2964-
MethodInvocationTree methodInvocation = (MethodInvocationTree) e;
29652960
Name name = getMethodName(methodInvocation);
29662961
if (!(methodInvocation.getMethodSelect() instanceof IdentifierTree)
29672962
|| name.length() > 4
@@ -3135,7 +3130,7 @@ private ExpressionTree getArrayBase(ExpressionTree node) {
31353130
@SuppressWarnings("for-rollout:NullAway")
31363131
private ExpressionTree getMethodReceiver(MethodInvocationTree methodInvocation) {
31373132
ExpressionTree select = methodInvocation.getMethodSelect();
3138-
return select instanceof MemberSelectTree ? ((MemberSelectTree) select).getExpression() : null;
3133+
return select instanceof MemberSelectTree memberSelectTree ? memberSelectTree.getExpression() : null;
31393134
}
31403135

31413136
private void dotExpressionArgsAndParen(ExpressionTree expression, Indent tyargIndent, Indent indent) {
@@ -3453,11 +3448,10 @@ private int argumentsAreTabular(List<? extends ExpressionTree> arguments) {
34533448
static int rowLength(List<? extends ExpressionTree> row) {
34543449
int size = 0;
34553450
for (ExpressionTree tree : row) {
3456-
if (!(tree instanceof NewArrayTree)) {
3451+
if (!(tree instanceof NewArrayTree array)) {
34573452
size++;
34583453
continue;
34593454
}
3460-
NewArrayTree array = (NewArrayTree) tree;
34613455
if (array.getInitializers() == null) {
34623456
size++;
34633457
continue;
@@ -3656,7 +3650,7 @@ int declareOne(
36563650
if (initializer.isPresent()) {
36573651
builder.space();
36583652
token(equals);
3659-
if (initializer.get() instanceof NewArrayTree && ((NewArrayTree) initializer.get()).getType() == null) {
3653+
if (initializer.get() instanceof NewArrayTree newArrayTree && newArrayTree.getType() == null) {
36603654
builder.open(minusFour);
36613655
builder.space();
36623656
initializer.get().accept(this, null);
@@ -3919,9 +3913,9 @@ private void classDeclarationTypeList(String token, List<? extends Tree> types)
39193913
*/
39203914
private List<VariableTree> variableFragments(PeekingIterator<? extends Tree> it, Tree first) {
39213915
List<VariableTree> fragments = new ArrayList<>();
3922-
if (first instanceof VariableTree) {
3916+
if (first instanceof VariableTree variableTree) {
39233917
int start = getStartPosition(first);
3924-
fragments.add((VariableTree) first);
3918+
fragments.add(variableTree);
39253919
while (it.hasNext() && it.peek() instanceof VariableTree && getStartPosition(it.peek()) == start) {
39263920
fragments.add((VariableTree) it.next());
39273921
}

‎open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,8 @@ public Void visitLiteral(LiteralTree literalTree, Void aVoid) {
194194
return null;
195195
}
196196
Tree parent = getCurrentPath().getParentPath().getLeaf();
197-
if (parent instanceof MemberSelectTree
198-
&& ((MemberSelectTree) parent).getExpression().equals(literalTree)) {
197+
if (parent instanceof MemberSelectTree memberSelectTree
198+
&& memberSelectTree.getExpression().equals(literalTree)) {
199199
return null;
200200
}
201201
int endPosition = getEndPosition(unit, literalTree);

‎open-java-format/src/main/java/com/palantir/javaformat/java/Trees.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,16 +136,16 @@ static String getSourceForNode(Tree node, TreePath path) {
136136
/** Returns the simple name of a (possibly qualified) method invocation expression. */
137137
static Name getMethodName(MethodInvocationTree methodInvocation) {
138138
ExpressionTree select = methodInvocation.getMethodSelect();
139-
return select instanceof MemberSelectTree
140-
? ((MemberSelectTree) select).getIdentifier()
139+
return select instanceof MemberSelectTree memberSelectTree
140+
? memberSelectTree.getIdentifier()
141141
: ((IdentifierTree) select).getName();
142142
}
143143

144144
/** Returns the receiver of a qualified method invocation expression, or {@code null}. */
145145
@SuppressWarnings("for-rollout:NullAway")
146146
static ExpressionTree getMethodReceiver(MethodInvocationTree methodInvocation) {
147147
ExpressionTree select = methodInvocation.getMethodSelect();
148-
return select instanceof MemberSelectTree ? ((MemberSelectTree) select).getExpression() : null;
148+
return select instanceof MemberSelectTree memberSelectTree ? memberSelectTree.getExpression() : null;
149149
}
150150

151151
/** Returns the string name of an operator, including assignment and compound assignment. */

0 commit comments

Comments
 (0)