You may download stack.csh and bashstack.sh (updated 02-02) to test your generated code.
First, we recall the code for the prog class is as follows:
class prog: """ A class that holds a parsed program. Its only data is a statement.""" def __init__(self,tlist): self.stmt = stmt(tlist) def gencode(self): self.stmt.gencode()
The code for a fragment of the stmt class is :
class stmt: ... def gencode(self): if self.type == 'IF': self.expr.gencode() flab=newlabel() endlab=newlabel() print "cJUMP %s"%flab self.tstmt.gencode() print "JUMP %s"%endlab print "%s:"%flab self.fstmt.gencode() print "%s:"%endlab ...
where the ...stands for code that works on other types of statements.
The generation of code should be nothing more than a traversal of your semantic tree, starting at the root (prog) and printing various instructions as needed. Note that since we are recursively generating code, attention must be paid to the order that items are generated in. In the if example, we will be generating code that checks the value of an expression and the conditionally executes one statment or the other. So, we must be able to jump to the false statement when the expression is zero (false) and jump past it if we execute the true statement.
This requires us to generate our labels for the jumps all at the same time. If we don't, the true or false statement may generate other labels, leading to mass confusion. The while and for statements would need to consider this as well.
Last modified by Brett Giles