Compiler Designs and Constructions

Download Report

Transcript Compiler Designs and Constructions

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
1
Simple Compiler
Example of a Simple Compiler
1. Language
A=2;
B=A;
C=A+B-2;
Method of representation:


Bachus-Naur-Form (BNF)
Syntax Diagram
ID
ID
+
=
;
Num
-
SALARY = 2+TOTAL – 17;
Chapter 2: A Simple Compiler
2
Simple Compiler
2. Grammar
<statement> ----> ID = <expression>;
<expression> ----> <primary>
<expression> ----><primary> <add_op>
<expression>
<primary> ----> ID
<primary> ----> NUM
<add_op> ----> +
<add_op> ----> Chapter 2: A Simple Compiler
3
Simple Compiler
3. Scanner (Lexical Analyzer)(Tokenizer)
Salary = 2 + Total – 17;
Token
id
Ass
num
plus
id
minus
num
semicolon
Token
Representation
10
50
15
51
10
51
15
53
Lexeme
Salary
=
2
+
Total
17
;
Chapter 2: A Simple Compiler
Token
Type (Attribute)
id
ass_op
num
add_op
id
add_op
num
semicolon
4
Simple Compiler
Symbol Table, Literal Table
Salary = 2 + Total – 17;
Identifier
Type
Value
Salary
Total
int
int
150
Chapter 2: A Simple Compiler
5
Simple Compiler
4. Parser (Syntax Analyzer):
a. Parse Tree:
Salary = 2 + Total – 17;
Chapter 2: A Simple Compiler
6
Simple Compiler
b.
Syntax Tree:
Salary = 2 + Total – 17;
Chapter 2: A Simple Compiler
7
Simple Compiler
5. Semantic Analyzer:
Salary = 2 + Total – 17;
Chapter 2: A Simple Compiler
8
Simple Compiler
6. Intermediate Code Generation:
Salary=2 + total –17 ;
Operator
OP1
OP2
Result
+
2
Total
Temp1
-
Temp1
17
Temp2
=
Temp2
Chapter 2: A Simple Compiler
Salary
9
Simple Compiler
 Why intermediate code and not assembly
code
C++
Python
Pascal
Intermediate Code
Final Object Code
Chapter 2: A Simple Compiler
10
Simple Compiler
7. Code Optimization:
a. Salary = 2 + Total – 17;
Operator
+
OP1
2
OP2
Total
Result
Temp1
-
Temp1
17
Salary
b. Salary = Total – 15;
Chapter 2: A Simple Compiler
11
Simple Compiler
8. Final Code Generation:
a. ADDL3 Total ,
#2, R5
SUBL3 R5,
#17, Salary
b. SUBL3
Total,
#15, Salary
Chapter 2: A Simple Compiler
12