JuliaLang / JuliaSyntax.jl

The Julia compiler frontend
Other
272 stars 35 forks source link

Feature request: `do` with infix calls #414

Closed MasonProtter closed 2 months ago

MasonProtter commented 7 months ago

I was disapointed today to learn that I can't write the following macro:

@forall x in y do a, b
    ...
end

because (x in y) do is a syntax error, one can only write in(x, y) do. Is this something reasonable to allow?

savq commented 7 months ago

You can do

@forall(x in y) do a, b
    # ...
end
c42f commented 2 months ago

Note that, in a bizarre twist of syntax, this form of @forall will make the do block visible to the macro call! (It's kind of bizarre. But also a good analogy to function calls with do syntax so it also makes sense.)

I think that's good enough for this use case?

Demo:

julia> macro forall(exs...)
           dump(exs)
           nothing
       end
@forall (macro with 6 methods)

julia> @forall(x in y) do a
       end
Tuple{Expr, Expr}
  1: Expr
    head: Symbol ->
    args: Array{Any}((2,))
      1: Expr
        head: Symbol tuple
        args: Array{Any}((1,))
          1: Symbol a
      2: Expr
        head: Symbol block
        args: Array{Any}((1,))
          1: LineNumberNode
            line: Int64 1
            file: Symbol REPL[15]
  2: Expr
    head: Symbol call
    args: Array{Any}((3,))
      1: Symbol in
      2: Symbol x
      3: Symbol y

See also the SyntaxNode AST which makes it clear that the macro will receive the do

julia> parsestmt(SyntaxNode, """
       @forall(x in y) do a
       end
       """)
line:col│ tree                                   │ file_name
   1:1  │[macrocall-p]
   1:2  │  @forall
   1:9  │  [call-i]
   1:9  │    x
   1:11 │    in
   1:14 │    y
   1:16 │  [do]
   1:19 │    [tuple]
   1:20 │      a
   1:21 │    [block]
MasonProtter commented 2 months ago

yeah, my hope was to try and do it without the parens, but oh well.