CS 338 Project: Phase 4
Grammar Start stmt eof Stmt id = expr | if (expr) then stmt | while (expr) do stmt | begin CS end CS stmt ; CS | ote: expr has the same rules seen in Phase 3
Translation rules: 1- Translation of id=expr: translation of expr pop id.lexeme 2- Translation of if (expr) then stmt: translation of expr pop r2 cmp r2, 0 be else translation of stmt else: 3- Translation of while (expr) do stmt : while: translation of expr pop r2 cmp r2, 0 be endwhile translation of stmt b while endwhile: 4- Translation of begin CS end is the translation of CS.
If (1) then X = – 5; Compiler Input file Push 1 Pop r2 Cmp r2,0 Be else Push 1 Push 2 Pop r1 Pop r2 Add r2, r1 Push r2 Push 5 Pop r1 Pop r2 Sub r2, r1 Push r2 Pop x else Output (Intermediate code)
New intermediate instructions: be: branch if equal b : unconditional branch Translation scheme Start stmt eof Stmt id = expr {printf(“pop %s”, id.lexeme)} | if (expr) {if1()} then stmt {if2()} | while {w1()} (expr) {w2()} do stmt {w3()} | begin CS end CS stmt ; CS |
Actions If1() { printf(“pop r2\ncmp r2,0\nbe else\n”); } If2() { printf(“else\n”); }
Actions (Cond) w1() { printf(“while\n”); } w2() { printf(“pop r2\ncmp r2,0\nbe endwhile\n”); } w1() { printf(“b while\nendwhile\n”); }