2013-05-09 53 views
0

我成功使用StringTemplate 4在Visual Studio中執行一些代碼生成。我已經安裝了StringTemplate和ANTLR的擴展,它們非常棒。StringTemplate與StringTemplateGroup

在測試中,我可以弄清楚如何使用* .st4(StringTemplate)文件,但如何使用* .stg(StringTemplateGroup)文件轉義我。它是可以嵌入到另一個StringTemplate中的定義的集合嗎?如果是這樣,代碼看起來像從* .stg而不是* .st4生成的代碼是什麼樣的?

回答

5

StringTemplate組文件是存儲在單個文件中的模板的集合。 GitHub上的ANTLR項目包含很多示例;例如​​其中包含ANTLR 4.

你可以找到幾個例子中從StringTemplate的C#項目本身的StringTemplateTests.cs文件在C#中使用StringTemplate的3全部爲Java對象的代碼生成模板。這不是最友好的文檔,但它確實包含涵蓋各種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()); 

所以它更容易閱讀,模板組文件代碼到測試看起來像這樣沒有轉義字符。

group dork; 

test(name) ::= <<<(name)()> 
>> 
first() ::= "the first" 
second() ::= "the second" 
+0

太棒了,非常感謝你Sam。 ANTLR4和ST4只是令人驚歎的工作 - 我對ANTLR4上的「它只是起作用」的說法持懷疑態度,但錯誤恢復是不可思議的。再次感謝,保持良好的工作。 – 2013-05-10 06:36:50

+0

PS,我沒有足夠的代表upvote,但如果我可以:( – 2013-05-10 06:37:32

1

我會在這裏回答我自己的問題,以補充Sam所提出的問題。我認爲我的困惑是ST3和ST4之間在命名約定和方法調用約定方面的巨大差異。下面是什麼山姆豎起來,用ST4

var sr = new StreamReader("dork.stg"); 
var txt = sr.ReadToEnd(); 
sr.Close(); 
TemplateGroup group = new TemplateGroupString(txt); 
var f = group.GetInstanceOf("test"); 
f.Add("name", "first"); 

// writes out "the first" 
Console.WriteLine(f.Render()); 

請讓我知道如果我錯過了什麼,山姆翻譯。謝謝。