Skip to content

Commit

Permalink
Merge pull request #9 from JuliaLang/sjk/at-compat
Browse files Browse the repository at this point in the history
Add @compat as discussed in #8
  • Loading branch information
stevengj committed Oct 16, 2014
2 parents 1fd143d + fe5df00 commit 1ed1f76
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module Compat
using Base.Meta

if VERSION < v"0.4.0-dev+980"
macro Dict(pairs...)
Expand All @@ -16,4 +17,42 @@ else
end
end

function rewrite_dict(ex)
length(ex.args) == 1 && return ex

f = ex.args[1]
if isexpr(f, :curly)
newex = Expr(:typed_dict, :($(f.args[2])=>$(f.args[3])))
else
newex = Expr(:dict)
end

for i = 2:length(ex.args)
pair = ex.args[i]
!isexpr(pair, :(=>)) && return ex
push!(newex.args, pair)
end
newex
end

function _compat!(ex::Expr)
if ex.head == :call
f = ex.args[1]
if VERSION < v"0.4.0-dev+980" && (f == :Dict || (isexpr(f, :curly) && length(f.args) == 3 && f.args[1] == :Dict))
return rewrite_dict(ex)
end
end
for i = 1:length(ex.args)
ex.args[i] = _compat!(ex.args[i])
end
ex
end
_compat!(ex) = ex

macro compat(ex)
esc(_compat!(ex))
end

export @compat

end # module
28 changes: 28 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,35 @@ d[1] = 1
@test Compat.@Dict(1 => 1) == d
@test Compat.@Dict(1 => v) == d

@test typeof(@compat(Dict(1 => 1))) == Dict{Int,Int}
@test @compat(Dict(1 => 1)) == d
@test @compat(Dict(1 => v)) == d

ad = Dict{Any,Any}()
ad[1] = 1
@test Compat.@AnyDict(1 => 1) == ad
@test Compat.@AnyDict(1 => v) == ad

@test typeof(@compat(Dict{Any,Any}(1 => 1))) == Dict{Any,Any}
@test @compat(Dict{Any,Any}(1 => 1)) == ad
@test @compat(Dict{Any,Any}(1 => v)) == ad

td = Dict{Int,Float64}()
td[1] = 1.0

@test typeof(@compat(Dict{Int,Float64}(1 => 1))) == Dict{Int,Float64}
@test @compat(Dict{Int,Float64}(1 => 1)) == td
@test @compat(Dict{Int,Float64}(1 => v)) == td

@test @compat(Dict()) == Dict()
@test @compat(Dict{Any,Any}()) == Dict{Any,Any}()
@test @compat(Dict([(1, 1)])) == Dict([(1, 1)])

@compat function f()
a = :a
b = :b
c = :c
d = :d
Dict(a => b, c => d)
end
@test f() == Dict([(:a, :b), (:c, :d)])

0 comments on commit 1ed1f76

Please sign in to comment.