CD_Lab_Report_1 (1)

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

Program 1: Write a LEX program to count the number

of tokens in the given statements.

%{
#include<stdio.h>
int n = 0;
%}

%%

"while"|"if"|"else" {n++; printf("\t keywords : %s", yytext);}


"int"|"float" {n++; printf("\t keywords: %s", yytext);}
[a-zA-Z_][a-zA-Z0-9_]* {n++; printf("\t identifier: %s", yytext);}
"<="|"=="|"="|"++"|"-"|"*"|"+" {n++; printf("\t operator: %s", yytext);}
[(){}|,;] {n++; printf("\t separator : %s", yytext);}
[0-9]*"."[0-9]+ {n++; printf("\t float : %s", yytext);}
[0-9]+ {n++; printf("\t integer : %s", yytext);}
. ;

%%

int main()
{
yylex();
printf("\n total no. of token = %d\n", n);
}

int yywrap()
{
return 1;
}

Output:
Program 2: Write LEX program to recognize valid
identifier, operators and keywords in the given text
file. Count the number of tokens in the given grammar.

%{
#include<stdio.h>
#include<stdlib.h>
int n = 0;
%}

%%

"while"|"if"|"else" {n++; printf("\t keywords : %s", yytext);}


"int"|"float" {n++; printf("\t keywords: %s", yytext);}
[a-zA-Z_][a-zA-Z0-9_]* {n++; printf("\t identifier: %s", yytext);}
"<="|"=="|"="|"++"|"-"|"*"|"+" {n++; printf("\t operator: %s", yytext);}
[(){}|,;] {n++; printf("\t separator : %s", yytext);}
[0-9]*"."[0-9]+ {n++; printf("\t float : %s", yytext);}
[0-9]+ {n++; printf("\t integer : %s", yytext);}
. ;

%%

int main(int argc, char* argv[])


{
if(argc < 2)
{
printf("Please specify filename");
return 1;
}

FILE *f = fopen(argv[1],"r");

if(f == NULL)
{
printf("File not found");
return 1;
}
yyin = f;
yylex();
printf("\n total no. of token = %d\n", n);
}

int yywrap()
{
return 1;
}

input.txt file contains:


if y == 5

Output:
Program 3: Write a LEX program to count the No. of
Vowels and Consonants in a Program.

%{
int vowel_count = 0;
int consonant_count = 0;
%}

%%

[aeiouAEIOU] { vowel_count++; }
[a-zA-Z] { consonant_count++; }
[^a-zA-Z] ; // Ignore non-alphabetical characters

%%

int main() {
yylex(); // Start scanning
printf("\nNumber of vowels: %d\n", vowel_count);
printf("Number of consonants: %d\n", consonant_count);
return 0;
}

int yywrap() {
return 1;
}

Output:
Program 4: Write a LEX program to eliminate comment
lines in a C/python program and copy the resulting
program into a separate file.

%{
FILE *outfile;
%}

%%

"//".* { /* Ignore C single-line comments */ }


"\n//".* { /* Ignore C single-line comments */ }
"\n/*"([^*]|\\*+[^/])*"*/" { /* Ignore C multi-line comments */ }
[^/].* { fprintf(yyout, "%s", yytext); } // Copy
non-comment lines
"/"[^/].* { fprintf(yyout, "%s", yytext); } //
Handle lines starting with '/'

%%

int main() {
// Open output file for writing the cleaned content
outfile = fopen("output.c", "w");
if (outfile == NULL) {
perror("Error opening file for writing");
return 1;
}

// Redirect output to the file


yyout = outfile;

printf("Enter your program (Ctrl+D to end input):\n");


yylex(); // Start scanning and removing comments

fclose(outfile); // Close output file after processing


printf("Program without comments has been written to 'output.c'.\n");
return 0;
}

int yywrap() {
return 1;
}

Output:

Contents of output.c file:

#include<stdio.h>

int main()
{
return 0;
}
Program 5: WAP to convert Non deterministic
grammar to deterministic grammar(left recursion).

#include <stdio.h>
#include <string.h>
void main()
{
char l[50], r[50], temp[10], productions[25][50];
int i = 0, j = 0, flag = 0, consumed = 0;
printf("Enter the productions: ");
scanf("%1s->%s", l, r);
printf("%s", r);
while (sscanf(r + consumed, "%[^|]s", temp) == 1 && consumed <=
strlen(r))
{
if (temp[0] == l[0])
{
flag = 1;
sprintf(productions[i++], "%s'->%s%s'\0", l, temp + 1, l);
}
else
sprintf(productions[i++], "%s->%s%s'\0", l, temp, l);
consumed += strlen(temp) + 1;
}
if (flag == 1)
{
sprintf(productions[i++], "%s'->ε\0", l);
printf("The productions after eliminating Left Recursion are:\n");
for (j = 0; j < i; j++)
printf("%s\n", productions[j]);
}
else
printf("The Given Grammar has no Left Recursion");
}

Output:
Program 6: WAP to compute First and Follow of an
LL(1) Grammar.

#include <malloc.h>
#include <stdio.h>
#include <string.h>

char **productions;
int fvar;

int findPos(char NonTer)


{
int i = 0;
while (productions[i][0] != NonTer)
i++;
return i;
}
char *findGenerating(char Ter)
{
int i = 0;
while (productions[i][0] != Ter)
i++;
return productions[i];
}
char findFirst(char *prod)
{
int i, j = 0;
for (i = 3; i < strlen(prod); i++)
{
if (prod[i] >= 97 && prod[i] <= 122 || prod[i] == ')' || prod[i] == '('
|| prod[i] == ',')
{
printf(" %c ", prod[i]);

while (prod[i] != '/' && prod[i] != '\0')


i++;
}
else if (prod[i] >= 65 && prod[i] <= 90)
{
if (findFirst(productions[findPos(prod[i])]) == '#')
{
continue;
}
else
{
while (prod[i] != '/' && prod[i] != '\0')
i++;
}
}
else if (prod[i] == '#')
{
return '#';
}
else
continue;
}
return '.';
}

void findFollow(char GeneratingSymbol, int n)


{
int i, j = 0;
if (GeneratingSymbol == 'X')
printf(" $ ");
for (j = 0; j < n; j++)
{
for (i = 3; i < strlen(productions[j]); i++)
{
if (GeneratingSymbol == productions[j][i])
{
if (productions[j][i + 1] >= 97 && productions[j][i + 1] <= 122
|| productions[j][i + 1] == ')' || productions[j][i + 1] == '(' ||
productions[j][i + 1] == ',')
{
printf(" %c ", productions[j][i + 1]);
}
else if (productions[j][i + 1] >= 65 && productions[j][i + 1] <=
90)
{
char ans = findFirst(findGenerating(productions[j][i + 1]));
}
else if (i + 1 == strlen(productions[j]))
{
findFollow(productions[j][0], n);
}
else
continue;
}
}
}
}

int main()
{
int j, i, n, k, tempInd, flag = 0;
__ssize_t len;
printf("Enter the number of productions");
scanf("%d\n", &n);
productions = (char **)malloc(sizeof(char *) * n);
for (i = 0; i < n; i++)
productions[i] = (char *)malloc(sizeof(char) * 20);

char **productionsDup = (char **)malloc(sizeof(char *) * n);


for (i = 0; i < n; i++)
productionsDup[i] = (char *)malloc(sizeof(char) * 20);

for (i = 0; i < n; i++)


{
getline(&productions[i], &len, stdin);
productionsDup[i] = productions[i];
}

// First Computation
for (i = 0; i < n; i++)
{
printf("\nFIRST(%c)={ ", productions[i][0]);
char ans = findFirst(productions[i]);
if (ans == '#')
printf(" #");
printf("}\n");
}

for (i = 0; i < n; i++)


{
printf("\nFOLLOW(%c)={", productions[i][0]);
findFollow(productions[i][0], n);
printf("}\n");
}
printf("\nThe End");
}
Output:
Program 7: WAP to construct LL(1) parsing table for
LL(1) grammar and validate the input string.

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>

void followfirst(char , int , int);


void findfirst(char , int , int);
void follow(char c);

int count,n=0;
char calc_first[10][100];
char calc_follow[10][100];
int m=0;
char production[10][10], first[10];
char f[10];
int k;
char ck;
int e;

int main(int argc,char **argv)


{
int jm=0;
int km=0;
int i,choice;
char c,ch;
printf("How many productions ? :");
scanf("%d",&count);
printf("\nEnter %d productions in form A=B where A and B are grammar
symbols :\n\n",count);
for(i=0;i<count;i++)
{
scanf("%s%c",production[i],&ch);
}
int kay;
char done[count];
int ptr = -1;
for(k=0;k<count;k++){
for(kay=0;kay<100;kay++){
calc_first[k][kay] = '!';
}
}
int point1 = 0,point2,xxx;
for(k=0;k<count;k++)
{
c=production[k][0];
point2 = 0;
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(c == done[kay])
xxx = 1;
if (xxx == 1)
continue;
findfirst(c,0,0);
ptr+=1;
done[ptr] = c;
printf("\n First(%c)= { ",c);
calc_first[point1][point2++] = c;
for(i=0+jm;i<n;i++){
int lark = 0,chk = 0;
for(lark=0;lark<point2;lark++){
if (first[i] == calc_first[point1][lark]){
chk = 1;
break;
}
}
if(chk == 0){
printf("%c, ",first[i]);
calc_first[point1][point2++] = first[i];
}
}
printf("}\n");
jm=n;
point1++;
}
printf("\n");
printf("-----------------------------------------------\n\n");
char donee[count];
ptr = -1;
for(k=0;k<count;k++){
for(kay=0;kay<100;kay++){
calc_follow[k][kay] = '!';
}
}
point1 = 0;
int land = 0;
for(e=0;e<count;e++)
{
ck=production[e][0];
point2 = 0;
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(ck == donee[kay])
xxx = 1;
if (xxx == 1)
continue;
land += 1;
follow(ck);
ptr+=1;
donee[ptr] = ck;
printf(" Follow(%c) = { ",ck);
calc_follow[point1][point2++] = ck;
for(i=0+km;i<m;i++){
int lark = 0,chk = 0;
for(lark=0;lark<point2;lark++){
if (f[i] == calc_follow[point1][lark]){
chk = 1;
break;
}
}
if(chk == 0){
printf("%c, ",f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf(" }\n\n");
km=m;
point1++;
}
char ter[10];
for(k=0;k<10;k++){
ter[k] = '!';
}
int ap,vp,sid = 0;
for(k=0;k<count;k++){
for(kay=0;kay<count;kay++){
if(!isupper(production[k][kay]) && production[k][kay]!= '#' &&
production[k][kay] != '=' && production[k][kay] != '\0'){
vp = 0;
for(ap = 0;ap < sid; ap++){
if(production[k][kay] == ter[ap]){
vp = 1;
break;
}
}
if(vp == 0){
ter[sid] = production[k][kay];
sid ++;
}
}
}
}
ter[sid] = '$';
sid++;
printf("\n\t\t\t\t\t\t\t The LL(1) Parsing Table for the above grammer
:-");

printf("\n\t\t\t\t\t\t\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\
n");

printf("\n\t\t\t===========================================================
==========================================================\n");
printf("\t\t\t\t|\t");
for(ap = 0;ap < sid; ap++){
printf("%c\t\t",ter[ap]);
}

printf("\n\t\t\t===========================================================
==========================================================\n");
char first_prod[count][sid];
for(ap=0;ap<count;ap++){
int destiny = 0;
k = 2;
int ct = 0;
char tem[100];
while(production[ap][k] != '\0'){
if(!isupper(production[ap][k])){
tem[ct++] = production[ap][k];
tem[ct++] = '_';
tem[ct++] = '\0';
k++;
break;
}
else{
int zap=0;
int tuna = 0;
for(zap=0;zap<count;zap++){
if(calc_first[zap][0] == production[ap][k]){
for(tuna=1;tuna<100;tuna++){
if(calc_first[zap][tuna] != '!'){
tem[ct++] = calc_first[zap][tuna];
}
else
break;
}
break;
}
}
tem[ct++] = '_';
}
k++;
}
int zap = 0,tuna;
for(tuna = 0;tuna<ct;tuna++){
if(tem[tuna] == '#'){
zap = 1;
}
else if(tem[tuna] == '_'){
if(zap == 1){
zap = 0;
}
else
break;
}
else{
first_prod[ap][destiny++] = tem[tuna];
}
}
}
char table[land][sid+1];
ptr = -1;
for(ap = 0; ap < land ; ap++){
for(kay = 0; kay < (sid + 1) ; kay++){
table[ap][kay] = '!';
}
}
for(ap = 0; ap < count ; ap++){
ck = production[ap][0];
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(ck == table[kay][0])
xxx = 1;
if (xxx == 1)
continue;
else{
ptr = ptr + 1;
table[ptr][0] = ck;
}
}
for(ap = 0; ap < count ; ap++){
int tuna = 0;
while(first_prod[ap][tuna] != '\0'){
int to,ni=0;
for(to=0;to<sid;to++){
if(first_prod[ap][tuna] == ter[to]){
ni = 1;
}
}
if(ni == 1){
char xz = production[ap][0];
int cz=0;
while(table[cz][0] != xz){
cz = cz + 1;
}
int vz=0;
while(ter[vz] != first_prod[ap][tuna]){
vz = vz + 1;
}
table[cz][vz+1] = (char)(ap + 65);
}
tuna++;
}
}
for(k=0;k<sid;k++){
for(kay=0;kay<100;kay++){
if(calc_first[k][kay] == '!'){
break;
}
else if(calc_first[k][kay] == '#'){
int fz = 1;
while(calc_follow[k][fz] != '!'){
char xz = production[k][0];
int cz=0;
while(table[cz][0] != xz){
cz = cz + 1;
}
int vz=0;
while(ter[vz] != calc_follow[k][fz]){
vz = vz + 1;
}
table[k][vz+1] = '#';
fz++;
}
break;
}
}
}
for(ap = 0; ap < land ; ap++){
printf("\t\t\t %c\t|\t",table[ap][0]);
for(kay = 1; kay < (sid + 1) ; kay++){
if(table[ap][kay] == '!')
printf("\t\t");
else if(table[ap][kay] == '#')
printf("%c=#\t\t",table[ap][0]);
else{
int mum = (int)(table[ap][kay]);
mum -= 65;
printf("%s\t\t",production[mum]);
}
}
printf("\n");

printf("\t\t\t-------------------------------------------------------------
--------------------------------------------------------");
printf("\n");
}
int j;
printf("\n\nPlease enter the desired INPUT STRING = ");
char input[100];
scanf("%s%c",input,&ch);

printf("\n\t\t\t\t\t=======================================================
====================\n");
printf("\t\t\t\t\t\tStack\t\t\tInput\t\t\tAction");

printf("\n\t\t\t\t\t=======================================================
====================\n");
int i_ptr = 0,s_ptr = 1;
char stack[100];
stack[0] = '$';
stack[1] = table[0][0];
while(s_ptr != -1){
printf("\t\t\t\t\t\t");
int vamp = 0;
for(vamp=0;vamp<=s_ptr;vamp++){
printf("%c",stack[vamp]);
}
printf("\t\t\t");
vamp = i_ptr;
while(input[vamp] != '\0'){
printf("%c",input[vamp]);
vamp++;
}
printf("\t\t\t");
char her = input[i_ptr];
char him = stack[s_ptr];
s_ptr--;
if(!isupper(him)){
if(her == him){
i_ptr++;
printf("POP ACTION\n");
}
else{
printf("\nString Not Accepted by LL(1) Parser !!\n");
exit(0);
}
}
else{
for(i=0;i<sid;i++){
if(ter[i] == her)
break;
}
char produ[100];
for(j=0;j<land;j++){
if(him == table[j][0]){
if (table[j][i+1] == '#'){
printf("%c=#\n",table[j][0]);
produ[0] = '#';
produ[1] = '\0';
}
else if(table[j][i+1] != '!'){
int mum = (int)(table[j][i+1]);
mum -= 65;
strcpy(produ,production[mum]);
printf("%s\n",produ);
}
else{
printf("\nString Not Accepted by LL(1) Parser
!!\n");
exit(0);
}
}
}
int le = strlen(produ);
le = le - 1;
if(le == 0){
continue;
}
for(j=le;j>=2;j--){
s_ptr++;
stack[s_ptr] = produ[j];
}
}
}

printf("\n\t\t\t===========================================================
============================================================\n");
if (input[i_ptr] == '\0'){
printf("\t\t\t\t\t\t\t\tYOUR STRING HAS BEEN ACCEPTED !!\n");
}
else
printf("\n\t\t\t\t\t\t\t\tYOUR STRING HAS BEEN REJECTED !!\n");
printf("\t\t\t=============================================================
==========================================================\n");
}

void follow(char c)
{
int i ,j;
if(production[0][0]==c){
f[m++]='$';
}
for(i=0;i<10;i++)
{
for(j=2;j<10;j++)
{
if(production[i][j]==c)
{
if(production[i][j+1]!='\0'){
followfirst(production[i][j+1],i,(j+2));
}
if(production[i][j+1]=='\0'&&c!=production[i][0]){
follow(production[i][0]);
}
}
}
}
}

void findfirst(char c ,int q1 , int q2)


{
int j;
if(!(isupper(c))){
first[n++]=c;
}
for(j=0;j<count;j++)
{
if(production[j][0]==c)
{
if(production[j][2]=='#'){
if(production[q1][q2] == '\0')
first[n++]='#';
else if(production[q1][q2] != '\0' && (q1 != 0 || q2 != 0))
{
findfirst(production[q1][q2], q1, (q2+1));
}
else
first[n++]='#';
}
else if(!isupper(production[j][2])){
first[n++]=production[j][2];
}
else {
findfirst(production[j][2], j, 3);
}
}
}
}

void followfirst(char c, int c1 , int c2)


{
int k;
if(!(isupper(c)))
f[m++]=c;
else{
int i=0,j=1;
for(i=0;i<count;i++)
{
if(calc_first[i][0] == c)
break;
}
while(calc_first[i][j] != '!')
{
if(calc_first[i][j] != '#'){
f[m++] = calc_first[i][j];
}
else{
if(production[c1][c2] == '\0'){
follow(production[c1][0]);
}
else{
followfirst(production[c1][c2],c1,c2+1);
}
}
j++;
}
}
}
Output:
Program 8: WAP to construct operator precedence
parsing table for the given grammar and check the
validity of the string (id+id*id).
E->E+T/T
T->T*F/F
F->(E)/id

#include <stdio.h>
#include <string.h>
#define MAX 100

// Operator precedence relations


char precTable[4][4] = {
{'>', '>', '<', '>'}, // +: > +, > *, < id, >
{'>', '>', '<', '>'}, // *: > +, > *, < id, >
{'<', '<', '=', '<'}, // id: < +, < *, = id, >
{'<', '<', '<', '='} // $: < +, < *, < id, = $
};

int isOperator(char c)
{
return (c == '+' || c == '*' || c == '(' || c == ')' || c == '$');
}

int precedenceIndex(char c)
{
switch (c)
{
case '+':
return 0;
case '*':
return 1;
case 'i':
return 2; // assuming 'i' represents 'id'
case '$':
return 3;
default:
return -1;
}
}
char getPrecedence(char stackTop, char input)
{
return precTable[precedenceIndex(stackTop)][precedenceIndex(input)];
}
int validateString(char *input)
{
char stack[MAX];
int top = -1;
int i = 0;
stack[++top] = '$';
while (input[i] != '\0')
{
if (input[i] == 'i' && input[i + 1] == 'd')
{
stack[++top] = 'i'; // Simplify 'id' to 'i'
i += 2; // Move past 'id'
}
else
{
switch (getPrecedence(stack[top], input[i]))
{
case '<':
stack[++top] = input[i++];
break;
case '=':
top--;
i++;
break;
case '>':
if (top == 0)
return 0; // Error: Invalid string
top--;
break;
default:
return 0; // Error: Invalid string
}
}
}
while (stack[top] != '$')
{
if (getPrecedence(stack[top - 1], stack[top]) == '>')
{
top--;
}
else
{
return 0; // Error: Invalid string
}
}
return 1;
}
int main()
{
char input[] = "id+id*id$";
if (validateString(input))
{
printf("The string is valid.\n");
}
else
{
printf("The string is invalid.\n");
}
return 0;
}

Output:
Program 9: Write a program to implement recursive
descent parsing.

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

char input[100];
int i = 0; // Initialize index to 0

bool E();
bool EP();
bool T();
bool TP();
bool F();

int main() {
printf("\nRecursive descent parsing for the following grammar\n");
printf("\nE->TE'\nE'->+TE'/@\nT->FT'\nT'->*FT'/@\nF->(E)/ID\n");
printf("\nEnter the string to be checked: ");

// Use fgets instead of gets for safer input


fgets(input, sizeof(input), stdin);
// Remove newline character from input if present
input[strcspn(input, "\n")] = 0;

if (E()) {
if (input[i] == '\0') {
printf("\nString is accepted\n");
} else {
printf("\nString is not accepted\n");
}
} else {
printf("\nString not accepted\n");
}

return 0;
}

bool E() {
if (T()) {
if (EP())
return true;
else
return false;
} else {
return false;
}
}

bool EP() {
if (input[i] == '+') {
i++;
if (T()) {
if (EP())
return true;
else
return false;
} else {
return false;
}
} else {
return true; // ε production
}
}

bool T() {
if (F()) {
if (TP())
return true;
else
return false;
} else {
return false;
}
}

bool TP() {
if (input[i] == '*') {
i++;
if (F()) {
if (TP())
return true;
else
return false;
} else {
return false;
}
} else {
return true; // ε production
}
}

bool F() {
if (input[i] == '(') {
i++;
if (E()) {
if (input[i] == ')') {
i++;
return true;
} else {
return false;
}
} else {
return false;
}
} else if ((input[i] >= 'a' && input[i] <= 'z') || (input[i] >= 'A' &&
input[i] <= 'Z')) {
i++;
return true;
} else {
return false;
}
}

Output:

You might also like