声明列表组成

时间:2015-01-02 23:35:19

标签: metaprogramming nim nimrod

我需要将一个语句列表拆分成多个部分,如下所示:

import macros

macro test: stmt =
    var first = quote do:
        var x = 1
    var second = quote do:
        echo x
    result = newStmtList()
    first.copyChildrenTo(result)
    second.copyChildrenTo(result)

    echo result.repr

test

但是编译器告诉我这个:

[..]

  var x = 1
  echo x
minimalist.nim(14, 0) Info: instantiation from here
minimalist.nim(7, 13) Error: undeclared identifier: 'x'
          echo x

鉴于在节点列表中声明了x,这非常令人困惑。我该如何正常工作? (如果它不明显,我确实需要将AST分成多个部分,原因是其他原因)

2 个答案:

答案 0 :(得分:3)

默认情况下,Nim会对引用块内的代码强制执行宏卫生规则。这意味着在一个块中引入的符号名称在另一个块中不可见。您可以通过为共享符号引入变量来解决这个问题:

import macros

macro test: stmt =
  var x = genSym()

  var first = quote do:
      var `x` = 1

  var second = quote do:
      echo `x`

  result = newStmtList()
  first.copyChildrenTo(result)
  second.copyChildrenTo(result)

test

引言是由应用于非脏模板的getAst操作提供支持。如果您自己使用较低级别的机制,也可以禁用引用的模板的卫生行为,如下所示:

import macros

macro test: stmt =
  template first {.dirty.} =
    var x = 1

  template second {.dirty.} =
    echo x

  result = newStmtList()
  getAst(first()).copyChildrenTo(result)
  getAst(second()).copyChildrenTo(result)

test

这将得到相同的结果。请记住,quote最终将获得一个标志,用于控制引用代码的脏污。

答案 1 :(得分:2)

如果你比较AST,你可以看到出了什么问题:

dumpTree:
  var x = 1
  echo x

打印:

StmtList
  VarSection
    IdentDefs
      Ident !"x"
      Empty
      IntLit 1
  Command
    Ident !"echo"
    Ident !"x"

然后在你的例子中:

macro test: stmt =
    var first = quote do:
        var x = 1
    var second = quote do:
        echo x

    result = newStmtList()
    first.copyChildrenTo(result)
    second.copyChildrenTo(result)

    echo result.treeRepr

test

打印:

StmtList
  VarSection
    IdentDefs
      Sym "x"
      Empty
      IntLit 1
  Command
    Sym "echo"
    Ident !"x"

注意区别?一次" x"是一个标识,另一个是Sym。不应该查找符号,也许这应该在编译器中更改。但是现在你可以帮助自己并再次用Idents替换所有Syms以强制进行新的查找:

import macros

proc symsToIdents(n): PNimrodNode {.compiletime.} =
    if n.kind == nnkSym:
        return newIdentNode($n)

    result = n
    for i in 0 .. <result.len:
      result[i] = symsToIdents(n[i])

macro test: stmt =
    var first = quote do:
        var x = 1
    var second = quote do:
        echo x

    result = newStmtList()
    first.copyChildrenTo(result)
    second.copyChildrenTo(result)
    result = symsToIdents(result)

test

编辑:现在报告为可能的错误:https://github.com/nim-lang/Nim/issues/1843