Antlr Eclipse插件 [install] http://antlreclipse.sourceforge.net/updates/
^--root !--不加入AST
Lexer-->Parser--(AST)-->TreeParser(Walk)
calc.g
header{
package com.antlr.calc;
}
class ExprParser extends Parser;
options{
buildAST=true;
}
expr: mexpr((PLUS^|MINUS^)mexpr)*;
mexpr: atom((MULTI^|DIV^)atom)*;
atom:
NUMBER
|
LPAREN! expr RPAREN!
;
class ExprTreeParser extends TreeParser;
node returns [float v=0]
{
float a,b;
}
: #(PLUS a=node b=node){v=a+b;}
| #(MINUS a=node b=node){v=a-b;}
| #(MULTI a=node b=node){v=a*b;}
| #(DIV a=node b=node){v=a/b;}
| i:NUMBER {v=Float.parseFloat(i.getText());}
;
class ExprLexer extends Lexer;
options{
k=2;
charVocabulary='/u0000'..'/u007F';//ascii
}
{
}
LPAREN: '(' ;
RPAREN: ')' ;
PLUS : '+' ;
MINUS : '-' ;
MULTI : '*' ;
DIV : '/' ;
NUMBER: ('0'..'9')+('.'('0'..'9')+)?;
WS : ( ' '
| '/r' '/n'
| '/n'
| '/t'
)
{$setType(Token.SKIP);}
;
Calc.java
package com.antlr.calc;
import java.io.ByteArrayInputStream;
import antlr.collections.AST;
import antlr.debug.misc.ASTFrame;
public class Calc {
public static void main(String[] args) throws Exception {
String s;
s="1.5+1+3*4/5";
ByteArrayInputStream bs=new ByteArrayInputStream(s.getBytes());
ExprLexer lexer = new ExprLexer(bs);
ExprParser parser = new ExprParser(lexer);
parser.expr();
AST ast=parser.getAST();
System.out.println(ast.toStringTree());
ExprTreeParser treeParser = new ExprTreeParser();
float x = treeParser.node(ast);
System.out.println(x);
ASTFrame frame = new ASTFrame("AST JTree Example", ast);
frame.setVisible(true);
}
}
out
( + ( + 1.5 1 ) ( / ( * 3 4 ) 5 ) )
4.9