PLC Laboratory 9
Contents
Compiler of Arithmetic Expressions Using ANTLR
Extend the interpreter of arithmetic expressions from previous Laboratory 7. In this laboratory, instead of interpreating expressions, generate a stack-based target code defining the computation.
The language description is still valid. Expressions contain +, -, *, / operators (with common priorities and left associativity) and parentheses. To simplify the task, consider we have only binary operators. There are no unary operators in our language. We will use only integer numbers.
The target stack-based code will constist of following instructions:
ADD, SUB, MUL, DIV
- it takes two values from the stack, computes the apropriate value and stores the result on stack.PUSH n
- it stores the valuen
on stack.PRINT
- it takes a value from stack and prints it on output.
Input specification
In the input, there are expressions, they are written in formatting. Each expression ends with semicolon. Numbers can be written similarly to C language constants. it can be either: decimal , octal (starting with zero) or hexadecimal (starting with characters 0x) number.
Output specification
For each expression write the instructions (one per line) that once performed, computes the resulting value for the expression. If there is any error in the input, you can stop the computation.
Example
- Input
9-10; 2 * (3+4);
5;
- Output
PUSH 9
PUSH 10
SUB
PRINT
PUSH 2
PUSH 3
PUSH 4
ADD
MUL
PRINT
PUSH 5
PRINT