calc (antlr版)

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
antlr_calc.GIF

已经公开 2007年6月11日 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值