Sei sulla pagina 1di 47

GKM College of engineering and technology

ht

tp

://

cs

et

ub

e.c

o.

nr

Allapakam-mappedu road, gkm nagar, Chennai.

Principles of compiler and design Lab Manual

http://csetube.co.nr/

IMPLEMENTATION OF A LEXICAL ANALYZER IN C

AIM:
To write and execute a C program to implement the lexical analyzer.

ALGORITHM:

nr

o.

e.c

ub

et

cs

://
tp

Start the program.


Declare the file pointer and necessary variables.
Open the input file in the read mode.
Use the analyze function to analyze the input program and store the
identifiers, keywords and operator on idhd, keyhd, ophd respectively.
Stores the tokens in data structure linked lists.
Increment the line number of each token and its occurrences.
Using the show function print the linked lists in a tabular format.
Stop the program.

ht

http://csetube.co.nr/

nr
o.
e.c
ub
et
cs
://

ht

tp

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<malloc.h>
struct lineno
{
int ln;
struct lineno *next;
};
struct lx
{
char str[20];
struct lineno *next;
struct lx *down;
};
typedef struct lineno node;
typedef struct lx lex;
lex *keyhd,*ophd,*idhd;
FILE *fp;
char temp[20];
int line=1;
lex *getkeynode();
node *getlnode();
void analyze();
void add(lex *);
void show(lex *);
int main()
{
keyhd=getkeynode();
ophd=getkeynode();
idhd=getkeynode();
fp=fopen("inp.c","rt");
if(fp==NULL)
{
printf("No input file!!");
/*exit(1);*/
}
analyze();
printf("\n\t\tKeywords\n\n");
show(keyhd);
printf("\n\t\tIDENTIFIER\n\n");
show(idhd);
printf("\n\t\tOPERATORS\n\n");

PROGRAM

http://csetube.co.nr/

/
nr
o.
e.c

ht

tp

://

cs

et

ub

show(ophd);
free(ophd);
free(idhd);
free(keyhd);
return 0;
}
lex *getkeynode()
{
lex *temp;
temp=(lex*)malloc(sizeof(struct lx));
temp->next=NULL;
temp->down=NULL;
return temp;
}
node *getlnode()
{
node *temp;
temp=(node*)malloc(sizeof(struct lineno));
temp->next=NULL;
return temp;
}
void analyze()
{
char ch;
int i,flag;
ch=fgetc(fp);
while(ch!=EOF)
{
if(ch=='\n')
{
ch=fgetc(fp);
line++;
continue;
}
if(isspace(ch))
{
ch=fgetc(fp);
continue;
}
if(ch== '/')
while((ch=fgetc(fp))!='/');
if(isalpha(ch))
{
i=0;
do
{

http://csetube.co.nr/

/
nr
o.
e.c
ub
et
cs
://
tp
ht

temp[i++]=ch;
ch=fgetc(fp);
}
while(isalpha(ch)||ch=='.');
fseek(fp,-1,1);
temp[i]='\0';
i=0;
flag=0;
while(strlen(key[i]))
{
if(strcmp(temp,key[i])==0)
{
add(keyhd);
flag=1;
break;
}
i++;
}
if(flag==0)
add(idhd);
}
else
{
temp[0]=ch;
temp[1]='\0';
add(ophd);
}
ch=fgetc(fp);
}
}
void add(lex *hd)
{
node *l,*m;
lex *q,*p=hd->down;
while(p)
{
if(strcmp(p->str,temp)==0)
break;
p=p->down;
}
if(p==NULL)
{
p=hd;
while(p->down)p=p->down;
q=getkeynode();
p->down=q;

http://csetube.co.nr/

/
nr
o.
e.c

ht

tp

://

cs

et

ub

strcpy(q->str,temp);
l=getlnode();
l->ln=line;
q->next=l;
}
else
{
m=getlnode();
l=p->next;
m->ln=line;
if(l==NULL)
p->next=m;
else
{
while(l->next)
l=l->next;
l->next=m;
}
}
}
void show(lex *hd)
{
lex *p=hd->down,*q;
node *l,*m;
int i=1,occ=0;
printf("\tTokens\t\tLineno\t\tOccurences\n\n");
while(p)
{
occ=1;
l=p->next;
printf("\t%s\t\t",p->str);
printf("%d",l->ln);
l=l->next;
while(l)
{
printf("%d",l->ln);
l=l->next;
occ++;
}
printf("\t\t%d",occ);
p=p->down;
printf("\n");
}
}

http://csetube.co.nr/

INPUTFILE:
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter the value of a& b");
scanf("%d%d",&a,&b);
c=a+b;
printf("%d",c);
}

o.

nr

OUTPUT:

ub

e.c

[3cse09@localhost ~]$ cc exp1.c


[3cse09@localhost ~]$ ./a.out

cs

1
1
2
2
4
5,8
6

://

include
stdio.h
void
main
int
printf
scanf

Occurences

tp

Lineno

1
1
1
1
1
2
1

ht

Tokens

et

KEYWORDS

IDENTIFIER
Tokens

Lineno

Occurences

a
b
c
Enter
the
value
of
d

4,5,6,7
4,5,6,7
4,7,8
5
5
5
5
6,6,8

4
4
3
1
1
1
1
3

http://csetube.co.nr/

OPERATORS
Occurences

nr

1
1
1
4
4
1
5
5
6
3
3
1
1
1

o.

1
1
1
2,5,6,8
2,5,6,8
3
4,4,6,6,8
4,5,6,7,8
5,5,6,6,8,8
5,6,6
6,6,8
7
7
9

ht

tp

://

cs

et

ub

#
<
>
(
)
{
,
;
"
&
%
=
+
}

Lineno

e.c

Tokens

RESULT:
Thus the implementation of lexical analyzer was successfully done.

http://csetube.co.nr/

IMPLEMENTATION OF A LEXICAL ANALYZER USING LEX


TOOL

AIM:
To implement the lexical analyzer using lex tool for a subset of C language.

nr

o.

e.c

ub

et

cs

://

tp

Start the program.


Declare necessary variables and creates token representation using
Regular.
Print the pre processor or directives, keywords by analysis of the input
program.
In the program check whether there are arguments.
Declare a file and open it as read mode.
Read the file and if any taken in source program matches with RE that all
returned as integer value.
Print the token identified using YYdex() function.
Stop the program.

ht

ALGORITHM:

http://csetube.co.nr/

PROGRAM:

ht

tp

://

cs

et

ub

e.c

o.

nr

%{
%}
identifier[a- zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto {printf("\n%s is a keyword",yytext);}
{identifier}\( {printf("\n function %s",yytext);}
\{ {printf("\nblock begins");}
\} {printf("\nblock ends");}
\( {printf("\n");ECHO;}
{identifier}(\[[0-9]*\])* {printf("\n%s is an identifier",yytext);}
\".*\" {printf("\n %s is a string ",yytext);}
[0-9]+ {printf("\n%s is a number",yytext);
}
\<= |
\>= |
\< |
\> |
\== {printf("\n %s is a relational operator",yytext);}
\= |
\+ |
\- |
\/ |
\& |
% {printf("\n %s is a operator",yytext);}
.|
\n;
%%
int main(int argc,char **argv)

http://csetube.co.nr/

ht

INPUT FILE:

tp

://

cs

et

ub

e.c

o.

nr

{
FILE *file;
file=fopen("inp.c","r");
if(!file)
{
printf("could not open the file!!!");
exit(0);
}
yyin=file;
yylex();
printf("\n\n");
return(0);
}
int yywrap()
{
return 1;
}

#include<stdio.h>
void main()
{
int a,b,c;
printf("enter the value for a,b");
scanf("%d%d",&a,&b)';
c=a+b;
printf("the value of c:%d",&c);
}

http://csetube.co.nr/

OUTPUT:

nr
o.
e.c

ht

tp

://

cs

et

ub

#include<stdio.h> is a preprocessor directive


void is a keyword
function main(
block begins
int is a keyword
a is an identifier
b is an identifier
c is an identifier
function printf(
"enter the value for a,b" is a string
function scanf(
"%d%d" is a string
& is a operator
a is an identifier
& is a operator
b is an identifier
c is an identifier
= is a operator
a is an identifier
+ is a operator
b is an identifier
function printf(
"the value of c:%d" is a string
& is a operator
c is an identifier
block ends

[3cse01@localhost ~]$ lex ex3.l


[3cse01@localhost ~]$ cc lex.yy.c
[3cse01@localhost ~]$ ./a.out

RESULT:
Thus the program to implement the lexical analyzer using lex tool for a subset of
C language was implemented and verified.

http://csetube.co.nr/

IMPLEMENTATION OF A RECURSIVE DESCENT PARSER


AIM:
To implement a recursive descent parser in a C program.
ALGORITHM:

ht

tp

://

cs

et

ub

e.c

o.

nr

Start the program.


Get the expression from the user and call the parser() function.
In lexer() get the input symbol and match with the look ahead
pointer and then return the token accordingly.
In E(), check whether the look ahead pointer is + or - else
return syntax error.
In T(),check whether the look ahead pointer is * or / else
return syntax error.
In F(),check whether the look ahead pointer is a member of any
identifier.
In main(), check if the current look ahead points to the token in
a given CFG it doesnt match the return syntax error.

http://csetube.co.nr/

nr
o.
e.c
ub
et
cs

ht

tp

://

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define DONE 260
#define NUM 257
#define ID 259
void E();
void T();
void F();
void parser();
int lexer();
void match(int);
void parsex();
int i=0,flag=9,lkahd;
char inp[75];
int cnt=-1;
int main()
{
int i=-1;
char c;
FILE *fp;
fp=fopen("ep1.text","rt");
while((c=fgetc(fp))!=EOF)
{
inp[i++]=c;
}
inp[i]=EOF;
parser();
}
int lexer()
{
int t;
while(1)
{
t=inp[cnt++];
if(t==' '||t=='\t'||t=='\n')
;
else if(t=='+'||t=='-'||t=='*'||t=='/')
{
printf("arithmetic operator %c\n",t);
return t;
}
else if(isdigit(t))
{

PROGRAM:

http://csetube.co.nr/

/
nr
o.
e.c
ub
et
cs
://
tp

ht

printf("\n number: %c\n",t);


return NUM;
}
else if(isalpha(t))
{
printf("\n identifier: %c\n",t);
return ID;
}
else if(t==EOF)
return DONE;
else
return t;
}}
void parser()
{
lkahd=lexer();
while(lkahd!=DONE)
{
E();
match(';');
}
if(lkahd==DONE)
parsex();
}
void match(int t)
{
if(lkahd==t)
lkahd=lexer();
else
return;
}
void F()
{
switch(lkahd)
{
case '(':
match('(');
E();
match(')');
break;
case NUM:
match(NUM);
break;
case ID:
match(ID);
break;

http://csetube.co.nr/

/
nr
o.
e.c
ub
et
cs
://
tp
ht

default:{
printf("syntax error");
flag=7;
}}}
void T()
{
int t;
F();
while(1)
{
switch(lkahd)
{
case '*':
t=lkahd;
match(lkahd);
F();
continue;
case '/':
t=lkahd;
match(lkahd);
F();
continue;
default:
return;
}}}
void E()
{
int t;
T();
while(1)
{
switch(lkahd)
{
case '+':
t=lkahd;
match(lkahd);
T();
continue;
case '-':
t=lkahd;
match(lkahd);
T();
continue;
default:
return;
}}}

http://csetube.co.nr/

void parsex()
{
if(flag!=7)
printf("parse seccessfull\n");
else
printf("parse successfull\n errors found\n");
exit(0);
}

INPUT FILE:
(a+b)*(c/d)-g;
1+5;
5-3;
a+2;

nr
o.
e.c
ub
et
cs
://

ht

tp

[3cse01@localhost ~]$ cc ex4.c


[3cse01@localhost ~]$ ./a.out
identifier: a
arithmetic operator +
identifier: b
arithmetic operator *
identifier: c
arithmetic operator /
identifier: d
arithmetic operator identifier: g
number: 1
arithmetic operator +
number: 5
number: 5
arithmetic operator number: 3
identifier: a
arithmetic operator +
number: 2
parse seccessfull

OUTPUT:

RESULT:
Thus the program to implement the recursive descent parser was implemented and
verified.

http://csetube.co.nr/

CONVERSION OF RE TO NFA

AIM:
To write and execute a C program to convert RE to NFA.

ALGORITHM:

nr

o.

e.c

ub

et

cs

://

tp

Start the program.


Get the RE and store it in RE.
Using a loop check whether the RE contains (re, [1], a) if so only a
function.
If re[i] contain b, then call on bfn.
Then check whether re[i] is * (or) /.
If there is * call star ().
If there is /then call or().
Continue the NFAs of all the component expression into single NFA and
print the corresponding RE.
Stop the program.

ht

http://csetube.co.nr/

PROGRAM:

ht

tp

://

cs

et

ub

e.c

o.

nr

#include<stdio.h>
#include<string.h>
char re[35];
int sta[20],fna[20],stb[20],fnb[20],ste[20],fne[20],cnt=0,cnta=0,cntb=0;
int cnte=0,tag=0,i=0,j=0,k=0,f=0,a=0,b=0,a1=0,b1=0;
void onlya(int sa,int fa)
{
sta[cnta]=sa;
fna[cnta]=fa;
cnta++;
}
void onlyb(int sa,int fa)
{
stb[cntb]=sa;
fnb[cntb]=fa;
cntb++;
}
void onlye(int sa,int fa)
{
ste[cnte]=sa;
fne[cnte]=fa;
cnte++;
}
void star()
{
int p=0;
if(re[i-1]!=')')
{
if(re[i-1]=='a')
{
onlye(fna[cnta-1],sta[cnta-1]);
onlye(sta[cnta-1],fna[cnta-1]);
}
if(re[i-1]=='b')
{
onlye(stb[cntb-1],fnb[cntb-1]);
onlye(fnb[cntb-1],stb[cntb-1]);
}}
else
{
j=i;
do
{
j--;

http://csetube.co.nr/

/
nr
o.
e.c
ub
et
cs
://
tp

ht

if(re[j]=='a')
a1++;
if(re[j]=='b')
b1++;
if(re[j]==')')
p++;
if(re[j]=='(')
p--;
}
while((re[j]!='(')||(p>0));
if((re[j+1]=='a')||(re[j+2]=='a'))
{
onlye(cnt,sta[cnta-a1]);
onlye(sta[cnta-a1],cnt);
}
if((re[j+1]=='b')||(re[j+2]=='b'))
{
onlye(cnt,stb[cntb-b1]);
onlye(stb[cntb-b1],cnt);
}}}
void or()
{
if((re[i-1]!='a')||(re[i-1]!='b'))
{
for(k=i-1;k>=0;k--)
{
if(re[k]=='a')
a++;
if(re[k]=='b')
b++;
if(re[k]=='(')
{
onlye(++cnt,cnta-a);
if(re[k+1]=='b')
onlye(++cnt,cntb-b);
}
}
if(re[i-1]=='(')
i++;
if(re[i+1]=='a')
{
i++;
f=cnt;
onlye(f,++cnt);
onlya(f,++cnt);
}

http://csetube.co.nr/

/
nr
o.
e.c
ub
et
cs
://

ht

tp

if(re[i+1]=='b')
{
i++;
f=cnt;
onlye(f,++cnt);
onlyb(f,++cnt);
}
}
else
{
if((re[i-1]=='a')&&(re[i+1]=='b'))
{
onlyb(sta[cnta-1],++cnt);
onlye(fna[cnta-1],++cnt);
onlye(fnb[cntb-1],cnt);
i++;
}
if((re[i-1]=='b')&&(re[i+1]=='a'))
{
onlya(stb[cntb-1],++cnt);
onlye(fnb[cntb-1],++cnt);
onlye(fna[cnta-1],cnt);
i++;
}}}
int main()
{
printf("Enter the expression:");
scanf("%s",re);
for(i=0;i<strlen(re);i++)
{
if(re[i]=='a')
{
f=cnt;
onlya(f,++cnt);
}
if(re[i]=='b')
{
f=cnt;
onlyb(f,++cnt);
}
if(re[i]=='*')
star();
if(re[i]=='|')
or();
}
printf("\n states\t|a\t|b\t|e\n");

http://csetube.co.nr/

tp

://

cs

et

ub

e.c

o.

nr

printf(".......................................");
while(tag<=cnt)
{
printf("\n");
printf("{%d}\t|",tag);
for(k=0;k<cnta;k++)
if(tag==sta[k])
printf("{%d}",fna[k]);
putchar('\t');
putchar('|');
for(k=0;k<=cntb;k++)
if(tag==stb[k])
printf("{%d}",fnb[k]);
putchar('\t');
putchar('|');
for(k=0;k<cnte;k++)
if(tag==ste[k])
printf("{%d}",fne[k]);
tag++;
printf("\n\t|\t|\t|");
}
putchar('\n');
return 0;
}

ht

OUTPUT:

[2cse54@localhost ~]$ ./a.out


Enter the expression:(ab)*
states |a |b
|e
.......................................
{0} |{1} |{0} |{2}
|
|
|
{1} |
|{2} |{2}
|
|
|
{2} |
|
|{0}{1}
|
|
|

RESULT:
Thus the program to convert RE to NFA was implemented and verified.

http://csetube.co.nr/

ANALYSIS OF SOURCE PROGRAM USING LEX AND YAC TOOL

AIM:
To write lex and yac program for implementation of syntax analyzer
using lex and yac tool.

nr

ALGORITHM:

ht

tp

://

cs

et

ub

e.c

o.

Start the program.


In lex program start lex specification with declararive section.
In translating rule section define data type identifier along with
their action.
In main function open the input file in read mode.
The key words, identifiers and data type are defined.
Stop the program.

http://csetube.co.nr/

nr
o.
e.c
ub
et
cs
://
tp
ht

%{
/*Definition Section*/
#include<stdio.h>
#include"y.tab.h"
//to keep track of errors
int lineno=1;
%}
identifier[a- zA-Z][a-zA-Z]*
number[0-9]+
%%
main|(1)return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float |
long return TYPE;
{identifier} return VAR;
{number} return NUM;
\< |
\> |
\<= |
\>= |
==return RELOP;
[:space:]+;
[\t]+;
\n lineno++;
.return yytext[0];
%%
int yywrap()
{
return 1;
}
Exp5.y:
%{
#include<stdio.h>
#include<string.h>
extern int lineno;
int errno=0;
%}

PROGRAM:

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

%token NUM VAR RELOP MAIN


%token IF ELSE WHILE TYPE
//define precedence and associativity of operators]
%left'-''+'
%left'*''/'
%%
PROGRAM:MAIN BLOCK
;
BLOCK:'{'CODE'}'
;
CODE:BLOCK
|STATEMENT CODE
|STATEMENT
;
STATEMENT:DECST';'
|DECST{printf("\n missing ';' lineno%d",lineno);errno++;}
|ASSIGNMENT';'
|ASSIGNMENT {printf("\nMissing ';' lineno%d",lineno);errno++;}
|CONDST
|WHILEST
;
DECST:TYPE VARLIST
;
VARLIST:VAR','VARLIST
|VAR
;
ASSIGNMENT:VAR'='EXPR
;
EXPR:EXPR'+'EXPR
|EXPR'-'EXPR
|EXPR'*'EXPR
|EXPR'/'EXPR
|'-'EXPR
|'('EXPR')'
|VAR
|NUM
;
CONDST:IFST
|IFST ELSEST
;
IFST:IF'('CONDITION')'
BLOCK
;
ELSEST:ELSE
BLOCK
;

http://csetube.co.nr/

e.c

o.

nr

CONDITION:VAR RELOP VAR


|VAR RELOP NUM
|VAR
|NUM
;
WHILEST:WHILELOOP
;
WHILELOOP:WHILE'('CONDITION')'
BLOCK
;
%%
#include"lex.yy.c"
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
fp=fopen(argv[1],"r");
yyin=fp;

ht

tp

://

cs

et

ub

while(!feof(yyin))
{
yyparse();
}
if(errno==0)
printf("\n no error found!! \n parsing successfull\n");
else
printf("\n%derrno(s) found!!",errno);
putchar('\n');
return 0;
}
yyerror()
{
printf("\n error on lineno:%d\n",lineno);
errno++;
}

http://csetube.co.nr/

://

cs

et

ub

e.c

o.

nr

Input:
main()
{
a=5;
b=4;
c=a+b;
if(a>b)
{
a=1;
}
else
{
c=2;
}
while(c==1)
{
a=1;
}
}

ht

tp

Output:
[2cse54@localhost]lex exp5.l
[2cse54@localhost]yacc -d exp5.y
[2cse54@localhost]cc y.tab.c -ll
No Errors Found!!
Parsing Sucessfull

RESULT:
Thus the program for implementation of a syntax analyzer using lex
and yac tools was successfully done.

http://csetube.co.nr/

ANALYSIS OF SOURCE PROGRAM USING LEX AND YAC TOOL

AIM:
To write lex and yac program for implementating calculator using lex
and yac tool.
ALGORITHM:

ht

tp

://

cs

et

ub

e.c

o.

nr

Start the program.


In lex program declare the identifier for log, cos, sin, tan and
memory.
Identify the identifier and return id to parser.
In yac program declare the possible symbol type which are the
tokens which are returned by lex.
Define precedence and associativity.
Define rule in cfg for non terminal.
In main() get the expression from user and print the output.
Stop the program.

http://csetube.co.nr/

PROGRAM:

ht

tp

://

cs

et

ub

e.c

o.

nr

%{
#include"y.tab.h"
#include<math.h>
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval=atof(yytext);return
NUMBER;}
log |
LOG {return LOG;}
In {return nLOG;}
sin |
SIN {return SINE;}
cos |
COS {return COS;}
tan |
TAN {return TAN;}
mem {return MEM;}
[\t];
\$ return 0;
\n|. return yytext[0];
%%
Exp6.y:
%{
double memvar;
%}
%union
{
double dval;
}
%token<dval>NUMBER
%token<dval>MEM
%token LOG SINE nLOG COS TAN
%left'-''+'
%left'*''/'
%right'^'
%left LOG SINE nLOG COS TAN
%nonassoc UMINUS
%type<dval>expression
%%
start:statement'\n'
|start statement'\n'
;
statement:MEM'='expression {memvar=$3;}
| expression{printf("Answer=%g\n",$1);}

http://csetube.co.nr/

/
nr

ht

tp

://

cs

et

ub

e.c

o.

;
expression:expression'+'expression {$$=$1+$3;}
| expression '-' expression {$$=$1-$3;}
| expression '*' expression {$$=$1*$3;}
| expression '/' expression
{
if($3==0)
yyerror("divide by zero");
else
$$=$1/$3;
}
|expression'^'expression {$$=pow($1,$3);}
;
expression:'-'expression %prec UMINUS{$$=-$2;}
|'('expression')'{$$=$2;}
|LOG expression {$$=log($2)/log(10);}
|nLOG expression {$$=log($2);}
|SINE expression {$$=sin($2*3.14/180);}
|COS expression {$$=cos($2*3.14/180);}
|TAN expression {$$=tan($2*3.14/180);}
|NUMBER {$$=$1;}
|MEM {$$=memvar;}
;
%%
main()
{
printf("Enter the expression");
yyparse();}
int yyerror(char *error)
{
printf("%s\n",error);}

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

Output:
[2cse54@localhost]$lex exp6.l
[2cse54@localhost]$yacc -d exp6.y
[2cse54@localhost]$cc lex.yy.c y.tab.c -ll -lm
[2cse54@localhost]$./a.out
Enter the expression:(5+2)*(3-1)/(2)
Answer=7
mem=cos45
sib45/mem
Answer=1

RESULT:
Thus the program for implementating calculating using lex and yac
tools was successfully done.

http://csetube.co.nr/

CONSTRUCTION OF TOP DOWN PARSING TABLE

AIM:
To write a c program that implement the construction of top-down parsing table.

ALGORITHM:
Start the program.

Initial get the number of terminals and non-terminals separately present in the
string from the user.

After entering terminals and non-terminals call function such that each terminal
with some non-terminals as the input gives out either or own terminal or no value.

Generate the table accordingly by the function called inside the program .

With the help of the table check the string whether it is valid or not.

Terminate the program.

ht

tp

://

cs

et

ub

e.c

o.

nr

http://csetube.co.nr/

PROGRAM:

ht

tp

://

cs

et

ub

e.c

o.

nr

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
int n,m,j,i,k,q,l,kl,ptr=0,x=0;
char nt[10],t[10],top[10][10][10],in[10],stack[10],temp[5],temp2[10];
void terminal(void);
void nonterminal(void);
void strrev(char *str);
int main()
{
int f,f1;
stack[ptr]='$';
printf("enter the no.of terminals");
scanf("%d",&m);
printf("enter the terminals\n");
printf("--------------------\n");
for(i=0;i<m;i++)
scanf("%s",&t[i]);
printf("enter the no.of non terminals");
scanf("%d",&n);
printf("enter the non terminals\n");
printf("---------------------\n");
for(i=0;i<n;i++)
scanf("%s",&nt[i]);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("enter the production for[%c][%c]::>",nt[i],t[j]);
scanf("%s",top[i][j]);
printf("------------------------\n");
for(j=0;j<m;j++)
printf("\t%c",t[j]);
printf("\n");
for(q=0;q<n;q++)
{
printf("\n");
printf("%c",nt[q]);
for(j=0;j<m;j++)
{
if(strcmp(top[q][j],"0")==0)
printf("\t- ");

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

else
printf("\t%c->%s",nt[q],top[q][j]);
}
}
printf("\nenter the string:");
scanf("%s",in);
l=strlen(in);
i=0;
stack[++ptr]=nt[0];
printf("\n stack\t\t input \t\taction\n");
printf("%s\t\t%s\t\t",stack,in);
do
{
k=kl=0;
if((in[i]==stack[ptr])&&(in[i]=='$')&&(stack[ptr]=='$'))
{
printf("\t \tvalid string");
exit(0);
}
else if((in[i]==stack[ptr])&&(in[i]!='$')&&(stack[ptr]!='$'))
{
printf("\t \ttop %c off the stack\n",stack[ptr]);
stack[ptr--]='\0';
for(f=0;f<=ptr;f++)
printf("%c",stack[f]);
printf("\t\t");
for(f=i+1;f<l;f++)
printf("%c",in[f]);
i++;
}
else
{
if(isupper(stack[ptr]))
{
nonterminal();
terminal();
if(strcmp(top[k][kl],"e")==0)
stack[ptr--]='\0';
else if(strcmp(top[k][kl],"0")==0)
{
printf("\t\tINVALID STRING");
exit(1);
}
else
{
strcpy(temp,top[k][kl]);

http://csetube.co.nr/

/
nr
o.

ht

tp

://

cs

et

ub

e.c

int b=0;
int v=0;
for(v=strlen(temp)-1;v>=0;v--)
temp2[b++]=temp[v];
temp2[b]='\0';
strcpy(temp,temp2);
stack[ptr--]='\0';
strcat(stack,temp);
ptr=strlen(stack)-1;
}
printf("\t\tpushing.. %c->%s\n",nt[k],top[k][kl]);
for(f=0;f<=ptr;f++)
printf("%c",stack[f]);
printf("\t\t");
for(f=x;f<l;f++)
printf("%c",in[f]);
x++;
}}}
while(ptr>=0);
return 0;
}
void nonterminal()
{
for(k=0;k<n;k++)
if(nt[k]==stack[ptr])
break;
}
void terminal()
{
for(kl=0;kl<m;kl++)
if(t[kl]==in[i])
break;
}
OUTPUT:
enter the no.of terminals5
enter the terminals
-------------------a
(
)
,
$
enter the no.of non terminals3
enter the non terminals
---------------------

http://csetube.co.nr/

parser table-----------------------a
(
)

nr
$

et

cs

A->e A->SA -

://

S->a
S->(L)
L->SA L->SA
-

enter the string:(a,a)$


Stack
$S
$)L(
$)L
$)AS
$)Aa
$)A
$)AS

Input
(a,a)$
(a,a)$
a,a)$
a,a)$
,a)$
,a)$
a)$

ht

tp

S
L
A

for[S][a]::>a
for[S][(]::>(L)
for[S][)]::>0
for[S][,]::>0
for[S][$]::>0
for[L][a]::>SA
for[L][(]::>SA
for[L][)]::>0
for[L][,]::>0
for[L][$]::>0
for[A][a]::>0
for[A][(]::>0
for[A][)]::>e
for[A][,]::>SA
for[A][$]::>0

o.

production
production
production
production
production
production
production
production
production
production
production
production
production
production
production

e.c

the
the
the
the
the
the
the
the
the
the
the
the
the
the
the

ub

S
L
A
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter

Action
pushing.. S->(L)
top ( off the stack
pushing.. L->SA
pushing.. S->a
top a off the stack
pushing.. A->SA
INVALID STRING

RESULT:
Thus the program to construct a top down parsing table was
successfully done.

http://csetube.co.nr/

GENERATION OF INTERMEDIATE CODE USING LEX AND YAC


TOOLS

AIM:
To write a program in linux to generate intermediate code using LEX and YACC.

ALGORITHM:
Start the program.

Include the header file.

In int code.l,declare the variable lie no as integer and assign it to be equal to 1.

Start the int code.l with declarative section.

In translation rules section define keywords ,data types and integer along with
their actions .

Start the main block.

In main block check the statement


1.declarative 2.assignment 3.conditional 4.if and else 5.While assignment.

Perform the actions of that particular block.

In main program declare the parameters arg c as int end *argv[] as char.

In main program open file in read mode.

Print the output in a file.

End the program.

ht

tp

://

cs

et

ub

e.c

o.

nr

http://csetube.co.nr/

nr
o.
e.c
ub
et
cs

ht

tp

://

%{
#include"y.tab.h"
#include<stdio.h>
int LineNo=1;
%}
identifier[a- zA-Z][_a-zA-Z0-9]*
number[0-9]+([0-9]*\.[0-9]+)
%%
Exp.y:
%{
#include<string.h>
#include<stdio.h>
struct quad
{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int item[100];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{
char var[10];
}
PROGRAM: MAIN BLOCK
;
BLOCK: '{' CODE '}'
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DECST';'
| ASSIGNMENT ';'
| CONDST
| WHILEST
;

PROGRAM:

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

DECST: TYPE VARLIST


;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '='EXPR {
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$); }
| EXPR '-' EXPR {AddQuadruple('-',$1,$3,$$); }
| EXPR '*' EXPR {AddQuadruple('*',$1,$3,$$); }
| EXPR '/' EXPR {AddQuadruple('/',$1,$3,$$); }
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$); }
| '(' EXPR ')' {strcpy($$,$2); }
| VAR
| NUM
;
CONST:IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST:IF '('CONDITION')'
{
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK{
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[index].result,"-1");
push(Index);
Index++;

http://csetube.co.nr/

/
nr
o.
e.c

ht

tp

://

cs

et

ub

}
;
ELSEST:ELSE{
tInd=pop();
Ind=pop();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK
{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
|NUM
;
WHILEST:WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP:WHILE '('CONDITION')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[index].result,"-1");
push(Index);
Index++;
}
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

int i;
if(argc>1)
{
fp=fopen(argv[1],"r");
if(!fp)
{
printf("\n file not found!");
exit(0);
}
yyin=fp;
}
yyparse();
printf("\n\n \t\t............\n\t\t pos operator arg1 arg2 result \n\t\t.....");
for(i=0;i<Index;i++)
{
printf("\n\t\t%d\t%s\t%s\t%s\t%s",i,QUAD[i],op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i]
.result);
}
printf("\n\t--------------");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\nstack overflow");
exit(0);
}
stk.items[stk.top]=data;
}
int pop(){
int data;
if(stk.top==-1)
{
printf("\nstack underflows");
exit(0);}
data=stk.items[stk.top--];
return data;
}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);

http://csetube.co.nr/

sprintf(QUAD[Index].result,"t%d",tIndex++);
strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\nError on line no: %d",LineNo);
}

ht

tp

://

cs

et

ub

e.c

o.

nr

Input:
main()
{
if(a<b)
{
a=a+b;
}
while(a<b)
{
a=a+b;
}
}
Output:
[2cse54@localhost]$./a.out in.c
.......................................................................................
Pos Operator A
Arg2
Result
0
<
a b
t0
1
==
t0
FALSE
5
2
+
a
b
t1
3
=
t1
a
4
GOTO
5
5
<
a
b
t2
6
==
t2
FALS
t0
7
+
a
b
t3
8
=
t3
a
...........................................................................................

RESULT:
Thus the program to generate an intermediate code using lex and yac
tools was successfully done

http://csetube.co.nr/

COVERSION OF INTERMEDIATE CODE INTO ASSEMBLY


LANGUAGE INSTRUCTION

AIM:
To convert the given intermediate Code into assembly language instruction using
c program.

ALGORITHM:
Start the program.

Open the source file and store the contents as quadruples.

Check for operators, in quadruples, if it is an arithmetic operator generate it or if


an assignment operator generate it, else perform unary minus on register c.

Write the generated code into output definition of the file.

Print the output.

Stop the program.

ht

tp

://

cs

et

ub

e.c

o.

nr

http://csetube.co.nr/

/
nr
o.
e.c
ub

ht

tp

://

cs

et

PROGRAM :
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct quad
{
char op[10],arg1[10],arg2[10],result[10];
}QUAD[30];
FILE *src,*dest;
int Reg_Index=0;
void Assignment();
void Un_Minus();
void Gen_Code(char op[5]);
int i=0,j=0;
void getquad()
{
src=fopen("inp.c","r");
while(!feof(src))
{
fscanf(src,"%s",QUAD[i].op);
fscanf(src,"%s",QUAD[i].arg1);
fscanf(src,"%s",QUAD[i].arg2);
fscanf(src,"%s",QUAD[i].result);
i++;
}
}
int main()
{
getquad();
dest=fopen("outp.c","w");
while(j<i)
{
if(!strcmp(QUAD[j].op,"+"))
Gen_code("ADD");
if(!strcmp(QUAD[j].op,"="))
Assignment();
if(!strcmp(QUAD[j].op,"- "))
Gen_code("SUB");
if(!strcmp(QUAD[j].op,"*"))
Gen_code("MUL");
if(!strcmp(QUAD[j].op,"/"))
Gen_code("DIV");
if(!strcmp(QUAD[j].op,"UMIN"))
Un_Minus();
j++;
}

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

fcloseall();
return 0;
Un_Minus();
j++;
}
fcloseall();
return 0;
}
void Gen_code(char op[5])
{
char strIns[25];
sprintf(strIns,"MOV R%d,%s\n",Reg_Index,QUAD[j].arg1);
fwrite(&strIns,strlen(strIns),1,dest);
sprintf(strIns,"%s R%d,%s\n",op,Reg_Index++,QUAD[j].arg2);
fwrite(&strIns,strlen(strIns),1,dest);
{
fscanf(src,"%s",QUAD[i].op);
fscanf(src,"%s",QUAD[i].arg1);
fscanf(src,"%s",QUAD[i].arg2);
fscanf(src,"%s",QUAD[i].result);
i++;
}
}
int main()
{
getquad();
dest=fopen("outp.c","w");
while(j<i)
{
if(!strcmp(QUAD[j].op,"+"))
Gen_code("ADD");
if(!strcmp(QUAD[j].op,"="))
Assignment();
if(!strcmp(QUAD[j].op,"- "))
Gen_code("SUB");
if(!strcmp(QUAD[j].op,"*"))
Gen_code("MUL");
if(!strcmp(QUAD[j].op,"/"))
Gen_code("DIV");
if(!strcmp(QUAD[j].op,"UMIN"))
Un_Minus();
j++;
}
fcloseall();
return 0;
}

http://csetube.co.nr/

ht

tp

://

cs

et

ub

e.c

o.

nr

void Gen_code(char op[5])


{
char strIns[25];
sprintf(strIns,"MOV R%d,%s\n",Reg_Index,QUAD[j].arg1);
fwrite(&strIns,strlen(strIns),1,dest);
sprintf(strIns,"%s R%d,%s\n",op,Reg_Index++,QUAD[j].arg2);
fwrite(&strIns,strlen(strIns),1,dest);
}
void Assignment()
{
char strIns[25];
if(QUAD[j].arg1[0]!='t')
{
sprintf(strIns,"MOV R%d,%s\n",Reg_Index++,QUAD[j].arg1);
fwrite(&strIns,strlen(strIns),1,dest);
}
sprintf(strIns,"MOV %s,R%d\n",QUAD[j].result,Reg_Index-1);
fwrite(&strIns,strlen(strIns),1,dest);
}
void Un_Minus()
{
char strIns[25];
sprintf(strIns,"MOV R%d,o\n",Reg_Index);
fwrite(&strIns,strlen(strIns),1,dest);
sprintf(strIns,"SUB R%d,%s\n",Reg_Index++,QUAD[j].arg1);
fwrite(&strIns,strlen(strIns),1,dest);
}

Input:
+
'
=
/
=
=

inp.c
a
t0
c
t1
c
t2
a

b
NULL
a
NULL
a
NULL
NULL

t0
a
t1
a
t2
b
c

http://csetube.co.nr/

OUTPUT: outp.c

ht

tp

://

cs

et

ub

e.c

o.

nr

MOV R0,a
ADD R0,b
MOV R1,t0
SUB R1,NULL
MOV a,R1
MOV R2,c
DIV R2,a
MOV b,R2
MOV R3,a
MOV c,R3

RESULT:
Thus the program to convert the given intermediate Code into
assembly language instruction using c program was successfully done.

http://csetube.co.nr/

Potrebbero piacerti anche