FluxML / MacroTools.jl

MacroTools provides a library of tools for working with Julia code and expressions.
https://fluxml.ai/MacroTools.jl/stable/
Other
310 stars 79 forks source link

sourcewalk introduces blocks #123

Open oxinabox opened 5 years ago

oxinabox commented 5 years ago

MWE:

using MacroTools
using MacroTools: textwalk

code = """
Rule(x -> -sin(x))
Rule(x -> 1 + tan(x)^2)
""";

after = textwalk(code) do expr
    @capture(expr, Rule(v_)) && return v
    return expr
end

println(after)

Output:

(x->begin
        -(sin(x))
    end)
(x->begin
        1 + tan(x) ^ 2
    end)
oxinabox commented 5 years ago

Workaround:

 textwalk(code) do expr
    @capture(expr, Rule(v_)) && return MacroTools.postwalk(MacroTools.unblock, v)
    return expr
end

Though that still changes spacing, and adds extra backets arround sin(x) and arraound the whole expression

Output

(x->-(sin(x)))
(x->1 + tan(x) ^ 2)
MikeInnes commented 5 years ago

This is unfortunately due to Base's default parsing/printing of lambdas:

julia> :(x->1)
:(x->begin
          #= REPL[1]:1 =#
          1
      end)

Would be great to fix, but unfortunately might require a fork of the Expr printing code (though there are likely several reasons to do this).

MikeInnes commented 5 years ago

Alternatively, since Expr(:->, :x, 1) seems to do the right thing, maybe we can just tweak CSTParser to not insert the block / line number.