在宏中扩展符号变量

Expanding symbol variable inside a macro

class Controller
  def index
    puts "hello"
  end
end

macro handler(controller, action)
  c = {{controller}}.new
  c.{{action.id}}
end

# this doesn't work
temp = :index
handler Controller, temp

# this works
handler Controller, :index

不知何故,在第一种情况下,宏被扩展为 c.temp 而不是 c.index

是否可以像上面的代码片段那样在 class 中调用函数。

编辑: 我正在努力实现这样的目标,https://github.com/Amber-Crystal/amber/blob/master/src/amber/dsl/router.cr#L16

temp 是一个运行时变量,而宏是在编译时解释的。这意味着 Crystal 编译器实际上无法知道 temp 的值,因为它只在运行时才知道。在某种程度上可以将变量跟踪到字面值,但使用起来会很昂贵且很脆弱,因为一个小的更改可能会使它变得不可能。

调用宏时,参数是实际的 AST 节点,即已解析源代码的表达式。因此,在您的示例中,宏将 TypeNode as first argument and a Var 作为第二个参数。