julia
8dab3f06 - syntax: Add labeled block break (#60481)

Commit
20 days ago
syntax: Add labeled block break (#60481) This is a redo of #60367 taking into account various feedback on that PR. In particular, it seemed like people strongly disliked the `break break` syntax for two primary reasons: 1. It scales poorly to multiple loops `break break break break` 2. It introduced footguns if extra loops are introduced between the loop and the break. Instead, the consensus seemed to be that labeled break should be the only facility available. Thus, this implements a proper labeled break facility that looks as follows: ``` @label :name for i = 1:10 for j = 1:10 break :name (i, j) end end # evaluate to `(1,1) ``` The idea is to re-use the `@label` macro for now, but possibly promote this to syntax in a future version if it gains widespread use. Note that parser changes are still required, since the `break` syntax is currently an error. However, compat.jl could provide `@goto break name val`, which parses fine. `continue` is extended with label support as well: ``` @label :outer while true for i = 1:10 a[i] && continue :outer end [...] end ``` However, the feature is not restricted to loops. A particular use case is to replace cleanup blocks written like ``` cond1 && @goto error cond2 && @goto error return true @label error error("foo") ``` by a labeled begin/end block: ``` @label :error begin cond1 && break :error cond2 && break :error return true end error("foo") ``` This doesn't save much typing work, but it makes this kind of pattern much more structured, e.g. for code-folding in IDEs. A similar pattern replaces the `for-then` construction originally proposed: ``` result = @label :result begin for x in arr pred(x) && break :result x end default end ``` For convenience, the label may be ommitted, in which case it defaults to `_`, i.e. the above can be written as: ``` result = @label begin for x in arr pred(x) && break _ x end default end ``` I've taken the liberty of converting some base code for testing and to give an idea of what the syntax looks like in practice, but didn't go through particularly comprehensively. These changes should be considered extended usage examples. Largely written by Claude, and I haven't looked at the implementation particularly carefully yet - for now I'm just interested in discussion of the syntax. --------- Co-authored-by: Keno Fischer <Keno@users.noreply.github.com>
Author
Parents
Loading