diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java index 82a68eebcca..ae9f4058fe6 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java @@ -1046,4 +1046,113 @@ void test(Object e) { """) .doTest(); } + + @Test + public void castVariableReassigned_brokenRefactoring() { + // TODO: b/395603588 - This refactoring is broken because 's' is reassigned, + // but pattern variables are implicitly final. It should be expectUnchanged(). + helper + .allowBreakingChanges() + .addInputLines( + "Test.java", + """ + class Test { + void test(Object o) { + if (o instanceof String) { + String s = (String) o; + s = "new value"; + System.out.println(s); + } + } + } + """) + .addOutputLines( + "Test.java", + """ + class Test { + void test(Object o) { + if (o instanceof String s) { + + s = "new value"; + System.out.println(s); + } + } + } + """) + .doTest(); + } + + @Test + public void scopeExpansionClobbering_brokenRefactoring() { + // TODO: b/395603588 - This refactoring is broken because the pattern variable 's' + // scope expands and clashes with 'int s = 0'. It should be expectUnchanged(). + helper + .allowBreakingChanges() + .addInputLines( + "Test.java", + """ + class Test { + void test(Object o) { + if (!(o instanceof String)) { + return; + } + { + String s = (String) o; + System.out.println(s); + } + int s = 0; + } + } + """) + .addOutputLines( + "Test.java", + """ + class Test { + void test(Object o) { + if (!(o instanceof String s)) { + return; + } + { + System.out.println(s); + } + int s = 0; + } + } + """) + .doTest(); + } + + @Test + public void patternVariableScopeDoesNotOverlapWithLaterDeclaration() { + helper + .addInputLines( + "Test.java", + """ + class Test { + void test(Object o) { + if (o instanceof String) { + String s = (String) o; + System.out.println(s); + } + int s = 0; + System.out.println(s); + } + } + """) + .addOutputLines( + "Test.java", + """ + class Test { + void test(Object o) { + if (o instanceof String s) { + + System.out.println(s); + } + int s = 0; + System.out.println(s); + } + } + """) + .doTest(); + } }