PROGRAM 5:
Program to Implement calculator using lex and yacc.
Program to Implement calculator using lex and yacc.
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:
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
programmer 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.
PROGRAM:
LEX PART
DIGIT [0-9]+\.?|[0-9]*\.[0-9]+
%option noyywrap
%%
[ ]
{DIGIT} { yylval=atof(yytext); return NUM;}
\n|. {return yytext[0];}
YACC PART
%{
#include<ctype.h>
#include<stdio.h>
#define YYSTYPE double
%}
%token NUM
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
S : S E '\n' { printf("Answer: %g \nEnter:\n", $2); }
| S '\n'
|
| error '\n' { yyerror("Error: Enter once more…\n" );yyerrok; }
;
E : E '+' E { $$ = $1 + $3; }
| E'-'E { $$=$1-$3; }
| E'*'E { $$=$1*$3; }
| E'/'E { $$=$1/$3; }
| '('E')' { $$=$2; }
| '-'E %prec UMINUS { $$= -$2; }
| NUM
;
%%
#include "lex.yy.c"
int main()
{
printf("Enter the expression: ");
yyparse();
}
yyerror (char * s)
{
printf ("% s \n", s);
exit (1);
}
COMPILATION
OUTPUT
$lex file name.l
$yacc file name.y
$cc y.tab.c
$./a.outOUTPUT
Enter the expression: 2+3
Answer: 5
Enter:
2-3
Answer: -1
Enter:
4/3
Answer: 1.33333
Enter:
4/2
Answer: 2
Enter:
1/0
Answer: inf
Enter:
0/1
Answer: 0
0 Comments
Post a Comment