ALGORITHM:
- A Yacc source program has three parts as follows:
Declarations
%%
translation rules
%%
supporting C routines
- 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.
- Rules Section: The rules section defines the rules that parse the input stream. Each rule of a grammar production and the associated semantic action.
- 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.
- 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. 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.
- lex contains the rules to generate these tokens from the input stream.
Cal.l
%{
#include
#include
#include"y.tab.h"
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {
yylval.dval=atof(yytext);
return NUMBER;}
MEM {return MEM;}
[\t];
\$ {return 0;}
\n {return yytext[0];}
. {return yytext[0];}
%%
Cal.y
%{
#include
#include
double memvar;
%}
%union
{
double dval;
}
%token NUMBER
%token MEM
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%type expression
%%
start:statement '\n'
|start statement '\n'
statement:MEM '=' expression {memvar=$3;}
|expression {printf("answer=%g\n",$1);}
;
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 %prec UMINUS {$$= -$2;}
|'('expression')' {$$=$2;}
|NUMBER {$$=$1;}
|MEM {$$=memvar;};
%%
int main(void)
{
printf("Enter the expression");
yyparse();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
int yyerror(char *error)
{
printf("%s\n",error);
return 0;
}
OUTPUT: [CSE@localhost ~]$ lex cal.l [CSE@localhost ~]$ yacc -d cal.y [CSE@localhost ~]$ cc lex.yy.c y.tab.c -ll [CSE@localhost ~]$ ./a.out Enter the expression5+3 answer=8 [cse@NFSSERVER ~]$ ./a.out Enter the expression5+-5 answer=0 [cse@NFSSERVER ~]$ ./a.out Enter the expression+5/ syntax error