Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private static Optional<JCheckBox> findCheckBox(Component root) {
if (root instanceof Container container) {
return Arrays.stream(container.getComponents())
.map(PalantirJavaFormatConfigurableTest::findCheckBox)
.flatMap(Optional::stream)
.<JCheckBox>mapMulti(Optional::ifPresent)
.findFirst();
}
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof Replacement) {
Replacement that = (Replacement) o;
if (o instanceof Replacement that) {
return replaceRange.equals(that.getReplaceRange()) && replacementString.equals(that.getReplacementString());
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,16 @@ public static String guessLineSeparator(String text) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (c) {
case '\r':
case '\r' -> {
if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
return "\r\n";
}
return "\r";
case '\n':
}
case '\n' -> {
return "\n";
default:
break;
}
default -> {}
}
}
return "\n";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,10 @@ public Optional<Boolean> wanted(State state) {

@Override
public BlankLineWanted merge(BlankLineWanted other) {
if (!(other instanceof ConditionalBlankLine)) {
if (!(other instanceof ConditionalBlankLine conditionalBlankLine)) {
return other;
}
return new ConditionalBlankLine(Iterables.concat(this.tags, ((ConditionalBlankLine) other).tags));
return new ConditionalBlankLine(Iterables.concat(this.tags, conditionalBlankLine.tags));
}
}
}
Expand Down Expand Up @@ -522,13 +522,12 @@ public OpsOutput build() {
int opsN = ops.size();
for (int i = 0; i < opsN; i++) {
Op op = ops.get(i);
if (op instanceof Token) {
if (op instanceof Token tokenOp) {
/*
* Token ops can have associated non-tokens, including comments, which we need to insert.
* They can also cause line breaks, so we insert them before or after the current level,
* when possible.
*/
Token tokenOp = (Token) op;
Input.Token token = tokenOp.getToken();
int j = i; // Where to insert toksBefore before.
while (0 < j && ops.get(j - 1) instanceof OpenOp) {
Expand Down Expand Up @@ -654,9 +653,9 @@ public OpsOutput build() {
Op op = ops.get(i);
if (afterForcedBreak
&& (op instanceof NonBreakingSpace
|| (op instanceof Break
&& ((Break) op).evalPlusIndent(State.startingState()) == 0
&& " ".equals(((Doc) op).getFlat())))) {
|| (op instanceof Break b
&& b.evalPlusIndent(State.startingState()) == 0
&& " ".equals(b.getFlat())))) {
continue;
}
newOps.add(op);
Expand All @@ -681,7 +680,7 @@ private static boolean isNonNlsComment(Input.Tok tokAfter) {
}

private static boolean isForcedBreak(Op op) {
return op instanceof Break && ((Break) op).isForced();
return op instanceof Break b && b.isForced();
}

private static List<Op> makeComment(Input.Tok comment) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@

public interface DocVisitor<T> {
default T visit(Doc doc) {
if (doc instanceof Level) {
return visitLevel((Level) doc);
} else if (doc instanceof Break) {
return visitBreak((Break) doc);
} else if (doc instanceof Token) {
return visitToken((Token) doc);
} else if (doc instanceof Comment) {
return visitComment((Comment) doc);
} else if (doc instanceof NonBreakingSpace) {
return visitSpace((NonBreakingSpace) doc);
if (doc instanceof Level level) {
return visitLevel(level);
} else if (doc instanceof Break b) {
return visitBreak(b);
} else if (doc instanceof Token token) {
return visitToken(token);
} else if (doc instanceof Comment comment) {
return visitComment(comment);
} else if (doc instanceof NonBreakingSpace space) {
return visitSpace(space);
}
throw new RuntimeException();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,11 @@ private Optional<Integer> tryToFitOnOneLine(int maxWidth, State state, Iterable<
int column = state.column();
int columnBeforeLastBreak = 0; // Not activated by default
for (Doc doc : docs) {
if (doc instanceof Break && ((Break) doc).hasColumnLimit()) {
if (doc instanceof Break b && b.hasColumnLimit()) {
columnBeforeLastBreak = column;
} else if (doc instanceof Level) {
} else if (doc instanceof Level innerLevel) {
// Levels might have nested levels that have a 'columnLimitBeforeLastBreak' set, so recurse.
State newState = state.withColumn(column);
Level innerLevel = (Level) doc;
Optional<Integer> newWidth = innerLevel.tryToFitOnOneLine(maxWidth, newState, innerLevel.getDocs());
if (!newWidth.isPresent()) {
return Optional.empty();
Expand Down Expand Up @@ -571,10 +570,10 @@ private static Optional<State> tryBreakInnerLevel_checkInner(
}
Level lastLevel2 = ((Level) getLast(innerLevel.docs));
switch (lastLevel2.getBreakabilityIfLastLevel()) {
case ABORT:
case CHECK_INNER:
case ABORT, CHECK_INNER -> {
return Optional.empty();
case ACCEPT_INLINE_CHAIN:
}
case ACCEPT_INLINE_CHAIN -> {
Exploration broken =
innerLevel.breakNormally(state, levelNode, commentsHelper, maxWidth);
return innerLevel.handle_breakOnlyIfInnerLevelsThenFitOnOneLine(
Expand All @@ -584,11 +583,13 @@ private static Optional<State> tryBreakInnerLevel_checkInner(
broken.state(),
keepIndentWhenInlined,
explorationNode);
case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER:
}
case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER -> {
// specific to lambda body expressions - falls back to `breakNormally` in
// `preferBreakingLastInnerLevel`
return Optional.empty();
default:
}
default ->
throw new RuntimeException("Unknown breakabilityIfLastLevel: " + lastLevel2);
}
})
Expand Down Expand Up @@ -633,10 +634,10 @@ private static SplitsBreaks splitByBreaks(List<Doc> docs) {
ImmutableSplitsBreaks.Builder builder = ImmutableSplitsBreaks.builder();
ImmutableList.Builder<Doc> currentSplit = ImmutableList.builder();
for (Doc doc : docs) {
if (doc instanceof Break) {
if (doc instanceof Break b) {
builder.addSplits(currentSplit.build());
currentSplit = ImmutableList.builder();
builder.addBreaks((Break) doc);
builder.addBreaks(b);
} else {
currentSplit.add(doc);
}
Expand Down Expand Up @@ -790,8 +791,7 @@ private int getMaxDepth() {
private int computeMaxDepth(Iterable<Doc> docs) {
int maxChildDepth = 0;
for (Doc doc : docs) {
if (doc instanceof Level) {
Level childLevel = (Level) doc;
if (doc instanceof Level childLevel) {
maxChildDepth = Math.max(maxChildDepth, childLevel.getMaxDepth());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,83 +79,30 @@ static CommandLineOptions parse(Iterable<String> options) {
}
// NOTE: update usage information in UsageException when new flags are added
switch (flag) {
case "-i":
case "-r":
case "-replace":
case "--replace":
optionsBuilder.inPlace(true);
break;
case "--lines":
case "-lines":
case "--line":
case "-line":
case "-i", "-r", "-replace", "--replace" -> optionsBuilder.inPlace(true);
case "--lines", "-lines", "--line", "-line" ->
parseRangeSet(optionsBuilder.linesBuilder(), getValue(flag, it, value));
break;
case "--character-ranges":
case "-character-ranges":
case "--character-range":
case "-character-range":
case "--character-ranges", "-character-ranges", "--character-range", "-character-range" ->
parseCharacterRanges(optionsBuilder.characterRangesBuilder(), getValue(flag, it, value));
break;
case "--offset":
case "-offset":
optionsBuilder.addOffset(parseInteger(it, flag, value));
break;
case "--length":
case "-length":
optionsBuilder.addLength(parseInteger(it, flag, value));
break;
case "--aosp":
case "-aosp":
case "-a":
case "--ojf":
case "-ojf":
case "--offset", "-offset" -> optionsBuilder.addOffset(parseInteger(it, flag, value));
case "--length", "-length" -> optionsBuilder.addLength(parseInteger(it, flag, value));
case "--aosp", "-aosp", "-a", "--ojf", "-ojf" ->
// There is one style. The old style flags are accepted so that a script keeps working, and
// Main warns about each of them.
optionsBuilder.addUnsupportedFlag(flag);
break;
case "--version":
case "-version":
case "-v":
optionsBuilder.version(true);
break;
case "--help":
case "-help":
case "-h":
optionsBuilder.help(true);
break;
case "--fix-imports-only":
optionsBuilder.fixImportsOnly(true);
break;
case "--skip-sorting-imports":
optionsBuilder.sortImports(false);
break;
case "--skip-removing-unused-imports":
optionsBuilder.removeUnusedImports(false);
break;
case "--skip-reflowing-long-strings":
optionsBuilder.reflowLongStrings(false);
break;
case "-":
optionsBuilder.stdin(true);
break;
case "-n":
case "--dry-run":
optionsBuilder.dryRun(true);
break;
case "--set-exit-if-changed":
optionsBuilder.setExitIfChanged(true);
break;
case "-assume-filename":
case "--assume-filename":
case "--version", "-version", "-v" -> optionsBuilder.version(true);
case "--help", "-help", "-h" -> optionsBuilder.help(true);
case "--fix-imports-only" -> optionsBuilder.fixImportsOnly(true);
case "--skip-sorting-imports" -> optionsBuilder.sortImports(false);
case "--skip-removing-unused-imports" -> optionsBuilder.removeUnusedImports(false);
case "--skip-reflowing-long-strings" -> optionsBuilder.reflowLongStrings(false);
case "-" -> optionsBuilder.stdin(true);
case "-n", "--dry-run" -> optionsBuilder.dryRun(true);
case "--set-exit-if-changed" -> optionsBuilder.setExitIfChanged(true);
case "-assume-filename", "--assume-filename" ->
optionsBuilder.assumeFilename(getValue(flag, it, value));
break;
case "-output-replacements":
case "--output-replacements":
optionsBuilder.outputReplacements(true);
break;
default:
throw new IllegalArgumentException("unexpected flag: " + flag);
case "-output-replacements", "--output-replacements" -> optionsBuilder.outputReplacements(true);
default -> throw new IllegalArgumentException("unexpected flag: " + flag);
}
}
return optionsBuilder.build();
Expand Down Expand Up @@ -196,15 +143,16 @@ private static void parseCharacterRanges(ImmutableRangeSet.Builder<Integer> resu
private static Range<Integer> parseCharacterRange(String range) {
List<String> args = COLON_SPLITTER.splitToList(range);
switch (args.size()) {
case 1:
case 1 -> {
int lowerUpperRange = Integer.parseInt(args.get(0));
return Range.closed(lowerUpperRange, lowerUpperRange);
case 2:
}
case 2 -> {
int lower = Integer.parseInt(args.get(0));
int higher = Integer.parseInt(args.get(1));
return Range.closed(lower, higher);
default:
throw new IllegalArgumentException(range);
}
default -> throw new IllegalArgumentException(range);
}
}

Expand All @@ -226,15 +174,16 @@ private static void parseRangeSet(RangeSet<Integer> result, String ranges) {
private static Range<Integer> parseRange(String arg) {
List<String> args = COLON_SPLITTER.splitToList(arg);
switch (args.size()) {
case 1:
case 1 -> {
int line = Integer.parseInt(args.get(0)) - 1;
return Range.closedOpen(line, line + 1);
case 2:
}
case 2 -> {
int line0 = Integer.parseInt(args.get(0)) - 1;
int line1 = Integer.parseInt(args.get(1)) - 1;
return Range.closedOpen(line0, line1 + 1);
default:
throw new IllegalArgumentException(arg);
}
default -> throw new IllegalArgumentException(arg);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,15 @@ static void render(
String formatterDecisionsJson) {

String javascript = String.format(
"window.palantirJavaFormat = {\njavaInput: %s,\nops: %s,\ndoc: %s,\njavaOutput: %s,\n"
+ "formatterDecisions: %s\n};\n",
"""
window.palantirJavaFormat = {
javaInput: %s,
ops: %s,
doc: %s,
javaOutput: %s,
formatterDecisions: %s
};
""",
jsonEscapedString(javaInput.getText()),
opsJson(opsOutput),
new JsonDocVisitor(finalState).visit(doc),
Expand Down Expand Up @@ -90,8 +97,7 @@ private static String opsJson(OpsOutput opsOutput) {

ImmutableList<Op> ops = opsOutput.ops();
for (Op op : ops) {
if (op instanceof Token) {
Token token = (Token) op;
if (op instanceof Token token) {
Input.Token inputToken = token.getToken();

ObjectNode json = arrayNode.addObject();
Expand All @@ -109,9 +115,7 @@ private static String opsJson(OpsOutput opsOutput) {
.collect(Collectors.joining()));
json.put("hue", computeHue(token));
}
if (op instanceof Break) {
Break breakOp = (Break) op;

if (op instanceof Break breakOp) {
ObjectNode json = arrayNode.addObject();
json.put("type", "break");
json.put("fillMode", breakOp.fillMode().toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,21 @@ private static Iterable<List<AnnotationTree>> reorderBySourcePosition(Deque<List
*/
private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) {
switch (node.getKind()) {
case ARRAY_TYPE:
case ARRAY_TYPE -> {
return extractDims(dims, ((ArrayTypeTree) node).getType());
case ANNOTATED_TYPE:
}
case ANNOTATED_TYPE -> {
AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node;
if (!(annotatedTypeTree.getUnderlyingType() instanceof ArrayTypeTree)) {
return node;
}
node = extractDims(dims, annotatedTypeTree.getUnderlyingType());
dims.addFirst(ImmutableList.copyOf(annotatedTypeTree.getAnnotations()));
return node;
default:
}
default -> {
return node;
}
}
}
}
Loading
Loading