0% found this document useful (0 votes)
81 views15 pages

Compiler Design Code Examples

The document provides code examples for lexical analysis and parsing in C language. It includes 6 code snippets: 1. Lexical analyzers (lex) and parsers (yacc) for arithmetic expressions. 2. Lexical analyzer and parser for strings containing 'a' and 'b'. 3. Predictive parsing table generator and parser for a sample grammar. 4. Shift-reduce parser for arithmetic expressions. 5. Code generator that takes an expression in infix form and generates assembly code. 6. Lexical analyzer that counts comments and identifiers/tokens in a C program.

Uploaded by

mukul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views15 pages

Compiler Design Code Examples

The document provides code examples for lexical analysis and parsing in C language. It includes 6 code snippets: 1. Lexical analyzers (lex) and parsers (yacc) for arithmetic expressions. 2. Lexical analyzer and parser for strings containing 'a' and 'b'. 3. Predictive parsing table generator and parser for a sample grammar. 4. Shift-reduce parser for arithmetic expressions. 5. Code generator that takes an expression in infix form and generates assembly code. 6. Lexical analyzer that counts comments and identifiers/tokens in a C program.

Uploaded by

mukul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1a.

lex
%{
#include<stdio.h>
int op=0,id=0,v=0;
%}
%%
[0-9]+ {id++;}
[\+\-\*\/] {op++;}
[(] {v++;}
[)] {v--;}
.|\n {;}
%%
int main()
{
printf("Enter an expression\n");
yylex();
if(id==op+1 && v==0)
{
printf("Its a valid expression\n");
printf("Operators= %d Identifiers= %d\n",op,id);
}
else
printf("Invalid expression\n");
return;
}
Output: lex 1a.lex
gcc lex.yy.c –ll
./a.out

1b.lex
%{
#include "y.tab.h"
extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;}
[\+\-\*\/] {return yytext[0];}
[)] {return yytext[0];}
[(] {return yytext[0];}
. {;}
\n {return 0;}
%%

1b.y
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token num
%left '+' '-'
%left '*' '/'
%%
input:exp {printf("%d\n",$$);exit(0);}
exp:exp'+'exp {$$=$1+$3;}
|exp'-'exp{$$=$1-$3;}
|exp'*'exp{$$=$1*$3;}
|exp'/'exp { if($3==0){printf("Divide by Zero\n");exit(0);}
else
$$=$1/$3;}
|'('exp')'{$$=$2;}
|num{$$=$1;};
%%
int yyerror()
{
printf("error");
exit(0);
}
int main()
{
printf("enter an expression\n");
yyparse();
}
Output: lex 1b.lex
yacc –d 1.b
gcc lex.yy.c y.tab.h –ll
./a.out

2.lex
%{
#include "y.tab.h"
%}
%%
a {return A;}
b {return B;}
. {return 0;}
[\n] { return '\n';}
%%

2.y
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token A B
%%
input:s'\n' {printf("successful grammar\n");exit(0);}
s: A s1 B| B
s1: ;| A s1
%%
int main()
{
printf("enter a string\n");
yyparse();
}
int yyerror()
{
printf("error\n");
exit(0);
}
Output: lex 2.lex
yacc –d 2.y
gcc lex.yy.c y.tab.c –ll
./a.out

3.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char prod[3][10]={"A->aBa","B->bB","B->@"};
char first[3][10]={"a","b","@"};
char follow[3][10]={"$","a","a"};
char table[3][4][10];
char input[10];
int top=-1;
char stack[25];
char curp[20];
push(char item)
{
stack[++top]=item;
}
pop()
{
top=top-1;
}
display()
{
int i;
for(i=top;i>=0;i--)
printf("%c",stack[i]);
}
numr(char c)
{
switch(c)
{
case 'A': return 1;
case 'B': return 2;
case 'a': return 1;
case 'b': return 2;
case '@': return 3;
}
return(1);
}
int main()
{
char c;
int i,j,k,n;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
strcpy(table[i][j],"e");
printf("\n Grammar:\n");
for(i=0;i<3;i++)
printf("%s\n",prod[i]);
printf("\nfirst= {%s,%s,%s}",first[0],first[1],first[2]);
printf("\nfollow ={%s %s}\n",follow[0],follow[1]);
printf("\nPredictive parsing table for the given grammar\n");
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");
strcpy(table[0][2],"b");
strcpy(table[0][3],"$");
strcpy(table[1][0],"A");
strcpy(table[2][0],"B");
for(i=0;i<3;i++)
{
k=strlen(first[i]);
for(j=0;j<k;j++)
if(first[i][j]!='@')
strcpy(table[numr(prod[i][0])][numr(first[i][j])],prod[i]);
else

strcpy(table[numr(prod[i][0])][numr(follow[i][j])],prod[i]);
}
printf("\n--------------------------------------------------------\n");
for(i=0;i<3;i++)
for(j=0;j<4;j++)
{
printf("%-10s",table[i][j]);
if(j==3)
printf("\n--------------------------------------------------------\n");
}
printf("enter the input string terminated with $ to parse :- ");
scanf("%s",input);
for(i=0;input[i]!='\0';i++)
if((input[i]!='a')&&(input[i]!='b')&&(input[i]!='$'))
{
printf("invalid string");
exit(0);
}
if(input[i-1]!='$')
{
printf("\n\nInput String Entered Without End marker $");
exit(0);
}
push('$');
push('A');
i=0;
printf("\n\n");
printf(" stack\t Input \taction ");
printf("\n--------------------------------------------------------\n");
while(input[i]!='$' && stack[top]!='$')
{
display();
printf("\t\t%s\t ",(input+i));
if (stack[top]==input[i])
{
printf("\tmatched %c\n",input[i]);
pop();
i++;
}
else
{
if(stack[top]>=65 && stack[top]<92)
{
strcpy(curp,table[numr(stack[top])][numr(input[i])]);
if(!(strcmp(curp,"e")))
{
printf("\n invalid string- Rejected\n");
exit(0);
}
else
{
printf(" \tapply production %s\n",curp);
if(curp[3]=='@')
pop();
else
{
pop();
n=strlen(curp);
for(j=n-1;j>=3;j--)
push(curp[j]);
}
}
}
}
}
display();
printf("\t\t%s\t ",(input+i));
printf("\n--------------------------------------------------------\n");
if(stack[top]=='$' && input[i]=='$' )
{
printf("\n valid string - Accepted\n");
}
else
{
printf("\ninvalid string- Rejected\n");
}
}
4.c
#include<stdio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
void main()
{
puts("GRAMMAR is E->E+E \n E->E*E \n E->(E) \n E->id");
puts("enter input string ");
gets(a);
c=strlen(a);
strcpy(act,"SHIFT->");
puts("stack \t input \t action");
for(k=0,i=0; j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
}
else

{
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%ssymbols",stk,a,act);
check();
}
}

}
void check()
{
strcpy(ac,"REDUCE TO E");
for(z=0; z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
j++;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='*' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';

printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
}
5.c
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char op[2],arg1[5],arg2[5],result[5];

void main()
{
FILE *fp1, *fp2;
fp1=fopen("input.txt","r");
fp2=fopen("output.txt","w");
while(!feof(fp1))
{
fscanf(fp1,"%s%s%s%s",result,arg1,op,arg2);
if(strcmp(op,"+")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nADD R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}

if(strcmp(op,"*")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nMul R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"-")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nSUB R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}

if(strcmp(op,"=")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nMOV %s,R0",result);
}
}
fclose(fp1);
fclose(fp2);
getchar();
}

6a.lex
%{
#include<stdio.h>
int c=0;
%}
%%
[/*].*["\n"].*[*/] {c++;}
[//].*[^"\n"] {c++;}
[a-zA-Z0-9] {fprintf(yyout,"%s",yytext);}
%%
int main(int argc,char *argv[])
{
yyin=fopen(argv[1],"r");
yyout=fopen(argv[2],"w");
yylex();
printf("the number of commented lines is %d",c);
return;
}

6b.lex
%{
#include <stdio.h>
#include "y.tab.h"
extern yylval;
%}
%%
[\t] {;}
[+|-|*|/|=|<|>] {printf("operator is %s\n",yytext);return OP;}
[0-9]+ {yylval = atoi(yytext); printf("numbers is %d\n",yylval); return DIGIT;}
int|char|bool|float|void|for|do|while|if|else|return|void {printf("keyword is %s\n",yytext);
return KEY;}
["].*["] {printf("String");}
[a-zA-Z0-9]+ {printf("identifier is %s\n",yytext);return ID;}
. {;}
%%
6b.y
%{
#include <stdio.h>
#include <stdlib.h>
int id=0, dig=0, key=0, op=0;
%}
%token DIGIT ID KEY OP
%%
input:DIGIT input { dig++; }
| ID input { id++; }
| KEY input { key++; }
| OP input {op++;}
| DIGIT { dig++; }
| ID { id++; }
| KEY { key++; }
| OP { op++;};
%%
#include <stdio.h>
extern int yylex();
extern int yyparse();
extern FILE *yyin;
main() {
FILE *myfile = fopen("fn.c", "r");
if (!myfile)
{printf("I can't open fn.c!");
return -1;
}
yyin = myfile;
do {
yyparse();
} while (!feof(yyin));
printf("numbers = %d\nKeywords = %d\nIdentifiers = %d\noperators = %d\n",
dig, key,id, op);
}
int yyerror()
{printf("EEK, parse error! Message: ");
exit(-1);
}
6aOutput: lex 6a.lex
gcc lex.yy.c –ll
./a.out f1.c f2.c
Cat f2.c
6bOutput: lex 6b.lex
yacc –d 6b.y
gcc lex.yy.c y.tab.c –ll
./a.out
7.c

#include<stdio.h>
int main()
{
int choice, wait_time=0,turnaround_time=0, n, at[10], bt[10], rt[10], count,
time_quantum,i,j,time,remain,flag=0, smallest, c;
double end;
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d:",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("ENTER YOUR CHOICE?\n\t1. ROUND ROBIN\n\t2. SRT\n\t3. EXIT");
scanf("%d", &choice);
if(choice==1)
{
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-
bt[count]);
wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count];
flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
}
else if(choice==2)
{
bt[9]=9999;
for(time=0;c!=n;time++)
{
smallest=9;
for(count=0;count<n;count++)
{
if(at[count]<=time && bt[count]<bt[smallest] && bt[count]>0 )
smallest=count;
}
bt[smallest]--;
if(bt[smallest]==0)
{
c++;
end=time+1;
wait_time= wait_time + end - at[smallest] - rt[smallest];
turnaround_time= turnaround_time + end - at[smallest];
}
}
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
}

8.c

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int alloc[10][10],max[10][10],need[10][10];
int avail[10],work[10],p,r,j,i,v=0;
bool finish[10];
bool check(int i)
{
for(j=0;j<r;j++)
{
if(need[i][j]>work[j])
return false;
}
return true;
}
int main()
{
printf("Enter the number of processes and resources\n");
scanf("%d %d",&p,&r);
int seq[p],i,k,j;
bool allocated=false;
printf("Enter the allocation values\n");

for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&alloc[i][j]);
printf("Enter the max values\n");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
for(i=0;i<p;i++)
for(j=0;j<r;j++)
need[i][j]=max[i][j]-alloc[i][j];
printf("Enter the available matrix\n");
for(i=0;i<r;i++)
{
scanf("%d",&avail[i]);
work[i]=avail[i];
}
//Safety algorithm
for(i=0;i<p;i++)
{
finish[i]=false;
}
while(v<p)
{
for(i=0;i<p;i++)
{
if(!finish[i] && check(i))
{
for(k=0;k<r;k++)
{
work[k]=work[k]+alloc[i][k];
}
allocated=finish[i]=true;
seq[v]=i;
v++;
}
}
if(!allocated)
break;
}
for(i=0;i<p;i++)
{
if(finish[i]==false)
{
printf("All processes not safely allocated\n");
exit(0);
}
}
printf("Processes safely allocated with the sequence \n");
for(i=0;i<v;i++)
printf("%d\t",seq[i]);
}
9.c

#include<stdio.h>
#include<stdlib.h>
void FIFO(char [ ],char [ ],int,int);
void lru(char [ ],char [ ],int,int);
int main()
{
int ch,YN=1,i,l,f;
char F[10],s[25];
printf("\n\n\tEnter the no of empty frames: ");
scanf("%d",&f);
printf("\n\n\tEnter the length of the string: ");
scanf("%d",&l);
printf("\n\n\tEnter the string: ");
scanf("%s",s);
for(i=0;i<f;i++)
F[i]=-1;
printf("\n\n\t1:FIFO\n\n\t2:LRU \n\n\t4:EXIT");
printf("\n\n\tEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
for(i=0;i<f;i++)
{
F[i]=-1;
}
FIFO(s,F,l,f);
break;
case 2:
for(i=0;i<f;i++)
{
F[i]=-1;
}
lru(s,F,l,f);
break;
case 4:
exit(0);
}
}
//FIFO
void FIFO(char s[],char F[],int l,int f)
{
int i,j=0,k,flag=0,cnt=0;
printf("\n\tPAGE\t FRAMES\t FAULTS");
for(i=0;i<l;i++)
{
for(k=0;k<f;k++)
{
if(F[k]==s[i])
flag=1;
}
if(flag==0)
{
printf("\n\t%c\t",s[i]);
F[j]=s[i];
j++;
for(k=0;k<f;k++)
{
printf(" %c",F[k]);
}
printf("\tPage-fault%d",cnt);
cnt++;
}
else
{
flag=0;
printf("\n\t%c\t",s[i]);
for(k=0;k<f;k++)
{
printf(" %c",F[k]);
}
printf("\tNo page-fault");
}
if(j==f)
j=0;
}
}
//LRU
void lru(char s[],char F[],int l,int f)
{
int i,j=0,k,m,flag=0,cnt=0,top=0;
printf("\n\tPAGE\t FRAMES\t FAULTS");
for(i=0;i<l;i++)
{
for(k=0;k<f;k++)
{
if(F[k]==s[i])
{
flag=1;
break;
}
}
printf("\n\t%c\t",s[i]);
if(j!=f && flag!=1)
{
F[top]=s[i];
j++;
if(j!=f)
top++;
}
else
{
if(flag!=1)
{
for(k=0;k<top;k++)
{
F[k]=F[k+1];
}
F[top]=s[i];
}
if(flag==1)
{
for(m=k;m<top;m++)
{
F[m]=F[m+1];
}
F[top]=s[i];
}
}
for(k=0;k<f;k++)
{
printf(" %c",F[k]);
}
if(flag==0)
{
printf("\tPage-fault%d",cnt);
cnt++;
}
else
printf("\tNo page fault");
flag=0;
}
}

You might also like