How to extract the body of a function?

question

#1

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)"]

#2
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.


#3

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)"]

#4
[string(subex) for subex in ex.args[2].args if subex.head != :line]

#5

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)

#6

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


#7

Tokenize doesn’t really do any parsing though.