Julia: allow @foo{...} macro calls

Created on 24 Jan 2020  Â·  3Comments  Â·  Source: JuliaLang/julia

I noticed that you cannot invoke a macro as @foo{...} — you have to do @foo {...}. Can we remove the requirement of a space before the brace? This would be useful for macros to construct parameterized types, for example.

Background: In a recent discourse discussion, I was looking at implementing a macro @NamedTuple that allows you to write @NamedTuple{raw::Vector{Float64}, value::Int} as a synonym for NamedTuple{(:raw, :value),Tuple{Array{Float64,1},Int64}}, via the implementation:

macro NamedTuple(ex)
    Meta.isexpr(ex, :braces) || error("@NamedTuple expects {...}")
    all(e -> Meta.isexpr(e, :(::)), ex.args) || error("@NamedTuple a sequence of name::type expressions")
    vars = [QuoteNode(e.args[1]) for e in ex.args]
    types = [e.args[2] for e in ex.args]
    return :(NamedTuple{($(vars...),), Tuple{$(types...)}})
end

This works with @NamedTuple {raw::Vector{Float64}, value::Int}, but omitting the space gives

julia> @NamedTuple{raw::Vector{Float64}, value::Int}
ERROR: syntax: invalid macro usage "@(NamedTuple{raw::Vector{Float64}, value::Int})"

Since this is currently a syntax error (that is, parsing fails), supporting it would be non-breaking.

parser speculative

Most helpful comment

:+1: We did this for @m[...], so this totally makes sense.

All 3 comments

:+1: We did this for @m[...], so this totally makes sense.

Looks like this patch should be sufficient:

diff --git a/src/julia-parser.scm b/src/julia-parser.scm
index 5172748c55..7578c1f741 100644
--- a/src/julia-parser.scm
+++ b/src/julia-parser.scm
@@ -2394,6 +2394,10 @@
          `(macrocall ,(macroify-name (cadr call))
                      ,startloc
                      ,@(cddr call)))
+        ((and (pair? call) (eq? (car call) 'curly))
+         `(macrocall ,(macroify-name (cadr call))
+                     ,startloc
+                     (braces ,@(cddr call))))
         ((and (pair? call) (eq? (car call) 'do))
          `(do ,(macroify-call s (cadr call) startloc) ,(caddr call)))
         (else

Haha, I knew this didn't work in <=1.4 so I thought I'd just PR a fix for it directly... but for some reason couldn't find the right place in the source.

Turns out it was fixed already :laughing: Nice!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

m-j-w picture m-j-w  Â·  3Comments

iamed2 picture iamed2  Â·  3Comments

musm picture musm  Â·  3Comments

omus picture omus  Â·  3Comments

StefanKarpinski picture StefanKarpinski  Â·  3Comments