Category Archives: Lex & Yacc

Lex & Yacc : Acceptance of string

Ques : Write a lex and yacc program to accept strings over {0,1} from the set {00,0000,000000….. , 11,1111,111111…..}

// (yacc file)
%{
#include<stdlib.h>
#include<stdio.h>
void yyerror(char *s);
%}
%token Z O
%%
S : S A {printf("Accepted ");}
| A ;
A : Z Z
| O O ;
%%
int main()
{
yyparse();
}
void yyerror(char *s)
{
fprintf(stdout,"\nNot Accepted !\n");
}

// Lex File

%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern int yylval;
%}
%%
0 {yylval=0;return Z;}
1 {yylval=1;return O;}
[ \t] {;}
\n return 0;
. return yytext[0];
%%

Output :-
00
Accepted !
0101
Not Accepted !

Conversion of arithmatic expression into postfix expression for given grammar

Grammars Are
E=E+T      E=T    T=T*F    T=F    F=NUM

// ( .y  File )

%{
#include<stdlib.h>
#include<stdio.h>
void yyerror(char *s);
%}
%token NUM
%%
E : E '+' T {printf("+");}
| T ;
T : T '*' F {printf("*");}
| F ;
F : NUM {printf("%d",yylval);};
%%
int main()
{
yyparse();
}
void yyerror(char *s)
{
fprintf(stdout,"\n%s",s);
}

// (.l File )

%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return NUM;}
[ \t] {;}
\n return 0;
. return yytext[0];
%%

/* To Compile :-
1) yacc -d filename.y
2) lex filename.l
3) gcc lex.yy.c y.tab.c -ll
4) ./a.out
Enter Expression like:  1+2*3
*/

Conversion from binary to decimal

<br />//(Yacc File : Save as .y)

//to compile and Run
//:-> yacc -d FileName.y
//:-> lex FileName.l
//:-> gcc lex.yy.c y.tab.c -ll
//:-> ./a.output
//:-> enter input as - 101
//:-> output:-> 5

%{
#include<stdio.h>
#include<stdlib.h>
void yyerror(char *s);
%}
%token ZERO ONE
%%
N: L {printf("\n%d",$$);}
L: L B {$$=$1*2+$2;}
| B {$$=$1;}
B:ZERO {$$=$1;}
|ONE {$$=$1;};
%%
int main()
{
while(yyparse());
}
yyerror(char *s)
{
fprintf(stdout,"\n%s",s);
}

// (Lex File : save as .l)

%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern int yylval;
%}
%%
0 {yylval=0;return ZERO;}
1 {yylval=1;return ONE;}

[ \t] {;}
\n return 0;
. return yytext[0];
%%

Output :-
101
5

LEX & YACC : Calculator

<br />//    Yacc  File (.y)

//calculator

%{
#include<stdio.h>
#include<stdlib.h>
void yyerror(char *s);
%}
%token NAME NUM
%%
statement: NAME'='expression
|expression{printf("\n%d\n",$1);};
expression:expression'+'NUM{$$=$1+$3;}
|expression'-'NUM{$$=$1-$3;}
|expression'/'NUM{$$=$1/$3;}
|expression'*'NUM{$$=$1*$3;}
|NUM{$$=$1;};
%%
int main()
{
while(yyparse());
}
yyerror(char *s)
{
fprintf(stdout,"\n%s",s);
}

// Lex file (.l)

%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return NUM;}
[ \t] {;}
\n return 0;
. return yytext[0];
%%

/*
To Compile :
1) yacc -d FileName.y
2) lex FileName.l
3) gcc lex.yy.c y.tab.c -ll
4) ./a.out
*/

Output :-
5+6
11