From 034b8f5599c3dcd3e770ba8af3a9c28ef2497532 Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Sun, 28 Sep 2014 16:06:39 -0400 Subject: [PATCH 1/7] make `a=>b` syntax for `Pair(a,b)` use Dict(iter) or Dict(::Pair...) as Dict constructors ref #6739 --- base/dict.jl | 44 ++++++++++++++++++++++++-------------------- base/exports.jl | 1 + base/operators.jl | 13 +++++++++++++ base/show.jl | 6 ++++++ src/julia-syntax.scm | 15 +++++++-------- 5 files changed, 51 insertions(+), 28 deletions(-) diff --git a/base/dict.jl b/base/dict.jl index 9fb66ab195748..8940db416ce3b 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -318,27 +318,41 @@ type Dict{K,V} <: Associative{K,V} n = 16 new(zeros(Uint8,n), Array(K,n), Array(V,n), 0, 0, identity) end - function Dict(ks, vs) - # TODO: eventually replace with a call to Dict(zip(ks,vs)) - n = min(length(ks), length(vs)) + function Dict(kv) h = Dict{K,V}() - for i=1:n - h[ks[i]] = vs[i] + for (k,v) in kv + h[k] = v end return h end - function Dict(kv) + Dict(p::Pair) = setindex!(Dict{K,V}(), p.second, p.first) + function Dict(ps::Pair...) h = Dict{K,V}() - for (k,v) in kv - h[k] = v + sizehint(h, length(ps)) + for p in ps + h[p.first] = p.second end return h end end Dict() = Dict{Any,Any}() +Dict(kv::()) = Dict() -Dict{K,V}(ks::AbstractArray{K}, vs::AbstractArray{V}) = Dict{K,V}(ks,vs) -Dict(ks, vs) = Dict{Any,Any}(ks, vs) +# TODO: this can probably be simplified using `eltype` as a THT (Tim Holy trait) +Dict{K,V}(kv::((K,V)...,)) = Dict{K,V}(kv) +Dict{K }(kv::((K,Any)...,)) = Dict{K,Any}(kv) +Dict{V }(kv::((Any,V)...,)) = Dict{Any,V}(kv) +Dict{K,V}(kv::(Pair{K,V}...,)) = Dict{K,V}(kv) +Dict (kv::(Pair...,)) = Dict{Any,Any}(kv) + +Dict{K,V}(kv::AbstractArray{(K,V)}) = Dict{K,V}(kv) +Dict{K,V}(kv::AbstractArray{Pair{K,V}}) = Dict{K,V}(kv) +Dict{K,V}(kv::Associative{K,V}) = Dict{K,V}(kv) + +Dict{K,V}(ps::Pair{K,V}...) = Dict{K,V}(ps) +Dict (ps::Pair...) = Dict{Any,Any}(ps) + +similar{K,V}(d::Dict{K,V}) = Dict{K,V}() # conversion between Dict types function convert{K,V}(::Type{Dict{K,V}},d::Dict) @@ -355,16 +369,6 @@ function convert{K,V}(::Type{Dict{K,V}},d::Dict) end convert{K,V}(::Type{Dict{K,V}},d::Dict{K,V}) = d -# syntax entry points -Dict{K,V}(ks::(K...), vs::(V...)) = Dict{K ,V }(ks, vs) -Dict{K }(ks::(K...), vs::Tuple ) = Dict{K ,Any}(ks, vs) -Dict{V }(ks::Tuple , vs::(V...)) = Dict{Any,V }(ks, vs) - -Dict{K,V}(kv::AbstractArray{(K,V)}) = Dict{K,V}(kv) -Dict{K,V}(kv::Associative{K,V}) = Dict{K,V}(kv) - -similar{K,V}(d::Dict{K,V}) = (K=>V)[] - function serialize(s, t::Dict) serialize_type(s, typeof(t)) write(s, int32(length(t))) diff --git a/base/exports.jl b/base/exports.jl index 926ea57277fcc..bccd63c7e9dbe 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -64,6 +64,7 @@ export Nullable, ObjectIdDict, OrdinalRange, + Pair, PollingFileWatcher, ProcessGroup, QuickSort, diff --git a/base/operators.jl b/base/operators.jl index e79647b8c09e0..da8e3a92a1245 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -400,6 +400,19 @@ function ifelse(c::AbstractArray{Bool}, x, y::AbstractArray) reshape([ifelse(c[i], x, y[i]) for i = 1 : length(c)], shp) end +# Pair + +immutable Pair{A,B} + first::A + second::B +end + +start(p::Pair) = 1 +done(p::Pair, i) = i>2 +next(p::Pair, i) = (getfield(p,i), i+1) + +indexed_next(p::Pair, i::Int, state) = (getfield(p,i), i+1) + # some operators not defined yet global //, .>>, .<<, >:, <|, |>, hcat, hvcat, ⋅, ×, ∈, ∉, ∋, ∌, ⊆, ⊈, ⊊, ∩, ∪, √, ∛ diff --git a/base/show.jl b/base/show.jl index 6673ec25c504e..24b7f56874879 100644 --- a/base/show.jl +++ b/base/show.jl @@ -113,6 +113,12 @@ print(io::IO, n::Unsigned) = print(io, dec(n)) show{T}(io::IO, p::Ptr{T}) = print(io, typeof(p), " @0x$(hex(unsigned(p), WORD_SIZE>>2))") +function show(io::IO, p::Pair) + show(io, p.first) + print(io, "=>") + show(io, p.second) +end + function show(io::IO, m::Module) if is(m,Main) print(io, "Main") diff --git a/src/julia-syntax.scm b/src/julia-syntax.scm index 35e8c351fa34e..de64adaa2a237 100644 --- a/src/julia-syntax.scm +++ b/src/julia-syntax.scm @@ -1761,14 +1761,13 @@ 'dict (lambda (e) + ;; TODO: deprecate `(call (top Dict) - (call (top tuple) - ,.(map (lambda (x) (expand-forms (cadr x))) (cdr e))) - (call (top tuple) - ,.(map (lambda (x) (expand-forms (caddr x))) (cdr e))))) + ,.(map expand-forms (cdr e)))) 'typed_dict (lambda (e) + ;; TODO: deprecate (let ((atypes (cadr e)) (args (cddr e))) (if (and (length= atypes 3) @@ -1776,12 +1775,12 @@ `(call (call (top apply_type) (top Dict) ,(expand-forms (cadr atypes)) ,(expand-forms (caddr atypes))) - (call (top tuple) - ,.(map (lambda (x) (expand-forms (cadr x))) args)) - (call (top tuple) - ,.(map (lambda (x) (expand-forms (caddr x))) args))) + ,.(map expand-forms args)) (error (string "invalid \"typed_dict\" syntax " (deparse atypes)))))) + '=> + (lambda (e) `(call (top Pair) ,(expand-forms (cadr e)) ,(expand-forms (caddr e)))) + 'cell1d (lambda (e) (let ((args (cdr e))) From cbd2d1ce09ca5e81a66b69b3ff621d9b880ac07f Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Sun, 28 Sep 2014 17:32:38 -0400 Subject: [PATCH 2/7] combine Base.Pair and Base.Collections.Pair add comparisons for Pair start fixing tests --- base/collections.jl | 46 ++++++++++++++++--------------------------- base/operators.jl | 5 +++++ test/priorityqueue.jl | 4 ++-- 3 files changed, 24 insertions(+), 31 deletions(-) diff --git a/base/collections.jl b/base/collections.jl index c1e601e4c270d..b95caef9ebaaf 100644 --- a/base/collections.jl +++ b/base/collections.jl @@ -5,7 +5,6 @@ import Base: setindex!, done, get, hash, haskey, isempty, length, next, getindex import ..Order: Forward, Ordering, lt export - Pair, PriorityQueue, dequeue!, enqueue!, @@ -107,17 +106,6 @@ end # PriorityQueue # ------------- -immutable Pair{A,B} - a::A - b::B -end - -function hash(p::Pair, h::Uint) - h = hash(p.a, h) - hash(p.b, h) -end -hash(p::Pair) = hash(p, zero(Uint)) - # A PriorityQueue that acts like a Dict, mapping values to their priorities, # with the addition of a dequeue! function to remove the lowest priority # element. @@ -179,23 +167,23 @@ PriorityQueue{K,V}(a::AbstractArray{(K,V)}, o::Ordering=Forward) = PriorityQueue length(pq::PriorityQueue) = length(pq.xs) isempty(pq::PriorityQueue) = isempty(pq.xs) haskey(pq::PriorityQueue, key) = haskey(pq.index, key) -peek(pq::PriorityQueue) = (kv = pq.xs[1]; (kv.a, kv.b)) +peek(pq::PriorityQueue) = (kv = pq.xs[1]; (kv.first, kv.second)) function percolate_down!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while (l = heapleft(i)) <= length(pq) r = heapright(i) - j = r > length(pq) || lt(pq.o, pq.xs[l].b, pq.xs[r].b) ? l : r - if lt(pq.o, pq.xs[j].b, x.b) - pq.index[pq.xs[j].a] = i + j = r > length(pq) || lt(pq.o, pq.xs[l].second, pq.xs[r].second) ? l : r + if lt(pq.o, pq.xs[j].second, x.second) + pq.index[pq.xs[j].first] = i pq.xs[i] = pq.xs[j] i = j else break end end - pq.index[x.a] = i + pq.index[x.second] = i pq.xs[i] = x end @@ -204,15 +192,15 @@ function percolate_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while i > 1 j = heapparent(i) - if lt(pq.o, x.b, pq.xs[j].b) - pq.index[pq.xs[j].a] = i + if lt(pq.o, x.second, pq.xs[j].second) + pq.index[pq.xs[j].first] = i pq.xs[i] = pq.xs[j] i = j else break end end - pq.index[x.a] = i + pq.index[x.first] = i pq.xs[i] = x end @@ -221,22 +209,22 @@ function force_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while i > 1 j = heapparent(i) - pq.index[pq.xs[j].a] = i + pq.index[pq.xs[j].first] = i pq.xs[i] = pq.xs[j] i = j end - pq.index[x.a] = i + pq.index[x.first] = i pq.xs[i] = x end function getindex{K,V}(pq::PriorityQueue{K,V}, key) - pq.xs[pq.index[key]].b + pq.xs[pq.index[key]].second end function get{K,V}(pq::PriorityQueue{K,V}, key, deflt) i = get(pq.index, key, 0) - i == 0 ? deflt : pq.xs[i].b + i == 0 ? deflt : pq.xs[i].second end @@ -244,7 +232,7 @@ end function setindex!{K,V}(pq::PriorityQueue{K, V}, value, key) if haskey(pq, key) i = pq.index[key] - oldvalue = pq.xs[i].b + oldvalue = pq.xs[i].second pq.xs[i] = Pair{K,V}(key, value) if lt(pq.o, oldvalue, value) percolate_down!(pq, i) @@ -275,11 +263,11 @@ function dequeue!(pq::PriorityQueue) y = pop!(pq.xs) if !isempty(pq) pq.xs[1] = y - pq.index[y.a] = 1 + pq.index[y.first] = 1 percolate_down!(pq, 1) end - delete!(pq.index, x.a) - x.a + delete!(pq.index, x.first) + x.first end function dequeue!(pq::PriorityQueue, key) @@ -297,7 +285,7 @@ done(pq::PriorityQueue, i) = done(pq.index, i) function next(pq::PriorityQueue, i) (k, idx), i = next(pq.index, i) - return ((k, pq.xs[idx].b), i) + return ((k, pq.xs[idx].second), i) end diff --git a/base/operators.jl b/base/operators.jl index da8e3a92a1245..a9e2108c11da9 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -413,6 +413,11 @@ next(p::Pair, i) = (getfield(p,i), i+1) indexed_next(p::Pair, i::Int, state) = (getfield(p,i), i+1) +hash(p::Pair, h::Uint) = hash(p.second, hash(p.first, h)) + +==(p::Pair, q::Pair) = (p.first==q.first) & (p.second==q.second) +isequal(p::Pair, q::Pair) = isequal(p.first,q.first) & isequal(p.second,q.second) + # some operators not defined yet global //, .>>, .<<, >:, <|, |>, hcat, hvcat, ⋅, ×, ∈, ∉, ∋, ∌, ⊆, ⊈, ⊊, ∩, ∪, √, ∛ diff --git a/test/priorityqueue.jl b/test/priorityqueue.jl index aae3da9b427e1..e3d00b0c21c97 100644 --- a/test/priorityqueue.jl +++ b/test/priorityqueue.jl @@ -24,7 +24,7 @@ end pmax = 1000 n = 10000 r = rand(1:pmax, n) -priorities = Dict(1:n, r) +priorities = Dict(zip(1:n, r)) # building from a dict pq = PriorityQueue(priorities) @@ -36,7 +36,7 @@ test_isrequested!(pq, 1:n) # building from two lists ks, vs = 1:n, rand(1:pmax, n) pq = PriorityQueue(ks, vs) -priorities = Dict(ks, vs) +priorities = Dict(zip(ks, vs)) test_issorted!(pq, priorities) From 45da1fb6a7210e854321d888a15455a5723ed6f0 Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Sun, 28 Sep 2014 21:27:53 -0400 Subject: [PATCH 3/7] fix a mistake I made in priorityqueue in the last commit add isless for Pair --- base/collections.jl | 3 +-- base/dict.jl | 5 +++++ base/operators.jl | 3 +++ base/show.jl | 1 - test/priorityqueue.jl | 3 --- 5 files changed, 9 insertions(+), 6 deletions(-) diff --git a/base/collections.jl b/base/collections.jl index b95caef9ebaaf..43e37f820c209 100644 --- a/base/collections.jl +++ b/base/collections.jl @@ -1,4 +1,3 @@ - module Collections import Base: setindex!, done, get, hash, haskey, isempty, length, next, getindex, start @@ -183,7 +182,7 @@ function percolate_down!(pq::PriorityQueue, i::Integer) break end end - pq.index[x.second] = i + pq.index[x.first] = i pq.xs[i] = x end diff --git a/base/dict.jl b/base/dict.jl index 8940db416ce3b..f63773385a734 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -352,6 +352,11 @@ Dict{K,V}(kv::Associative{K,V}) = Dict{K,V}(kv) Dict{K,V}(ps::Pair{K,V}...) = Dict{K,V}(ps) Dict (ps::Pair...) = Dict{Any,Any}(ps) +Dict(kv) = dict_with_eltype(kv, eltype(kv)) +dict_with_eltype{K,V}(kv, ::Type{(K,V)}) = Dict{K,V}(kv) +dict_with_eltype{K,V}(kv, ::Type{Pair{K,V}}) = Dict{K,V}(kv) +dict_with_eltype{K,V}(kv, t) = Dict{Any,Any}(kv) + similar{K,V}(d::Dict{K,V}) = Dict{K,V}() # conversion between Dict types diff --git a/base/operators.jl b/base/operators.jl index a9e2108c11da9..0060f13860e9b 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -418,6 +418,9 @@ hash(p::Pair, h::Uint) = hash(p.second, hash(p.first, h)) ==(p::Pair, q::Pair) = (p.first==q.first) & (p.second==q.second) isequal(p::Pair, q::Pair) = isequal(p.first,q.first) & isequal(p.second,q.second) +isless(p::Pair, q::Pair) = ifelse(!isequal(p.first,q.first), isless(p.first,q.first), + isless(p.second,q.second)) + # some operators not defined yet global //, .>>, .<<, >:, <|, |>, hcat, hvcat, ⋅, ×, ∈, ∉, ∋, ∌, ⊆, ⊈, ⊊, ∩, ∪, √, ∛ diff --git a/base/show.jl b/base/show.jl index 24b7f56874879..eb7b3c92b03d8 100644 --- a/base/show.jl +++ b/base/show.jl @@ -1,4 +1,3 @@ - show(x) = show(STDOUT::IO, x) print(io::IO, s::Symbol) = (write(io,s);nothing) diff --git a/test/priorityqueue.jl b/test/priorityqueue.jl index e3d00b0c21c97..7873589fffa2a 100644 --- a/test/priorityqueue.jl +++ b/test/priorityqueue.jl @@ -1,7 +1,5 @@ - using Base.Collections - # Test dequeing in sorted order. function test_issorted!(pq::PriorityQueue, priorities) last = dequeue!(pq) @@ -93,4 +91,3 @@ for priority in values(priorities) heappush!(xs, priority) end @test issorted([heappop!(xs) for _ in length(priorities)]) - From b58c380c082784a658670cc337a1a45202766868 Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Fri, 3 Oct 2014 18:12:08 -0400 Subject: [PATCH 4/7] allow parsing => as an identifier, and make it an alias for Pair this way `a=>b` is lowered like every other operator call, except in the old dict syntax during the deprecation period. this is probably a good way to deal with it, and we can later decide to remove the `Pair` alias if we want to. --- base/exports.jl | 1 + base/operators.jl | 2 ++ src/julia-parser.scm | 3 ++- src/julia-syntax.scm | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/base/exports.jl b/base/exports.jl index 847300237e997..22847d26f05ba 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -242,6 +242,7 @@ export ~, :, ÷, + =>, A_ldiv_B!, A_ldiv_Bc, A_ldiv_Bt, diff --git a/base/operators.jl b/base/operators.jl index 0060f13860e9b..ded6dfd9e42ed 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -407,6 +407,8 @@ immutable Pair{A,B} second::B end +const => = Pair + start(p::Pair) = 1 done(p::Pair, i) = i>2 next(p::Pair, i) = (getfield(p,i), i+1) diff --git a/src/julia-parser.scm b/src/julia-parser.scm index b1e7b69ccd280..97db514656b77 100644 --- a/src/julia-parser.scm +++ b/src/julia-parser.scm @@ -1650,7 +1650,8 @@ ; parse numbers, identifiers, parenthesized expressions, lists, vectors, etc. (define (parse-atom s) (let ((ex (parse-atom- s))) - (if (or (syntactic-op? ex) + ;; TODO: remove this hack when we remove the special Dict syntax + (if (or (and (not (eq? ex '=>)) (syntactic-op? ex)) (eq? ex '....)) (error (string "invalid identifier name \"" ex "\""))) ex)) diff --git a/src/julia-syntax.scm b/src/julia-syntax.scm index fa537d46b17c6..4c216d7502ac3 100644 --- a/src/julia-syntax.scm +++ b/src/julia-syntax.scm @@ -1788,7 +1788,7 @@ (error (string "invalid \"typed_dict\" syntax " (deparse atypes)))))) '=> - (lambda (e) `(call (top Pair) ,(expand-forms (cadr e)) ,(expand-forms (caddr e)))) + (lambda (e) `(call => ,(expand-forms (cadr e)) ,(expand-forms (caddr e)))) 'cell1d (lambda (e) From fd6338dd25a8770ff9ce568d289c19710a9efad2 Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Fri, 3 Oct 2014 18:29:10 -0400 Subject: [PATCH 5/7] update Dict show() to use the new standard syntax --- base/dict.jl | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/base/dict.jl b/base/dict.jl index d0933a08b551f..771fc89509d50 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -18,14 +18,14 @@ end function show{K,V}(io::IO, t::Associative{K,V}) if isempty(t) - print(io, typeof(t),"()") + print(io, typeof(t), "()") else - if K === Any && V === Any - delims = ['{','}'] + if isleaftype(K) && isleaftype(V) + print(io, typeof(t).name) else - delims = ['[',']'] + print(io, typeof(t)) end - print(io, delims[1]) + print(io, '(') first = true for (k, v) in t first || print(io, ',') @@ -34,7 +34,7 @@ function show{K,V}(io::IO, t::Associative{K,V}) print(io, "=>") show(io, v) end - print(io, delims[2]) + print(io, ')') end end From 3f1101f68f767aaaf893a702b806e787fa07f574 Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Mon, 6 Oct 2014 13:40:28 -0400 Subject: [PATCH 6/7] deprecate old dict syntax and change uses in base and tests --- base/LineEdit.jl | 22 +++++----- base/REPL.jl | 17 ++++---- base/cartesian.jl | 8 ++-- base/client.jl | 4 +- base/combinatorics.jl | 6 +-- base/datafmt.jl | 2 +- base/dates/adjusters.jl | 14 +++---- base/dates/io.jl | 12 +++--- base/dates/query.jl | 28 ++++++------- base/dict.jl | 6 ++- base/latex_symbols.jl | 4 +- base/loading.jl | 4 +- base/multi.jl | 4 +- base/pkg/generate.jl | 2 +- base/pkg/github.jl | 6 +-- base/pkg/query.jl | 34 +++++++-------- base/pkg/resolve.jl | 6 +-- base/pkg/resolve/interface.jl | 8 ++-- base/pkg/resolve/maxsum.jl | 2 +- base/primes.jl | 2 +- base/profile.jl | 12 +++--- base/quadgk.jl | 6 +-- base/show.jl | 6 +-- src/jlfrontend.scm | 8 ++-- src/julia-parser.scm | 78 +++++++++++++++++++++++------------ test/collections.jl | 32 +++++++------- test/core.jl | 18 ++++---- test/dates/io.jl | 6 +-- test/dates/query.jl | 8 ++-- test/hashing.jl | 4 +- test/keywordargs.jl | 4 +- test/lineedit.jl | 12 +++--- test/repl.jl | 6 +-- test/resolve.jl | 70 +++++++++++++++---------------- test/sparse.jl | 2 +- test/spawn.jl | 2 +- test/strings.jl | 14 +++---- 37 files changed, 253 insertions(+), 226 deletions(-) diff --git a/base/LineEdit.jl b/base/LineEdit.jl index 8b3ae98afcb0a..304943ee015cb 100644 --- a/base/LineEdit.jl +++ b/base/LineEdit.jl @@ -5,7 +5,7 @@ using ..Terminals import ..Terminals: raw!, width, height, cmove, getX, getY, clear_line, beep -import Base: ensureroom, peek, show +import Base: ensureroom, peek, show, AnyDict abstract TextInterface @@ -835,7 +835,7 @@ end const escape_defaults = merge!( {char(i) => nothing for i=[1:26, 28:31]}, # Ignore control characters by default - { # And ignore other escape sequences by default + AnyDict( # And ignore other escape sequences by default "\e*" => nothing, "\e[*" => nothing, # Also ignore extended escape sequences @@ -856,7 +856,7 @@ const escape_defaults = merge!( "\eOD" => "\e[D", "\eOH" => "\e[H", "\eOF" => "\e[F", -}) +)) function write_response_buffer(s::PromptState, data) offset = s.input_buffer.ptr @@ -997,7 +997,7 @@ end function setup_search_keymap(hp) p = HistoryPrompt(hp) - pkeymap = { + pkeymap = AnyDict( "^R" => (s,data,c)->(history_set_backward(data, true); history_next_result(s, data)), "^S" => (s,data,c)->(history_set_backward(data, false); history_next_result(s, data)), '\r' => (s,o...)->accept_result(s, p), @@ -1066,12 +1066,12 @@ function setup_search_keymap(hp) edit_insert(data.query_buffer, input); update_display_buffer(s, data) end, "*" => (s,data,c)->(edit_insert(data.query_buffer, c); update_display_buffer(s, data)) - } + ) p.keymap_func = keymap([pkeymap, escape_defaults]) - skeymap = { + skeymap = AnyDict( "^R" => (s,o...)->(enter_search(s, p, true)), "^S" => (s,o...)->(enter_search(s, p, false)), - } + ) (p, skeymap) end @@ -1118,7 +1118,7 @@ function commit_line(s) end const default_keymap = -{ +AnyDict( # Tab '\t' => (s,o...)->begin buf = buffer(s) @@ -1226,9 +1226,9 @@ const default_keymap = edit_insert(s, input) end, "^T" => (s,o...)->edit_transpose(s), -} +) -const history_keymap = { +const history_keymap = AnyDict( "^P" => (s,o...)->(history_prev(s, mode(s).hist)), "^N" => (s,o...)->(history_next(s, mode(s).hist)), # Up Arrow @@ -1239,7 +1239,7 @@ const history_keymap = { "\e[5~" => (s,o...)->(history_prev(s, mode(s).hist)), # Page Down "\e[6~" => (s,o...)->(history_next(s, mode(s).hist)) -} +) function deactivate(p::Union(Prompt,HistoryPrompt), s::Union(SearchState,PromptState), termbuf) clear_input_area(termbuf, s) diff --git a/base/REPL.jl b/base/REPL.jl index ed1bef5a664f3..d5225c7480f6b 100644 --- a/base/REPL.jl +++ b/base/REPL.jl @@ -14,7 +14,8 @@ import Base: AsyncStream, Display, display, - writemime + writemime, + AnyDict import ..LineEdit: CompletionProvider, @@ -675,9 +676,9 @@ function setup_interface(repl::LineEditREPL; hascolor = repl.hascolor, extra_rep # Setup history # We will have a unified history for all REPL modes - hp = REPLHistoryProvider((Symbol=>Any)[:julia => julia_prompt, - :shell => shell_mode, - :help => help_mode]) + hp = REPLHistoryProvider(Dict{Symbol,Any}(:julia => julia_prompt, + :shell => shell_mode, + :help => help_mode)) if !repl.no_history_file try f = open(find_hist_file(), true, true, true, false, false) @@ -704,7 +705,7 @@ function setup_interface(repl::LineEditREPL; hascolor = repl.hascolor, extra_rep extra_repl_keymap = [extra_repl_keymap] end - const repl_keymap = { + const repl_keymap = AnyDict( ';' => function (s,o...) if isempty(s) || position(LineEdit.buffer(s)) == 0 buf = copy(LineEdit.buffer(s)) @@ -775,14 +776,14 @@ function setup_interface(repl::LineEditREPL; hascolor = repl.hascolor, extra_rep end end end, - } + ) a = Dict{Any,Any}[hkeymap, repl_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults] prepend!(a, extra_repl_keymap) julia_prompt.keymap_func = LineEdit.keymap(a) - const mode_keymap = { + const mode_keymap = AnyDict( '\b' => function (s,o...) if isempty(s) || position(LineEdit.buffer(s)) == 0 buf = copy(LineEdit.buffer(s)) @@ -801,7 +802,7 @@ function setup_interface(repl::LineEditREPL; hascolor = repl.hascolor, extra_rep transition(s, :reset) LineEdit.refresh_line(s) end - } + ) b = Dict{Any,Any}[hkeymap, mode_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults] prepend!(b, extra_repl_keymap) diff --git a/base/cartesian.jl b/base/cartesian.jl index 6e84a3ac45568..39e293929cb77 100644 --- a/base/cartesian.jl +++ b/base/cartesian.jl @@ -451,10 +451,10 @@ end ## Resolve expressions at parsing time ## -const exprresolve_arith_dict = (Symbol=>Function)[:+ => +, - :- => -, :* => *, :/ => /, :^ => ^, :div => div] -const exprresolve_cond_dict = (Symbol=>Function)[:(==) => ==, - :(<) => <, :(>) => >, :(<=) => <=, :(>=) => >=] +const exprresolve_arith_dict = Dict{Symbol,Function}(:+ => +, + :- => -, :* => *, :/ => /, :^ => ^, :div => div) +const exprresolve_cond_dict = Dict{Symbol,Function}(:(==) => ==, + :(<) => <, :(>) => >, :(<=) => <=, :(>=) => >=) function exprresolve_arith(ex::Expr) if ex.head == :call && haskey(exprresolve_arith_dict, ex.args[1]) && all([isa(ex.args[i], Number) for i = 2:length(ex.args)]) diff --git a/base/client.jl b/base/client.jl index c3c05477d9c93..d07eac7035d52 100644 --- a/base/client.jl +++ b/base/client.jl @@ -3,7 +3,7 @@ const ARGS = UTF8String[] -const text_colors = { +const text_colors = AnyDict( :black => "\033[1m\033[30m", :red => "\033[1m\033[31m", :green => "\033[1m\033[32m", @@ -14,7 +14,7 @@ const text_colors = { :white => "\033[1m\033[37m", :normal => "\033[0m", :bold => "\033[1m", -} +) have_color = false @unix_only default_color_answer = text_colors[:bold] diff --git a/base/combinatorics.jl b/base/combinatorics.jl index dba483b35393e..96cb9933dc46d 100644 --- a/base/combinatorics.jl +++ b/base/combinatorics.jl @@ -354,7 +354,7 @@ function nextpartition(n, as) xs end -let _npartitions = (Int=>Int)[] +let _npartitions = Dict{Int,Int}() global npartitions function npartitions(n::Int) if n < 0 @@ -424,7 +424,7 @@ function nextfixedpartition(n, m, bs) return as end -let _nipartitions = ((Int,Int)=>Int)[] +let _nipartitions = Dict{(Int,Int),Int}() global npartitions function npartitions(n::Int,m::Int) if n < m || m == 0 @@ -489,7 +489,7 @@ function nextsetpartition(s::AbstractVector, a, b, n, m) end -let _nsetpartitions = (Int=>Int)[] +let _nsetpartitions = Dict{Int,Int}() global nsetpartitions function nsetpartitions(n::Int) if n < 0 diff --git a/base/datafmt.jl b/base/datafmt.jl index e90616443edcf..3ff8b8d620a70 100644 --- a/base/datafmt.jl +++ b/base/datafmt.jl @@ -285,7 +285,7 @@ end const valid_opts = [:header, :has_header, :ignore_invalid_chars, :use_mmap, :quotes, :comments, :dims, :comment_char, :skipstart, :skipblanks] const valid_opt_types = [Bool, Bool, Bool, Bool, Bool, Bool, NTuple{2,Integer}, Char, Integer, Bool] -const deprecated_opts = [ :has_header => :header ] +const deprecated_opts = Dict(:has_header => :header) function val_opts(opts) d = Dict{Symbol,Union(Bool,NTuple{2,Integer},Char,Integer)}() for (opt_name, opt_val) in opts diff --git a/base/dates/adjusters.jl b/base/dates/adjusters.jl index 17ddca789d121..c2ebcd9955867 100644 --- a/base/dates/adjusters.jl +++ b/base/dates/adjusters.jl @@ -107,13 +107,13 @@ function DateTime(func::Function,y,m,d,h,mi,s;step::Period=Millisecond(1),negate end # Return the next TimeType that falls on dow -ISDAYOFWEEK = [Mon=>DateFunction(ismonday,false,Date(0)), - Tue=>DateFunction(istuesday,false,Date(0)), - Wed=>DateFunction(iswednesday,false,Date(0)), - Thu=>DateFunction(isthursday,false,Date(0)), - Fri=>DateFunction(isfriday,false,Date(0)), - Sat=>DateFunction(issaturday,false,Date(0)), - Sun=>DateFunction(issunday,false,Date(0))] +ISDAYOFWEEK = Dict(Mon=>DateFunction(ismonday,false,Date(0)), + Tue=>DateFunction(istuesday,false,Date(0)), + Wed=>DateFunction(iswednesday,false,Date(0)), + Thu=>DateFunction(isthursday,false,Date(0)), + Fri=>DateFunction(isfriday,false,Date(0)), + Sat=>DateFunction(issaturday,false,Date(0)), + Sun=>DateFunction(issunday,false,Date(0))) # "same" indicates whether the current date can be considered or not tonext(dt::TimeType,dow::Int;same::Bool=false) = adjust(ISDAYOFWEEK[dow],same ? dt : dt+Day(1),Day(1),7) diff --git a/base/dates/io.jl b/base/dates/io.jl index 4df40407d2e8d..d83ac54740d14 100644 --- a/base/dates/io.jl +++ b/base/dates/io.jl @@ -22,14 +22,14 @@ end Base.show(io::IO,x::Date) = print(io,string(x)) ### Parsing -const english = (UTF8String=>Int)["january"=>1,"february"=>2,"march"=>3,"april"=>4, +const english = Dict{UTF8String,Int}("january"=>1,"february"=>2,"march"=>3,"april"=>4, "may"=>5,"june"=>6,"july"=>7,"august"=>8,"september"=>9, - "october"=>10,"november"=>11,"december"=>12] -const abbrenglish = (UTF8String=>Int)["jan"=>1,"feb"=>2,"mar"=>3,"apr"=>4, + "october"=>10,"november"=>11,"december"=>12) +const abbrenglish = Dict{UTF8String,Int}("jan"=>1,"feb"=>2,"mar"=>3,"apr"=>4, "may"=>5,"jun"=>6,"jul"=>7,"aug"=>8,"sep"=>9, - "oct"=>10,"nov"=>11,"dec"=>12] -const MONTHTOVALUE = (UTF8String=>Dict{UTF8String,Int})["english"=>english] -const MONTHTOVALUEABBR = (UTF8String=>Dict{UTF8String,Int})["english"=>abbrenglish] + "oct"=>10,"nov"=>11,"dec"=>12) +const MONTHTOVALUE = Dict{UTF8String,Dict{UTF8String,Int}}("english"=>english) +const MONTHTOVALUEABBR = Dict{UTF8String,Dict{UTF8String,Int}}("english"=>abbrenglish) # Date/DateTime Parsing abstract Slot{P<:AbstractTime} diff --git a/base/dates/query.jl b/base/dates/query.jl index 141f04b03d7d0..86c23128a7321 100644 --- a/base/dates/query.jl +++ b/base/dates/query.jl @@ -17,12 +17,12 @@ dayofweek(dt::TimeType) = dayofweek(days(dt)) const Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday = 1,2,3,4,5,6,7 const Mon,Tue,Wed,Thu,Fri,Sat,Sun = 1,2,3,4,5,6,7 -const english_daysofweek = [1=>"Monday",2=>"Tuesday",3=>"Wednesday", - 4=>"Thursday",5=>"Friday",6=>"Saturday",7=>"Sunday"] -const VALUETODAYOFWEEK = (UTF8String=>Dict{Int,UTF8String})["english"=>english_daysofweek] -const english_daysofweekabbr = [1=>"Mon",2=>"Tue",3=>"Wed", - 4=>"Thu",5=>"Fri",6=>"Sat",7=>"Sun"] -const VALUETODAYOFWEEKABBR = (UTF8String=>Dict{Int,UTF8String})["english"=>english_daysofweekabbr] +const english_daysofweek = Dict(1=>"Monday",2=>"Tuesday",3=>"Wednesday", + 4=>"Thursday",5=>"Friday",6=>"Saturday",7=>"Sunday") +const VALUETODAYOFWEEK = Dict{UTF8String,Dict{Int,UTF8String}}("english"=>english_daysofweek) +const english_daysofweekabbr = Dict(1=>"Mon",2=>"Tue",3=>"Wed", + 4=>"Thu",5=>"Fri",6=>"Sat",7=>"Sun") +const VALUETODAYOFWEEKABBR = Dict{UTF8String,Dict{Int,UTF8String}}("english"=>english_daysofweekabbr) dayname(dt::Integer;locale::String="english") = VALUETODAYOFWEEK[locale][dt] dayabbr(dt::Integer;locale::String="english") = VALUETODAYOFWEEKABBR[locale][dt] dayname(dt::TimeType;locale::String="english") = VALUETODAYOFWEEK[locale][dayofweek(dt)] @@ -64,14 +64,14 @@ end const January,February,March,April,May,June = 1,2,3,4,5,6 const July,August,September,October,November,December = 7,8,9,10,11,12 const Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec = 1,2,3,4,5,6,7,8,9,10,11,12 -const english_months = [1=>"January",2=>"February",3=>"March",4=>"April", - 5=>"May",6=>"June",7=>"July",8=>"August",9=>"September", - 10=>"October",11=>"November",12=>"December"] -const VALUETOMONTH = (UTF8String=>Dict{Int,UTF8String})["english"=>english_months] -const englishabbr_months = [1=>"Jan",2=>"Feb",3=>"Mar",4=>"Apr", - 5=>"May",6=>"Jun",7=>"Jul",8=>"Aug",9=>"Sep", - 10=>"Oct",11=>"Nov",12=>"Dec"] -const VALUETOMONTHABBR = (UTF8String=>Dict{Int,UTF8String})["english"=>englishabbr_months] +const english_months = Dict(1=>"January",2=>"February",3=>"March",4=>"April", + 5=>"May",6=>"June",7=>"July",8=>"August",9=>"September", + 10=>"October",11=>"November",12=>"December") +const VALUETOMONTH = Dict{UTF8String,Dict{Int,UTF8String}}("english"=>english_months) +const englishabbr_months = Dict(1=>"Jan",2=>"Feb",3=>"Mar",4=>"Apr", + 5=>"May",6=>"Jun",7=>"Jul",8=>"Aug",9=>"Sep", + 10=>"Oct",11=>"Nov",12=>"Dec") +const VALUETOMONTHABBR = Dict{UTF8String,Dict{Int,UTF8String}}("english"=>englishabbr_months) monthname(dt::Integer;locale::String="english") = VALUETOMONTH[locale][dt] monthabbr(dt::Integer;locale::String="english") = VALUETOMONTHABBR[locale][dt] monthname(dt::TimeType;locale::String="english") = VALUETOMONTH[locale][month(dt)] diff --git a/base/dict.jl b/base/dict.jl index 771fc89509d50..eb3795b1fdcc9 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -338,6 +338,8 @@ end Dict() = Dict{Any,Any}() Dict(kv::()) = Dict() +const AnyDict = Dict{Any,Any} + # TODO: this can probably be simplified using `eltype` as a THT (Tim Holy trait) Dict{K,V}(kv::((K,V)...,)) = Dict{K,V}(kv) Dict{K }(kv::((K,Any)...,)) = Dict{K,Any}(kv) @@ -355,7 +357,7 @@ Dict (ps::Pair...) = Dict{Any,Any}(ps) Dict(kv) = dict_with_eltype(kv, eltype(kv)) dict_with_eltype{K,V}(kv, ::Type{(K,V)}) = Dict{K,V}(kv) dict_with_eltype{K,V}(kv, ::Type{Pair{K,V}}) = Dict{K,V}(kv) -dict_with_eltype{K,V}(kv, t) = Dict{Any,Any}(kv) +dict_with_eltype(kv, t) = Dict{Any,Any}(kv) similar{K,V}(d::Dict{K,V}) = Dict{K,V}() @@ -730,7 +732,7 @@ end type WeakKeyDict{K,V} <: Associative{K,V} ht::Dict{Any,V} - WeakKeyDict() = new((Any=>V)[]) + WeakKeyDict() = new(Dict{Any,V}()) end WeakKeyDict() = WeakKeyDict{Any,Any}() diff --git a/base/latex_symbols.jl b/base/latex_symbols.jl index a6c359227ddbb..d4f05bb23891f 100644 --- a/base/latex_symbols.jl +++ b/base/latex_symbols.jl @@ -60,7 +60,7 @@ end # Finally, we also add some symbols manually (at the top) as needed. -const latex_symbols = [ +const latex_symbols = Dict( # manual additions: @@ -2535,4 +2535,4 @@ const latex_symbols = [ "\\mtteight" => "𝟾", # mathematical monospace digit 8 "\\mttnine" => "𝟿", # mathematical monospace digit 9 -] +) diff --git a/base/loading.jl b/base/loading.jl index 760370c512e5a..e3dcf2d6fd501 100644 --- a/base/loading.jl +++ b/base/loading.jl @@ -33,9 +33,9 @@ function find_source_file(file) end # Store list of files and their load time -package_list = (ByteString=>Float64)[] +package_list = Dict{ByteString,Float64}() # to synchronize multiple tasks trying to require something -package_locks = (ByteString=>Any)[] +package_locks = Dict{ByteString,Any}() require(fname::String) = require(bytestring(fname)) require(f::String, fs::String...) = (require(f); for x in fs require(x); end) diff --git a/base/multi.jl b/base/multi.jl index 3f25cc2546291..4deec51e5ec42 100644 --- a/base/multi.jl +++ b/base/multi.jl @@ -1117,7 +1117,7 @@ function launch(manager::LocalManager, np::Integer, config::Dict, resp_arr::Arra for i in 1:np io, pobj = open(detach(`$(dir)/$(exename) $exeflags --bind-to $(LPROC.bind_addr)`), "r") io_objs[i] = io - configs[i] = merge(config, {:process => pobj}) + configs[i] = merge(config, AnyDict(:process => pobj)) end # ...and then read the host:port info. This optimizes overall start times. @@ -1279,7 +1279,7 @@ function addprocs_internal(np::Integer; exename=(ccall(:jl_is_debugbuild,Cint,())==0?"./julia":"./julia-debug"), sshflags::Cmd=``, manager=LocalManager(), exeflags=``, max_parallel=10) - config={:dir=>dir, :exename=>exename, :exeflags=>`$exeflags --worker`, :tunnel=>tunnel, :sshflags=>sshflags, :max_parallel=>max_parallel} + config = AnyDict(:dir=>dir, :exename=>exename, :exeflags=>`$exeflags --worker`, :tunnel=>tunnel, :sshflags=>sshflags, :max_parallel=>max_parallel) disable_threaded_libs() ret = Array(Int, 0) diff --git a/base/pkg/generate.jl b/base/pkg/generate.jl index 56f1047755894..2d6ba66c1ec48 100644 --- a/base/pkg/generate.jl +++ b/base/pkg/generate.jl @@ -428,6 +428,6 @@ $(copyright(years,authors)) > of your accepting any such warranty or additional liability. """ -const LICENSES = [ "MIT" => mit, "BSD" => bsd, "ASL" => asl ] +const LICENSES = Dict("MIT" => mit, "BSD" => bsd, "ASL" => asl) end # module diff --git a/base/pkg/github.jl b/base/pkg/github.jl index cc32239a366f2..5d998e73b06ee 100644 --- a/base/pkg/github.jl +++ b/base/pkg/github.jl @@ -3,11 +3,11 @@ module GitHub import Main, ..Git, ..Dir const AUTH_NOTE = "Julia Package Manager" -const AUTH_DATA = { +const AUTH_DATA = Dict{Any,Any}( "scopes" => ["repo"], "note" => AUTH_NOTE, "note_url" => "http://docs.julialang.org/en/latest/manual/packages/", -} +) function user() if !success(`git config --global github.user`) @@ -36,7 +36,7 @@ function curl(url::String, opts::Cmd=``) out, proc = open(`curl -i -s -S $opts $url`,"r") head = readline(out) status = int(split(head,r"\s+";limit=3)[2]) - header = (String=>String)[] + header = Dict{String,String}() for line in eachline(out) if !ismatch(r"^\s*$",line) (k,v) = split(line, r":\s*"; limit=2) diff --git a/base/pkg/query.jl b/base/pkg/query.jl index ad0cfe8e119c8..7939d36fa5555 100644 --- a/base/pkg/query.jl +++ b/base/pkg/query.jl @@ -25,9 +25,9 @@ function requirements(reqs::Dict, fix::Dict, avail::Dict) reqs end -function dependencies(avail::Dict, fix::Dict = (ByteString=>Fixed)["julia"=>Fixed(VERSION)]) +function dependencies(avail::Dict, fix::Dict = Dict{ByteString,Fixed}("julia"=>Fixed(VERSION))) avail = deepcopy(avail) - conflicts = (ByteString=>Set{ByteString})[] + conflicts = Dict{ByteString,Set{ByteString}}() for (fp,fx) in fix delete!(avail, fp) for (ap,av) in avail, (v,a) in copy(av) @@ -126,13 +126,13 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber # To each version in each package, we associate a BitVector. # It is going to hold a pattern such that all versions with # the same pattern are equivalent. - vmask = (ByteString=>Dict{VersionNumber, BitVector})[] + vmask = Dict{ByteString,Dict{VersionNumber, BitVector}}() # Parse requirements and store allowed versions. - allowed = (ByteString=>Dict{VersionNumber, Bool})[] + allowed = Dict{ByteString,Dict{VersionNumber, Bool}}() for (p,vs) in reqs @assert !haskey(allowed, p) - allowed[p] = (VersionNumber=>Bool)[] + allowed[p] = Dict{VersionNumber,Bool}() allowedp = allowed[p] for vn in keys(deps[p]) allowedp[vn] = vn in vs @@ -141,10 +141,10 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber @assert any(collect(values(allowedp))) end - filtered_deps = (ByteString=>Dict{VersionNumber,Available})[] + filtered_deps = Dict{ByteString,Dict{VersionNumber,Available}}() for (p,depsp) in deps - filtered_deps[p] = (VersionNumber=>Available)[] - allowedp = get(allowed, p, (VersionNumber=>Bool)[]) + filtered_deps[p] = Dict{VersionNumber,Available}() + allowedp = get(allowed, p, Dict{VersionNumber,Bool}()) fdepsp = filtered_deps[p] for (vn,a) in depsp if !isempty(allowedp) && !allowedp[vn] @@ -177,7 +177,7 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber # Grow the pattern by the number of classes luds = length(uniqdepssets) @assert !haskey(vmask, p) - vmask[p] = (VersionNumber=>BitVector)[] + vmask[p] = Dict{VersionNumber,BitVector}() vmaskp = vmask[p] for vn in keys(fdepsp) vmaskp[vn] = falses(luds) @@ -209,8 +209,8 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber # At this point, the vmask patterns are computed. We divide them into # classes so that we can keep just one version for each class. - pruned_vers = (ByteString=>Vector{VersionNumber})[] - eq_classes = (ByteString=>Dict{VersionNumber,Vector{VersionNumber}})[] + pruned_vers = Dict{ByteString,Vector{VersionNumber}}() + eq_classes = Dict{ByteString,Dict{VersionNumber,Vector{VersionNumber}}}() for (p, vmaskp) in vmask vmask0_uniq = unique(values(vmaskp)) nc = length(vmask0_uniq) @@ -224,7 +224,7 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber # For each nonempty class, we store only the highest version) pruned_vers[p] = VersionNumber[] prunedp = pruned_vers[p] - eq_classes[p] = (VersionNumber=>Vector{VersionNumber})[] + eq_classes[p] = Dict{VersionNumber,Vector{VersionNumber}}() eqclassp = eq_classes[p] for cl in classes if !isempty(cl) @@ -248,7 +248,7 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber # Put all remaining packages into eq_classes for (p, depsp) in deps haskey(eq_classes, p) && continue - eq_classes[p] = (VersionNumber=>Vector{VersionNumber})[] + eq_classes[p] = Dict{VersionNumber,Vector{VersionNumber}}() eqclassp = eq_classes[p] for vn in keys(depsp) eqclassp[vn] = [vn] @@ -257,7 +257,7 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber # Recompute deps. We could simplify them, but it's not worth it - new_deps = (ByteString=>Dict{VersionNumber,Available})[] + new_deps = Dict{ByteString,Dict{VersionNumber,Available}}() for (p,depsp) in deps @assert !haskey(new_deps, p) @@ -265,7 +265,7 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber new_deps[p] = depsp continue end - new_deps[p] = (VersionNumber=>Available)[] + new_deps[p] = Dict{VersionNumber,Available}() pruned_versp = pruned_vers[p] for (vn,a) in depsp in(vn, pruned_versp) || continue @@ -297,7 +297,7 @@ function prune_versions(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber return new_deps, eq_classes end prune_versions(deps::Dict{ByteString,Dict{VersionNumber,Available}}) = - prune_versions((ByteString=>VersionSet)[], deps) + prune_versions(Dict{ByteString,VersionSet}(), deps) # Build a subgraph incuding only the (direct and indirect) dependencies # of a given package set @@ -320,7 +320,7 @@ function dependencies_subset(deps::Dict{ByteString,Dict{VersionNumber,Available} sub_deps = Dict{ByteString,Dict{VersionNumber,Available}}() for p in allpkgs - haskey(sub_deps, p) || (sub_deps[p] = (VersionNumber=>Available)[]) + haskey(sub_deps, p) || (sub_deps[p] = Dict{VersionNumber,Available}()) sub_depsp = sub_deps[p] for (vn, a) in deps[p] sub_depsp[vn] = a diff --git a/base/pkg/resolve.jl b/base/pkg/resolve.jl index fd5393fb5a375..18632f9a363f3 100644 --- a/base/pkg/resolve.jl +++ b/base/pkg/resolve.jl @@ -48,10 +48,10 @@ function sanity_check(deps::Dict{ByteString,Dict{VersionNumber,Available}}) deps, eq_classes = Query.prune_versions(deps) - ndeps = (ByteString=>Dict{VersionNumber,Int})[] + ndeps = Dict{ByteString,Dict{VersionNumber,Int}}() for (p,depsp) in deps - ndeps[p] = ndepsp = (VersionNumber=>Int)[] + ndeps[p] = ndepsp = Dict{VersionNumber,Int}() for (vn,a) in depsp ndepsp[vn] = length(a.requires) end @@ -83,7 +83,7 @@ function sanity_check(deps::Dict{ByteString,Dict{VersionNumber,Available}}) continue end - sub_reqs = (ByteString=>VersionSet)[p=>VersionSet([vn, nvn])] + sub_reqs = Dict{ByteString,VersionSet}(p=>VersionSet([vn, nvn])) sub_deps = Query.prune_dependencies(sub_reqs, deps) interface = Interface(sub_reqs, sub_deps) diff --git a/base/pkg/resolve/interface.jl b/base/pkg/resolve/interface.jl index d888849e90314..071b89326f1a0 100644 --- a/base/pkg/resolve/interface.jl +++ b/base/pkg/resolve/interface.jl @@ -65,7 +65,7 @@ type Interface end # generate vdict - vdict = [(VersionNumber=>Int)[] for p0 = 1:np] + vdict = [Dict{VersionNumber,Int}() for p0 = 1:np] for (p,depsp) in deps p0 = pdict[p] vdict0 = vdict[p0] @@ -103,7 +103,7 @@ function compute_output_dict(sol::Vector{Int}, interface::Interface) pvers = interface.pvers spp = interface.spp - want = (ByteString=>VersionNumber)[] + want = Dict{ByteString,VersionNumber}() for p0 = 1:np p = pkgs[p0] s = sol[p0] @@ -170,7 +170,7 @@ function enforce_optimality!(sol::Vector{Int}, interface::Interface) pdeps = [ Array(Requires, spp[p0]-1) for p0 = 1:np ] # prevdeps[p1][p0][v0] is the VersionSet of package p1 which package p0 version v0 # depends upon - prevdeps = [ (Int=>Dict{Int,VersionSet})[] for p0 = 1:np ] + prevdeps = [ Dict{Int,Dict{Int,VersionSet}}() for p0 = 1:np ] for (p,d) in deps p0 = pdict[p] @@ -181,7 +181,7 @@ function enforce_optimality!(sol::Vector{Int}, interface::Interface) for (rp, rvs) in a.requires p1 = pdict[rp] if !haskey(prevdeps[p1], p0) - prevdeps[p1][p0] = (Int=>VersionSet)[] + prevdeps[p1][p0] = Dict{Int,VersionSet}() end prevdeps[p1][p0][v0] = rvs end diff --git a/base/pkg/resolve/maxsum.jl b/base/pkg/resolve/maxsum.jl index 70336337d1d08..61cc615294b16 100644 --- a/base/pkg/resolve/maxsum.jl +++ b/base/pkg/resolve/maxsum.jl @@ -89,7 +89,7 @@ type Graph gadj = [ Int[] for i = 1:np ] gmsk = [ BitMatrix[] for i = 1:np ] gdir = [ Int[] for i = 1:np ] - adjdict = [ (Int=>Int)[] for i = 1:np ] + adjdict = [ Dict{Int,Int}() for i = 1:np ] for (p,d) in deps p0 = pdict[p] diff --git a/base/primes.jl b/base/primes.jl index a8898aeb7895f..0d81c8e1325ce 100644 --- a/base/primes.jl +++ b/base/primes.jl @@ -77,7 +77,7 @@ const PRIMES = primes(10000) function factor{T<:Integer}(n::T) 0 < n || error("number to be factored must be positive") - h = (T=>Int)[] + h = Dict{T,Int}() n == 1 && return h n <= 3 && (h[n] = 1; return h) local s::T, p::T diff --git a/base/profile.jl b/base/profile.jl index 9f2a5a8bfd8ec..3934ae6bf1a52 100644 --- a/base/profile.jl +++ b/base/profile.jl @@ -132,11 +132,11 @@ function lookup(ip::Uint) end end -error_codes = (Int=>ASCIIString)[ +error_codes = Dict{Int,ASCIIString}( -1=>"cannot specify signal action for profiling", -2=>"cannot create the timer for profiling", -3=>"cannot start the timer for profiling", - -4=>"cannot unblock SIGUSR1"] + -4=>"cannot unblock SIGUSR1") function fetch() len = len_data() @@ -157,7 +157,7 @@ const btskip = 0 ## Print as a flat list # Counts the number of times each line appears, at any nesting level function count_flat{T<:Unsigned}(data::Vector{T}) - linecount = (T=>Int)[] + linecount = Dict{T,Int}() toskip = btskip for ip in data if toskip > 0 @@ -249,7 +249,7 @@ end # Identify and counts repetitions of all unique backtraces function tree_aggregate{T<:Unsigned}(data::Vector{T}) iz = find(data .== 0) # find the breaks between backtraces - treecount = (Vector{T}=>Int)[] + treecount = Dict{Vector{T},Int}() istart = 1+btskip for iend in iz tmp = data[iend-1:-1:istart] @@ -321,7 +321,7 @@ function tree{T<:Unsigned}(io::IO, bt::Vector{Vector{T}}, counts::Vector{Int}, l # Organize backtraces into groups that are identical up to this level if combine # Combine based on the line information - d = (LineInfo=>Vector{Int})[] + d = Dict{LineInfo,Vector{Int}}() for i = 1:length(bt) ip = bt[i][level+1] key = lidict[ip] @@ -346,7 +346,7 @@ function tree{T<:Unsigned}(io::IO, bt::Vector{Vector{T}}, counts::Vector{Int}, l end else # Combine based on the instruction pointer - d = (T=>Vector{Int})[] + d = Dict{T,Vector{Int}}() for i = 1:length(bt) key = bt[i][level+1] indx = Base.ht_keyindex(d, key) diff --git a/base/quadgk.jl b/base/quadgk.jl index 177b4c05fd234..a1d89ef61b5a4 100644 --- a/base/quadgk.jl +++ b/base/quadgk.jl @@ -1,7 +1,7 @@ module QuadGK export gauss, kronrod, quadgk using Base.Collections -import Base.isless, Base.Order.Reverse +import Base: isless, Order.Reverse, AnyDict # Adaptive Gauss-Kronrod quadrature routines (arbitrary precision), # written and contributed to Julia by Steven G. Johnson, 2013. @@ -11,7 +11,7 @@ import Base.isless, Base.Order.Reverse # cache of (T,n) -> (x,w,gw) Kronrod rules, to avoid recomputing them # unnecessarily for repeated integration. We initialize it with the # default n=7 rule for double-precision calculations. -const rulecache = (Any=>Any)[ (Float64,7) => # precomputed in 100-bit arith. +const rulecache = AnyDict( (Float64,7) => # precomputed in 100-bit arith. ([-9.9145537112081263920685469752598e-01, -9.4910791234275852452618968404809e-01, -8.6486442335976907278971278864098e-01, @@ -31,7 +31,7 @@ const rulecache = (Any=>Any)[ (Float64,7) => # precomputed in 100-bit arith. [1.2948496616886969327061143267787e-01, 2.797053914892766679014677714229e-01, 3.8183005050511894495036977548818e-01, - 4.1795918367346938775510204081658e-01]) ] + 4.1795918367346938775510204081658e-01]) ) # integration segment (a,b), estimated integral I, and estimated error E immutable Segment diff --git a/base/show.jl b/base/show.jl index eb7b3c92b03d8..b5c4cc11c91eb 100644 --- a/base/show.jl +++ b/base/show.jl @@ -240,9 +240,9 @@ const uni_ops = Set{Symbol}([:(+), :(-), :(!), :(¬), :(~), :(<:), :(>:), :(√) const expr_infix_wide = Set([:(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(&=), :(|=), :($=), :(>>>=), :(>>=), :(<<=), :(&&), :(||)]) const expr_infix = Set([:(:), :(<:), :(->), :(=>), symbol("::")]) -const expr_calls = [:call =>('(',')'), :calldecl =>('(',')'), :ref =>('[',']'), :curly =>('{','}')] -const expr_parens = [:tuple=>('(',')'), :vcat=>('[',']'), :cell1d=>('{','}'), - :hcat =>('[',']'), :row =>('[',']')] +const expr_calls = Dict(:call =>('(',')'), :calldecl =>('(',')'), :ref =>('[',']'), :curly =>('{','}')) +const expr_parens = Dict(:tuple=>('(',')'), :vcat=>('[',']'), :cell1d=>('{','}'), + :hcat =>('[',']'), :row =>('[',']')) ## AST decoding helpers ## diff --git a/src/jlfrontend.scm b/src/jlfrontend.scm index d63c62457c0e3..e32c05a35aa20 100644 --- a/src/jlfrontend.scm +++ b/src/jlfrontend.scm @@ -18,10 +18,10 @@ `(incomplete ,msg) e)) (begin - ;;(newline) - ;;(display "unexpected error: ") - ;;(prn e) - ;;(print-stack-trace (stacktrace)) + (newline) + (display "unexpected error: ") + (prn e) + (print-stack-trace (stacktrace)) '(error "malformed expression")))) thk)) diff --git a/src/julia-parser.scm b/src/julia-parser.scm index 97db514656b77..de71be87a1230 100644 --- a/src/julia-parser.scm +++ b/src/julia-parser.scm @@ -94,6 +94,18 @@ abstract typealias type bitstype immutable ccall do module baremodule using import export importall)) +(define (assignment? e) + (and (pair? e) (eq? (car e) '=))) + +(define (assignment-like? e) + (and (pair? e) (is-prec-assignment? (car e)))) + +(define (kwarg? e) + (and (pair? e) (eq? (car e) 'kw))) + +(define (dict-literal? l) + (and (length= l 3) (eq? (car l) '=>))) + ;; Parser state variables ; disable range colon for parsing ternary conditional operator @@ -140,18 +152,6 @@ `(with-bindings ((whitespace-newline #f)) ,@body)) -(define (assignment? e) - (and (pair? e) (eq? (car e) '=))) - -(define (assignment-like? e) - (and (pair? e) (is-prec-assignment? (car e)))) - -(define (kwarg? e) - (and (pair? e) (eq? (car e) 'kw))) - -(define (dict-literal? l) - (and (length= l 3) (eq? (car l) '=>))) - ;; --- lexer --- (define special-char? @@ -498,6 +498,21 @@ (begin0 (ts:last-tok s) (ts:set-tok! s #f)))) +;; --- misc --- + +(define (syntax-deprecation-warning s what instead) + (io.write + *stderr* + (string + #\newline "WARNING: deprecated syntax \"" what "\"" + (if (eq? current-filename 'none) + "" + (string " at " current-filename ":" (input-port-line (ts:port s)))) + "." + (if (equal? instead "") + "" + (string #\newline "Use \"" instead "\" instead." #\newline))))) + ;; --- parser --- ; parse left-to-right binary operator @@ -653,16 +668,7 @@ ex) (let ((argument (cond ((closing-token? (peek-token s)) - (io.write - *stderr* - (string - #\newline "WARNING: deprecated syntax \"x[i:]\"" - (if (eq? current-filename 'none) - "" - (string - " at " - current-filename ":" (input-port-line (ts:port s)))) - "." #\newline "Use \"x[i:end]\" instead." #\newline)) + (syntax-deprecation-warning s "x[i:]" "x[i:end]") ':) ; missing last argument ((newline? (peek-token s)) (error "line break in \":\" expression")) @@ -898,6 +904,11 @@ (parse-resword s ex) (parse-call-chain s ex #f)))) +(define (deprecated-dict-replacement ex) + (if (dict-literal? ex) + (string "Dict{" (deparse (cadr ex)) #\, (deparse (caddr ex)) "}") + "Dict")) + (define (parse-call-chain s ex one-call) (let loop ((ex ex)) (let ((t (peek-token s))) @@ -928,13 +939,21 @@ ;; ref is syntax, so we can distinguish ;; a[i] = x from ;; ref(a,i) = x - (let ((al (with-end-symbol (parse-cat s #\] )))) + (let ((al (with-end-symbol (parse-cat s #\] (dict-literal? ex))))) (if (null? al) (if (dict-literal? ex) - (loop (list 'typed_dict ex)) + (begin + (syntax-deprecation-warning + s (string #\( (deparse ex) #\) "[]") + (string (deprecated-dict-replacement ex) "()")) + (loop (list 'typed_dict ex))) (loop (list 'ref ex))) (case (car al) - ((dict) (loop (list* 'typed_dict ex (cdr al)))) + ((dict) + (syntax-deprecation-warning + s (string #\( (deparse ex) #\) "[a=>b, ...]") + (string (deprecated-dict-replacement ex) "(a=>b, ...)")) + (loop (list* 'typed_dict ex (cdr al)))) ((hcat) (loop (list* 'typed_hcat ex (cdr al)))) ((vcat) (if (any (lambda (x) @@ -1476,7 +1495,7 @@ (loop (peek-token s))) t))) -(define (parse-cat s closer) +(define (parse-cat s closer . isdict) (with-normal-ops (with-inside-vec (if (eqv? (require-token s) closer) @@ -1489,7 +1508,12 @@ (take-token s) (parse-dict-comprehension s first closer)) (else - (parse-dict s first closer))) + (if (eqv? closer #\}) + (syntax-deprecation-warning s "{a=>b, ...}" "Dict{Any,Any}(a=>b, ...)") + (or + (and (pair? isdict) (car isdict)) + (syntax-deprecation-warning s "[a=>b, ...]" "Dict(a=>b, ...)"))) + (parse-dict s first closer))) (case (peek-token s) ((#\,) (parse-vcat s first closer)) diff --git a/test/collections.jl b/test/collections.jl index e88475b03c3b9..3543c1430e826 100644 --- a/test/collections.jl +++ b/test/collections.jl @@ -36,7 +36,7 @@ end for i=10000:20000 @test h[i]==i+1 end -h = {"a" => 3} +h = Dict{Any,Any}("a" => 3) @test h["a"] == 3 h["a","b"] = 4 @test h["a","b"] == h[("a","b")] == 4 @@ -54,7 +54,7 @@ let @test get_KeyError end -_d = {"a"=>0} +_d = Dict("a"=>0) @test isa([k for k in filter(x->length(x)==1, collect(keys(_d)))], Vector{Any}) # issue #1821 @@ -71,8 +71,8 @@ let bestkey(d, key) = key bestkey{K<:String,V}(d::Associative{K,V}, key) = string(key) bar(x) = bestkey(x, :y) - @test bar([:x => [1,2,5]]) == :y - @test bar(["x" => [1,2,5]]) == "y" + @test bar(Dict(:x => [1,2,5])) == :y + @test bar(Dict("x" => [1,2,5])) == "y" end # issue #1438 @@ -100,10 +100,10 @@ begin end @test isequal(Dict(), Dict()) -@test isequal({1 => 1}, {1 => 1}) -@test !isequal({1 => 1}, {}) -@test !isequal({1 => 1}, {1 => 2}) -@test !isequal({1 => 1}, {2 => 1}) +@test isequal(Dict(1 => 1), Dict(1 => 1)) +@test !isequal(Dict(1 => 1), {}) +@test !isequal(Dict(1 => 1), Dict(1 => 2)) +@test !isequal(Dict(1 => 1), Dict(2 => 1)) # Generate some data to populate dicts to be compared data_in = [ (rand(1:1000), randstring(2)) for _ in 1:1001 ] @@ -144,13 +144,13 @@ d4[1001] = randstring(3) # Here is what currently happens when dictionaries of different types # are compared. This is not necessarily desirable. These tests are # descriptive rather than proscriptive. -@test !isequal({1 => 2}, {"dog" => "bone"}) +@test !isequal(Dict(1 => 2), Dict("dog" => "bone")) @test isequal(Dict{Int, Int}(), Dict{String, String}()) # get! (get with default values assigned to the given location) let f(x) = x^2, - d = {8=>19}, + d = Dict(8=>19), def = {} @test get!(d, 8, 5) == 19 @@ -168,15 +168,15 @@ let f(x) = x^2, f(4) end == 16 - @test d == {8=>19, 19=>2, 42=>4} + @test d == Dict(8=>19, 19=>2, 42=>4) end # show -for d in (["\n" => "\n", "1" => "\n", "\n" => "2"], +for d in (Dict("\n" => "\n", "1" => "\n", "\n" => "2"), [string(i) => i for i = 1:30], [reshape(1:i^2,i,i) => reshape(1:i^2,i,i) for i = 1:24], [utf8(Char['α':'α'+i]) => utf8(Char['α':'α'+i]) for i = (1:10)*10], - ["key" => zeros(0, 0)]) + Dict("key" => zeros(0, 0))) for cols in (12, 40, 80), rows in (2, 10, 24) # Ensure output is limited as requested s = IOBuffer() @@ -208,11 +208,11 @@ end # issue #2540 d = {x => 1 for x in ['a', 'b', 'c']} -@test d == {'a'=>1, 'b'=>1, 'c'=> 1} +@test d == Dict('a'=>1, 'b'=>1, 'c'=> 1) # issue #2629 -d = (String => String)[ a => "foo" for a in ["a","b","c"]] -@test d == ["a"=>"foo","b"=>"foo","c"=>"foo"] +d = Dict{String,String}([ a => "foo" for a in ["a","b","c"]]) +@test d == Dict("a"=>"foo","b"=>"foo","c"=>"foo") # issue #5886 d5886 = Dict() diff --git a/test/core.jl b/test/core.jl index b3c1f61bfd615..2839462d80091 100644 --- a/test/core.jl +++ b/test/core.jl @@ -1516,15 +1516,15 @@ end # make sure that incomplete tags are detected correctly # (i.e. error messages in src/julia-parser.scm must be matched correctly # by the code in base/client.jl) -for (str, tag) in ["" => :none, "\"" => :string, "#=" => :comment, "'" => :char, - "`" => :cmd, "begin;" => :block, "quote;" => :block, - "let;" => :block, "for i=1;" => :block, "function f();" => :block, - "f() do x;" => :block, "module X;" => :block, "type X;" => :block, - "immutable X;" => :block, "(" => :other, "[" => :other, - "{" => :other, "begin" => :other, "quote" => :other, - "let" => :other, "for" => :other, "function" => :other, - "f() do" => :other, "module" => :other, "type" => :other, - "immutable" => :other] +for (str, tag) in Dict("" => :none, "\"" => :string, "#=" => :comment, "'" => :char, + "`" => :cmd, "begin;" => :block, "quote;" => :block, + "let;" => :block, "for i=1;" => :block, "function f();" => :block, + "f() do x;" => :block, "module X;" => :block, "type X;" => :block, + "immutable X;" => :block, "(" => :other, "[" => :other, + "{" => :other, "begin" => :other, "quote" => :other, + "let" => :other, "for" => :other, "function" => :other, + "f() do" => :other, "module" => :other, "type" => :other, + "immutable" => :other) @test Base.incomplete_tag(parse(str, raise=false)) == tag end diff --git a/test/dates/io.jl b/test/dates/io.jl index e9b441078933b..6a069b3345707 100644 --- a/test/dates/io.jl +++ b/test/dates/io.jl @@ -186,7 +186,7 @@ f2 = "dd/mm/yy" @test Dates.Date("28/05/2014",f) == Dates.Date(2014,5,28) @test Dates.Date("28/05/14",f2) + Dates.Year(2000) == Dates.Date(2014,5,28) -const french = ["janv"=>1,"févr"=>2,"mars"=>3,"avril"=>4,"mai"=>5,"juin"=>6,"juil"=>7,"août"=>8,"sept"=>9,"oct"=>10,"nov"=>11,"déc"=>12] +const french = Dict("janv"=>1,"févr"=>2,"mars"=>3,"avril"=>4,"mai"=>5,"juin"=>6,"juil"=>7,"août"=>8,"sept"=>9,"oct"=>10,"nov"=>11,"déc"=>12) Dates.MONTHTOVALUEABBR["french"] = french Dates.VALUETOMONTHABBR["french"] = [v=>k for (k,v) in french] @@ -214,8 +214,8 @@ f = "dduuuyyyy" @test Dates.Date("01Dec2009",f) == Dates.Date(2009,12,1) @test Dates.format(Dates.Date(2009,12,1),f) == "01Dec2009" f = "duy" -const globex = ["f"=>Dates.Jan,"g"=>Dates.Feb,"h"=>Dates.Mar,"j"=>Dates.Apr,"k"=>Dates.May,"m"=>Dates.Jun, - "n"=>Dates.Jul,"q"=>Dates.Aug,"u"=>Dates.Sep,"v"=>Dates.Oct,"x"=>Dates.Nov,"z"=>Dates.Dec] +const globex = Dict("f"=>Dates.Jan,"g"=>Dates.Feb,"h"=>Dates.Mar,"j"=>Dates.Apr,"k"=>Dates.May,"m"=>Dates.Jun, + "n"=>Dates.Jul,"q"=>Dates.Aug,"u"=>Dates.Sep,"v"=>Dates.Oct,"x"=>Dates.Nov,"z"=>Dates.Dec) Dates.MONTHTOVALUEABBR["globex"] = globex Dates.VALUETOMONTHABBR["globex"] = [v=>uppercase(k) for (k,v) in globex] @test Dates.Date("1F4",f;locale="globex") + Dates.Year(2010) == Dates.Date(2014,1,1) diff --git a/test/dates/query.jl b/test/dates/query.jl index 3ae0652e0725f..6c06f4a8c1be1 100644 --- a/test/dates/query.jl +++ b/test/dates/query.jl @@ -32,8 +32,8 @@ for (i,dt) in enumerate([jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec]) end # Customizing locale -const french_daysofweek = [1=>"Lundi",2=>"Mardi",3=>"Mercredi",4=>"Jeudi", - 5=>"Vendredi",6=>"Samedi",7=>"Dimanche"] +const french_daysofweek = Dict(1=>"Lundi",2=>"Mardi",3=>"Mercredi",4=>"Jeudi", + 5=>"Vendredi",6=>"Samedi",7=>"Dimanche") Dates.VALUETODAYOFWEEK["french"] = french_daysofweek @test Dates.dayname(nov;locale="french") == "Lundi" @test Dates.dayname(jan;locale="french") == "Mardi" @@ -43,8 +43,8 @@ Dates.VALUETODAYOFWEEK["french"] = french_daysofweek @test Dates.dayname(feb;locale="french") == "Samedi" @test Dates.dayname(may;locale="french") == "Dimanche" -const french_months = [1=>"janvier",2=>"février",3=>"mars",4=>"avril",5=>"mai",6=>"juin", - 7=>"juillet",8=>"août",9=>"septembre",10=>"octobre",11=>"novembre",12=>"décembre"] +const french_months = Dict(1=>"janvier",2=>"février",3=>"mars",4=>"avril",5=>"mai",6=>"juin", + 7=>"juillet",8=>"août",9=>"septembre",10=>"octobre",11=>"novembre",12=>"décembre") Dates.VALUETOMONTH["french"] = french_months @test Dates.monthname(jan;locale="french") == "janvier" @test Dates.monthname(feb;locale="french") == "février" diff --git a/test/hashing.jl b/test/hashing.jl index 6bb0f1bff3ad7..fba0b1fcad291 100644 --- a/test/hashing.jl +++ b/test/hashing.jl @@ -54,12 +54,12 @@ vals = {[1,2,3,4], [1 3;2 4], {1,2,3,4}, [1,3,2,4], Set([1,2,3,4]), Set([1:10]), # these lead to different key orders Set([7,9,4,10,2,3,5,8,6,1]), # - [42 => 101, 77 => 93], {42 => 101, 77 => 93}, + Dict(42 => 101, 77 => 93), Dict(42 => 101, 77 => 93), (1,2,3,4), (1.0,2.0,3.0,4.0), (1,3,2,4), ("a","b"), (SubString("a",1,1), SubString("b",1,1)), # issue #6900 [x => x for x in 1:10], - [7=>7,9=>9,4=>4,10=>10,2=>2,3=>3,8=>8,5=>5,6=>6,1=>1]} + Dict(7=>7,9=>9,4=>4,10=>10,2=>2,3=>3,8=>8,5=>5,6=>6,1=>1)} for a in vals, b in vals @test isequal(a,b) == (hash(a)==hash(b)) diff --git a/test/keywordargs.jl b/test/keywordargs.jl index b313238e753b6..b18d3eca07cec 100644 --- a/test/keywordargs.jl +++ b/test/keywordargs.jl @@ -66,7 +66,7 @@ opkwf1(a=0,b=1;k=2) = (a,b,k) @test isequal(opkwf1(k=8), ( 0, 1,8)) # dictionaries as keywords -@test kwf1(4; {:hundreds=>9, :tens=>5}...) == 954 +@test kwf1(4; Dict(:hundreds=>9, :tens=>5)...) == 954 # with inner function let @@ -85,7 +85,7 @@ extravagant_args(x,y=0,rest...;color="blue",kw...) = @test isequal(extravagant_args(1), (1,0,(),"blue",86)) @test isequal(extravagant_args(1;hundreds=7), (1,0,(),"blue",786)) -@test isequal(extravagant_args(1,2,3;{:color=>"red", :hundreds=>3}...), +@test isequal(extravagant_args(1,2,3;Dict(:color=>"red", :hundreds=>3)...), (1,2,(3,),"red",386)) # passing empty kw container to function with no kwargs diff --git a/test/lineedit.jl b/test/lineedit.jl index 60efd42db265f..c5cf284f12be4 100644 --- a/test/lineedit.jl +++ b/test/lineedit.jl @@ -3,23 +3,23 @@ using TestHelpers a_foo = 0 -const foo_keymap = { +const foo_keymap = Dict( 'a' => (o...)->(global a_foo; a_foo += 1) -} +) b_foo = 0 -const foo2_keymap = { +const foo2_keymap = Dict( 'b' => (o...)->(global b_foo; b_foo += 1) -} +) a_bar = 0 b_bar = 0 -const bar_keymap = { +const bar_keymap = Dict( 'a' => (o...)->(global a_bar; a_bar += 1), 'b' => (o...)->(global b_bar; b_bar += 1) -} +) test1_func = LineEdit.keymap([foo_keymap]) diff --git a/test/repl.jl b/test/repl.jl index e535605af79d1..4a15febc40f0c 100644 --- a/test/repl.jl +++ b/test/repl.jl @@ -86,9 +86,9 @@ begin help_mode = interface.modes[3] histp = interface.modes[4] - hp = REPL.REPLHistoryProvider((Symbol=>Any)[:julia => repl_mode, - :shell => shell_mode, - :help => help_mode]) + hp = REPL.REPLHistoryProvider(Dict{Symbol,Any}(:julia => repl_mode, + :shell => shell_mode, + :help => help_mode)) fakehistory = """ # time: 2014-06-30 17:32:49 EDT diff --git a/test/resolve.jl b/test/resolve.jl index d22ee631476b5..70bfc4cd05294 100644 --- a/test/resolve.jl +++ b/test/resolve.jl @@ -60,10 +60,10 @@ function deps_from_data(deps_data) for d in deps_data p = d[1]; vn = d[2]; r = d[3:end] if !haskey(deps, p) - deps[p] = (VersionNumber=>Available)[] + deps[p] = Dict{VersionNumber,Available}() end if !haskey(deps[p], vn) - deps[p][vn] = Available("$(p)_$(vn)_sha1", (ByteString=>VersionSet)[]) + deps[p][vn] = Available("$(p)_$(vn)_sha1", Dict{ByteString,VersionSet}()) end isempty(r) && continue rp = r[1] @@ -77,7 +77,7 @@ function deps_from_data(deps_data) deps end function reqs_from_data(reqs_data) - reqs = (ByteString=>VersionSet)[] + reqs = Dict{ByteString,VersionSet}() for r in reqs_data p = r[1] reqs[p] = VersionSet(VersionNumber[r[2:end]...]) @@ -124,14 +124,14 @@ reqs_data = { } want = resolve_tst(deps_data, reqs_data) -@test want == ["B"=>v"2"] +@test want == Dict("B"=>v"2") # require just A: must bring in B reqs_data = { {"A"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"2"] +@test want == Dict("A"=>v"2", "B"=>v"2") ## DEPENDENCY SCHEME 2: TWO PACKAGES, CYCLIC @@ -149,21 +149,21 @@ reqs_data = { {"A"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"2"] +@test want == Dict("A"=>v"2", "B"=>v"2") # require just B, force lower version reqs_data = { {"B", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"1"] +@test want == Dict("A"=>v"2", "B"=>v"1") # require just A, force lower version reqs_data = { {"A", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"1", "B"=>v"2"] +@test want == Dict("A"=>v"1", "B"=>v"2") ## DEPENDENCY SCHEME 3: THREE PACKAGES, CYCLIC, TWO MUTUALLY EXCLUSIVE SOLUTIONS @@ -183,21 +183,21 @@ reqs_data = { {"A"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"1", "C"=>v"2"] +@test want == Dict("A"=>v"2", "B"=>v"1", "C"=>v"2") # require just B (must choose solution which has the highest version for B) reqs_data = { {"B"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"1", "B"=>v"2", "C"=>v"1"] +@test want == Dict("A"=>v"1", "B"=>v"2", "C"=>v"1") # require just A, force lower version reqs_data = { {"A", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"1", "B"=>v"2", "C"=>v"1"] +@test want == Dict("A"=>v"1", "B"=>v"2", "C"=>v"1") # require A and C, incompatible versions reqs_data = { @@ -220,7 +220,7 @@ reqs_data = { {"B"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["B"=>v"1"] +@test want == Dict("B"=>v"1") ## DEPENDENCY SCHEME 5: THREE PACKAGES, DAG, WITH IMPLICIT INCONSISTENCY @@ -242,7 +242,7 @@ reqs_data = { {"A"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"1", "B"=>v"2", "C"=>v"2"] +@test want == Dict("A"=>v"1", "B"=>v"2", "C"=>v"2") # require A, force highest version (impossible) reqs_data = { @@ -293,14 +293,14 @@ reqs_data = { {"A"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"2", "C"=>v"2"] +@test want == Dict("A"=>v"2", "B"=>v"2", "C"=>v"2") # require C reqs_data = { {"C"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"2", "C"=>v"2"] +@test want == Dict("A"=>v"2", "B"=>v"2", "C"=>v"2") # require C, lowest version (impossible) reqs_data = { @@ -366,16 +366,16 @@ reqs_data = { {"F"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"3", "B"=>v"2", "C"=>v"2", - "D"=>v"2", "E"=>v"1", "F"=>v"2"] +@test want == Dict("A"=>v"3", "B"=>v"2", "C"=>v"2", + "D"=>v"2", "E"=>v"1", "F"=>v"2") # require just F, lower version reqs_data = { {"F", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"2", "D"=>v"2", - "E"=>v"1", "F"=>v"1"] +@test want == Dict("A"=>v"2", "B"=>v"2", "D"=>v"2", + "E"=>v"1", "F"=>v"1") # require F and B; force lower B version -> must bring down F, A, and D versions too reqs_data = { @@ -383,8 +383,8 @@ reqs_data = { {"B", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"1", "B"=>v"1", "D"=>v"1", - "E"=>v"1", "F"=>v"1"] +@test want == Dict("A"=>v"1", "B"=>v"1", "D"=>v"1", + "E"=>v"1", "F"=>v"1") # require F and D; force lower D version -> must not bring down F version reqs_data = { @@ -392,8 +392,8 @@ reqs_data = { {"D", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"3", "B"=>v"2", "C"=>v"2", - "D"=>v"1", "E"=>v"1", "F"=>v"2"] +@test want == Dict("A"=>v"3", "B"=>v"2", "C"=>v"2", + "D"=>v"1", "E"=>v"1", "F"=>v"2") # require F and C; force lower C version -> must bring down F and A versions reqs_data = { @@ -401,8 +401,8 @@ reqs_data = { {"C", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"2", "C"=>v"1", - "D"=>v"2", "E"=>v"1", "F"=>v"1"] +@test want == Dict("A"=>v"2", "B"=>v"2", "C"=>v"1", + "D"=>v"2", "E"=>v"1", "F"=>v"1") ## DEPENDENCY SCHEME 10: SIX PACKAGES, DAG, WITH PRERELEASE/BUILD VERSIONS deps_data = { @@ -440,16 +440,16 @@ reqs_data = { {"F"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2.1", "B"=>v"1.0.1", "C"=>v"2", - "D"=>v"2", "E"=>v"1", "F"=>v"2"] +@test want == Dict("A"=>v"2.1", "B"=>v"1.0.1", "C"=>v"2", + "D"=>v"2", "E"=>v"1", "F"=>v"2") # require just F, lower version reqs_data = { {"F", v"1", v"2-"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"1.0.1", "D"=>v"2", - "E"=>v"1", "F"=>v"1.1"] +@test want == Dict("A"=>v"2", "B"=>v"1.0.1", "D"=>v"2", + "E"=>v"1", "F"=>v"1.1") # require F and B; force lower B version -> must bring down F, A, and D versions too reqs_data = { @@ -457,8 +457,8 @@ reqs_data = { {"B", v"1", v"1.0.1-"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"1", "B"=>v"1", "D"=>v"1", - "E"=>v"1", "F"=>v"1.1"] +@test want == Dict("A"=>v"1", "B"=>v"1", "D"=>v"1", + "E"=>v"1", "F"=>v"1.1") # require F and D; force lower D version -> must not bring down F version reqs_data = { @@ -466,8 +466,8 @@ reqs_data = { {"D", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2.1", "B"=>v"1.0.1", "C"=>v"2", - "D"=>v"1", "E"=>v"1", "F"=>v"2"] +@test want == Dict("A"=>v"2.1", "B"=>v"1.0.1", "C"=>v"2", + "D"=>v"1", "E"=>v"1", "F"=>v"2") # require F and C; force lower C version -> must bring down F and A versions reqs_data = { @@ -475,5 +475,5 @@ reqs_data = { {"C", v"1", v"2"} } want = resolve_tst(deps_data, reqs_data) -@test want == ["A"=>v"2", "B"=>v"1.0.1", "C"=>v"1+BLD", - "D"=>v"2", "E"=>v"1", "F"=>v"2-rc.1"] +@test want == Dict("A"=>v"2", "B"=>v"1.0.1", "C"=>v"1+BLD", + "D"=>v"2", "E"=>v"1", "F"=>v"2-rc.1") diff --git a/test/sparse.jl b/test/sparse.jl index 74b772a393f0b..271d3cbda2d3e 100644 --- a/test/sparse.jl +++ b/test/sparse.jl @@ -458,5 +458,5 @@ end @test_throws BoundsError sparse([0],[-1],[1.0],2,2) # issue #8363 -@test_throws BoundsError sparsevec([-1=>1,1=>2]) +@test_throws BoundsError sparsevec(Dict(-1=>1,1=>2)) diff --git a/test/spawn.jl b/test/spawn.jl index d58c422dcfab3..b5154d8870c97 100644 --- a/test/spawn.jl +++ b/test/spawn.jl @@ -84,7 +84,7 @@ rm(file) end readall(setenv(`sh -c "echo \$TEST"`,["TEST=Hello World"])) == "Hello World\n" -readall(setenv(`sh -c "echo \$TEST"`,["TEST"=>"Hello World"])) == "Hello World\n" +readall(setenv(`sh -c "echo \$TEST"`,Dict("TEST"=>"Hello World"))) == "Hello World\n" readall(setenv(`sh -c "pwd"`;dir="/")) == readall(setenv(`sh -c "cd / && pwd"`)) # Here we test that if we close a stream with pending writes, we don't lose the writes. diff --git a/test/strings.jl b/test/strings.jl index 810935020530c..49d916849dbc4 100644 --- a/test/strings.jl +++ b/test/strings.jl @@ -1042,13 +1042,13 @@ end # isvalid(), chr2ind() and ind2chr() for SubString{DirectIndexString} let s="lorem ipsum", - sdict=[SubString(s,1,11)=>s, - SubString(s,1,6)=>"lorem ", - SubString(s,1,0)=>"", - SubString(s,2,4)=>"ore", - SubString(s,2,16)=>"orem ipsum", - SubString(s,12,14)=>"" - ] + sdict=Dict(SubString(s,1,11)=>s, + SubString(s,1,6)=>"lorem ", + SubString(s,1,0)=>"", + SubString(s,2,4)=>"ore", + SubString(s,2,16)=>"orem ipsum", + SubString(s,12,14)=>"" + ) for (ss,s) in sdict for i in -1:12 @test isvalid(ss,i)==isvalid(s,i) From d8232ecd0e275e12ffe239bca66e9440b589a3cc Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Mon, 6 Oct 2014 14:03:56 -0400 Subject: [PATCH 7/7] update NEWS and docs for dict syntax change --- NEWS.md | 16 +++++++++++++--- doc/manual/dates.rst | 2 +- doc/manual/interacting-with-julia.rst | 4 ++-- doc/manual/packages.rst | 6 +++++- doc/stdlib/base.rst | 19 ++++++++++--------- 5 files changed, 31 insertions(+), 16 deletions(-) diff --git a/NEWS.md b/NEWS.md index 87637f3a9d4c0..4dce228bc54b1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -20,6 +20,15 @@ Language changes * `Nothing` (the type of `nothing`) is renamed to `Void` ([#8423]). + * `Dict` literal syntax `[a=>b,c=>d]` is replaced with `Dict(a=>b,c=>d)`. + `{a=>b}` is replaced with `Dict{Any,Any}(a=>b)`. + `(K=>V)[...]` is replaced with `Dict{K,V}(...)`. + The new syntax has many advantages: all of its components are first-class, + it generalizes to other types of containers, it is easier to guess how to + specify key and value types, and the syntaxes for empty and pre-populated + dicts are synchronized. As part of this change, `=>` is parsed as a normal + operator, and `Base` defines it to construct `Pair` objects ([#6739]). + Library improvements -------------------- @@ -74,7 +83,7 @@ New language features generated. Constructors that look like `MyType(a, b) = new(a, b)` do not need to be added manually ([#4026], [#7071]). - * Expanded array type hierarchy to include an abstract ``DenseArray`` for + * Expanded array type hierarchy to include an abstract `DenseArray` for in-memory arrays with standard strided storage ([#987], [#2345], [#6212]). @@ -199,8 +208,8 @@ Library improvements * `writedlm` and `writecsv` now accept any iterable collection of iterable rows, in addition to `AbstractArray` arguments, and the - ``writedlm`` delimiter can be any printable object (e.g. a - ``String``) instead of just a ``Char``. + `writedlm` delimiter can be any printable object (e.g. a + `String`) instead of just a `Char`. * `isempty` now works for any iterable collection ([#5827]). @@ -991,3 +1000,4 @@ Too numerous to mention. [#7311]: https://github.com/JuliaLang/julia/issues/7311 [#8423]: https://github.com/JuliaLang/julia/issues/8423 [#8152]: https://github.com/JuliaLang/julia/pull/8152 +[#6739]: https://github.com/JuliaLang/julia/issues/6739 diff --git a/doc/manual/dates.rst b/doc/manual/dates.rst index 35e61f88a2e50..c927208c62e4d 100644 --- a/doc/manual/dates.rst +++ b/doc/manual/dates.rst @@ -210,7 +210,7 @@ As well as information about the ``TimeType``'s year and quarter:: The ``dayname`` and ``monthname`` methods can also take an optional ``locale`` keyword that can be used to return the name of the day or month of the year for other languages/locales:: - julia> const french_daysofweek = [1=>"Lundi",2=>"Mardi",3=>"Mercredi",4=>"Jeudi",5=>"Vendredi",6=>"Samedi",7=>"Dimanche"]; + julia> const french_daysofweek = Dict(1=>"Lundi",2=>"Mardi",3=>"Mercredi",4=>"Jeudi",5=>"Vendredi",6=>"Samedi",7=>"Dimanche"); # Load the mapping into the Dates module under locale name "french" julia> Dates.VALUETODAYOFWEEK["french"] = french_daysofweek; diff --git a/doc/manual/interacting-with-julia.rst b/doc/manual/interacting-with-julia.rst index 326620dfc10b4..4737862336a82 100644 --- a/doc/manual/interacting-with-julia.rst +++ b/doc/manual/interacting-with-julia.rst @@ -169,12 +169,12 @@ Julia's REPL keybindings may be fully customized to a user's preferences by pass import Base: LineEdit, REPL - const mykeys = { + const mykeys = Dict{Any,Any}( # Up Arrow "\e[A" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)), # Down Arrow "\e[B" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_next(s, LineEdit.mode(s).hist)) - } + ) Base.active_repl.interface = REPL.setup_interface(Base.active_repl; extra_repl_keymap = mykeys) diff --git a/doc/manual/packages.rst b/doc/manual/packages.rst index c847fe910f438..fd24c2fc30507 100644 --- a/doc/manual/packages.rst +++ b/doc/manual/packages.rst @@ -36,7 +36,11 @@ Packages can be in more complicated states, indicated by annotations to the righ For programmatic usage, ``Pkg.installed()`` returns a dictionary, mapping installed package names to the version of that package which is installed:: julia> Pkg.installed() - ["Distributions"=>v"0.2.8","Stats"=>v"0.2.6","UTF16"=>v"0.2.0","NumericExtensions"=>v"0.2.17"] + Dict{ASCIIString,VersionNumber} with 4 entries: + "Distributions" => v"0.2.8" + "Stats" => v"0.2.6" + "UTF16" => v"0.2.0" + "NumericExtensions" => v"0.2.17" Adding and Removing Packages ---------------------------- diff --git a/doc/stdlib/base.rst b/doc/stdlib/base.rst index 32e404e1ef8bb..69d234ab11cf3 100644 --- a/doc/stdlib/base.rst +++ b/doc/stdlib/base.rst @@ -958,22 +958,23 @@ Associative Collections ``ObjectIdDict`` is a special hash table where the keys are always object identities. ``WeakKeyDict`` is a hash table implementation where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table. -Dicts can be created using a literal syntax: ``{"A"=>1, "B"=>2}``. Use of curly brackets will create a ``Dict`` of type ``Dict{Any,Any}``. Use of square brackets will attempt to infer type information from the keys and values (i.e. ``["A"=>1, "B"=>2]`` creates a ``Dict{ASCIIString, Int64}``). To explicitly specify types use the syntax: ``(KeyType=>ValueType)[...]``. For example, ``(ASCIIString=>Int32)["A"=>1, "B"=>2]``. +Dicts can be created by passing pair objects constructed with ``=>`` to a ``Dict`` constructor: ``Dict("A"=>1, "B"=>2)``. This call will attempt to infer type information from the keys and values (i.e. this example creates a ``Dict{ASCIIString, Int64}``). +To explicitly specify types use the syntax ``Dict{KeyType,ValueType}(...)``. +For example, ``Dict{ASCIIString,Int32}("A"=>1, "B"=>2)``. As with arrays, ``Dicts`` may be created with comprehensions. For example, -``{i => f(i) for i = 1:10}``. +``[i => f(i) for i = 1:10]``. Given a dictionary ``D``, the syntax ``D[x]`` returns the value of key ``x`` (if it exists) or throws an error, and ``D[x] = y`` stores the key-value pair ``x => y`` in ``D`` (replacing any existing value for the key ``x``). Multiple arguments to ``D[...]`` are converted to tuples; for example, the syntax ``D[x,y]`` is equivalent to ``D[(x,y)]``, i.e. it refers to the value keyed by the tuple ``(x,y)``. -.. function:: Dict() +.. function:: Dict([itr]) - ``Dict{K,V}()`` constructs a hash + ``Dict{K,V}()`` constructs a hash table with keys of type K and values of type V. + Given a single iterable argument, constructs a ``Dict`` whose key-value pairs + are taken from 2-tuples ``(key,value)`` generated by the argument. - - - table with keys of type K and values of type V. - The literal syntax is ``{"A"=>1, "B"=>2}`` for a ``Dict{Any,Any}``, or - ``["A"=>1, "B"=>2]`` for a ``Dict`` of inferred type. + Alternatively, a sequence of pair arguments may be passed: + ``Dict{K,V}("A"=>1, "B"=>2)``. .. function:: haskey(collection, key) -> Bool