前言
//demo.stg decl(type, name, value) ::= " ;" init(v) ::= " = "
decl(type, name, value)、init(v)为模板名和模板参数,为条件表达式(conditions),其它<...>为占位符。
STGroup group = new STGroupFile("demo.stg");//绝对路径 ST st = group.getInstanceOf("decl");//获取模板实例 st.add("type", "int");//填充占位符 st.add("name", "x"); st.add("value", 0); String result = st.render();//模板输出
语法 | 说明 |
%foo(a={}, b={},...) | 模板构建语法:创建模板foo,设置其属性a、b... |
%({<<nameExpr>>}(a={}...)) | 间接模板构造引用,nameExpr是计算出的模板名称,其他部分与模板构造语法相同 |
%x.y=<<z>> | 将模板x的属性y赋值为值z |
%{<<expr>>}.y=<<z>> | 将StringTemplate类型表达式expr的属性赋值为表达式z的值 |
%{<<stringExpr>>} | 从String类型stringExpr创建匿名模板 |
3+4*5
output:
; public class Calc extends Object { ...} .class public Calc .super java/lang/Object ; public Calc() { super(); } // calls java.lang.Object() .method public ()V aload_0 invokenonvirtual java/lang/Object/()V return .end method ; main(): Expr.g will generate bytecode in this method .method public static main([Ljava/lang/String;)V .limit stack 4 ; how much stack space do we need? .limit locals 1 ; how many locals do we need? getstatic java/lang/System/out Ljava/io/PrintStream; ; code translated from input stream ; compute 3+4*5 ldc 3 ldc 4 ldc 5 imul iadd ; print result on top of stack invokevirtual java/io/PrintStream/println(I)V return .end method
int x; void foo(){ int y; y = 1; g(34, y); x = h(); }
int x; void foo(){ int y; y = 1; write_to("y", y) g(34, y); call("g"); x = eval_r("h", h()); write_to("x", x) }
grammar Expr; options{output=AST;ASTLabelType=CommonTree;} @header{ package template; import java.util.HashMap; } @members { int numOps = 0;//operation count HashMap locals = new HashMap();//local variable name-count map int localVarNum = 1;//local variable count } prog : stat+; stat : expr NEWLINE -> expr | ID '=' expr NEWLINE { if(locals.get($ID.text)==null){ locals.put($ID.text, new Integer(localVarNum++)); } } -> ^('=' ID expr) | NEWLINE -> ; expr : multExpr ('+'^|'-'^) multExpr {numOps++;} ; multExpr: atom ('*'^ atom {numOps++;})* ; atom : INT | ID | '('! expr ')'!; ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ; INT : '0'..'9'+; WS : ( ' '| '\t'| '\r'| '\n') {$channel=HIDDEN;} ; NEWLINE : '\r'?'\n';
tree grammar Gen; options { tokenVocab=Expr; ASTLabelType=CommonTree; output=template; } @header { package template; import java.util.HashMap; } @members { HashMap locals; } prog[int numOps, HashMap locals] @init {this.locals= locals;} : (s+=stat)+ -> jasminFile(instructions={$s}, maxStackDepth={numOps+1+1}, maxLocals={locals.size()+1}) ; stat : expr -> exprStat(v={$expr.st}, descr={$expr.text}) | ^('=' ID expr) -> assign(id={$ID.text}, descr={$text}, varNum={locals.get($ID.text)}, v={$expr.st}) ; expr returns [int value] : ^('+' a=expr b=expr) -> add(a={$a.st}, b={$b.st}) | ^('-' a=expr b=expr) -> sub(a={$a.st}, b={$b.st}) | ^('*' a=expr b=expr) -> mult(a={$a.st}, b={$b.st}) | INT -> int(v={$INT.text}) | ID -> var(id={$ID.text}, varNum={locals.get($ID.text)}) ;
group ByteCode; jasminFile(maxStackDepth, maxLocals, instructions) ::= << ; public class Calc extends Object { ...} .class public Calc .super java/lang/Object ; public Calc() { super(); } // calls java.lang.Object() .method public \()V aload_0 invokenonvirtual java/lang/Object/\()V return .end method ; main(): Expr.g will generate bytecode in this method .method public static main([Ljava/lang/String;)V .limit stack ; how much stack space do we need? .limit locals ; how many locals do we need? getstatic java/lang/System/out Ljava/io/PrintStream; ; code translated from input stream ; print result on top of stack invokevirtual java/io/PrintStream/println(I)V return .end method >> assign(varNum, v ,descr, id) ::= << ;compute descr istore : id >> exprStat(v, descr) ::= << ; compute >> add(a, b) ::= << iadd >> sub(a, b) ::= << isub >> mult(a, b) ::= << imul >> int(v) ::= "ldc " var(id, varNum) ::= "iload ; "
package template; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.InputStream; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.CommonTreeNodeStream; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateGroup; public class ByteCodeGeneratorTest { public static void main(String[] args) throws Exception { FileReader groupFileReader = new FileReader("D:/workspace/maven/antlrv3/grammar/template/generator/ByteCode.stg"); StringTemplateGroup templateGroup = new StringTemplateGroup(groupFileReader); groupFileReader.close(); // [1]3+4*5 // [2]a=3+4 // a InputStream is = new FileInputStream(new File("D:/workspace/maven/antlrv3/language/template.test")); ANTLRInputStream inputStream = new ANTLRInputStream(is); ExprLexer lexer = new ExprLexer(inputStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); ExprParser parser = new ExprParser(tokenStream); ExprParser.prog_return r = parser.prog(); // tree walker to generate template's value CommonTree tree = (CommonTree) r.getTree(); CommonTreeNodeStream treeNodeStream = new CommonTreeNodeStream(tree); treeNodeStream.setTokenStream(tokenStream); Gen walker = new Gen(treeNodeStream); walker.setTemplateLib(templateGroup); Gen.prog_return r2 = walker.prog(parser.numOps, parser.locals); StringTemplate output = (StringTemplate) r2.getTemplate(); System.out.println(output.toString()); } }
grammar CMinus; options{output=template;rewrite=true;} program : declaration+; declaration : variable | function ; variable: type ID';'; function: type ID '(' (formalParameter (',' formalParameter)* )? ')' block; formalParameter : type ID; type : 'int'|'void'; stat scope{boolean isAssign;} : expr ';' | block | ID '=' {$stat::isAssign=true;} expr ';' -> template(id={$ID.text}, assign={$text}) " write_to(\"\", )" | ';' ; block : '{' variable* stat* '}'; expr : ID | INT | ID '(' (expr (',' expr)* )? ')' -> {$stat::isAssign}? template(id={$ID.text}, e={$text}) "eval_r(\"\", )" ->template(id={$ID.text}, e={$text}) "; call(\"\")" | '(' expr ')' ; ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ; INT : '0'..'9'+ ; COMMENT : '' {$channel=HIDDEN;} ; WS : ( ' '| '\t'| '\r'| '\n') {$channel=HIDDEN;};
package template.rewriter; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.TokenRewriteStream; public class Test { public static void main(String[] args) throws Exception { InputStream is = new FileInputStream(new File("D:/workspace/maven/antlrv3/language/rewriter/CMinus.test")); ANTLRInputStream input = new ANTLRInputStream(is); CMinusLexer lexer = new CMinusLexer(input); TokenRewriteStream tokens = new TokenRewriteStream(lexer); CMinusParser parser = new CMinusParser(tokens); parser.program(); System.out.println(tokens.toString()); } }