Skip to content

Initial support for pattern matching in switches #999

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 8, 2023
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 @@ -83,14 +83,20 @@ public Void visitBindingPattern(BindingPatternTree node, Void unused) {
}

private void visitBindingPattern(ModifiersTree modifiers, Tree type, Name name) {
builder.open(plusFour);
if (modifiers != null) {
List<AnnotationTree> annotations =
visitModifiers(modifiers, Direction.HORIZONTAL, Optional.empty());
visitAnnotations(annotations, BreakOrNot.NO, BreakOrNot.YES);
}
scan(type, null);
builder.breakOp(" ");
visit(name);
if (name.isEmpty()) {
token("_");
} else {
visit(name);
}
builder.close();
}

@Override
Expand Down Expand Up @@ -222,6 +228,11 @@ public Void visitCase(CaseTree node, Void unused) {
List<? extends CaseLabelTree> labels = node.getLabels();
boolean isDefault =
labels.size() == 1 && getOnlyElement(labels).getKind().name().equals("DEFAULT_CASE_LABEL");
builder.open(
node.getCaseKind().equals(CaseTree.CaseKind.RULE)
&& !node.getBody().getKind().equals(Tree.Kind.BLOCK)
? plusFour
: ZERO);
if (isDefault) {
token("default", plusTwo);
} else {
Expand Down Expand Up @@ -259,22 +270,24 @@ public Void visitCase(CaseTree node, Void unused) {
builder.space();
token("-");
token(">");
builder.space();
if (node.getBody().getKind() == Tree.Kind.BLOCK) {
builder.space();
// Explicit call with {@link CollapseEmptyOrNot.YES} to handle empty case blocks.
visitBlock(
(BlockTree) node.getBody(),
CollapseEmptyOrNot.YES,
AllowLeadingBlankLine.NO,
AllowTrailingBlankLine.NO);
} else {
builder.breakOp(" ");
scan(node.getBody(), null);
}
builder.guessToken(";");
break;
default:
throw new AssertionError(node.getCaseKind());
}
builder.close();
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
import com.google.googlejavaformat.OpsBuilder;
import com.google.googlejavaformat.java.java17.Java17InputAstVisitor;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.ConstantCaseLabelTree;
import com.sun.source.tree.DeconstructionPatternTree;
import com.sun.source.tree.DefaultCaseLabelTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.PatternCaseLabelTree;
import com.sun.source.tree.PatternTree;

/**
* Extends {@link Java17InputAstVisitor} with support for AST nodes that were added or modified in
Expand All @@ -33,4 +38,42 @@ public Java21InputAstVisitor(OpsBuilder builder, int indentMultiplier) {
protected ExpressionTree getGuard(final CaseTree node) {
return node.getGuard();
}

@Override
public Void visitDefaultCaseLabel(DefaultCaseLabelTree node, Void unused) {
token("default");
return null;
}

@Override
public Void visitPatternCaseLabel(PatternCaseLabelTree node, Void unused) {
scan(node.getPattern(), null);
return null;
}

@Override
public Void visitConstantCaseLabel(ConstantCaseLabelTree node, Void aVoid) {
scan(node.getConstantExpression(), null);
return null;
}

@Override
public Void visitDeconstructionPattern(DeconstructionPatternTree node, Void unused) {
scan(node.getDeconstructor(), null);
builder.open(plusFour);
token("(");
builder.breakOp();
boolean first = true;
for (PatternTree pattern : node.getNestedPatterns()) {
if (!first) {
token(",");
builder.breakOp(" ");
}
first = false;
scan(pattern, null);
}
builder.close();
token(")");
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public class FormatterIntegrationTest {
.putAll(15, "I603")
.putAll(16, "I588")
.putAll(17, "I683", "I684", "I696")
.putAll(21, "SwitchGuardClause")
.putAll(
21, "SwitchGuardClause", "SwitchRecord", "SwitchDouble", "SwitchUnderscore", "I880")
.build();

@Parameters(name = "{index}: {0}")
Expand Down Expand Up @@ -94,7 +95,7 @@ public static Iterable<Object[]> data() throws IOException {
String expectedOutput = outputs.get(fileName);
Optional<Integer> version =
VERSIONED_TESTS.inverse().get(fileName).stream().collect(toOptional());
if (version.isPresent() && Runtime.version().feature() < version.get()) {
if (Runtime.version().feature() < version.orElse(Integer.MAX_VALUE)) {
continue;
}
testInputs.add(new Object[] {fileName, input, expectedOutput});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class I880 {
public String f(int i) {
return switch (i) {
case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 -> "looooooooooooooooooooooooooooooooooooooooong expression";
default -> "looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong expression";
};
}

public boolean test(int i) {
return switch (i) {
case 0 -> // zero
false;
case 1 -> "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".length()
== 0;
default -> // otherwise
true;
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class I880 {
public String f(int i) {
return switch (i) {
case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ->
"looooooooooooooooooooooooooooooooooooooooong expression";
default ->
"looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong expression";
};
}

public boolean test(int i) {
return switch (i) {
case 0 -> // zero
false;
case 1 ->
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".length() == 0;
default -> // otherwise
true;
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class SwitchDouble {
void x(Object o) {
switch (o) {
case null, default:
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class SwitchDouble {
void x(Object o) {
switch (o) {
case null, default:
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
record SwitchRecord(int i) {
int x(Object o) {
return switch (o) {
case SwitchRecord(int i) -> i;
default -> 0;
};
}
int f(Object o) {
return switch (o) {
case SwitchRecord(int one, int two, int three, int four, int five, int six, int seven, int eight, int nine) -> nine;
default -> 0;
};
}
int g(Object o) {
return switch (o) {
case SwitchRecord(int one, int two, int three, int four, int five, int six, int seven, int eight, int nine) ->
System.err.println("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");
default -> 0;
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
record SwitchRecord(int i) {
int x(Object o) {
return switch (o) {
case SwitchRecord(int i) -> i;
default -> 0;
};
}

int f(Object o) {
return switch (o) {
case SwitchRecord(
int one,
int two,
int three,
int four,
int five,
int six,
int seven,
int eight,
int nine) ->
nine;
default -> 0;
};
}

int g(Object o) {
return switch (o) {
case SwitchRecord(
int one,
int two,
int three,
int four,
int five,
int six,
int seven,
int eight,
int nine) ->
System.err.println(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor"
+ " incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis"
+ " nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo"
+ " consequat.");
default -> 0;
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
public class SwitchUnderscore {
void x(Object o) {
switch (o) {
case String _:
default:
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
public class SwitchUnderscore {
void x(Object o) {
switch (o) {
case String _:
default:
}
}
}