Desk Calculator with Error Recovery - Yacc Program - Compiler Design

Program:

// Lex file: desk.l

DIGIT [0-9]+\.?|[0-9]*\.[0-9]+

%%

[ ]
{DIGIT}    {yylval=atof(yytext);return NUM;}
\n|.             {return yytext[0];}

// Yacc file: desk.y

%{
    #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();
}

Output:

nn@linuxmint ~ $ lex desk.l
nn@linuxmint ~ $ yacc desk.y
nn@linuxmint ~ $ gcc y.tab.c -ly -lfl
nn@linuxmint ~ $ ./a.out
Enter the expression: 1.8+2.8
Answer: 4.6
Enter:
1.8*10
Answer: 18
Enter:
20.34/.2
Answer: 101.7
Enter:
101.7*.2
Answer: 20.34
Enter:
20.34-18.31
Answer: 2.03
Enter:
^C
nn@linuxmint ~ $

1 comment:

Related Posts Plugin for WordPress, Blogger...