Stripping line numbers from Julia AST

Viewed 220

I am using the following function to strip the line numbers from Julia ASTs:

function filter_lineno(ex::Expr)
           filter!(ex.args) do e
               isa(e, LineNumberNode) && return false
               if isa(e, Expr)
                   (e::Expr).head === :line && return false
                   filter_lineno(e::Expr)
               end
               return true
           end
           return ex
       end

But this doesn't seem to work properly when there are macros in the code. Here is a failing example:

expr = Meta.parse("begin run(``) end")
filter_lineno(expr)

I get the following error:

BoundsError: attempt to access 2-element Array{Any,1} at index [3]

Another example when processing docstrings:

expr = Meta.parse("begin \"Here is the doc\"\nmodule X end end")
filter_lineno(expr)

Yields the following:

quote
    Core.@doc module X
        end
end

What is wrong with this function, and how can I fix it?

2 Answers

Just use the MacroTools package:


julia> using MacroTools

julia> cc = Meta.parse("begin \"Here is the doc\"\nmodule X end end")
quote
    #= none:1 =#
    #= none:1 =# Core.@doc "Here is the doc" module X
        #= none:2 =#
        #= none:2 =#
        end
end

julia> MacroTools.striplines(cc)
quote
    Core.@doc "Here is the doc" module X
        end
end

This is a duplicate question, which I've answered here on SO before: Just use Base.remove_linenums!(ex) and it should work (TM).

Related