简体   繁体   English

如何使用字符串模板

[英]How to use string template

I am trying to use ANTLR to create understand how grammar works.我正在尝试使用 ANTLR 来理解语法的工作原理。 I have started playing with ANTLR and created a simple addition program.我已经开始使用 ANTLR 并创建了一个简单的加法程序。 Below is my simple grammar.下面是我的简单语法。

grammar addition;
expr: NUMBER PLUS NUMBER;
NUMBER: [0-9]+
PLUS: '+';
SPACE
  :  ' ' {skip();};

This grammar works perfect for input like "1+1".这种语法非常适合像“1+1”这样的输入。 But what I am trying to do is to generate below C# code for input "1+1":但我想要做的是在 C# 代码下方生成输入“1+1”:

var a = 1;
var b = 1;
Console.WriteLine(1+1);

When I researched, I found that I can use string templates with ANTLR C#.当我研究时,我发现我可以将字符串模板与 ANTLR C# 一起使用。 I tried exploring them but didn't find much help.我尝试探索它们,但没有找到太多帮助。 The documentation is a little hard to understand.文档有点难以理解。 Can somebody please tell me or provide some study references through which I will be able to know how to use string templates with ANTLR.有人可以告诉我或提供一些学习参考资料,通过这些参考资料我将能够知道如何在 ANTLR 中使用字符串模板。

Add Package StringTemplate4 from nuget:从 nuget 添加 Package StringTemplate4:

 Install-Package StringTemplate4 -Version 4.0.8

A Minimal example:一个最小的例子:

public string SumNumbers()
        {
        //Create string template and enclose variables between <..>
            var template = @"
A template for sum (a,b):

a= <a>
b= <b>
Sum = <sum>  
";
          //Instantiate Template class  
            var strTemplate = new Template(template);
            int a = 5;
            int b = 6;
            var sum = a + b;
            
            //define variables used by template 
            strTemplate.Add("a", a);
            strTemplate.Add("b", b);
            strTemplate.Add("sum", sum);
            //render the template
            return strTemplate.Render();
        }

output: output:

A template for sum (a,b): sum (a,b) 的模板:

a= 5 a= 5

b= 6 b = 6

Sum = 11总和 = 11

you can find a detailed documentation in using StringTemplat4 in project site :您可以在项目站点中找到使用 StringTemplat4 的详细文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM