Fix hasNullCase

This commit is contained in:
Chris Smowton
2023-11-15 15:03:42 +00:00
parent 480781b049
commit de2b98f4a1
4 changed files with 14 additions and 3 deletions

View File

@@ -1547,7 +1547,10 @@ class SwitchExpr extends Expr, StmtParent, @switchexpr {
}
/** Holds if this switch has a case handling a null literal. */
predicate hasNullCase() { this.getAConstCase().getValue(_) instanceof NullLiteral }
predicate hasNullCase() {
this.getAConstCase().getValue(_) instanceof NullLiteral or
this.getACase() instanceof NullDefaultCase
}
/** Gets a printable representation of this expression. */
override string toString() { result = "switch (...)" }

View File

@@ -413,7 +413,10 @@ class SwitchStmt extends Stmt, @switchstmt {
Expr getExpr() { result.getParent() = this }
/** Holds if this switch has a case handling a null literal. */
predicate hasNullCase() { this.getAConstCase().getValue(_) instanceof NullLiteral }
predicate hasNullCase() {
this.getAConstCase().getValue(_) instanceof NullLiteral or
this.getACase() instanceof NullDefaultCase
}
override string pp() { result = "switch (...)" }

View File

@@ -12,6 +12,11 @@ public class G {
default -> System.out.println("Something else");
}
var x = switch(s) { // OK; null case (combined with default) means this doesn't throw.
case "foo" -> "foo";
case null, default -> "bar";
};
switch(s) { // BAD; lack of a null case means this may throw.
case "foo" -> System.out.println("Foo");
case String s2 -> System.out.println("Other string of length " + s2.length());

View File

@@ -35,4 +35,4 @@
| C.java:233:7:233:8 | xs | Variable $@ may be null at this access because of $@ assignment. | C.java:231:5:231:56 | int[] xs | xs | C.java:231:11:231:55 | xs | this |
| F.java:11:5:11:7 | obj | Variable $@ may be null at this access as suggested by $@ null guard. | F.java:8:18:8:27 | obj | obj | F.java:9:9:9:19 | ... == ... | this |
| F.java:17:5:17:7 | obj | Variable $@ may be null at this access as suggested by $@ null guard. | F.java:14:18:14:27 | obj | obj | F.java:15:9:15:19 | ... == ... | this |
| G.java:15:12:15:12 | s | Variable $@ may be null at this access as suggested by $@ null guard. | G.java:3:27:3:34 | s | s | G.java:5:9:5:17 | ... == ... | this |
| G.java:20:12:20:12 | s | Variable $@ may be null at this access as suggested by $@ null guard. | G.java:3:27:3:34 | s | s | G.java:5:9:5:17 | ... == ... | this |