2014-02-22 13 views
1

這裏是StringTemplate4修改測試1到模板,它給了我一個錯誤:如何解決一個StringTempate4錯誤:環境傳送2個ARGS與申報ARG

#!/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」擴展到某個地方,但我不清楚如何,所以我不明白這個錯誤。什麼是寫這個代碼的正確方法?

回答

0

這看起來像是對地圖運算符的錯誤使用,因爲variables中的每個項目都是Decl的單個實例。您不需要將v映射到decl,您只需調用decl,如下所示。

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

然而,由於使用的是addAggr,而不是僅僅add,你還需要通過正確的屬性。

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