Skip to content

Commit

Permalink
Closes #73: Fix bug where we detect unreachable case pattern when usi…
Browse files Browse the repository at this point in the history
…ng 'if' in pattern
  • Loading branch information
jaccomoc committed Dec 12, 2024
1 parent 5ecf45a commit 3f140ab
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/main/java/io/jactl/resolver/SwitchResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@ public static JactlType visitSwitch(Resolver resolver, Expr.Switch expr) {

// Check that if there is a pattern covering all cases that there are no subsequent patterns and no default
Set<JactlType> coveredTypes = new HashSet<>();
expr.cases.forEach(c -> c.patterns.stream().map(pair -> pair.first).forEach(p -> {
JactlType type = coveringType(p);
if (coveredTypes.stream().anyMatch(ct -> ct.is(ANY) || ct.is(subjectType) || ct.isAssignableFrom(p.type) || (type != null && ct.isAssignableFrom(type)))) {
resolver.error("Unreachable switch case (covered by a previous case)", p.location);
expr.cases.forEach(c -> c.patterns.stream().forEach(pair -> {
Expr pattern = pair.first;
Expr ifCond = pair.second;
JactlType type = coveringType(pattern);
if (coveredTypes.stream().anyMatch(ct -> ct.is(ANY) || ct.is(subjectType) || ct.isAssignableFrom(pattern.type) || (type != null && ct.isAssignableFrom(type)))) {
resolver.error("Unreachable switch case (covered by a previous case)", pattern.location);
}
if (type != null) {
if (type != null && ifCond == null) {
coveredTypes.add(type);
}
}));
Expand Down
3 changes: 3 additions & 0 deletions src/test/java/io/jactl/SwitchTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,9 @@ public class SwitchTests extends BaseTest {
test("def x = [[[3,7]],[[4,9]]]; switch (x) { [[_],[[3,7]]] -> 3; [[[3,7]],_] -> 4; _ -> null }", 4);
test("def x = [[[3,7]],[[4,9]]]; switch (x) { [[_],[[3,7]]] -> 3; [_,[a]] -> a; _ -> null } == [4,9]", true);
test("def x = [[[3,7]],[[4,9]]]; switch (x) { [[_],[[3,7]]] -> 3; [_,[List a]] -> a; _ -> null } == [4,9]", true);
test("switch (3) {\n int if it == 3 -> '3'\n int -> 'something else'\n}", "3");
test("def x = [1,2,3]; switch (x) { _ if it.size() == 2 -> 2; _ if it.size() == 3 -> 3 }", 3);
testError("def x = [1,2,3]; switch (x) { _ -> 2; _ if it.size() == 3 -> 3 }", "unreachable switch case");
}

@Test public void switchArrays() {
Expand Down

0 comments on commit 3f140ab

Please sign in to comment.