Parsing a Julia file

How can I parse a .jl file into a Vector{Expr}, similar to what include does (but without executing of course). I expected Meta.parse to accept an IO, but it doesn’t.

1 Like

Not sure if this is the best way, but I have personally used

parsefile(file) = parse(join(["quote", readstring(file), "end"], ";"))

If you take the .args[1].args, you have a Vector{Expr} of everything.

1 Like

Thanks, that’s a good solution. I ended up with

parsecode(code::String)::Vector =
    # https://discourse.julialang.org/t/parsing-a-julia-file/32622
    filter(x->!(x isa LineNumberNode),
           Meta.parse(join(["quote", code, "end"], ";")).args[1].args)

One drawback of this approach is that it looses all location information from the file. E.g. line-numbers and filename. Is there a way to keep that information?

1 Like