Skip to content

Commit

Permalink
[Enhanced Switch] Bug 575652 - [17][codegen][switch pattern] Unnecessary
Browse files Browse the repository at this point in the history
casts in switch

* Fixes eclipse-jdt#3465
  • Loading branch information
srikanth-sankaran committed Dec 18, 2024
1 parent 9d3138b commit 427208c
Show file tree
Hide file tree
Showing 2 changed files with 133 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ public void generateCode(BlockScope currentScope, CodeStream codeStream, BranchL
} else {

if (!this.isTotalTypeNode) {
boolean checkCast = JavaFeature.PRIMITIVES_IN_PATTERNS.isSupported(currentScope.compilerOptions()) ?
!this.local.binding.type.isBaseType() : true;
boolean checkCast = TypeBinding.notEquals(this.outerExpressionType, this.local.binding.type) &&
(JavaFeature.PRIMITIVES_IN_PATTERNS.isSupported(currentScope.compilerOptions()) ? !this.local.binding.type.isBaseType() : true);
if (checkCast)
codeStream.checkcast(this.local.binding.type);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9670,4 +9670,135 @@ public static void main(String[] args) {
String unexpectedOutput = "static synthetic int[] $SWITCH_TABLE$E();\n";
SwitchPatternTest.verifyClassFile(expectedOutput, unexpectedOutput, "X.class", ClassFileBytesDisassembler.SYSTEM);
}

// https://github.com/eclipse-jdt/eclipse.jdt.core/issues/3465
// [Enhanced Switch] Bug 575652 - [17][codegen][switch pattern] Unnecessary casts in switch
public void testIssue3465() throws Exception {
runConformTest(
new String[] {
"X.java",
"""
import static java.util.stream.IntStream.rangeClosed;
public interface X {
static String fizzbuzz(int i) {
return switch((Integer) i) {
case Integer v when v % 15 == 0 -> "FizzBuzz";
case Integer v when v % 5 == 0 -> "Buzz";
case Integer v when v % 3 == 0 -> "Fizz";
case Integer v -> "" + v;
};
}
static void main(String[] args) {
rangeClosed(1, 100).mapToObj(i -> fizzbuzz(i)).forEach(System.out::println);
}
}
"""
},
"""
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz""");
String expectedOutput = "typeSwitch";
String unexpectedOutput = "checkcast";
SwitchPatternTest.verifyClassFile(expectedOutput, unexpectedOutput, "X.class", ClassFileBytesDisassembler.SYSTEM);
}
}

0 comments on commit 427208c

Please sign in to comment.