【问题标题】:Stripping line numbers from Julia AST从 Julia AST 中剥离行号
【发布时间】:2020-09-09 11:33:07
【问题描述】:

我正在使用以下函数从 Julia AST 中删除行号:

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

但是当代码中有宏时,这似乎无法正常工作。这是一个失败的例子:

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

我收到以下错误:

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

处理文档字符串时的另一个例子:

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

产生以下结果:

quote
    Core.@doc module X
        end
end

这个功能有什么问题,我该如何解决?

【问题讨论】:

    标签: recursion julia metaprogramming abstract-syntax-tree


    【解决方案1】:

    只需使用MacroTools 包:

    
    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
    

    【讨论】:

    • 这不适用于嵌套结构。在这种情况下,您需要MacroTools.prewalk(rmlines, expr)MacroTools.striplines(expr)。如果您编辑回复,我将能够将其标记为正确答案。
    • 我应该用第二个例子而不是第一个例子来测试。谢谢!
    【解决方案2】:

    这是一个重复的问题,我已经answered here on SO before: 只需使用Base.remove_linenums!(ex),它应该可以工作(TM)。

    【讨论】:

    • 适用于第一个示例,但不适用于第二个示例。
    • 我不这么认为,因为它在很多情况下都有效,而且不像其他响应使用核心 Julia 函数。
    猜你喜欢
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2016-04-23
    • 2017-04-04
    • 2019-04-08
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    相关资源
    最近更新 更多