[pattern-switch] Guards

Brian Goetz brian.goetz at oracle.com
Fri Jan 8 21:26:48 UTC 2021



> And in the original Java grammar and to this day, `instanceof` has 
> higher precedence than either `&` or `&&`.  Right now this precedence 
> principle is relevant only for the left-hand operand of `instanceof`; 
> but if this parsing principle is to be preserved consistently, it will 
> also be applied to the right-hand operand of `instanceof`, and it will 
> therefore be necessary to use parentheses around an __AND expression 
> that is the right-hand operand of `instanceof` if __AND is spelled as 
> either `&` or `&&`:
>
>     if (x instanceof P && Q)    should be interpreted as     if ((x 
> instanceof P) && Q)
>
> and if Q turns out to be a type or other pattern but not a valid 
> expression, tough noogies: the parsing decision got made when you saw 
> the ‘&&’ (remember, the parser is LALR(1)).
>
>     if (x instanceof (P && Q))     should be used if you want a 
> conjunctive pattern
>
> We could choose to violate the parsing principle, and say that 
> `instanceof` higher precedence than a `&` or `&&` to its left but 
> lower precedence than a `&` or `&&` to its right, but I predict that 
> such a move would cause enormous confusion among both implementors and 
> users, so I strongly counsel against such a move.

I agree such a move would be poor.  That was my motivation for 
suggesting & for "pattern conjunction" instead of &&; to relegate these 
concerns to irrelevance.  So

     if (x instanceof P & X)

says X is a pattern and we're testing x against the composite pattern P 
AND X, and

     if (x instanceof P && X)

says X is a boolean expression.

> Therefore I don’t see much need for `&` in patterns, but then again 
> allowing it for conciseness (and to indicate that variables matched on 
> its LHS are _not_ in scope on its RHS?) would do no harm.  Same for `|`.
>
>> But I think we can use `&`.  We don't need it much in instanceof, 
>> since we already have &&, but we can in switch:
>>
>>     case P(var x) & true(x > 0):
>>     case P(var x) & false(x > 0):
>
> And so for consistency, I would recommend that this example be 
> rendered using `&&`, because using `&` would be an indication that the 
> binding of `x` in `var x` is not in scope within the expression `x > 0`.

The intent of this example was that the `x` from `var x` would be in 
scope for `x > 0` -- I'm trying to represent the "guarded" pattern 
"P(var x) when x>0".  So I'm a little confused what you are suggesting 
-- is it that && is better for pattern conjunction than &, or something 
else?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20210108/33678842/attachment-0001.htm>


More information about the amber-spec-experts mailing list