RFR: 8334722: Error emitted when switch expression does not yield any value lacks reasoning [v3]
Jan Lahoda
jlahoda at openjdk.org
Mon Jun 24 08:44:12 UTC 2024
On Sun, 23 Jun 2024 21:04:41 GMT, Evemose <duke at openjdk.org> wrote:
>> Please review this trivial enhancement to informativity of error emiited when switch expression does not yield value in any branch lacks reasoning.
>>
>> Issue body:
>> Currently, when switch expression does not yield any value, compiler emits following error: "switch expression does not have any result expressions". While this gives information on how to solve the issue, the exact reason of this error stays unclear, expecially because switch *statements* do not have same requirement. Recently, there even were question about this in one of jdk mailing lists.
>>
>> The source of issue becomes obvious if we look where this error is reported: it is emmited in Attr class when javac is unable to assign type to switch expression. Therefore, I propose to change the emitted error text to following: "Unable to determine switch expression type: no branch that yields value found".
>>
>> If anyone have ideas on how to furthernore improve this error message, please feel free to share.
>
> Evemose has updated the pull request with a new target base due to a merge or a rebase. The incremental webrev excludes the unrelated changes brought in by the merge/rebase. The pull request contains three additional commits since the last revision:
>
> - Merge branch 'openjdk:master' into improved-switch-expr-error
> - fix typo
> - init
Sorry, but I am not quite sure what's the problem with the (existing) error, and if the new one is better.
There are two reasons for that:
a) the specification:
https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.28.1
literally says:
> It is a compile-time error if a switch expression has no result expressions.
It does not say it is a compile-time error is that the switch expression's type cannot be determined (see below), but that it is an error if there are not result expression. And while trouble determining the expressions type are likely a part of the motivation for this assertion, it is not the only one, I think.
b) for code like:
private void c() {
test(switch (0) {
default -> 0;
});
}
private void test(int i) {}
the type of the switch expression is not determined by the result expressions, but by the target type. I.e. in this case, the type of the expression is `int`, regardless whether there is any `yield` returning `int` or not. It would, in principle, be possible to permit no result expression in cases like this, I think. It is unclear what would be the usefulness of that, though.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/19837#issuecomment-2185938289
More information about the compiler-dev
mailing list