컴퓨터 공학

컴파일러 - javacc로 계산기 만들기(소스)

혼새미로 2015. 11. 27. 02:20
반응형

options {

STATIC = false;

}


PARSER_BEGIN(Calculator)

import java.io.PrintStream;


class Calculator{

static public void main(String[] args) throws ParseException, TokenMgrError,NumberFormatException{

Calculator parser=new Calculator(System.in);

parser.Start(System.out);

}

double previousValue=0.0;

}

PARSER_END(Calculator)


SKIP : {" "}

TOKEN : { < EOL : "\n" | "\r" | "\r\n" > }

TOKEN : { < PLUS : "+" > }

TOKEN : { < MINUS : "-" > }

TOKEN : { < TIMES : "*" > }

TOKEN : { < DIVIDE : "/" > }

TOKEN : { < NUMBER : (["0"-"9"])+ | (["0"-"9"])+ | (["0"-"9"])+ "." | "." (["0"-"9"])+ > }

TOKEN : { < #DIGITS : (["0"-"9"])+ > }


void Start(PrintStream printStream) throws NumberFormatException :

{}

{

(

previousValue = Expression()

<EOL>

{printStream.println(previousValue);}

)*

<EOF>

}


double Expression() throws NumberFormatException :

{

double i;

double value;

}

{

value=Term()

(

<PLUS>

i=Term()

{value += i;}

|

<MINUS>

i = Term()

{ value -= i;}

)*

{return value;}

}


double Term() throws NumberFormatException :

{

double i;

double value;

}

{

value = Primary()

(

<TIMES>

i=Primary()

{value *= i;}

|

<DIVIDE>

i=Primary()

{value /=i;}

)*

{return value;}

}


double Primary() throws NumberFormatException :

{

Token t;

}

{

t=<NUMBER>

{return Double.parseDouble(t.image);}

}

반응형