yacc arithmetic
YACC arithmetic expression
First, make sure you have Flex installed:
For installing on Ubuntu- sudo apt-get install flex bison
How to Compile and Run:
Clean and rebuild:
Plain Text
Copy
bison -d parser.y
flex lexer.l
gcc lex.yy.c parser.tab.c -o calculator -lm
Run the calculator:
Plain Text
Copy
./calculator
Just in case -
rm -f lex.yy.c parser.tab.* calculator
Assembly
Copy
---Save as lexer.l---
%{
#include "parser.tab.h"
#include <stdlib.h>
extern char* yytext;
void yyerror(char *);
%}
%%
[0-9]+(\.[0-9]+)? { yylval.dval = atof(yytext); return NUMBER; }
[ \t] ; /* ignore whitespace */
\n { return '\n'; }
. { return yytext[0]; }
%%
int yywrap(void) {
return 1;
}
Assembly
Copy
---Save as parser.y---
%{
#include <stdio.h>
#include <math.h>
void yyerror(char *);
int yylex(void);
extern char* yytext;
%}
%union {
double dval;
}
%token <dval> NUMBER
%type <dval> expr
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
input: /* empty */
| input expr '\n' { printf("= %g\n", $2); }
| input '\n' /* ignore empty lines */
;
expr: NUMBER { $$ = $1; }
| '(' expr ')' { $$ = $2; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '-' expr %prec UMINUS { $$ = -$2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main(void) {
printf("Enter arithmetic expressions (one per line, Ctrl+D to exit):\n");
yyparse();
return 0;
}
Comments
Post a Comment