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

Compiler Class Work

13 July 2023

Submi ed By:-Aakri (21BCE3263)

Submi ed To:- Vishnupriya

tt
tt
ti

1. Code for Construct Recursive Descent parser


(((a,a),↑,(a),a) .
S-> a|↑|(T)
T->T¸S|S

Solution:-
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char inp[100];
int ptr = 0;
int er_f = 0;
void S();
void T();
void match(char expected) {
if (inp[ptr] == expected) {
ptr++;
} else {
er_f = 1;
}
}
void S() {
if (inp[ptr] == 'a') {
match('a');

} else if (inp[ptr] == '^') {


match('^');
} else if (inp[ptr] == '(') {
match('(');
T();
match(')');
} else {
er_f = 1;
}
}
void T() {
S();
if (inp[ptr] == ',') {
match(',');
T();
}
}
int main() {
printf("Sarthak Goyal 21BCE0968\n\n”);
printf("Enter the sentence to parse: ");
fgets(inp, sizeof(inp), stdin);
inp[strcspn(inp, "\n")] = '\0';

S();

if (inp[ptr] == '\0' && er_f == 0) {


printf("Parsing successful. Sentence is valid.\n");
} else {
printf("Parsing failed. Sentence is invalid.\n");
}
printf("Sarthak Goyal 21BCE0968\n\n”);
return 0;
}

Screenshot:-

Output:-

2. Code for the predictive parser for the given grammar and parse the sentence
(((a,a),↑,(a),a) .
S-> a|↑|(T)
T->T¸S|S

Code
#include <stdio.h>

#include <stdlib.h>
#include <string.h>
char input[100];
int ptr= 0;
int er_f = 0;

void S();
void T();

void match(char expected) {


if (input[pointer] == expected) {
pointer++;
} else {
er_f = 1;
}
}

void S() {
if (input[pointer] == 'a') {
match('a');
prin ("S -> a\n");
} else if (input[pointer] == '^') {
match('^');
prin ("S -> ^\n");
} else if (input[pointer] == '(') {
match('(');
T();
match(')');
prin ("S -> (T)\n");
} else {
er_f = 1;
}

tf
tf
tf

void T() {
S();
if (input[pointer] == ',') {
match(',');
T();
prin ("T -> T,S\n");
} else {
prin ("T -> S\n");
}
}

int main() {
prin ("Sarthak Goyal 21BCE0968\n\n");
prin ("Enter the sentence to parse: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';

S();

if (input[pointer] == '\0' && er_f == 0) {


prin ("Parsing successful. Sentence is valid.\n");
} else {
prin ("Parsing failed. Sentence is invalid.\n");
}
prin ("Sarthak Goyal 21BCE0968\n\n");

return 0;
}

tf
tf
tf

tf
tf
tf
tf

Screenshot:-

Output:-

Thank You

You might also like