CD Lab 9
CD Lab 9
/*Description:
LR parsing is a bottom-up technique used in compilers to analyze the syntax of a
given input string based on a context-free grammar. It involves reading the input
from left to right and constructing a rightmost derivation in reverse. The main
components are an input buffer, a stack, and a parsing table (with action and goto
tables). The parser uses these components to perform shift, reduce, goto, and
accept actions, ensuring the input string matches the grammar rules. If the input
adheres to the grammar, it is accepted; otherwise, it is rejected. This method
efficiently handles complex grammars without backtracking.
*/
/*Source Code: */
#include <stdio.h>
#include <string.h>
char stack[30];
int top = -1;
void push(char c) {
top++;
stack[top] = c;
}
char pop() {
char c;
if (top != -1) {
c = stack[top];
top--;
return c;
}
return 'x';
}
void printstat() {
int i;
printf("\n $");
for (i = 0; i <= top; i++)
printf("%c", stack[i]);
}
void main() {
int i, l;
char s1[20], ch1, ch2, ch3;
printf("\n\n LR PARSING");
printf("\n ENTER THE EXPRESSION: ");
scanf("%s", s1);
l = strlen(s1);
printf("\n $");
for (i = 0; i < l; i++) {
if (s1[i] == 'i' && s1[i+1] == 'd') {
s1[i] = ' ';
s1[i+1] = 'E';
printstat();
printf("id");
push('E');
printstat();
} else if (s1[i] == '+' || s1[i] == '-' || s1[i] == '*' || s1[i] == '/' ||
s1[i] == 'd') {
push(s1[i]);
printstat();
}
}
printstat();
while (top != -1) {
ch1 = pop();
if (ch1 == 'x') {
printf("\n $");
break;
}
if (ch1 == '+' || ch1 == '/' || ch1 == '*' || ch1 == '-') {
ch3 = pop();
if (ch3 != 'E') {
printf("\n error");
return;
} else {
push('E');
printstat();
}
}
ch2 = ch1;
}
printf("\n");
getchar();
}
/*
Output:
LR PARSING
ENTER THE EXPRESSION: id+id*id
$
$id
$E
$E+
$E+id
$E+E
$E+E*
$E+E*id
$E+E*E
$E+E*E
$E+E
$E
*/