Practical File: Department of Computer Science and Engineering

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

Department of Computer Science and Engineering

PRACTICAL FILE

Course Title: Compiler Design Lab


Course CODE: BTCS 604-18
Semester: 6th

Submitted To: Submitted By:


Ms. Mandeep Kaur Tanvi Wadhwa
1815818
CSE-Y
INDEX

Sr. No. Experiment Name Page No. Remarks


Design a lexical analyser for given language and the lexical
analyser should ignore redundant spaces, tabs and new
lines. It should also ignore comments. Although the syntax
1. 3-5
specification states that identifiers can be arbitrarily long,
you may restrict the length to some reasonable value.
Simulate the same in C language.
Write a C program to identify whether a given line is a
2. 6-7
comment or not.
Write a C program to recognize strings under 'a', 'a*b+',
3. 8-9
'abb'
Write a C program to test whether a given identifier is valid
4. 10
or not.
Write a C program to simulate lexical analyzer for
5. 11-12
validating operators.
Implement the lexical analyzer using JLex, flex or other
6. 13-14
lexical analyzer generating tools
Write a C program for implementing the functionalities
7. of predictive parser for the mini language specified in 15-16
Note 1.
a) Write a C program for constructing of LL (1)
parsing.
b) Construction of recursive descent parsing for the
following grammar
8. 17-22
E->TE'
E'->+TE/@ "@ represents null character"
T->FT'
T`->*FT'/@
F->(E)/ID
9. Write a program to Design LALR Bottom up Parser. 23-27
a) Write a C program to implement operator
precedence parsing.
b) Write a C program to implement Program semantic
10. 28-32
rules to calculate the expression that takes an
expression with digits, + and * and computes the
value

2|Page
Experiment No. 1
AIM: Design a lexical analyzer for given language and the lexical analyzer should ignore
redundant spaces, tabs and new lines. It should also ignore comments. Although the syntax
specification states that identifiers can be arbitrarily long, you may restrict the length to some
reasonable value. Simulate the same in C language.

DESCRIPTION:

CODE:-

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
bool isDelimiter(char ch)
{
if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == ',' || ch == ';' || ch == '>' ||
ch == '<' || ch == '=' || ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '{' || ch == '}')
return (true);
return (false);
}
bool isOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' ||ch == '/' || ch == '>' || ch == '<' ||ch == '=')
return (true);
return (false);
}

bool validIdentifier(char* str)


{
if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||str[0] == '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' ||str[0] == '9' || isDelimiter(str[0]) == true)
return (false);
return (true);
}

bool isKeyword(char* str)


{
if (!strcmp(str, "if") || !strcmp(str, "else") ||!strcmp(str, "while") || !strcmp(str, "do") ||
!strcmp(str, "break") ||!strcmp(str, "continue") || !strcmp(str, "int") || !strcmp(str, "double") ||
!strcmp(str, "float") || !strcmp(str, "return") || !strcmp(str, "char")|| !strcmp(str, "case") ||
!strcmp(str, "char")|| !strcmp(str, "sizeof") || !strcmp(str, "long")|| !strcmp(str, "short") ||
!strcmp(str, "typedef")|| !strcmp(str, "switch") || !strcmp(str, "unsigned")|| !strcmp(str, "void")
|| !strcmp(str, "static") || !strcmp(str, "struct") || !strcmp(str, "goto")
)
return (true);
return (false);
}
3|Page
bool isInteger(char* str)
{
int i, len = strlen(str);
if (len == 0)
return (false);
for (i = 0; i < len; i++)
{
if (str[i] != '0'&& str[i] != '1'&& str[i] != '2'&& str[i] != '3'&& str[i] != '4'&& str[i] != '5'&&
str[i] != '6'&& str[i] != '7'&& str[i] != '8'&& str[i] != '9' || (str[i] == '-'&& i > 0))
return (false);
}
return (true);
}
bool isRealNumber(char* str)
{
int i, len = strlen(str);
bool hasDecimal = false;
if (len == 0)
return (false);
for (i = 0; i < len; i++)
{
if (str[i] != '0'&& str[i] != '1'&& str[i] != '2'&& str[i] != '3'&& str[i] != '4'&& str[i] != '5'&&
str[i] != '6'&& str[i] != '7'&& str[i] != '8'&& str[i] != '9'&& str[i] != '.' || (str[i] == '-'&& i >
0)
)
return (false);
if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}
char* subString(char* str, int left, int right)
{
int i;
char* subStr = (char*)malloc( sizeof(char) * (right - left + 2));
for (i = left; i <= right; i++)
subStr[i - left] = str[i];
subStr[right - left + 1] = '\0';
return (subStr);
}
void parse(char* str)
{
int left = 0, right = 0;
int len = strlen(str);
while (right <= len && left <= right)
{
if (isDelimiter(str[right]) == false)
right++;
if (isDelimiter(str[right]) == true && left == right)

4|Page
{
if (isOperator(str[right]) == true)
printf("'%c' IS AN OPERATOR\n", str[right]);
right++;
left = right;
}
else if (isDelimiter(str[right]) == true && left != right || (right == len && left != right))
{
char* subStr = subString(str, left, right - 1);
if (isKeyword(subStr) == true)
printf("'%s' IS A KEYWORD\n", subStr);
else if (isInteger(subStr) == true)
printf("'%s' IS AN INTEGER\n", subStr);
else if (isRealNumber(subStr) == true)
printf("'%s' IS A REAL NUMBER\n", subStr);
else if (validIdentifier(subStr) == true && isDelimiter(str[right - 1]) == false)
printf("'%s' IS A VALID IDENTIFIER\n", subStr);
else if (validIdentifier(subStr) == false && isDelimiter(str[right - 1]) == false)
printf("'%s' IS NOT A VALID IDENTIFIER\n", subStr);
left = right;
}
}
return;
}
int main()
{
char str[100] = "int z = q + 20; ";
parse(str);
return (0);
}
OUTPUT:-

5|Page
Experiment No. 2
AIM:- Write a C program to identify whether a given line is a comment or not.

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<conio.h>
void main(){
char com[30];
int i=2,a=0;
printf("\n Enter comment:");
gets(com);
if(com[0]=='/')
{
if(com[1]=='/')
printf("\n It is a comment");
else if(com[1]=='*')
{
for(i=2;i<=30;i++)
{
if(com[i]=='*'&&com[i+1]=='/')
{
printf("\n It is a comment");
a=1;
break;
}
else
continue;
}
if(a==0)
printf("\n It is not a comment");
}
else
printf("\n It is not a comment");
}
else
printf("\n It is not a comment");
getch();
}

OUTPUT:-

6|Page
7|Page
Experiment No. 3
AIM:- Write a C program to recognize strings under 'a', 'a*b+', 'abb'.

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char s[20],c;
int state=0,i=0;
printf("\n Enter a string:");
gets(s);
while(s[i]!='\0')
{
switch(state)
{
case 0: c=s[i++];
if(c=='a')
state=1;
else if(c=='b')
state=2;
else state=6;
break;
case 1: c=s[i++];
if(c=='a')
state=3;
else if(c=='b')
state=4;
else state=6;
break;
case 2: c=s[i++];
if(c=='a')
state=6;
else if(c=='b')
state=2;
else
state=6;
break;
case 3: c=s[i++];
if(c=='a')
state=3;
else if(c=='b')
state=2;

8|Page
else
state=6;
break;
case 4: c=s[i++];
if(c=='a')
state=6;
else if(c=='b')
state=5;
else
state=6;
break;
case 5: c=s[i++];
if(c=='a')
state=6;
else if(c=='b')
state=2;
else
state=6;
break;
case 6:
printf("\n %s is not recognised.",s);
exit(0);
}
}
if(state==1)
printf("\n %s is accepted under rule 'a'",s);
else if((state==2)||(state==4))
printf("\n %s is accepted under rule 'a*b+'",s);
else if(state==5)
printf("\n %s is accepted under rule 'abb'",s);
getch();
}

OUTPUT:-

9|Page
Experiment No. 4
AIM:- Write a C program to test whether a given identifier is valid or not..

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<ctype.h>
void main()
{
char a[10];
int flag, i=1;
printf("Enter an identifier: ");
gets(a);
if(isalpha(a[0]))
flag=1;
else
printf("\nNot a valid identifier");
while(a[i]!='\0')
{
if(!isdigit(a[i])&&!isalpha(a[i]))
{
flag=0;
break;
}
i++;
}
if(flag==1)
printf("\nValid identifier");
getch();
}

OUTPUT:-

10 | P a g e
Experiment No. 5
AIM:- Write a C program to simulate lexical analyzer for validating operators.

DESCRIPTION:

CODE:-

#include<stdio.h>
void main()
{
char s[5];
printf("\nEnter any operator: ");
gets(s);
switch(s[0]){
case'>': if(s[1]=='=')
printf("\nGreater than or equal");
else
printf("\nGreater than");
break;
case'<': if(s[1]=='=')
printf("\nLess than or equal");
else
printf("\nLess than");
break;
case'=': if(s[1]=='=')
printf("\nEqual to");
else
printf("\nAssignment");
break;
case'!': if(s[1]=='=')
printf("\nNot Equal");
else
printf("\nBit Not");
break;
case'&': if(s[1]=='&')
printf("\nLogical AND");
else
printf("\n Bitwise AND");
break;
case'|': if(s[1]=='|')
printf("\nLogical OR");
else
printf("\nBitwise OR");
break;
case'+': printf("\nAddition");
break;
case'-': printf("\nSubstraction");
break;

11 | P a g e
case'*': printf("\nMultiplication");
break;
case'/': printf("\nDivision");
break;
case'%': printf("Modulus");
break;
default: printf("\nNot a operator");
}}

OUTPUT:-

12 | P a g e
Experiment No. 6
AIM: - Implement the lexical analyzer using JLex, flex or other lexical analyzer generating tools

DESCRIPTION:

CODE:-

#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>
int main()
{
FILE *f1;
char c,str[10];
int lineno=1,num=0,i=0;
printf("\nEnter the c program\n");
f1=fopen("input.txt","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input.txt","r");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
num=c-48;
c=getc(f1);
while(isdigit(c))
{
num=num*10+(c-48);
c=getc(f1);
}
printf("%d is a number \n",num);
ungetc(c,f1);
}
else if(isalpha(c))
{
str[i++]=c;
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
str[i++]=c;
c=getc(f1);
}
str[i++]='\0';
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||

13 | P a g e
strcmp("double",str)==0||strcmp("static",str)==0|
strcmp("switch",str)==0||strcmp("case",str)==0)
printf("%s is a keyword\n",str);
else
printf("%s is a identifier\n",str);
ungetc(c,f1);
i=0;
}
else if(c==' '||c=='\t')
printf("\n");
else if(c=='\n')
lineno++;
else
printf("%c is a special symbol\n",c);
}
printf("Total no. of lines are: %d\n",lineno);
fclose(f1);
getch();
return 0;
}
OUTPUT:-

14 | P a g e
Experiment No. 7
AIM: - Write a C program for implementing the functionalities of predictive parser for the mini
language specified in Note 1.

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<string.h>
char prol[7][10]={"S","A","A","B","B","C","C"};
char pror[7][10]={"A","Bb","Cd","aB","@","Cc","@"};
char prod[7][10]={"S->A","A->Bb","A->Cd","B->aB","B->@","C->Cc","C>@"};
char first[7][10]={"abcd","ab","cd","a@","@","c@","@"}; char
follow[7][10]={"$","$","$","a$","b$","c$","d$"};
char table[5][6][10];
int numr(char c)
{
switch(c){
case 'S': return 0;
case 'A': return 1;
case 'B': return 2;
case 'C': return 3;
case 'a': return 0;
case 'b': return 1;
case 'c': return 2;
case 'd': return 3;
case '$': return 4;
}
return(2);
}
void main()
{
int i,j,k;
for(i=0;i<5;i++)
for(j=0;j<6;j++)
strcpy(table[i][j]," ");
printf("\nThe following is the predictive parsing table for the following
grammar:\n");
for(i=0;i<7;i++)
printf("%s\n",prod[i]);
printf("\nPredictive parsing table is\n");
fflush(stdin);
for(i=0;i<7;i++){
k=strlen(first[i]);
for(j=0;j<10;j++)
if(first[i][j]!='@')
strcpy(table[numr(prol[i][0])+1][numr(first[i][j])+1],prod[i]);

15 | P a g e
}
for(i=0;i<7;i++){
if(strlen(pror[i])==1)
{
if(pror[i][0]=='@')
{
k=strlen(follow[i]);
for(j=0;j<k;j++)
strcpy(table[numr(prol[i][0])+1][numr(follow[i][j])+1],prod[i]);
}
}
}
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");
strcpy(table[0][2],"b");
strcpy(table[0][3],"c");
strcpy(table[0][4],"d");
strcpy(table[0][5],"$");
strcpy(table[1][0],"S");
strcpy(table[2][0],"A");
strcpy(table[3][0],"B");
strcpy(table[4][0],"C");
printf("\n--------------------------------------------------------\n");
for(i=0;i<5;i++)
for(j=0;j<6;j++){
printf("%-10s",table[i][j]);
if(j==5)
printf("\n--------------------------------------------------------\n");
}
}

OUTPUT:-

16 | P a g e
Experiment No. 8a
AIM: - Write a C program for constructing of LL (1) parsing.

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<conio.h>
#include<string.h>
char s[20],stack[20];
void main()
{
char m[5][6][3]={"tb"," "," ","tb"," "," "," ","+tb"," "," ","n","n","fc"," "," ","fc"," "," ","
","n","*fc"," a","n","n","i"," "," ","(e)"," "," "};
int size[5][6]={2,0,0,2,0,0,0,3,0,0,1,1,2,0,0,2,0,0,0,1,3,0,1,1,1,0,0,3,0,0};
int i,j,k,n,str1,str2;
printf("\n Enter the input string: ");
scanf("%s",s);
strcat(s,"$");
n=strlen(s);
stack[0]='$';
stack[1]='e';
i=1;
j=0;
printf("\nStack Input\n");
printf("__________________\n");
while((stack[i]!='$')&&(s[j]!='$'))
{
if(stack[i]==s[j]){
i--;
j++;
}
switch(stack[i]){
case 'e': str1=0;
break;
case 'b': str1=1;
break;
case 't': str1=2;
break;
case 'c': str1=3;
break;
case 'f': str1=4;
break;
}
switch(s[j])
{
case 'i': str2=0;

17 | P a g e
break;
case '+': str2=1;
break;
case '*': str2=2;
break;
case '(': str2=3;
break;
case ')': str2=4;
break;
case '$': str2=5;
break}
if(m[str1][str2][0]=='\0'){
printf("\nERROR");
exit(0);}
else if(m[str1][str2][0]=='n')
i--;
else if(m[str1][str2][0]=='i')
stack[i]='i';
else
{
for(k=size[str1][str2]-1;k>=0;k--){
stack[i]=m[str1][str2][k];
i++;
}
i--;
}
for(k=0;k<=i;k++)
printf(" %c",stack[k]);
printf(" ");
for(k=j;k<=n;k++)
printf("%c",s[k]);
printf(" \n ");
}
printf("\nSUCCESS");
getch();
}

OUTPUT:-

18 | P a g e
19 | P a g e
Experiment No. 8b
AIM:- Construction of recursive descent parsing for the following grammar
E->TE'
E'->+TE/@ "@ represents null character"
T->FT'
T`->*FT'/@
F->(E)/ID
DESCRIPTION:
CODE:-

#include<stdio.h>
#include<conio.h>
#include<string.h>
char input[100];
int i,l;
void 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:");
gets(input);
if(E())
{
if(input[i+1]=='\0')
printf("\nString is accepted");
else
printf("\nString is not accepted");
}
else
printf("\nString not accepted");
getch();
}
E()
{
if(T())
{
if(EP())
return(1);
else
return(0);
}
else
return(0);
}
EP()
{
if(input[i]=='+')
20 | P a g e
{
i++;
if(T())
{
if(EP())
return(1);
else
return(0);
}
else
return(0);
}
else
return(1);
}
T(){
if(F())
{
if(TP())
return(1);
else
return(0);
}
else
return(0);
}
TP(){
if(input[i]=='*')
{
i++;
if(F()){
if(TP())
return(1);
else
return(0);
}
else
return(0);
}
else
return(1);
}
F(){
if(input[i]=='(')
{
i++;
if(E())
{
if(input[i]==')'){

21 | P a g e
i++;
return(1);
}
else
return(0);
}
else
return(0);
}
else if(input[i]>='a'&&input[i]<='z'||input[i]>='A'&&input[i]<='Z')
{
i++;
return(1);
}
else
return(0);
}

OUTPUT:-

22 | P a g e
Experiment No. 9
AIM: - Write a program to Design LALR Bottom up Parser.

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void push(char *,int *,char);
char stacktop(char *);
void isproduct(char,char);
int ister(char);
int isnter(char);
int isstate(char);
void error();
void isreduce(char,char); char pop(char *,int *);
void printt(char *,int *,char [],int);
void rep(char [],int);
struct action{
char row[6][5];};
const struct action A[12]={
{"sf","emp","emp","se","emp","emp"},{"emp","sg","emp","emp","emp","acc"},
{"emp","rc","sh","emp","rc","rc"},{"emp","re","re","emp","re","re"},
{"sf","emp","emp","se","emp","emp"},{"emp","rg","rg","emp","rg","rg"},
{"sf","emp","emp","se","emp","emp"},{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","sl","emp"},{"emp","rb","sh","emp","rb","rb"},
{"emp","rb","rd","emp","rd","rd"},{"emp","rf","rf","emp","rf","rf"}};
struct gotol
{
char r[3][4];
};
const struct gotol G[12]={
{"b","c","d"},{"emp","emp","emp"},{"emp","emp","emp"},{"emp","emp","emp"},
{"i","c","d"},{"emp","emp","emp"},{"emp","j","d"},{"emp","emp","k"},{"emp","emp
","emp"},{"emp","emp","emp"},};
char ter[6]={'i','+','*',')','(','$'};
char nter[3]={'E','T','F'};
char states[12]={'a','b','c','d','e','f','g','h','m','j','k','l'};
char stack[100];
int top=-1;
char temp[10];
struct grammar{
char left;
char right[5];
};
const struct grammar rl[6]={
{'E',"e+T"},{'E',"T"},{'T',"T*F"},{'T',"F"},{'F',"(E)"},{'F',"i"},};

23 | P a g e
void main()
{
char inp[80],x,p,dl[80],y,bl='a';
int i=0,j,k,l,n,m,c,len;
printf(" Enter the input :");
scanf("%s",inp);
len=strlen(inp);
inp[len]='$';
inp[len+1]='\0';
push(stack,&top,bl);
printf("\nStack \t\t\t Input");
printt(stack,&top,inp,i);
do{
x=inp[i];
p=stacktop(stack);
isproduct(x,p);
if(strcmp(temp,"emp")==0)
error();
if(strcmp(temp,"acc")==0)
break;
else{
if(temp[0]=='s')
{
push(stack,&top,inp[i]);
push(stack,&top,temp[1]);
i++;
}
else
{
if(temp[0]=='r')
{
j=isstate(temp[1]);
strcpy(temp,rl[j-2].right);
dl[0]=rl[j-2].left;
dl[1]='\0';
n=strlen(temp);
for(k=0;k<2*n;k++)
pop(stack,&top);
for(m=0;dl[m]!='\0';m++)
push(stack,&top,dl[m]);
l=top; y=stack[l-1];
isreduce(y,dl[0]);
for(m=0;temp[m]!='\0';m++)
push(stack,&top,temp[m]);
}
}
}
printt(stack,&top,inp,i);
}
while(inp[i]!='\0');
if(strcmp(temp,"acc")==0)

24 | P a g e
printf(" \n Input Accepted");
else
printf(" \n Input Not Accepted ");
}
void push(char *s,int *sp,char item){
if(*sp==100)
printf(" Stack is Full ");
else{
*sp=*sp+1;
s[*sp]=item;
}}
char stacktop(char *s){
char i; i=s[top];
return i;
}
void isproduct(char x,char p){
int k,l; k=ister(x);
l=isstate(p);
strcpy(temp,A[l-1].row[k-1]);
}
int ister(char x){
int i; for(i=0;i<6;i++)
if(x==ter[i])
return i+1;
return 0;
}
int isnter(char x){
int i;
for(i=0;i<3;i++)
if(x==nter[i])
return i+1;
return 0;
}
int isstate(char p){
int i;
for(i=0;i<12;i++)
if(p==states[i]){
return i+1;}
return 0;
}
void error(){
printf(" Error in the input ");
exit(0);
}
void isreduce(char x,char p){
int k,l;
k=isstate(x);
l=isnter(p);
strcpy(temp,G[k-1].r[l-1]);
}
char pop(char *s,int *sp){

25 | P a g e
char item;
if(*sp==-1)
printf(" Stack is Empty ");
else
item=s[*sp];
*sp=*sp-1;
return item;
}
void printt(char *t,int *p,char inp[],int i){
int r; printf("\n");
for(r=0;r<=*p;r++)
rep(t,r);
printf("\t\t\t");
for(r=i;inp[r]!='\0';r++)
printf("%c",inp[r]);
}
void rep(char t[],int r){
char c;
c=t[r];
switch(c){
case 'a': printf("0");
break;
case 'b': printf("1");
break;
case 'c': printf("2");
break;
case 'd': printf("3");
break;
case 'e': printf("4");
break;
case 'f': printf("5");
break;
case 'g': printf("6");
break;
case 'h': printf("7");
break;
case 'm': printf("8");
break;
case 'j': printf("9");
break;
case 'k': printf("10");
break;
case 'l': printf("11");
break;
default :printf("%c",t[r]);
break;
}
}

OUTPUT:-

26 | P a g e
27 | P a g e
Experiment No. 10a
AIM: - Write a C program to implement operator precedence parsing.

DESCRIPTION:

CODE:-

#include<stdio.h>
#include<string.h>
char str[50],opstr[75];
int f[2][9]={2,3,4,4,4,0,6,6,0,1,1,3,3,5,5,0,5,0};
int col,col1,col2;
char c;
swt(){
switch(c){
case'+':col=0;break;
case'-':col=1;break;
case'*':col=2;break;
case'/':col=3;break;
case'^':col=4;break;
case'(':col=5;break;
case')':col=6;break;
case'd':col=7;break;
case'$':col=8;break;
default:printf("\nTERMINAL MISSMATCH\n");
exit(1);
break;}
}
main(){
int i=0,j=0,col1,cn,k=0;
int t1=0,foundg=0;
char temp[20];
printf("\nEnter arithmetic expression:");
scanf("%s",&str);
while(str[i]!='\0')
i++;
str[i]='$';
str[++i]='\0';
printf("%s\n",str);
come:
i=0;
opstr[0]='$';
j=1;
c='$';
swt();
col1=col;
c=str[i];
swt();
col2=col;
if(f[1][col1]>f[2][col2]){

28 | P a g e
opstr[j]='>';
j++;}
else if(f[1][col1]<f[2][col2]){
opstr[j]='<';
j++;}
else{
opstr[j]='=';j++;}
while(str[i]!='$'){c=str[i];
swt();
col1=col;
c=str[++i];
swt();
col2=col;
opstr[j]=str[--i];
j++;
if(f[0][col1]>f[1][col2]){
opstr[j]='>';
j++;}
else if(f[0][col1]<f[1][col2]){
opstr[j]='<';
j++;}
else{
opstr[j]='=';j++;}
i++;
}
opstr[j]='$';
opstr[++j]='\0';
printf("\nPrecedence Input:%s\n",opstr);
i=0;
j=0;
while(opstr[i]!='\0'){
foundg=0;
while(foundg!=1){
if(opstr[i]=='\0')goto redone;
if(opstr[i]=='>')foundg=1;
t1=i;
i++;}
if(foundg==1)
for(i=t1;i>0;i--)
if(opstr[i]=='<')break;
if(i==0){
printf("\nERROR\n");
exit(1);}
cn=i;
j=0;
i=t1+1;
while(opstr[i]!='\0'){
temp[j]=opstr[i];
j++;i++;}
temp[j]='\0';
opstr[cn]='E';

29 | P a g e
opstr[++cn]='\0';
strcat(opstr,temp);
printf("\n%s",opstr);
i=1;}
redone:k=0;
while(opstr[k]!='\0'){
k++;
if(opstr[k]=='<'){
printf("\nError");
exit(1);}}
if((opstr[0]=='$')&&(opstr[2]=='$'))
goto sue;
i=1;
while(opstr[i]!='\0'){
c=opstr[i];
if(c=='+'||c=='*'||c=='/'||c=='$'){
temp[j]=c;j++;}
i++;}
temp[j]='\0';
strcpy(str,temp);
goto come;
sue:
printf("\n success");
return 0;}

OUTPUT:-

30 | P a g e
Experiment No. 10b
AIM: - Write a C program to implement Program semantic rules to calculate the expression that
takes an expression with digits, + and * and computes the value.

DESCRIPTION:

CODE:-

cal.l
%{
#include<stdio.h>
#include<math.h>
#include"y.tab.h"
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval=atof(yytext);
return NUMBER;}
MEM {return MEM;}
[\t];
\$ {return 0;}
\n {return yytext[0];}
. {return yytext[0];}
%%
cal.y
{
#include<stdio.h>
#include<math.h>
double memvar;
%}
%union
{
double dval;
}
%token<dval> NUMBER
%token<dval> MEM
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%type<dval> expression
%%
start:statement '\n'
|start statement '\n'
statement:MEM '=' expression {memvar=$3;}
|expression {printf("Result=%g\n",$1);}
;
expression:expression'+'expression {$$=$1+$3;}
|expression'-'expression {$$=$1-$3;}
|expression'*'expression {$$=$1*$3;}
|expression'/'expression {if($3==0)
yyerror("divide by zero");

31 | P a g e
else
$$=$1/$3;
};
expression:'-'expression %prec UMINUS {$$= -$2;}
|'('expression')' {$$=$2;}
|NUMBER {$$=$1;}
|MEM {$$=memvar;};
%%
int main(void)
{
printf("Enter the expression:");
yyparse();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
int yyerror(char *error)
{
printf("%s\n",error);
return 0;
}

OUTPUT:-

32 | P a g e

You might also like