C++ Recursive Descent Parser: Examining Nonterminal Classes Expr, Eprime, Term, and Tprime, Slides of Compiler Construction

An in-depth look into the implementation of the c++ classes for the nonterminals expr, eprime, term, and tprime in a recursive descent parser. The grammar rules for each nonterminal are presented, followed by the code for their respective ispresent() functions. These functions are responsible for parsing the input stream and constructing the parse tree.

Typology: Slides

2011/2012

Uploaded on 11/03/2012

ekavia
ekavia 🇮🇳

4.3

(58)

241 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Compiler
Construction
Lecture 15
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download C++ Recursive Descent Parser: Examining Nonterminal Classes Expr, Eprime, Term, and Tprime and more Slides Compiler Construction in PDF only on Docsity!

Compiler

Construction

Lecture 15

2

Recusive Descent Parser

 Let’s consider the

implementation of the C++

classes for the non-

terminal

 Start with Expr; recall the

grammar

4 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 )

5 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;

7 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);

8

Eprime* op3 = new Eprime(s, tree); if(op3->isPresent()) tree = op3->AST(); return true; } else return false; }

10 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; }

11 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); ......

13 1 Goal expr 2 exprterm 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 )

14 bool Factor::isPresent() { int op=s->nextToken(); if(op == ID || op == NUM) { tree = new TreeNode(op,s->tokenValue()); s->advance(); return true; }

......