简体   繁体   中英

How to use string template

I am trying to use ANTLR to create understand how grammar works. I have started playing with ANTLR and created a simple addition program. 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". But what I am trying to do is to generate below C# code for input "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#. 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.

Add Package StringTemplate4 from nuget:

 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:

A template for sum (a,b):

a= 5

b= 6

Sum = 11

you can find a detailed documentation in using StringTemplat4 in project site :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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