Macro: no method matching size

Would you help me with Macros

Why macros does not see functions: size() or length()?

Julia ver 1.1.1

macro test_macro(e::Expr)
	return (ones(size(e)[1]) .+ e)
end

MethodError: no method matching size(::Expr)
Closest candidates are:
  size(!Matched::BitArray{1}) at bitarray.jl:77
  size(!Matched::BitArray{1}, !Matched::Any) at bitarray.jl:81
  size(!Matched::Core.Compiler.StmtRange) at show.jl:1561
  ...

Stacktrace:
 [1] @test_macro(::LineNumberNode, ::Module, ::Expr) at ./In[96]:4774:

Julia ver 1.3 error

LoadError: MethodError: no method matching size(::Expr)
Closest candidates are:
  size(!Matched::BitArray{1}) at bitarray.jl:77
  size(!Matched::BitArray{1}, !Matched::Integer) at bitarray.jl:81
  size(!Matched::Core.Compiler.StmtRange) at show.jl:1598
  ...
in expression starting at G:\My Drive\Booth\Political_firms\Programs\Jl\TopicModeling_v1.jl:127
@test_macro3(::LineNumberNode, ::Module, ::Expr) at TopicModeling_v1.jl:133

Macros operate on expressions, not values. That is, they input and output Julia code. So you can’t check the size of e or add e to anything, because e is an expression, not an array. What you can do instead is this:

macro test_macro2(e::Expr)
	return esc( :( ones(size($e)[1]) .+ $e) )
end

Then @test_macro2 [a,b,c] will return the expression ones(size([a,b,c][1]) .+ [a,b,c] which is then evaluated outside the macro. Contrast this with

function test_func(a::Array)
	return (ones(size(a)[1]) .+ a)
end

Then when you write test_func([a,b,c]), [a,b,c] is evaluated first, and the resulting array is bound to a inside test_func, which uses it to construct a new array.

3 Likes

Thank you so much