Lexy Acc
-
Upload
ganesh-chavan -
Category
Documents
-
view
1 -
download
0
description
Transcript of Lexy Acc
LEX AND YACC
Implementation of Calculator using LEX and YACC.
Description:
Lex is used for breaking up an input stream into more usable elements. Lex is used for tokenizing input
i.e separating input into the lowest-level objects that your grammar defines.
YACC is used for analyzing the structure of the input stream.YACC stands for “Yet Another Compiler
Compiler”. YACC is a parser that tokenizes input provided by Lex. YACC performs parsing of grammer.
//LEX FILE
%{
#include <math.h>
#include "y.tab.h"
extern double vblt[26];
%}
%%([0-9]+|([0-9]*\.[0-9]+)([eE][+-]?[0-9]+)?) {yylval.dval=atof(yytext);
return NUMBER;}
[\t ] ;
sqrt {return SQRT;}
log {return LOG;}
[a-z] { yylval.vblno=yytext[0]-'a';
return NAME; }
"$" {return 0;}
\n|. return yytext[0];
%%
//yacc file
%{
#include<stdio.h>
#include <math.h>
double vblt[26];
%}
/*%union is used to collect all the attributes which are going to used in our program */
%union {
float dval;
int vblno;
}
/*this is used to know yacc file that which attribute is attached to which terminal */
%token <vblno> NAME%token <dval> NUMBER%token SQRT LOG
/* Priority & associativity */
%left '-' '+'%left '*' '/'
%nonassoc UMINUS
/*this is used to know yacc file that which attribute is attached to which non-terminal */
%type <dval> expression
%%
statement_list:statement '\n'| statement_list statement '\n'
;
statement: NAME '=' expression {vblt[$1]=$3;}| expression {printf("=%f\n",$1);}
;
expression: expression '+' expression {$$=$1+$3;}
| expression '-' expression {$$=$1-$3;}
| expression '*' expression {$$=$1*$3;}
| expression '/' expressionif($3==0.0)
yyerror("divide by zero");
else
$$=$1/$3;}
| '-' expression %prec UMINUS {$$=-$2;}
| '(' expression ')' {$$=$2;} | SQRT '(' expression ')' {$$=sqrt($3);} | LOG '(' expression ')' {$$=log($3);}
| NUMBER
| NAME {$$=vblt[$1];};
%%
main()
{ //extern double sqrt(),exp(),log();
yyparse(); return 0;
}
int yyerror(char *s)
{
printf("%s",s);
return 0;
}