Ex. No: 4 C
Date:
4C Implementation
of Calculator using LEX and YACC
To implement a calculator to compute the given expression using semantic rules of the yacc program.
ALGORITHM:
1. A Yacc source program has three parts as follows.
Declarations
%%
translation rules
%%
supporting C routines
2. Declarations Section
This section contains entries that:
•Include standard I/O header file.
•Define global variables.
•Define the list rule as the place to start processing.
•Define the tokens used by the parser.
•Define the operators and their precedence.
3. Rules Section
The rules section defines the rules that parse the input stream. Each rule consists of a grammar production and the associated semantic action.
Programs Section
4. The programs section
It 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.
Main The required main program that calls the yyparse subroutine to start the program.
yyerror(s) This error-handling subroutine only prints a syntax error message. yywrap The wrap-up subroutine that returns a value of 1 when the end of input occurs.
5. The calc.lex file contains include statements for standard input and output, as well as for the y.tab.h file. The yacc program generates that file from the yacc grammar 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.
6. calc.lex contains the rules to generate these tokens from the input stream.
PROGRAM
calc.l
%{
#include<stdio.h>
#include"y.tab.h"
int c;
extern int yylval;
%}
%%
" " ;
[a-z] {
c=yytext[0];
yylval=c-'a';
return(LETTER);
}
[0-9] {
c=yytext[0];
yylval=c-'0';
return(DIGIT);
}
[^a-z 0-9\b] {
c=yytext[0];
return(c);
}
calc.y
%{
#include<stdio.h>
int regs[26];
int base;
%}
%start list
%token DIGIT LETTER
%left '|'
%left '&'
%left '+''-'
%left '*''/''%'
%left UMINUS
%%
list:
|
list stat '\n'
|
list error '\n'
{
yyerrok;
}
;
stat: expr
{
printf("%d\n",$1);
}
|
LETTER '=' expr
{
regs[$1]=$3;
}
;
expr: '(' expr ')'
{
$$=$2;
}
|
expr '*' expr
{
$$=$1*$3;
}
|
expr '/' expr
{
$$=$1/$3;
}
|
expr '%' expr
{
$$=$1%$3;
}
|
expr '+' expr
{
$$=$1+$3;
}
|
expr '-' expr
{
$$=$1-$3;
}
|
expr '&' expr
{
$$=$1&$3;
}
|
'-'expr %prec UMINUS
{
$$=-$2;
}
|
LETTER
{
$$=regs[$1];
}
|
number
;
number: DIGIT
{
$$=$1;
base=($1==0)?8:10;
}
|
number DIGIT
{
$$=base * $1+$2;
}
;
%%
main()
{
return(yyparse());
}
yyerror(s)
char *s;
{
fprintf(stderr,"%s\n",s);
}
yywrap()
{
return(1);
}
OUTPUT:
D:\MOHANRAJ\CS6612 COMPILER LAB\lex_yacc\yacc\calc>lex calc.l
D:\MOHANRAJ\CS6612 COMPILER LAB\lex_yacc\yacc\calc>yacc -d calc.y
D:\MOHANRAJ\CS6612 COMPILER LAB\lex_yacc\yacc\calc>cc lex.yy.c y.tab.c
D:\MOHANRAJ\CS6612 COMPILER LAB\lex_yacc\yacc\calc>a.exe
4+5
9
-4+5
1
5-20
-15
m=8
m+3
11
^C
D:\MOHANRAJ\CS6612 COMPILER LAB\lex_yacc\yacc\calc>
RESULT:
Thus the calculator is implemented using Lex and Yacc.
No comments:
Post a Comment