CD 6 PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Prac cal-6

Objec ve (s): Write a program for implementa on of Predic ve Parser


Theory: Predic ve Parser in Compiler Design Predic ve Parser: A predic ve parser is
a recursive descent parser with no backtracking or backup. It is a top-down parser
that does not require backtracking.
At each step, the choice of the rule to be expanded is made upon the next terminal
symbol. A -> A1 | A2 | ... | An If the non-terminal is to be further expanded to ‘A’, the
rule is selected based on the current input symbol ‘a’ only.

Predic ve Parser Algorithm:


Make a transi on diagram(DFA/NFA) for every rule of grammar. Op mize the DFA by
reducing the number of states, yielding the final transi on diagram. Simulate the
string on the transi on diagram to parse a string. If the transi on diagram reaches an
accept state a er the input is consumed, it is parsed. Consider the following
grammar-
E->E+T|T

T->T*F|F

F->(E)|id

A er removing le recursion, le factoring

E->TT'

T'->+TT'|ε

T->FT''

T''->*FT''|ε

F->(E)|id

STEP 1: Make a transi on diagram(DFA/NFA) for every rule of grammar.

E->TT’

T’->+TT’|ε
STEP 2: Op mize the DFA by decreases the number of states, yielding the final
transi on diagram.
STEP 3:
Simula on on the input string.
Steps involved in the simula on procedure are: Start from the star ng state.
If a terminal arrives consume it, move to the next state.
If a non-terminal arrive go to the state of the DFA of the non-terminal and return on
reached up to the final state.
Return to actual DFA and Keep doing parsing. If one completes reading the input
string completely, you reach a final state, and the string is successfully parsed.
Program:
#include <iostream>
#include <string>
using namespace std;
class Predic veParser {
private:
string input;
int index;
char lookahead() {
return input[index];
}
void match(char expected) {
if (lookahead() == expected)
index++;
else
cout << "Error: Unexpected token '" << lookahead() << "'" << endl;
}
void E() {
T();
EPrime();
}
void EPrime() {
if (lookahead() == '+') {
match('+');
T();
EPrime();
}
}
void T() {
F();
TPrime();
}
void TPrime() {
if (lookahead() == '*') {
match('*');
F();
TPrime();
}
}
void F() {
if (lookahead() == '(') {
match('(');
E();
match(')');
} else if (isalnum(lookahead())) {
match(lookahead());
} else {
cout << "Error: Unexpected token '" << lookahead() << "'" << endl;
}
}
public:
Predic veParser(string inputString) {
input = inputString;
index = 0;
}
void parse() {
E();
if (lookahead() == '$') // Ensure end of input
cout << "Parsing Successful!" << endl;
else
cout << "Error: Unexpected token '" << lookahead() << "'" << endl;
}
};
int main() {
string input;
cout<<"Gungun Sahu EN21CS301277"<<endl;
cout << "Enter the expression to parse: ";
cin >> input;
input += '$'; // Append end of input marker
Predic veParser parser(input);
parser.parse();
return 0;
}
Output:

You might also like