How do I fix a StringTempate4 error: context passed 2 args to template with 1 declared arg

StackOverflow https://stackoverflow.com/questions/21947638

  •  14-10-2022
  •  | 
  •  

Here is a modified test from StringTemplate4, it gives me an error:

#!/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())

This is the error:

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)

It seems that "v" is expanded somewhere but it is not clear to me how, so I don't understand the error. What is the right way to write this code?

有帮助吗?

解决方案

This looks like an incorrect use of the map operator, because each item in variables is a single instance of Decl. You don't need to map v to decl, you just need to invoke decl, as follows.

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

However, since you are using addAggr instead of just add, you also need to pass the correct property.

<variables:{ v | <decl(v.decl)>}; separator="\n">
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top