Compiler Design Lab Programs
Compiler Design Lab Programs
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}
yyerror(char*s)
{
}
Output:
[root@localhost]# lex arith_id.1
[root@localhost]# yacc d arith_id.y
[root@localhost]# gcc lex.yy.c y.tab.c
[root@localhost]# ./a.out
x=a+b;
Identifier is x
Operator is EQUAL
Identifier is a
Operator is PLUS
Identifier is b
b) Program to recognise a valid variable which starts with a letter followed by any number
of letters or digits.
Program name: variable_test.l
%{
/* This LEX program returns the tokens for the Expression */
#include "y.tab.h"
%}
%%
"int " {return INT;}
"float" {return FLOAT;}
"double" {return DOUBLE;}
[a-zA-Z]*[0-9]*{
printf("\nIdentifier is %s",yytext);
return ID;
}
return yytext[0];
\n return 0;
int yywrap()
{
return 1;
}
[root@localhost]# ./a.out
Enter some valid string
aaaaaaaaab
Invalid string
[root@localhost]# ./a.out
Enter some valid string
aaaaaaaaaaab
Valid string [root@localhost]#
d) Implementation of Calculator using LEX and YACC
Program name:calci.l
%{
#include "y.tab.h" /*defines the tokens*/
#include ,math.h.
%}
%%
/*To recognise a valid number*/
([0-9] + |([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval = atof(yytext);
return NUMBER;}
/*For log no | Log no (log base 10)*/
log | LOG {return LOG;}
/*For ln no (Natural Log)*/
ln {return nLOG;}
/*For sin angle*/
sin | SIN {return SINE;}
/*For cos angle*/
cos | COS {return COS;}
/*For tan angle*/
tan | TAN {return TAN;}
/*For memory*/
mem {return MEM;}
[\t] ; /*Ignore white spaces*/
/*End of input*/
\$ {return 0;}
else
$$ = $1 / $3;
}
| expression ^ expression {$$ = pow($1,$3);}
;
/*For unary operators*/
expression: -expression %prec UMINUS {$$ = -$2;}
/*%prec UMINUS signifies that unary minus should have the highest precedence*/
| ( expression ) {$$ = $2}
| LOG expression {$$ = log($2)/log(10);}
| nLOG expression {$$ = log($2);}
*/Trigonometric functions*/
| SINE expression {$$ = sin($2 * 3.141592654 / 180);}
| COS expression {$$ = cos($2 * 3.141592654 / 180);}
| TAN expression {$$ = tan($2 * 3.141592654 / 180);}
| NUMBER {$$ = $1;}
| MEM {$$ = $1;}
; /*Retrieving the memory contents*/
%%
main()
{
printf(Enter the expression:);
yyparse();
}
int yyerror(char *error)
{
fprintf(stderr,%s\n,error);
}
Output:
The output of the program can be obtained by following commands
[root@localhost]]# lex calci.l
[root@localhost]]# yacc d calci.y
[root@localhost]]# cc y.tab.c lexyy.c ll ly lm
[root@localhost]]# ./a.out
Enter the expression: 2+@
Answer = 4
2*2+5/4
Answer = 5.25
mem = cos 45
sin 45/mem
Answer = 1
ln 10
Answer = 2.30259