You are on page 1of 42

HOW TO INSTALL LEX AND YACC IN 

UBUNTU?

To install lex:

sudo apt-get install byacc flex


%{
#include <stdio.h>
%}

%%
stop printf("Stop command received\n");
start printf("Start command received\n");
%%
To compile Example 1, do this:
lex example1.l
cc lex.yy.c -o example1 -ll
Regular expressions in matches
This example wasn't very useful in itself, and our next one won't be either. It will however show
how to use regular expressions in Lex, which are massively useful later on.
Example 2:
%{
#include <stdio.h>
%}

%%
[0123456789]+ printf("NUMBER\n");
[a-zA-Z][a-zA-Z0-9]* printf("WORD\n");
%%
The corresponding Lex file is Example 3:
%{
#include <stdio.h>

1
%}

%%
[a-zA-Z][a-zA-Z0-9]* printf("WORD ");
[a-zA-Z0-9\/.-]+ printf("FILENAME ");
\" printf("QUOTE ");
\{ printf("OBRACE ");
\} printf("EBRACE ");
; printf("SEMICOLON ");
\n printf("\n");
[ \t]+ /* ignore whitespace */;
%%

A Lex Source Example


%{
/*
* Example lex source file
* This first section contains necessary
* C declarations and includes
* to use throughout the lex specifications.
*/
#include <stdio.h>
%}
bin_digit [01]
%%

{bin_digit}* {
/* match all strings of 0's and 1's */

2
/* Print out message with matching text */
printf("BINARY: %s\n", yytext);
}
([ab]*aa[ab]*bb[ab]*)|([ab]*bb[ab]*aa[ab]*) {
/* match all strings over (a,b) containing aa and bb */
printf("AABB\n");
}
\n ; /* ignore newlines */

%%
/*
* Now this is where you want your main program
*/
int main(int argc, char *argv[]) {
/*
* call yylex to use the generated lexer
*/
yylex();
/*
* make sure everything was printed
*/
fflush(yyout);
exit(0);
}

Lex Library Function Calls


• yylex()
– default main() contains a return yylex();
3
• yywarp()
– called by lexical analyzer if end of the input file
– default yywarp() always return 1
• yyless(n)
– n characters in yytext are retained
• yymore()
– the next input expression recognized is to be appended to the end of this input
Example
%{ int lengs[100]; }%
%%
[a-z]+ { lengs[yyleng]++; }
.|
\n ;
%%
yywrap()
{
int i;
printf("Length No. words\n");
for(i=0; i<100; i++)
if (lengs[i] > 0)
printf("%5d%10d\n",i,lengs[i]); return(1);

IMPLEMENTATION OF SYMBOL TABLE MANAGEMENT


4
AIM:

To write a program for implementing Symbol Table using C.

ALGORITHM:

1. Start the program for performing insert, display, delete, search and
modify option in symbol table
2. Define the structure of the Symbol Table
3. Enter the choice for performing the operations in the symbol Table
4. If the entered choice is 1, search the symbol table for the symbol to be
inserted. If the symbol is already present, it displays “Duplicate Symbol”.
Else, insert the symbol and the corresponding address in the symbol
table.
5. If the entered choice is 2, the symbols present in the symbol table are
displayed.
6. If the entered choice is 3, the symbol to be deleted is searched in the
symbol table.
7. If it is not found in the symbol table it displays “Label Not found”. Else,
the symbol is deleted.
8. If the entered choice is 5, the symbol to be modified is searched in the
symbol table. The label or address or both can be modified.

9. PROGRAM:
10. # include <stdio.h>
# include <conio.h>
# include <alloc.h>
# include <string.h>
# define null 0
int size=0;

5
void insert();
void del();
int search(char lab[]);
void modify();
void display();
struct symbtab
{
char label[10];
int addr;
struct symtab *next;
};
struct symbtab *first,*last;
void main()
{
int op;
int y;
char la[10];
clrscr();
do
{
printf("\nSYMBOL TABLE IMPLEMENTATION\n");
printf("1. INSERT\n");
printf("2. DISPLAY\n");
printf("3. DELETE\n");
printf("4. SEARCH\n");
printf("5. MODIFY\n");
printf("6. END\n");
printf("Enter your option : ");
scanf("%d",&op);
switch(op)
{
case 1:

6
insert();
display();
break;
case 2:
display();
break;
case 3:
del();
display();
break;
case 4:
printf("Enter the label to be searched : ");
scanf("%s",la);
y=search(la);
if(y==1)
{
printf("The label is already in the symbol Table");
}
else
{
printf("The label is not found in the symbol table");
}
break;
case 5:
modify();
display();
break;
case 6:
break;
}
}
while(op<6);

7
getch();
}
void insert()
{
int n;
char l[10];
printf("Enter the label : ");
scanf("%s",l);
n=search(l);
if(n==1)
{
printf("The label already exists. Duplicate cant be inserted\n");
}
else
{
struct symbtab *p;
p=malloc(sizeof(struct symbtab));
strcpy(p->label,l);
printf("Enter the address : ");
scanf("%d",&p->addr);
p->next=null;
if(size==0)
{
first=p;
last=p;
}
else
{
last->next=p;
last=p;
}

8
size++;
}
}
void display()
{
int i;
struct symbtab *p;
p=first;
printf("LABEL\tADDRESS\n");
for(i=0;i<size;i++)
{
printf("%s\t%d\n",p->label,p->addr);
p=p->next;
}
}
int search(char lab[])
{
int i,flag=0;
struct symbtab *p;
p=first;
for(i=0;i<size;i++)
{
if(strcmp(p->label,lab)==0)
{
flag=1;
}
p=p->next;
}
return flag;
}
void modify()
{

9
char l[10],nl[10];
int add, choice, i, s;
struct symbtab *p;
p=first;
printf("What do you want to modify?\n");
printf("1. Only the label\n");
printf("2. Only the address of a particular label\n");
printf("3. Both the label and address\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the old label\n");
scanf("%s",l);
printf("Enter the new label\n");
scanf("%s",nl);
s=search(l);
if(s==0)
{
printf("NO such label");
}
else
{
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
{
strcpy(p->label,nl);
}
p=p->next;
}

10
}
break;
case 2:
printf("Enter the label whose address is to modified\n");
scanf("%s",l);
printf("Enter the new address\n");
scanf("%d",&add);
s=search(l);
if(s==0)
{
printf("NO such label");
}
else
{
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
{
p->addr=add;
}
p=p->next;
}
}
break;
case 3:
printf("Enter the old label : ");
scanf("%s",l);
printf("Enter the new label : ");
scanf("%s",nl);
printf("Enter the new address : ");
scanf("%d",&add);
s=search(l);

11
if(s==0)
{
printf("NO such label");
}
else
{
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
{
strcpy(p->label,nl);
p->addr=add;
}
p=p->next;
}
}
break;
}
}
void del()
{
int a;
char l[10];
struct symbtab *p,*q;
p=first;
printf("Enter the label to be deleted\n");
scanf("%s",l);
a=search(l);
if(a==0)
{
printf("Label not found\n");
}

12
else
{
if(strcmp(first->label,l)==0)
{
first=first->next;
}
else if(strcmp(last->label,l)==0)
{
q=p->next;
while(strcmp(q->label,l)!=0)
{
p=p->next;
q=q->next;
}
p->next=null;
last=p;
}
else
{
q=p->next;
while(strcmp(q->label,l)!=0)
{
p=p->next;
q=q->next;
}
p->next=q->next;
}
size--;
}
}

OUTPUT:
13
SYMBOL TABLE IMPLEMENTATION

1.INSERT

2.DISPLAY

3.DELETE

4.SEARCH

5.MODIFY

6.END

Enter your option:1

Enter the label: A

Enter the address: 10

LABEL ADDRESS

A 10

SYMBOL TABLE IMPLEMENTATION

1.INSERT

2.DISPLAY

3.DELETE

4.SEARCH

5.MODIFY

6.END

Enter your option:1

Enter the label: B

14
IMPLEMENTATION OF A LEXICAL ANALYZER USING LEX

AIM:

To write a program for implementing a Lexical analyser using LEX tool in


Linux platform.

ALGORITHM:

1. Lex program contains three sections: definitions, rules, and user subroutines.
Each section must be separated from the others by a line containing only the
delimiter, %%.
The format is as follows:
definitions
%%
rules
%%
user_subroutines
2. In definition section, the variables make up the left column, and their
definitions make up the right column. Any C statements should be enclosed
in %{..}%. Identifier is defined such that the first letter of an identifier is
alphabet and remaining letters are alphanumeric.
3. In rules section, the left column contains the pattern to be recognized in an
input file to yylex(). The right column contains the C program fragment
executed when that pattern is recognized. The various patterns are
keywords, operators, new line character, number, string, identifier, beginning
and end of block, comment statements, preprocessor directive statements
etc.
4. Each pattern may have a corresponding action, that is, a fragment of C
source code to execute when the pattern is matched.
15
5. When yylex() matches a string in the input stream, it copies the matched
text to an external character array, yytext, before it executes any actions in
the rules section.

6. In user subroutine section, main routine calls yylex(). yywrap() is used to get
more input.
7. The lex command uses the rules and actions contained in file to generate a
program, lex.yy.c, which can be compiled with the cc command. That
program can then receive input, break the input into the logical pieces
defined by the rules in file, and run program fragments contained in the
actions in file.

Problem Statement :-

To find & replace count digits,characters,words from input file.

******************** lfile.l ******************/


%{
#include<stdio.h>
FILE *fp;
int i,j,k,l,m,charcnt,digitcnt,wordcnt,newlcnt;
%}
word [a-zA-Z]+
digit [0-9]+
%%
{word} {wordcnt++;charcnt+=yyleng;}
{digit} {digitcnt+=yyleng;}
%%
int main()

16
{
fp=fopen("lexems.txt","r");
yyin=fp;
charcnt=wordcnt=digitcnt=0;
yylex();
fclose(fp);
printf("\n chars is = %d",charcnt);
printf("\n digits are :- %d",digitcnt);
printf("\n Words are = %d",wordcnt);
return(0);
}
/********* lexmes.txt ********/
My name is Prashant Kulkarni
Roll No :- 40
KKWIEER,Nashik
*!@#$%?
/********* output *********/
[a40@localhost ~]$ lex lfile.l
[a40@localhost ~]$ cc lex.yy.c -ll
[a40@localhost ~]$ ./a.out
chars is = 43
digits are :- 2
Words are = 9

Assignment No :- 2
* Problem Statement :-
To find & replace String using Lex.

/********* lfr.l *******/

17
%{
#include<stdio.h>
#include<string.h>
FILE *ff,*fr;
char p[20],q[20],r[20],fname[20];
%}
word [a-zA-Z]+
eol \n
%%
{word} {
if(strcmp(p,yytext)==0)
fprintf(fr,q);
else
fprintf(fr,yytext);
}
{eol} {fprintf(fr,yytext);}
. {fprintf(fr,yytext);}
%%
int main(int argc,char *argv[])
{
strcpy(fname,argv[1]);
strcpy(p,argv[2]);
strcpy(q,argv[3]);
ff=fopen(fname,"r+");
fr=fopen("rep.txt","w+");
yyin=ff;
yylex();
return(0);
}
/********* find.txt *******/
Hello...
18
Prashant Kulkarni
KKWIEER NASHIK...
Have a nice day..!!!
/********* output **********/
[a40@localhost ~]$ lex lfr.l
[a40@localhost ~]$ cc lex.yy.c -ll
[a40@localhost ~]$ ./a.out find.txt Prashant PK
[a40@localhost ~]$ cat rep.txt
Hello...
PK Kulkarni
KKWIEER NASHIK...
Have a nice day..!!!
/********* final rep.txt *******/
Hello...
PK Kulkarni
KKWIEER NASHIK...
Have a nice day..!!!

IMPLEMENTATION OF CALCULATOR USING YACC

AIM:
To write a program for implementing a calculator for computing the given
expression using semantic rules of the YACC tool.

ALGORITHM:

19
1. A Yacc source program has three parts as follows:
Declarations
%%
translation rules
%%
supporting C routines
2. Declarations Section:
This section contains entries that:
i. Include standard I/O header file.
ii. Define global variables.
iii. Define the list rule as the place to start processing.
iv. Define the tokens used by the parser.
v. Define the operators and their precedence.
3. Rules Section:
The rules section defines the rules that parse the input stream. Each
rule of a grammar production and the associated semantic action.
4. Programs Section:
The programs section contains the following subroutines. Because
these subroutines are included in this file, it is not necessary to use
the yacc library when processing this file.
5. Main- The required main program that calls the yyparse subroutine to start
the program.
6. yyerror(s) -This error-handling subroutine only prints a syntax error
message.
7. yywrap -The wrap-up subroutine that returns a value of 1 when the end of
input occurs. The calc.lex file contains include statements for standard input
and output, as programmar file information if we use the -d flag with the
yacc command. The y.tab.h file contains definitions for the tokens that the
parser program uses.
8. calc.lex contains the rules to generate these tokens from the input stream.

20
********************** calci.l *************************/
%{
#include<stdio.h>
#include<math.h>
#include "y.tab.h"
%}
%%
[0-9]+ {
yylval.dval=atoi(yytext);
return NUMBER;
}
[t];
n return 0;
. {return yytext[0];}
%%
void yyerror(char *str)
{
printf("n Invalid Character...");
}
int main()
{
printf("Enter Expression => ");
yyparse();
return(0);
}
********************** calci.y ***********************
%{
#include<stdio.h>
int yylex(void);
%}
%union
{
float dval;
}
%token <dval> NUMBER
%left '+' '-'
%left '*' '/'
21
%nonassoc UMINUS
%type <dval> exp
%%
state : exp {printf("Answer = %fn",$1);}
;
exp : NUMBER
| exp '+' exp {$$=$1+$3;}
| exp '-' exp {$$=$1-$3;}
| exp '*' exp {$$=$1*$3;}
| exp '/' exp {$$=$1/$3;}
| '('exp')' {$$=$2;}
| '-' exp %prec UMINUS {$$=-$2;}
;
%%
********************** Output ***********************
[a40@localhost ~]$ lex calci.l
[a40@localhost ~]$ yacc -d calci.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out

Enter Expression => 10+7


Answer = 17

RESULT:
Thus the program for implementation of Calculator using YACC tool is
executed and verified

Assignment No :-
* Problem Statement :-
Assignment To implement a parser that accept all strings
22
that begins or ends with different characters for E={a,b}
* Roll No :- 40 Batch :- A2
* BE(Computer)
* Date :- / /2011/
****************************** anyab.l ************************
**********/
%{
#include<stdio.h>
#include<math.h>
#include "y.tab.h"
int flag=0;
%}
%%
[a] {yylval.dval=atoi(yytext);return ON;}
[b] {yylval.dval=atoi(yytext);return OFF;}
[\t];
\n return 0;
. {return yytext[0];}
%%
void yyerror(char * str)
{
flag=1;
printf("\n Error...");
}
int main()
{
printf("\n Enter an Expression => ");
yyparse();
if(flag!=1)
printf("\n Success...!!!");
return 0;
23
}
/********************** anyab.y ***********************/
%{
#include<stdio.h>
int flag;
int yylex(void);
%}
%union
{
int dval;
}
%token <dval> ON
%token <dval> OFF
%type <dval> S
%type <dval> E
%%
S : ON E OFF {}
| OFF E ON {}
| ON OFF {}
| OFF ON {}
;
E : ON {}
| OFF {}
| E ON {}
| E OFF {}
;
%%
/********************** Output ***********************
"anyab.y" 25L, 258C written
[a40@localhost ~]$ lex anyab.l
[a40@localhost ~]$ yacc -d anyab.y
24
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out
Enter an Expression => ab
Success...!!![a40@localhost ~]$ ./a.out
Enter an Expression => ababaaaab
Success...!!![a40@localhost ~]$ ./a.out
Enter an Expression => ba
Success...!!![a40@localhost ~]$ ./a.out
Enter an Expression => b
Error...[a40@localhost ~]$ ./a.out
Enter an Expression => abbbb
Success...!!![a40@localhost ~]$ ./a.out
Enter an Expression => bbbbbb
Error...[a40@localhost ~]$
*/

Assignment No :-
* Problem Statement :-
Assignment To Optimize the Three Address Code for a
given expression...
* Roll No :- 40 Batch :- A2
* BE(Computer)
* Date :- / /2011
************************ opt.l ***********************/
%{
#include<stdio.h>
#include<math.h>
#include "y.tab.h"
%}
%%

25
[a-zA-Z0-9] {yylval.dval=yytext[0];return NUM;}
[\t];
\n return NL;
. {return yytext[0];}
%%
void yyerror(char *str)
{
printf("\n Invalid...");
}
int main()
{
yyin=fopen("test.txt","r");
yyparse();
return(0);
}
/********************** opt.y ***********************/
%{
#include<stdio.h>
int yylex(void);
char r1[20],r2[20],r3[20],l[20],rr1[20],rr2[20],rr3[20],ll[20];
char w,x,y,z;
int k=0,i,j,p=0,flag[20],pk[20];
%}
%union
{
char dval;
}
%token <dval> NUM
%token <dval> NL
%left '+' '-'
%left '*' '/'
26
%nonassoc UMINUS
%type <dval> S
%type <dval> E
%%
S : N '=' E LINE {}
|{
for(i=0;i<20;i++)
pk[i]=flag[i]=0;
/*
r1[],r2[],r3[] are the arrays used to store character on RHS of '=' of 3 address generated code.
l[] array used for storing LHS character of expression of 3 address generated code.
rr1[],rr2[],rr3[] are the arrays used to store character on RHS of '=' of optimized code.
ll[] array used for storing LHS character of expression of optimized code.
pk[] is array for replacement in optimization. flag[] is array used to check whether RHS of
expression is repeated or not. w,x,y,z are the characters used for elliminating Dead
code generation in optimized code.
*/
for(i=0;i<k;i++)
{
for(j=i+1;j<k;j++)
{
if(r1[i]==r1[j] && r2[i]==r2[j] && r3[i]==r3[j] && flag[j]!=1)
{
flag[j]=1;
pk[j]=i;
}
}
}
for(i=0;i<k;i++)
{
if(flag[i]!=1)
27
{
x=rr1[p]=r1[i];
y=rr2[p]=r2[i];
z=rr3[p]=r3[i];
ll[p]=l[i];
p++;
}
else
{
rr1[p]='\0';
rr2[p]='\0';
rr3[p]='\0';
ll[p]='\0';
p++;
}
}
for(i=0;i<p;i++)
{
if(flag[i]==1)
{
for(j=0;j<p;j++)
{
if(rr1[j]==l[i])
rr1[j]=l[pk[i]];
if(rr3[j]==l[i])
z=rr3[j]=l[pk[i]];
}
}
}
printf("\n Optimized Code is => ");
for(i=0;i<p-1;i++)
28
{
if(ll[i]!='\0' || rr1[i]!='\0' || rr2[i]!='\0' || rr3[i]!='\0')
{
printf("\n %C=%C%C%C",ll[i],rr1[i],rr2[i],rr3[i]);
}
}
printf("\n %C=%C%C%C",w,x,y,z);
}
;
N : NUM {w=l[k]=$1;}
;
LINE : NL S {}
| {}
;
E : NUM {$$=$1;}
| E '+' E {r1[k]=$1;r2[k]='+';r3[k]=$3;k++;}
| E '-' E {r1[k]=$1;r2[k]='-';r3[k]=$3;k++;}
| E '*' E {r1[k]=$1;r2[k]='*';r3[k]=$3;k++;}
| E '/' E {r1[k]=$1;r2[k]='/';r3[k]=$3;k++;}
;
%%
/********************** test.txt ***********************/
A=1*2
B=1*2
C=A+B
D=3*4
E=C+D
F=1*2
G=E+F
H=3*4
I=G+H
29
J=I
/********************** Output ************************/
[a40@localhost ~]$ lex opt.l
[a40@localhost ~]$ yacc -d opt.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out
Optimized Code is =>
A=1*2
C=A+A
D=3*4
E=C+D
G=E+A
J=G+D

Assignment No :-
* Problem Statement :-
Assignment To implement a parser that accept all strings
that begin with "10" .
* Roll No :- 40 Batch :- A2
* BE(Computer)
* Date :- / /2011/
********************** 10.l ***********************
%{
#include<stdio.h>
#include<math.h>
#include "y.tab.h"
int flag=0;
%}
%%
1 {yylval.dval=atoi(yytext);return ON;}
0 {yylval.dval=atoi(yytext);return OFF;}
30
[\t];
\n return 0;
. {return yytext[0];}
%%
void yyerror(char *str)
{
flag=1;
printf("\n Invalid Language...");
}
int main()
{
printf("\n Enter Expression => ");
yyparse();
if(flag!=1)
printf("\n Successfull...");
return(0);
}
********************** 10.y ***********************
%{
#include<stdio.h>
int yylex(void);
%}
%union
{
int dval;
}
%token <dval> ON
%token <dval> OFF
%token <dval> NL
%type <dval> S
%type <dval> A
31
%%
S : ON OFF A {}
| ON OFF {}
;
A : ON A {}
| OFF A {}
| ON {}
| OFF {}
;
%%
********************** Output ***********************
[a40@localhost ~]$ lex 10.l
[a40@localhost ~]$ yacc -d 10.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out
Enter Expression => 101011110
Successfull...[a40@localhost ~]$ ./a.out
Enter Expression => 1101
Invalid Language...[a40@localhost ~]$

Assignment To generate Three Address Code for a given


expression…
********************** threee.l ***********************
%{
#include
#include
#include “y.tab.h”
%}
%%
[0-9]+ {yylval.dval=atoi(yytext);return NUM;}
[t];
32
n return 0;
. {return yytext[0];}
%%
void yyerror(char *str)
{
printf(“n Invalid Character…”);
}
int main()
{
printf(“Enter Expression x => “);
yyparse();
return(0);
}
********************** threee.y ***********************
%{
#include
int yylex(void);
char p=’A’-1;
%}
%union
{
char dval;
}
%token NUM
%left ‘+’ ‘-‘
%left ‘*’ ‘/’
%nonassoc UMINUS
%type S
%type E
%%
S : E {printf(” x = %cn”,$$);}
33
;
E : NUM {}
| E ‘+’ E {p++;printf(“n %c = %c + %c “,p,$1,$3);$$=p;}
| E ‘-‘ E {p++;printf(“n %c = %c – %c “,p,$1,$3);$$=p;}
| E ‘*’ E {p++;printf(“n %c = %c * %c “,p,$1,$3);$$=p;}
| E ‘/’ E {p++;printf(“n %c = %c / %c “,p,$1,$3);$$=p;}
| ‘(‘E’)’ {$$=p;}
| ‘-‘ E %prec UMINUS {p++;printf(“n %c = -%c “,p,$2);$$=p;}
;
%%
********************** Output ***********************
[a40@localhost ~]$ lex threee.l
[a40@localhost ~]$ yacc -d threee.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out

Enter Expression x => 1+2-3*3/1+4*5

A = 1+2
B = 3*3
C = B/1
D = A-C
E = 4*5
F = D+E
X=F
[a40@localhost ~]$ ./a.out

Enter Expression x => 1+2*(3+4)/5

A = 3+4
B = 2*A
C = B/5
D = 1+C

34
X=D
[a40@localhost ~]$ ./a.out

Enter Expression x => 1+2*(-3+-6/1)*3

A = -3
B = -6
C = B/1
D = A+C
E = 2*D
F = E*3
G = 1+F
X=G

Problem Statement :-
Assignment To implement a parser to convert infix
to postfix expression & write the output to a file
named "postfix.txt".
* Roll No :- 40 Batch :- A2
* BE(Computer)
* Date :- 15/09/2011
********************** inpost.l ***********************
%{
#include<stdio.h>
#include<math.h>
#include "y.tab.h"
%}
%%
[0-9]+ {
yylval.dval=yytext[0];
return NUMBER;
}
[t];
n return 0;
. {return yytext[0];}
%%
35
void yyerror(char *str)
{
printf("n Invalid Character...");
}
int main()
{
printf("Enter Expression => ");
yyparse();
return(0);
}
********************** inpost.y ***********************
%{
#include<stdio.h>
int yylex(void);
int k=0;
int i;
char sym[26];
FILE *fp;
%}
%union
{
char dval;
}
%token <dval> NUMBER
%left '+' '-'
%left '*' '/'
%nonassoc UMINUS
%type <dval> state
%type <dval> exp
%%
state : exp {
printf("nConverted Postfix expression is => ");
fp=fopen("postfix.txt","w
for(i=0;i<k;i++)
{
fprintf(fp,"%c",sym[i]);
printf("%c",sym[i]);
36
}
fclose(fp);
}
;
exp : NUMBER {$$=$1;sym[k]=(char)$$;k++}
| exp '+' exp {sym[k]='+';k++}
| exp '-' exp {sym[k]='-';k++}
| exp '*' exp {sym[k]='*';k++}
| exp '/' exp {sym[k]='/';k++}
;
%%
********************** Output ***********************
[a40@localhost ~]$ lex inpost.l
[a40@localhost ~]$ yacc -d inpost.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out

Enter Expression => 7*9+6/2-1


Converted Postfix expression is => 79*62/+1-
**************** Output postfix.txt*******************
79*62/+1

37
IMPLEMENTATION OF A LEXICAL ANALYZER USING LEX

AIM:

To write a program for implementing a Lexical analyser using LEX tool in


Linux platform.

ALGORITHM:

8. Lex program contains three sections: definitions, rules, and user subroutines.
Each section must be separated from the others by a line containing only the
delimiter, %%.
The format is as follows:
definitions
%%
rules
%%
user_subroutines
9. In definition section, the variables make up the left column, and their
definitions make up the right column. Any C statements should be enclosed

38
in %{..}%. Identifier is defined such that the first letter of an identifier is
alphabet and remaining letters are alphanumeric.
10. In rules section, the left column contains the pattern to be recognized
in an input file to yylex(). The right column contains the C program fragment
executed when that pattern is recognized. The various patterns are
keywords, operators, new line character, number, string, identifier, beginning
and end of block, comment statements, preprocessor directive statements
etc.
11. Each pattern may have a corresponding action, that is, a fragment of C
source code to execute when the pattern is matched.
12. When yylex() matches a string in the input stream, it copies the
matched text to an external character array, yytext, before it executes any
actions in the rules section.

13. In user subroutine section, main routine calls yylex(). yywrap() is used
to get more input.
14. The lex command uses the rules and actions contained in file to
generate a program, lex.yy.c, which can be compiled with the cc command.
That program can then receive input, break the input into the logical pieces
defined by the rules in file, and run program fragments contained in the
actions in file.

Problem Statement :-

To find & replace count digits,characters,words from input file.

******************** lfile.l ******************/


%{
#include<stdio.h>
FILE *fp;

39
int i,j,k,l,m,charcnt,digitcnt,wordcnt,newlcnt;
%}
word [a-zA-Z]+
digit [0-9]+
%%
{word} {wordcnt++;charcnt+=yyleng;}
{digit} {digitcnt+=yyleng;}
%%
int main()
{
fp=fopen("lexems.txt","r");
yyin=fp;
charcnt=wordcnt=digitcnt=0;
yylex();
fclose(fp);
printf("\n chars is = %d",charcnt);
printf("\n digits are :- %d",digitcnt);
printf("\n Words are = %d",wordcnt);
return(0);
}
/********* lexmes.txt ********/
My name is Prashant Kulkarni
Roll No :- 40
KKWIEER,Nashik
*!@#$%?
/********* output *********/
[a40@localhost ~]$ lex lfile.l
[a40@localhost ~]$ cc lex.yy.c -ll
[a40@localhost ~]$ ./a.out
40
chars is = 43
digits are :- 2
Words are = 9

Assignment No :- 2
* Problem Statement :-
To find & replace String using Lex.

/********* lfr.l *******/


%{
#include<stdio.h>
#include<string.h>
FILE *ff,*fr;
char p[20],q[20],r[20],fname[20];
%}
word [a-zA-Z]+
eol \n
%%
{word} {
if(strcmp(p,yytext)==0)
fprintf(fr,q);
else
fprintf(fr,yytext);
}
{eol} {fprintf(fr,yytext);}
. {fprintf(fr,yytext);}
%%
int main(int argc,char *argv[])
{
strcpy(fname,argv[1]);
strcpy(p,argv[2]);
41
strcpy(q,argv[3]);
ff=fopen(fname,"r+");
fr=fopen("rep.txt","w+");
yyin=ff;
yylex();
return(0);
}
/********* find.txt *******/
Hello...
Prashant Kulkarni
KKWIEER NASHIK...
Have a nice day..!!!
/********* output **********/
[a40@localhost ~]$ lex lfr.l
[a40@localhost ~]$ cc lex.yy.c -ll
[a40@localhost ~]$ ./a.out find.txt Prashant PK
[a40@localhost ~]$ cat rep.txt
Hello...
PK Kulkarni
KKWIEER NASHIK...
Have a nice day..!!!
/********* final rep.txt *******/
Hello...
PK Kulkarni
KKWIEER NASHIK...
Have a nice day..!!!

42

You might also like