Compiler Designs and Constructions Chapter 2: A Simple Compiler Compiler Designs and Constructions Chapter 2: A Simple Compiler Objectives: Demonstration of a simple Compiler One Pass Compiler Dr. Mohsen Chitsaz Chapter 2: A Simple Compiler COSC 470
Chapter 2: A Simple Compiler Example of a Simple Compiler Language A=2; B=A; C=A+B-2; Method of representation: Bachus-Naur-Form (BNF) Syntax Diagram SALARY = 2+TOTAL – 17; ID Num = + - ; Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Grammar <statement> ----> ID = <expression>; <expression> ----> <primary> <expression> ----><primary> <add_op> <expression> <primary> ----> ID <primary> ----> NUM <add_op> ----> + <add_op> ----> - Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Scanner (Lexical Analyzer)(Tokenizer) Salary = 2 + Total – 17; Token Token Token Representation Lexeme Type (Attribute) id 10 Salary id Ass 50 = ass_op num 15 2 num plus 51 + add_op id 10 Total id minus 51 - add_op num 15 17 num semicolon 53 ; semicolon Chapter 2: A Simple Compiler
Simple Compiler Symbol Table, Literal Table Salary = 2 + Total – 17; Identifier Type Value Salary int Total int 150 Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Parser (Syntax Analyzer): Parse Tree: Salary = 2 + Total – 17; Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Syntax Tree: Salary = 2 + Total – 17; Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler 5. Semantic Analyzer: Salary = 2 + Total – 17; Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Intermediate Code Generation: Salary=2 + total –17 ; Operator OP1 OP2 Result + 2 Total Temp1 - 17 Temp2 = Salary Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Why intermediate code and not assembly code C++ Pascal Python Intermediate Code Final Object Code Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Code Optimization: a. Salary = 2 + Total – 17; b. Salary = Total – 15; Operator OP1 OP2 Result + 2 Total Temp1 - 17 Salary Chapter 2: A Simple Compiler
Chapter 2: A Simple Compiler Final Code Generation: a. ADDL3 Total , #2, R5 SUBL3 R5, #17, Salary b. SUBL3 Total, #15, Salary Chapter 2: A Simple Compiler COSC 470