Disallowing break label (and continue label) inside an expression switch

Brian Goetz brian.goetz at oracle.com
Fri Mar 23 19:41:51 UTC 2018


> The symptom of this design choice is the large number of X
> entries in the break-e column, where there are few X entries
> in the return column.
>
> I suppose you are aiming in this direction to reduce occasional
> ambiguities between break-e and break-l.  But such ambiguities
> can be controlled in other ways while getting more free passage
> of break-e to its enclosing switch, through intervening control
> flow.

I am not worried that there will be occasional ambiguities; I'm worried 
that the code reader will see "break X" in a switch statement and _not 
be able to know what it means_ without doing a nonlocal analysis.  Given 
that the requirement for a nested switch statement to break-e out of an 
enclosing switch expression already seems tenuous, it seemed best to 
segregate the break forms.  Either break/break-L is allowed in a given 
context, or break-E is allowed in that context, but not both.

> Specifically, this should not be ruled out, IMO:
>
> int x = switch (e) (
> case 0:
>   for (int y : someInts) {
>     if (y < x)  break (y);
>   }
>   return 0;
> default: return e;
> };

I would prefer to rule it out.  We don't allow returns out of the middle 
of a conditional, after all.  I prefer the simplicity that "all 
expressions either complete normally or complete abruptly with cause 
exception."  If you really need this kind of control flow, where maybe 
you yield a value or maybe you return, use a switch statement:

     int result;
     switch (e) {
         case 0:
             for (int y : someInts) {
                 if (y < x) { result = y; break ; }
             }
            return 0;
        default: return e;
     }
     // consume result here

> We have already discussed ways to deal with the ambiguity that
> could (rarely!!) arise if a name like "y" above also looks like a 
> statement
> label.  Reporting the ambiguity as an error is an easy thing to do,
> or quietly accepting the label in preference to the expression is
> also easy.  Under either rule, users can use parens (as above) to
> make clear which kind of break statement they mean.
>
> Am I missing some other consideration?
>

I think so.  Its not detecting the ambiguity, its that the possibility 
of mixing control flow kinds means the poor reader has to reason about 
all the possibilities, and not be sure what "break FOO" means in a 
switch statement.




More information about the amber-spec-experts mailing list