1

这是来自 StringTemplate4 的修改后的测试,它给了我一个错误:

#!/usr/bin/env groovy

@Grab(group="org.antlr", module="ST4", version="4.0.7")
import org.stringtemplate.v4.ST
import org.stringtemplate.v4.STGroup
import org.stringtemplate.v4.STGroupString

class Decl {
  def name
  def type
  Decl(name, type) {
    this.name = name
    this.type = type
  }
}
String templates =
  "file(variables) ::= <<\n" +
  "<variables:{ v | <v:decl(v)>}; separator=\"\\n\">\n"+
  ">>\n"+
  "decl(v) ::= \"<v.type> <v.name> = 0;\"";
STGroup group = new STGroupString(templates);
ST f = group.getInstanceOf("file");
f.addAggr("variables.{decl}", ["a", "int"] as Decl);
f.addAggr("variables.{decl}", ["b", "int"] as Decl);
println(f.render())

这是错误:

context [/file /_sub1] 1:20 passed 2 arg(s) to template /decl with 1 declared arg(s)
context [/file /_sub1] 1:20 passed 2 arg(s) to template /decl with 1 declared arg(s)

似乎“v”在某处扩展但我不清楚如何扩展,所以我不明白这个错误。编写此代码的正确方法是什么?

4

1 回答 1

0

这看起来像是对 map 运算符的错误使用,因为其中的每个项目variables都是Decl. 不需要映射vdecl,只需要调用decl,如下。

<variables:{ v | <decl(v)>}; separator="\n">

但是,由于您使用addAggr而不是 just add,因此您还需要传递正确的属性。

<variables:{ v | <decl(v.decl)>}; separator="\n">
于 2014-02-22T14:01:19.643 回答