StringTemplate与StringTemplateGroup

Bru*_*son 1 c# antlr stringtemplate visual-studio

我成功使用StringTemplate 4在Visual Studio中进行代码生成.我已经安装了StringTemplate和ANTLR的扩展,它们非常棒.

在测试中,我可以弄清楚如何使用*.st4(StringTemplate)文件,但是如何使用*.stg(StringTemplateGroup)文件逃避了我.它是可以嵌入到另一个StringTemplate中的定义集合吗?如果是这样,那么从*.stg而不是*.st4生成的代码是什么样的?

Sam*_*ell 6

StringTemplate组文件是存储在单个文件中的模板集合.GitHub上的ANTLR项目包含很多例子; 例如,Java.stg包含ANTLR 4的Java目标的所有代码生成模板.

您可以在StringTemplate C#项目本身的StringTemplateTests.cs文件中找到几个在C#中使用StringTemplate 3的示例.它不是最友好的文档,但它确实包含了涵盖各种ST3功能的示例.以下是一个使用示例StringTemplateGroup:

string templates =
        "group dork;" + newline +
        "" + newline +
        "test(name) ::= <<" +
        "<(name)()>" + newline +
        ">>" + newline +
        "first() ::= \"the first\"" + newline +
        "second() ::= \"the second\"" + newline
        ;
StringTemplateGroup group =
        new StringTemplateGroup( new StringReader( templates ) );
StringTemplate f = group.GetInstanceOf( "test" );
f.SetAttribute( "name", "first" );
string expecting = "the first";
Assert.AreEqual( expecting, f.ToString() );
Run Code Online (Sandbox Code Playgroud)

所以它更容易阅读,模板组文件代码进入该测试看起来像没有转义字符.

group dork;

test(name) ::= <<<(name)()>
>>
first() ::= "the first"
second() ::= "the second"
Run Code Online (Sandbox Code Playgroud)