Skip to content

Commit

Permalink
Port implicit named tuple and keyword argument names
Browse files Browse the repository at this point in the history
  • Loading branch information
omus committed Jul 28, 2021
1 parent 78bba10 commit 4775c30
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ changes in `julia`.

## Supported features

* Implicit keywords arguments or named tuples is supported using the `@compat` macro, e.g. `@compat f(; x, f.p)` and `@compat (; x, f.p)` is equivalent to `f(; x=x, p=f.p)` and `(; x=x, f.p)` respectively. ([#34331])

* `get` accepts tuples and numbers ([#41007], [#41032]) (since Compat 3.31)

* `muladd(A,B,z)` now accepts arrays ([#37065]) (since Compat 3.30)
Expand Down Expand Up @@ -252,3 +254,4 @@ Note that you should specify the correct minimum version for `Compat` in the
[#37065]: https://github.com/JuliaLang/julia/pull/37065
[#41007]: https://github.com/JuliaLang/julia/pull/41007
[#41032]: https://github.com/JuliaLang/julia/pull/41032
[#34331]: https://github.com/JuliaLang/julia/pull/34331
28 changes: 28 additions & 0 deletions src/compatmacro.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ function _compat(ex::Expr)
# Passthrough
return ex
end

# https://github.com/JuliaLang/julia/pull/34331
@static if VERSION < v"1.5.0-DEV.499"
if ex.head === :call || ex.head === :tuple
ex = _assign_implicit_keywords(ex)
end
end

return Expr(ex.head, map(_compat, ex.args)...)
end

Expand Down Expand Up @@ -66,3 +74,23 @@ function _create_import_expression(path_aliases::Vector{Pair{Vector{Symbol}, Sym
return_expr = Expr(:toplevel, module_expr, const_exprs..., nothing)
return return_expr
end

function _assign_implicit_keywords(ex::Expr)
kwargs = if ex.head === :call && Meta.isexpr(ex.args[2], :parameters)
ex.args[2].args
elseif ex.head === :tuple && Meta.isexpr(ex.args[1], :parameters)
ex.args[1].args
else
[]
end

for (i, k) in enumerate(kwargs)
if k isa Symbol
kwargs[i] = Expr(:kw, k, k)
elseif Meta.isexpr(k, :.)
kwargs[i] = Expr(:kw, k.args[2].value, k)
end
end

return ex
end
19 changes: 19 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1067,3 +1067,22 @@ end
@test get(() -> c[]+=1, x, (3,2,1)) == 3
end
end

# https://github.com/JuliaLang/julia/pull/34331
struct X
x
end

@testset "implicit keywords" begin
f(; x=0) = x
x = 1
s = X(2)
nested = X(X(3))

@test (@compat f(; x)) == 1
@test (@compat f(; s.x)) == 2
@test (@compat f(; nested.x.x)) == 3
@test (@compat (; x)) == (; x=1)
@test (@compat (; s.x)) == (; x=2)
@test (@compat (; nested.x.x)) == (; x=3)
end

0 comments on commit 4775c30

Please sign in to comment.