|
| 1 | +module SimpleUnPack |
| 2 | + |
| 3 | +export @unpack |
| 4 | + |
| 5 | +""" |
| 6 | + @unpack a, b, ... = rhs |
| 7 | +
|
| 8 | +Destructure properties `a`, `b`, ... of `rhs` into variables of the same name. |
| 9 | +
|
| 10 | +The behaviour of the macro is equivalent to `(; a, b, ...) = rhs` which was introduced in [Julia#39285](https://github.com/JuliaLang/julia/pull/39285) and is available in Julia >= 1.7.0-DEV.364. |
| 11 | +""" |
| 12 | +macro unpack(args::Expr) |
| 13 | + return unpack(args) |
| 14 | +end |
| 15 | + |
| 16 | +function unpack(args::Expr) |
| 17 | + # Extract properties and RHS |
| 18 | + if !Meta.isexpr(args, :(=), 2) |
| 19 | + throw(ArgumentError("`@unpack` can only be applied to expressions of the form `a, b = c`")) |
| 20 | + end |
| 21 | + lhs, rhs = args.args |
| 22 | + properties = if lhs isa Symbol |
| 23 | + [lhs] |
| 24 | + elseif Meta.isexpr(lhs, :tuple) && !isempty(lhs.args) && all(x -> x isa Symbol, lhs.args) |
| 25 | + lhs.args |
| 26 | + else |
| 27 | + throw(ArgumentError("`@unpack` can only be applied to expressions of the form `a, b = c`")) |
| 28 | + end |
| 29 | + |
| 30 | + if VERSION >= v"1.7.0-DEV.364" |
| 31 | + # Fall back to destructuring in Base when available: |
| 32 | + # https://github.com/JuliaLang/julia/pull/39285 |
| 33 | + return Expr(:(=), Expr(:tuple, Expr(:parameters, (esc(p) for p in properties)...)), esc(rhs)) |
| 34 | + else |
| 35 | + @gensym object |
| 36 | + block = Expr(:block) |
| 37 | + for p in properties |
| 38 | + push!(block.args, Expr(:(=), esc(p), Expr(:call, :getproperty, esc(object), QuoteNode(p)))) |
| 39 | + end |
| 40 | + return quote |
| 41 | + $(esc(object)) = $(esc(rhs)) # In case the RHS is an expression |
| 42 | + $block |
| 43 | + $(esc(object)) # Return evaluation of rhs to ensure the behaviour is the same as (; ...) = rhs |
| 44 | + end |> Base.remove_linenums! |
| 45 | + end |
| 46 | +end |
| 47 | + |
| 48 | +end |
0 commit comments