Crystal Lang:在宏中调用宏?

时间:2018-12-03 06:53:54

标签: crystal-lang

我想知道一种在另一个宏中调用宏的方法。

赞:

macro parse(str)
  {{ str.split "/" }}
end

macro do_sth(path)
  {% pathes = parse path %}
  {% for file in pathes %}
    p {{file}}
  {% end %}
end

do_sth "aa/bb/cc"

parse中的代码可能真的很复杂。

示例代码无法使用消息undefined macro method: 'parse'进行编译。

2 个答案:

答案 0 :(得分:1)

正如弗拉德·浮士德(Vlad Faust)所说,这仍然是不可能的。最后,我采用了JonneHaß这样的技巧。

macro macro_return(*vals, &block)
  \{% begin %}
  \{%
  {% for arg, ind in block.args %}
    {{arg}} = {{vals[ind]}}
  {% end %}
  %}
  {{ block.body }}
  \{% end %}
end

macro parse(str, &block)
  macro_return {{ str.split "/" }} {{block}}
end

macro do_sth(path)
  parse({{path}}) do |pathes|
    \{% for a in pathes %}
      p \{{a}}
    \{% end %}
  end
end

do_sth "aa/bb/cc"

希望本机支持。

答案 1 :(得分:0)

It's impossible right now. You should not put a macro call inside another macro. If you really need to extract a compile-time functionality in an outer call, I'd suggest you to experiment with run - it puts the raw output right into the code.