Draft JEP on pattern matching
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Sun Jun 4 21:13:50 UTC 2017
On 04/06/17 14:52, Mark Raynsford wrote:
> How would the following behave with guards?
>
> switch (c) {
> case Integer i && i >= 0: return 1;
> case Integer i && i >= 1: return 2;
> default: return 3;
> }
>
> What happens if c == 2?
> What happens if the guards have side effects?
>
> For that matter:
>
> switch (c) {
> case Integer i: return 1;
> case Number n: return 2;
> case Object o: return 3;
> default: return 4;
> }
>
> What happens if c is an Integer? A Number? An Object? Is the default
> branch actually necessary if one of the branches specifies Object with
> no guards?
Hi Mark,
we are planning to extend flow analysis to reason about pattern
reachability - we have informally been talking about a 'dominance'
relation between patterns - e.g. 'Object o' dominates 'Integer i', etc.
If a pattern occurs after another that dominates it, then it is a
compile-time error, as the pattern is unreachable. This is the basic
story, and seems to be working well - in the absence of
break/continue/guards. Obviously we need to extend this basic story to
take into account abnormal completion (continue) - but that should be
easy to do. E.g. a pattern dominates some other pattern only if it
completes normally (no continue).
As for guards, if you imagine desugaring guards as follows:
case p && g: ...
as
case p:
if (!g) continue;
...
Then it follows that in your example no pattern is unreachable. That
said, this story is potentially incomplete - as it doesn't cover the
fact that there could be different guards which evaluate to true with
similar inputs - e.g.
case Integer i && (i >= 0 && i < 5): return 1;
case Integer i && (i < 5 && i >= 0: return 2;
Using my proposed solution, this would be ok for the static compiler,
but obviously the two guards are the same thing, just written in
different way. My sense is that we can't do much for this kind of things
in flow analysis, as you can always come up with more convoluted example
which would defeat whatever complex logic you put into the static checks.
Maurizio
More information about the amber-dev
mailing list