The Crystal Programming Language Forum

Calling a macro from another macro

Now that I am learning how to write simple macros, is it possible to call macro B from macro A
with some arguments ?

macro macro_B(arg1,arg2)
  def  example()
    x = {{arg1}}({{arg2}})
  end    
end

macro macro_A(name,arg1,arg2)

  def {{name}} : Array({{arg1}})
    ... some code ...
    # call macro_B
    macro_B arg1, arg2
  end	
end

macro_A "abc", 123, 456
1 Like

Of course. You just need to expand the arguments in the calling macro’s body like with any other call: macro_B {{arg1}}, {{arg2}}

I tried the following at https://play.crystal-lang.org/ (0.32.1)
It seems macro_B is not called but rather the text “macro_B {{arg1}}, {{arg2}}” is echoed.

Note: This is just an example and not valid crystal code.

macro macro_B(arg1,arg2)
  def example()
    x = {{arg1}}({{arg2}})
  end
end
 
macro macro_A(name,arg1,arg2)
 
  def {{name}} : Array({{arg1}})
    x = 1
    # call macro_B
    macro_B {{arg1}}, {{arg2}}
  end
  {{debug}}
end
 
macro_A abc, 123, 456

and the output

def abc : Array(123)
  x = 1
  # call macro_B
  macro_B 123, 456
end

This is correct. Then the block is evaluated again by the macro system and macro_B is going to be expanded ;-)

So basically macro_B is not called and expanded ie one cannot call macros from macros.

That’s correct. There’s no way to call a macro from another macro. You can only have a macro generate code that calls another macro.