Source code of a function


#1

Hello,

Is it possible to recover the source code of a function as a string?
For example,

f(x,y) = 2sin(x+y)+1

Is there a function call on f that can get me s="2sin(x+y)+1"?

Thanks!


#2

If you do

@which f(x,y)

it will print the file and line number where the function was defined (or it will tell you it was done in the REPL). Try, for example @which sin(π).


#3

In the REPL you could also try

@less f(x,y)

which wraps the call to the pager on the result from @which


#4

For reference, the source expression is available using the following:

Base.uncompressed_ast(methods(f).ms[1]).code

But right now it is necessary to go to the original code to get the unparsed version, as suggested above. It’s on the roadmap for 1.0; see this issue and others cross-referenced there.


#5

Take a look at Sugar.jl, specifically to its macro_form() function. It first tries to find and parse function’s source, and only if it’s unavailable, falls back to parsing AST. macro_form often fails for functions generated using @eval (since source code includes interpolated values from the context) and may produce somewhat different results for functions defined in REPL, but in general I found this function extremely helpful.


#6

Thanks! That’s exactly what I was looking for.

In particular, these lines did it:

using Sugar
method = Sugar.get_method(f, types)
code, str = Sugar.get_source(method)

#7

It took me some time to realize that types is supposed to be a tuple.
So, if you want to get the source of a method with the type Vector{Float64} you need to write :
method = Sugar.get_method(f, (Vector{Float64),))


#8

well, the Gallium debugger seems to be capable of showing the source, either in a file or if entered from the REPL. how does it do it?

and, more importantly, in 1.0, what is the syntax that I should use to view the method source for function f?

regards,

/iaw


#9

The rcnlee procedure with Sugar.jl works just fine…


#10

IIRC Gallium reparses the source.