Skip to content

Commit e496bdc

Browse files
authored
Merge pull request #86 from openjavaformat/errorprone-warnings
Use the Java idioms error-prone asks for: instanceof patterns, arrow switches, text blocks
2 parents 1a01c3b + 9e18a06 commit e496bdc

20 files changed

Lines changed: 356 additions & 485 deletions

File tree

‎open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ private static Optional<JCheckBox> findCheckBox(Component root) {
108108
if (root instanceof Container container) {
109109
return Arrays.stream(container.getComponents())
110110
.map(PalantirJavaFormatConfigurableTest::findCheckBox)
111-
.flatMap(Optional::stream)
111+
.<JCheckBox>mapMulti(Optional::ifPresent)
112112
.findFirst();
113113
}
114114
return Optional.empty();

‎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/Newlines.java‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,15 +71,16 @@ public static String guessLineSeparator(String text) {
7171
for (int i = 0; i < text.length(); i++) {
7272
char c = text.charAt(i);
7373
switch (c) {
74-
case '\r':
74+
case '\r' -> {
7575
if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
7676
return "\r\n";
7777
}
7878
return "\r";
79-
case '\n':
79+
}
80+
case '\n' -> {
8081
return "\n";
81-
default:
82-
break;
82+
}
83+
default -> {}
8384
}
8485
}
8586
return "\n";

‎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: 12 additions & 12 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();
@@ -571,10 +570,10 @@ private static Optional<State> tryBreakInnerLevel_checkInner(
571570
}
572571
Level lastLevel2 = ((Level) getLast(innerLevel.docs));
573572
switch (lastLevel2.getBreakabilityIfLastLevel()) {
574-
case ABORT:
575-
case CHECK_INNER:
573+
case ABORT, CHECK_INNER -> {
576574
return Optional.empty();
577-
case ACCEPT_INLINE_CHAIN:
575+
}
576+
case ACCEPT_INLINE_CHAIN -> {
578577
Exploration broken =
579578
innerLevel.breakNormally(state, levelNode, commentsHelper, maxWidth);
580579
return innerLevel.handle_breakOnlyIfInnerLevelsThenFitOnOneLine(
@@ -584,11 +583,13 @@ private static Optional<State> tryBreakInnerLevel_checkInner(
584583
broken.state(),
585584
keepIndentWhenInlined,
586585
explorationNode);
587-
case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER:
586+
}
587+
case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER -> {
588588
// specific to lambda body expressions - falls back to `breakNormally` in
589589
// `preferBreakingLastInnerLevel`
590590
return Optional.empty();
591-
default:
591+
}
592+
default ->
592593
throw new RuntimeException("Unknown breakabilityIfLastLevel: " + lastLevel2);
593594
}
594595
})
@@ -633,10 +634,10 @@ private static SplitsBreaks splitByBreaks(List<Doc> docs) {
633634
ImmutableSplitsBreaks.Builder builder = ImmutableSplitsBreaks.builder();
634635
ImmutableList.Builder<Doc> currentSplit = ImmutableList.builder();
635636
for (Doc doc : docs) {
636-
if (doc instanceof Break) {
637+
if (doc instanceof Break b) {
637638
builder.addSplits(currentSplit.build());
638639
currentSplit = ImmutableList.builder();
639-
builder.addBreaks((Break) doc);
640+
builder.addBreaks(b);
640641
} else {
641642
currentSplit.add(doc);
642643
}
@@ -790,8 +791,7 @@ private int getMaxDepth() {
790791
private int computeMaxDepth(Iterable<Doc> docs) {
791792
int maxChildDepth = 0;
792793
for (Doc doc : docs) {
793-
if (doc instanceof Level) {
794-
Level childLevel = (Level) doc;
794+
if (doc instanceof Level childLevel) {
795795
maxChildDepth = Math.max(maxChildDepth, childLevel.getMaxDepth());
796796
}
797797
}

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

Lines changed: 28 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -79,83 +79,30 @@ static CommandLineOptions parse(Iterable<String> options) {
7979
}
8080
// NOTE: update usage information in UsageException when new flags are added
8181
switch (flag) {
82-
case "-i":
83-
case "-r":
84-
case "-replace":
85-
case "--replace":
86-
optionsBuilder.inPlace(true);
87-
break;
88-
case "--lines":
89-
case "-lines":
90-
case "--line":
91-
case "-line":
82+
case "-i", "-r", "-replace", "--replace" -> optionsBuilder.inPlace(true);
83+
case "--lines", "-lines", "--line", "-line" ->
9284
parseRangeSet(optionsBuilder.linesBuilder(), getValue(flag, it, value));
93-
break;
94-
case "--character-ranges":
95-
case "-character-ranges":
96-
case "--character-range":
97-
case "-character-range":
85+
case "--character-ranges", "-character-ranges", "--character-range", "-character-range" ->
9886
parseCharacterRanges(optionsBuilder.characterRangesBuilder(), getValue(flag, it, value));
99-
break;
100-
case "--offset":
101-
case "-offset":
102-
optionsBuilder.addOffset(parseInteger(it, flag, value));
103-
break;
104-
case "--length":
105-
case "-length":
106-
optionsBuilder.addLength(parseInteger(it, flag, value));
107-
break;
108-
case "--aosp":
109-
case "-aosp":
110-
case "-a":
111-
case "--ojf":
112-
case "-ojf":
87+
case "--offset", "-offset" -> optionsBuilder.addOffset(parseInteger(it, flag, value));
88+
case "--length", "-length" -> optionsBuilder.addLength(parseInteger(it, flag, value));
89+
case "--aosp", "-aosp", "-a", "--ojf", "-ojf" ->
11390
// There is one style. The old style flags are accepted so that a script keeps working, and
11491
// Main warns about each of them.
11592
optionsBuilder.addUnsupportedFlag(flag);
116-
break;
117-
case "--version":
118-
case "-version":
119-
case "-v":
120-
optionsBuilder.version(true);
121-
break;
122-
case "--help":
123-
case "-help":
124-
case "-h":
125-
optionsBuilder.help(true);
126-
break;
127-
case "--fix-imports-only":
128-
optionsBuilder.fixImportsOnly(true);
129-
break;
130-
case "--skip-sorting-imports":
131-
optionsBuilder.sortImports(false);
132-
break;
133-
case "--skip-removing-unused-imports":
134-
optionsBuilder.removeUnusedImports(false);
135-
break;
136-
case "--skip-reflowing-long-strings":
137-
optionsBuilder.reflowLongStrings(false);
138-
break;
139-
case "-":
140-
optionsBuilder.stdin(true);
141-
break;
142-
case "-n":
143-
case "--dry-run":
144-
optionsBuilder.dryRun(true);
145-
break;
146-
case "--set-exit-if-changed":
147-
optionsBuilder.setExitIfChanged(true);
148-
break;
149-
case "-assume-filename":
150-
case "--assume-filename":
93+
case "--version", "-version", "-v" -> optionsBuilder.version(true);
94+
case "--help", "-help", "-h" -> optionsBuilder.help(true);
95+
case "--fix-imports-only" -> optionsBuilder.fixImportsOnly(true);
96+
case "--skip-sorting-imports" -> optionsBuilder.sortImports(false);
97+
case "--skip-removing-unused-imports" -> optionsBuilder.removeUnusedImports(false);
98+
case "--skip-reflowing-long-strings" -> optionsBuilder.reflowLongStrings(false);
99+
case "-" -> optionsBuilder.stdin(true);
100+
case "-n", "--dry-run" -> optionsBuilder.dryRun(true);
101+
case "--set-exit-if-changed" -> optionsBuilder.setExitIfChanged(true);
102+
case "-assume-filename", "--assume-filename" ->
151103
optionsBuilder.assumeFilename(getValue(flag, it, value));
152-
break;
153-
case "-output-replacements":
154-
case "--output-replacements":
155-
optionsBuilder.outputReplacements(true);
156-
break;
157-
default:
158-
throw new IllegalArgumentException("unexpected flag: " + flag);
104+
case "-output-replacements", "--output-replacements" -> optionsBuilder.outputReplacements(true);
105+
default -> throw new IllegalArgumentException("unexpected flag: " + flag);
159106
}
160107
}
161108
return optionsBuilder.build();
@@ -196,15 +143,16 @@ private static void parseCharacterRanges(ImmutableRangeSet.Builder<Integer> resu
196143
private static Range<Integer> parseCharacterRange(String range) {
197144
List<String> args = COLON_SPLITTER.splitToList(range);
198145
switch (args.size()) {
199-
case 1:
146+
case 1 -> {
200147
int lowerUpperRange = Integer.parseInt(args.get(0));
201148
return Range.closed(lowerUpperRange, lowerUpperRange);
202-
case 2:
149+
}
150+
case 2 -> {
203151
int lower = Integer.parseInt(args.get(0));
204152
int higher = Integer.parseInt(args.get(1));
205153
return Range.closed(lower, higher);
206-
default:
207-
throw new IllegalArgumentException(range);
154+
}
155+
default -> throw new IllegalArgumentException(range);
208156
}
209157
}
210158

@@ -226,15 +174,16 @@ private static void parseRangeSet(RangeSet<Integer> result, String ranges) {
226174
private static Range<Integer> parseRange(String arg) {
227175
List<String> args = COLON_SPLITTER.splitToList(arg);
228176
switch (args.size()) {
229-
case 1:
177+
case 1 -> {
230178
int line = Integer.parseInt(args.get(0)) - 1;
231179
return Range.closedOpen(line, line + 1);
232-
case 2:
180+
}
181+
case 2 -> {
233182
int line0 = Integer.parseInt(args.get(0)) - 1;
234183
int line1 = Integer.parseInt(args.get(1)) - 1;
235184
return Range.closedOpen(line0, line1 + 1);
236-
default:
237-
throw new IllegalArgumentException(arg);
185+
}
186+
default -> throw new IllegalArgumentException(arg);
238187
}
239188
}
240189

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

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,15 @@ static void render(
6161
String formatterDecisionsJson) {
6262

6363
String javascript = String.format(
64-
"window.palantirJavaFormat = {\njavaInput: %s,\nops: %s,\ndoc: %s,\njavaOutput: %s,\n"
65-
+ "formatterDecisions: %s\n};\n",
64+
"""
65+
window.palantirJavaFormat = {
66+
javaInput: %s,
67+
ops: %s,
68+
doc: %s,
69+
javaOutput: %s,
70+
formatterDecisions: %s
71+
};
72+
""",
6673
jsonEscapedString(javaInput.getText()),
6774
opsJson(opsOutput),
6875
new JsonDocVisitor(finalState).visit(doc),
@@ -90,8 +97,7 @@ private static String opsJson(OpsOutput opsOutput) {
9097

9198
ImmutableList<Op> ops = opsOutput.ops();
9299
for (Op op : ops) {
93-
if (op instanceof Token) {
94-
Token token = (Token) op;
100+
if (op instanceof Token token) {
95101
Input.Token inputToken = token.getToken();
96102

97103
ObjectNode json = arrayNode.addObject();
@@ -109,9 +115,7 @@ private static String opsJson(OpsOutput opsOutput) {
109115
.collect(Collectors.joining()));
110116
json.put("hue", computeHue(token));
111117
}
112-
if (op instanceof Break) {
113-
Break breakOp = (Break) op;
114-
118+
if (op instanceof Break breakOp) {
115119
ObjectNode json = arrayNode.addObject();
116120
json.put("type", "break");
117121
json.put("fillMode", breakOp.fillMode().toString());

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,18 +103,21 @@ private static Iterable<List<AnnotationTree>> reorderBySourcePosition(Deque<List
103103
*/
104104
private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) {
105105
switch (node.getKind()) {
106-
case ARRAY_TYPE:
106+
case ARRAY_TYPE -> {
107107
return extractDims(dims, ((ArrayTypeTree) node).getType());
108-
case ANNOTATED_TYPE:
108+
}
109+
case ANNOTATED_TYPE -> {
109110
AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node;
110111
if (!(annotatedTypeTree.getUnderlyingType() instanceof ArrayTypeTree)) {
111112
return node;
112113
}
113114
node = extractDims(dims, annotatedTypeTree.getUnderlyingType());
114115
dims.addFirst(ImmutableList.copyOf(annotatedTypeTree.getAnnotations()));
115116
return node;
116-
default:
117+
}
118+
default -> {
117119
return node;
120+
}
118121
}
119122
}
120123
}

0 commit comments

Comments
 (0)