Compilers-PA1
Introduction
This assignment asks you to write a short Cool program. The purpose is to acquaint you with the Cool language and to give you experience with some of the tools used in the course.A machine with only a single stack for storage is a stack machine. Consider the following very primitive language for programming a stack machine:
Command | Meaning |
---|---|
int | push the integer int on the stack |
+ | push a ‘+’ on the stack |
s | push an ‘s’ on the stack |
e | evaluate the top of the stack (see below) |
d | display contents of the stack |
x | stop |
The ‘d’ command simply prints out the contents of the stack, one element per line, beginning with the top of the stack. The behavior of the ‘e’ command depends on the contents of the stack when ‘e’ is issued:
• If ‘+’ is on the top of the stack, then the ‘+’ is popped off the stack, the following two integers are popped and added, and the result is pushed back on the stack.
• If ‘s’ is on top of the stack, then the ‘s’ is popped and the following two items are swapped on the stack.
• If an integer is on top of the stack or the stack is empty, the stack is left unchanged.
Some tips about COOL-lang
First of all, it’s crucial to thoroughly read Sections 6 to 10 of the Cool manual and analyze the provided examples.
What’s more, if a method contains multiple statements,it is recommended to enclosed them in “{}” so that the code can be written in a more CPP-style manner.
Solution
According to the PA1 and the provided examples, obviously, the stack can be implemented as a head-insertion linked list by modifying the file “examples/list.cl”.
1 | class List { |
Then, we need a method which could determine whether this machine needs to stop.
1 | isFinish(str : String ) : Bool { |
We also need a method to display contents of the stack
1 | print_list(l : List) : Object { |
The most important thing is the “evaluate” method
1 | evaluate(sta : List): List { |
note:
this is a pop operation
1 | a <- transfer.a2i_aux(sta.head()); |
this is a push operation
1 | sta <- sta.cons(transfer.i2a_aux(a+b)); |
Finally, combining these methods in the main function
1 | main(): Object { |