Lecture_15
Lecture_15
Construction
Sohail Aslam
Lecture 15
Recusive Descent Parser
Let’s consider the
implementation of the C++
classes for the non-
terminal
Start with Expr; recall the
grammar
2
Recusive Descent Parser
Let’s consider the
implementation of the C++
classes for the non-
terminal
Start with Expr; recall the
grammar
3
1 Goal → expr
2 expr → term expr'
3 expr' → + term expr'
4 | - term expr'
5 |
6 term → factor term'
7 term' → * factor term'
8 | ∕ factor term'
9 |
10 factor → number
11 | id
4
12 | ( expr )
bool Expr::isPresent() {
Term* op1 = new Term(s);
if(!op1->isPresent())
return false;
tree = op1->AST();
Eprime* op2 =
new Eprime(s, tree);
if(op2->isPresent())
tree = op2->AST();
return true;
}
5
1 Goal → expr
2 expr → term expr'
3 expr' → + term expr'
4 | - term expr'
5 |
6 term → factor term'
7 term' → * factor term'
8 | ∕ factor term'
9 |
10 factor → number
11 | id
12 | ( expr ) 6
bool Eprime::isPresent()
{
int op=s->nextToken();
if(op==PLUS || op==MINUS){
s->advance();
Term* op2=new Term(s);
if(!op2->isPresent())
syntaxError(s);
TreeNode* t2=op2->AST();
tree = new
TreeNode(op,exprSofar,t2);
......
7
. ... ..
Eprime* op3 =
new Eprime(s, tree);
if(op3->isPresent())
tree = op3->AST();
return true;
}
else return false;
}
8
1 Goal → expr
2 expr → term expr'
3 expr' → + term expr'
4 | - term expr'
5 |
6 term → factor term'
7 term' → * factor term'
8 | ∕ factor term'
9 |
10 factor → number
11 | id
12 | ( expr ) 9
bool Term::isPresent()
{
Factor* op1 = new Factor(s);
if(!op1->isPresent())
return false;
tree = op1->AST();
Tprime* op2 =
new Tprime(s, tree);
if(op2->isPresent())
tree = op2->AST();
return true;
}
10
bool Tprime::isPresent()
{
int op=s->nextToken();
if(op == MUL || op == DIV){
s->advance();
Factor* op2=new Factor(s);
if(!op2->isPresent())
syntaxError(s);
TreeNode* t2=op2->AST();
tree = new
TreeNode(op,exprSofar,t2);
......
11
. ... ..
Tprime* op3 =
new Tprime(s, tree);
if(op3->isPresent())
tree = op3->AST();
return true;
}
else return false;
}
12
1 Goal → expr
2 expr → term expr'
3 expr' → + term expr'
4 | - term expr'
5 |
6 term → factor term'
7 term' → * factor term'
8 | ∕ factor term'
9 |
10 factor → number
11 | id
12 | ( expr ) 13
bool Factor::isPresent()
{
int op=s->nextToken();
if(op == ID || op == NUM)
{
tree = new
TreeNode(op,s->tokenValue());
s->advance();
return true;
}
. . . . . .
14
if( op == LPAREN ){
s->advance();
Expr* opr = new Expr(s);
if(!opr->isPresent() )
syntaxError(s);
if(s->nextToken() != RPAREN)
syntaxError(s);
s->advance();
tree = opr->AST();
return true;
}
return false;
}
15