Meta.parse failes on double newlines

Why do double newlines throw an error when parsing a string?
I had problems with this when running files using DaemonMode.

julia> Meta.parse("begin end")
quote
    #= none:1 =#
end

julia> Meta.parse("begin end\n")
quote
    #= none:1 =#
end

julia> Meta.parse("begin end\n\n")
ERROR: Base.Meta.ParseError("extra token after end of expression")
Stacktrace:
 [1] parse(::String) at ./meta.jl:215
 [2] top-level scope at REPL[73]:1
 [3] run_repl(::REPL.AbstractREPL, ::Any) at /build/julia/src/julia-1.5.3/usr/share/julia/stdlib/v1.5/REPL/src/REPL.jl:288
1 Like

Meta.parse("...") will only consume one toplevel expression and raise an error if there is anything after the first toplevel expression. You can use Meta.parse("...", 1) to only consume the first expression and get back the parsed expression and the index of the string it stopped parsing at. In Julia 1.6, there is also Meta.parseall, which will parse all toplevel expressions at once. If it’s just about trailing newlines though, you might also just want to remove those beforehand using strip.

4 Likes