Daniel B. answered 12/17/20
PhD in Computer Science with 42 years in Computer Research
I do not know what is expected of you, but this is what I did and did not do below.
I am not showing the lexical phase, as that would be too tedious.
I am assume the input stream is already tokenized.
I am showing the syntactic phase by the keyword "Scan" which gives the token scanned.
I am showing parsing by indicating what the compiler would "Push" on its stack
and what it would "Pop".
I am showing code generation using "Emit", which emits an instruction for a
hypothetical computer.
I am assuming the computer to have
- at least two registers R1 and R2,
- Instruction for "Load" and "Store" between memory and registers.
- Arithmetic instructions between a register and memory, overwriting the register.
I am not showing anything involving the symbol table; instead I am using the
variable names from the high level code in the generated instructions.
Scan 'a'
Push 'a' on the stack
Scan '='
Push '=' on the stack
Scan 'b'
Push 'b' on the stack
Scan '+'
Push '+' on the stack
Scan 'c'
Push 'c' on the stack
Scan '*'
Push '*' on the stack
Scan 'd'
Push 'd' on the stack
Scan '+'
Emit 'Load d into R1'
Pop 'd' from the stack
Pop '*' from the stack
Pop 'c' from the stack
Emit 'Mult R1,c into R1'
Pop '+' from the stack
Pop 'b' from the stack
Emit 'Add R1,b into R1'
Push 'R1' on the stack
Push '+' on the stack
Scan 'e'
Push 'e' on the stack
Scan '-'
Push '-' on the stack
Scan 'f'
Push 'f' on the stack
Scan '*'
Push '*' on the stack
Scan '25'
Push '25' on the stack
Scan ';'
Pop '25' from the stack
Emit 'Load 25 into R2'
Pop '*' from the stack
Pop 'f' from the stack
Emit 'Mult R2,f into R2'
Pop '-' from the stack
Pop 'e' from the stack
Emit 'Sub e,R2 into R2'
Pop '+' from the stack
Pop 'R1' from the stack
Emit 'Add R1,R2 into R1'
Pop '=' from the stack
Pop 'a' from the stack
Emit 'Store R1 into a'