Simple One-Pass Compiler part II Natawut Nupairoj, Ph.D. Department of Computer Engineering Chulalongkorn University
Outline Abstract Stack Machine. Simple Code Generation.
Abstract Stack Machine Basic machine with stack only for computation. Ex: push 10 push 5 add push 2 minus
Abstract Stack Machine Variables Use value from variable r-value. Store value to variable l-value. k := k Ex: lvalue k push 5 := push 2 rvalue k add (addr) k k := 5
Stack Manipulation push vpush v on top of stack pop vpop v from top of stack rvalue lpush content of data l lvalue lpush address of data l :=put r-value on top to l-value below and pop both from top copypush copy of top
Translation of Expression day := (1461 * y) div 4 + (153 * m + 2) div 5 + d lvalue daypush 153div push 1461rvalue madd rvalue ymulrvalue d mulpush 2add push 4add:= divpush 5
Translation Scheme for Simple Expression expr ::= expr + term {print(‘add’);} expr ::= expr – term {print(‘minus’);} expr ::= term term ::= 0{print(‘push 0’);} term ::= 1{print(‘push 1’);}... term ::= 9{print(‘push 9’);}
Example expr +{ print(‘add’) } exprterm - { print(‘minus’) } 2{ print(‘push 2’) } exprterm term 5{ print(‘push 5’) } 9 { print(‘push 9’) } Input: 9 – Output: push 9 push 5 minus push 2 add
Translation Scheme for Simple Expression with Tokens expr ::= expr + term {print(‘add’);} expr ::= expr – term {print(‘minus’);} expr ::= term term ::= number {print(‘push ’); print(number.lexeme);} term ::= id {print(‘lvalue ); print(id.lexeme);}
Example expr ::= expr + term {print(‘add’);} expr ::= expr – term {print(‘minus’);} expr ::= term term ::= number {print(‘push ’); print(number.lexeme);} term ::= id {print(‘rvalue ’); print(id.lexeme);} Input: 2 + k – m Output: push 2 rvalue k add rvalue m minus
Translation Scheme for Assignment Statement stmt ::= id := {print(‘lvalue’); print(id.lexeme);} expr {print(‘:=‘);} Input: k := k + 1 Output: lvalue k rvalue k push 1 add := exprstmt
Control Flow eqpop top two values and compare, if equal push 1 on top of the stack, otherwise push 0. ltpop top two values and compare, if bottom less than first push 1 on top of thestack, otherwise push 0. gtsimilar to “lt”. label ltarget for jump goto ljump to lable l gofalse lpop top; jump if zero gotrue lpop top; jump if nonzero
Translation of if Statement stmt ::= if expr {out:=newlabel; print(‘gofalse’); print(out);} then stmt1 {print(‘label ’); print(out);} Code for expr gofalse lb01 Code for stmt1 label lb01 if k+1 < 0 then m := 3; rvalue k rush 1 add push 0 lt gofalse lb01 lvalue m push 3 := label lb01 stmt