Professional Documents
Culture Documents
Compiler Moghadameh
Compiler Moghadameh
COM
:
Compilers, Principles, Techniques, and Tools
Alfred V. Aho :
:
ramin.samad@yahoo.com
WWW.IRANMEET.COM
:(
.
.
:(
)
)
:
)
.
.
Back end
.
)
.
Back end
Front end
ramin.samad@yahoo.com
WWW.IRANMEET.COM
(BNF)
.
(
.
)
BNF
.
(BNF)
(Terminals)
(Variables)
(Products)
(Start)
.
.
.
(W)
S
W'
W => W'
W'
W =>=> W'
:
L(G) = {W: S =>=> W}
L(G)
G
:
V = {A, B, S}
T = {a, b}
G = {S AB, A
L(G) = anbm
Aa, B
Bb, A
a, B
b}
.S =>=> a2b4 :
L(G)
a2b4
.
.
:
list
list + digit | list digit | digit
digit
0|1|2|3|4|5|6|7|8|9
:
95+2
list
list
list
digit
digit
digit
ramin.samad@yahoo.com
WWW.IRANMEET.COM
.
.
:
num
digit
+
:
9+5+2
.
.
:
right
letter
(=)
expr
expr + term | expr term | term
term term * factor | term / factor | factor
factor
digit | (expr)
(...
.
.
expr
expr
expr
term
term
term
expr1 + term
expr1 term
term
0
1
9
term.t := '9'
ramin.samad@yahoo.com
WWW.IRANMEET.COM
.
.
:
t
expr.t = 952+
expr.t = 95expr.t = 9
term.t = 2
term.t = 5
term.t = 9
.
.
.
.
expr
expr
expr
expr
term
term
term
{Print('+')}
expr
expr
+
{Print('-')}
{Print('9')}
(
{Print('2')}
term
term
term
{Print('5')}
)
:
.
ramin.samad@yahoo.com
WWW.IRANMEET.COM
)
(recursive descent)
(
.
lookahead
.
.
.
lookahead
.
a
type simple | array [simple] of type
simple
integer | char | num .. num
.
First(a) .
First(a) lookahead
First(type) = {integer, char, num, array}
First(simple) = {integer, char, num}
A
b A
a
First
.
(back-tracking)
First(b) First(a)
(Concrete)
(Abstract)
.
.
:
+
-
expr
term
:
expr + term | expr term | term
0|1||9
expr
:(
expr
rest
term
95+2
expr
:E )
term rest
+ expr | - expr | E
0|1||9
.
:
95-2+
9-5+2
rest
95+2(
rest
952+- (
)
)
:
expr
rest
term
term rest
+ term {print('+')} rest | - term {print('-')} rest | E
0 {print('0')}
ramin.samad@yahoo.com
WWW.IRANMEET.COM
:95-2+
expr
term
95+2
rest
rest
{Print('9')}
term
{Print('+')}
{Print('-')}
term
+
5
rest
{Print('5')}
2
{Print('2')}
E
:
expr()
{
term(); rest();
}
rest()
{
if (lookahead == '+') {
match('+'); term(); putchar('+'); rest();
}
else if (lookahead) == '-') {
match('-'); term(); putchar('-'); rest();
}
else ;
}
term()
{
if (isdigit(lookahead) {
putchar(lookahead); match(lookahead);
}
else error();
}
:
expr()
{
term();
while (1)
if (lookahead == '+')
match('+'); term(); putchar('+');
}
else if (lookahead == '-') {
match('-'); term(); putchar('-');
}
else break;
}
ramin.samad@yahoo.com