How to extract the body of a function?

I need to parse functions and extract the
function body. How can I achieve this with
the parser or by other means?

For example given the text of the function

function fun(n::Int)
	s = 2 * n
	println(s)
end

the result should by the list of strings

["s = 2 * n", "println(s)"]
julia> parse("""
 function fun(n::Int)
   s = 2 * n
   println(s)
 end
""")

The result shall be an expression (defined in the Metaprogramming section of the manual). See also JuliaParser.

2 Likes

It’s nice to get something like

(:function, (:call, :fun, (:(::), :n, :Int)), 
(:block,
    (:line, 2, :none),
    (:(=), :s, (:call, :*, 2, :n)),
    (:line, 3, :none),
    (:call, :println, :s)
  ))

but how can I proceed from this back to the required form

["s = 2 * n", "println(s)"]
[string(subex) for subex in ex.args[2].args if subex.head != :line]
2 Likes

Now that’s brilliant! Thanks!
For other beginners here the full solution:

using JuliaParser
src = """
 function fun(n::Int)
   s = 2 * n
   println(s)
 end
"""
ast = Parser.parse(src);
Meta.show_sexpr(ast)
funbody = [string(subex) for subex in ast.args[2].args if subex.head != :line]
print(funbody)

Here is another option: https://github.com/KristofferC/Tokenize.jl

Tokenize doesn’t really do any parsing though.