Yes, it was always the intention to expand base/meta.jl once we had an idea
what more should go into it. I did an initial commit with what I felt was
the absolutely most essential tools for metaprogramming, plus show_sexpr
which is at least incredibly useful. So anyone who has code that they keep
reusing for metaprogramming, please submit a pull request against meta.jl,
and we can take the discussion from there. I think that we should put some
effort into making what we put there simple and consistent, though, so it
might take some iterations.
Regarding the function ASTs, I keep reusing split_fdef, given by
macro expect(pred)
quote
$(esc(pred)) ? nothing : error(
$(string("expected: ", sprint(Base.show_unquoted, pred)", == true"
)))
end
end
function is_fdef(ex::Expr)
isexpr(ex,:function,2) || (isexpr(ex,:(=),2)&&isexpr(ex.args[1],:call))
end
is_fdef(ex) = false
# Return the signature and body from a named method definition, either
syntax.
# E.g. split_fdef( :( f(x) = x^2) ) == (:(f(x)), :(x^2))
function split_fdef(fdef::Expr)
@expect (fdef.head == :function) || (fdef.head == :(=))
@expect length(fdef.args) == 2
signature, body = fdef.args
@expect isexpr(signature, :call)
@expect length(signature.args) >= 1
(signature, body)
end
split_fdef(f::Any) = error("split_fdef: expected function definition,
got\n$f")
That only goes for named method definitions, though.
To answer the more general question, yes, macro writing definitely has some
tricky corners, especially when start to take apart existing ASTs, and not
just putting together new ones from some given pieces. I don't believe that
there is any official documentation for the AST format; what I know I have
from hard-earned experience. Also, the format as been known to change
without notice a few times when new syntax was added. I'm not sure that the
AST format can be considered a public interface at this point.
That said, it is often extremely rewarding and powerful to work with, and
there is a limited number of corners that you run into. So with some more
effort to work out the basic metaprogramming tools, and perhaps a little
pressure to streamline the AST format in some extreme cases and to consider
it part of the user interface, I think that metaprogramming can be made
more straightforward.
On Thursday, 30 January 2014 16:51:32 UTC+1, Tim Holy wrote:
>
> There are some similar facilities in base/cartesian.jl and IProfile.jl.
> Seems
> like it might be time to centralize some of this. Perhaps we should expand
> base/meta.jl?
>
> Best,
> --Tim
>
>