Skip to content

Commit

Permalink
SONARJAVA-4617 S1226 - Fix CFG construction inside "return switch" ex…
Browse files Browse the repository at this point in the history
…pression for yield without break cases (#4533)
  • Loading branch information
irina-batinic-sonarsource authored Nov 21, 2023
1 parent cf2b33d commit 751ab82
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
import java.util.function.Supplier;

class A {

public String foo(int dt, String myString) {
dt = 1; // Noncompliant
myString = switch (dt) { // Compliant - FN
case 1 -> {
yield myString + "";
}
default -> null;
};
return myString;
}

public String foo3(int dt, String myString) {
dt = 1; // Noncompliant
myString = switch (dt) { // Noncompliant
case 1 -> {
yield "";
}
default -> null;
};
return myString;
}

public String foo2(int dt, String myString2) {
String str = switch (dt) { // Compliant
case 1 -> {
try {
yield myString2 + "";
} catch (Exception e) {
yield "Exc";
}
}
default -> null;
};
}
public void f() {
}
abstract void method();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@
import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath;

class ParameterReassignedToCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile("src/test/files/checks/ParameterReassignedToCheck.java")
.onFile(nonCompilingTestSourcesPath("checks/ParameterReassignedToCheck.java"))
.withCheck(new ParameterReassignedToCheck())
.verifyIssues();
}
Expand Down
2 changes: 1 addition & 1 deletion java-frontend/src/main/java/org/sonar/java/cfg/CFG.java
Original file line number Diff line number Diff line change
Expand Up @@ -923,7 +923,7 @@ private void buildBreakStatement(BreakStatementTree tree) {
}

private void buildYieldStatement(YieldStatementTree tree) {
currentBlock = createUnconditionalJump(tree, breakTargets.getLast(), currentBlock);
currentBlock = createUnconditionalJump(tree, breakTargets.isEmpty() ? null : breakTargets.getLast(), currentBlock);
build(tree.expression());
currentBlock.exitBlock = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,11 @@ void compute_cfg() {
cfg = method.cfg();
assertThat(cfg).isNotNull();
assertThat(method.cfg()).isSameAs(cfg);

MethodTree methodWithSwitchAndYield = getUniqueMethod("class A { String foo(int arg) {return switch (arg) {case 1: yield \"Got a 1\"; case 2: yield \"Got a 2\"; default: yield \"More than 2\";};}}");
cfg = methodWithSwitchAndYield.cfg();
assertThat(cfg).isNotNull();
assertThat(methodWithSwitchAndYield.cfg()).isSameAs(cfg);
}

@Test
Expand Down

0 comments on commit 751ab82

Please sign in to comment.