Calculator using ANTLR

Skip to end of metadata
Go to start of metadata

In this exercise, your goal is to learn how to embed actions within a grammar. You are to build a simple calculator with *, /, +, - operators as well as the unary negation operator -. Further, the calculator has a simple global memory where we can associate values to names. The input is a sequence of commands and there are two commands: assignment and print statements. For example, here is a valid program:

Note: ANTLR will buffer up all of the input and then print results all at once after you hit the end of file key. The results should look like:

Treat all numbers as floating point but accept simple int literals like the above.

The first thing to do is build a grammar that recognizes such input while properly handling operator precedence. * and / have higher precedence than + and -. unary - is higher precedence than any other operator though. for example, -x+2*3 does the -x first, then the multiplication, and then the addition. Allow parentheses in their usual positions. Only print output upon the print command.

You should put the main() directly in the @members section of your grammar (Calc.g) for convenience:

Store variables in a single HashMap that maps identifier names to float values. We will only deal with floating-point numbers. Skip whitespace. There is no comment syntax. identifiers are 'a'..'z'+.

Most of your rules will return an integer value like this:

That way, rules that reference other rules can reference their return values to build up the result. for example, to print out a value, use this action: System.out.println($expr.v);.

Submission

You will create a jar file called calc.jar containing source and *.class files and place in your build directory:

https://www/svn/userid/cs652/calc/build/calc.jar

I will run your code by executing the following:

$java -cp "calc.jar:$CLASSPATH" CalcParser < Sample-calculator-input

You can use the svn account for development of the software too if you would like, but I will only be looking at your jar file in the build directory.

For more information, see svn in CS601. Naturally you will have to substitute cs652 for cs601.

Labels: