-
-
Save ffbit/8169990 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%{ | |
#include "parser.h" | |
%} | |
%option noyywrap | |
%% | |
"+" { return ADD; } | |
"-" { return SUB; } | |
"*" { return MUL; } | |
"/" { return DIV; } | |
"|" { return ABS; } | |
"!" { return NEGATE; } | |
"(" { return OP; } | |
")" { return CP; } | |
-?[0-9]+ { yylval = atof(yytext); return NUMBER; } | |
\n { return EOL; } | |
[ \t] { /* ignore */ } | |
. { /* ignore */ } | |
%% | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all: calc | |
calc: parser lexer | |
CC lexer.c parser.c -o calc | |
lexer: | |
flex -o lexer.c lexer.l | |
parser: | |
bison -d -o parser.c parser.y | |
clean: | |
rm -f parser.[h,c] | |
rm -f lexer.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%{ | |
#include <stdio.h> | |
extern int yylex(void); | |
extern int yyerror(char *s); | |
%} | |
%token NUMBER | |
%token ADD SUB MUL DIV | |
%token ABS NEGATE | |
%token EOL | |
%token OP CP | |
%% | |
calclist: /*nothing*/ | |
| calclist exp EOL { printf("= %d\n", $2); } | |
; | |
exp: factor | |
| exp ADD factor { $$ = $1 + $3; } | |
| exp SUB factor { $$ = $1 - $3; } | |
; | |
factor: term | |
| factor MUL term { $$ = $1 * $3; } | |
| factor DIV term { $$ = $1 / $3; } | |
; | |
term: NUMBER | |
| ABS term { $$ = $2 >= 0 ? $2 : - $2; } | |
| NEGATE term { $$ = $2 * -1; } | |
| OP exp CP { $$ = $2; } | |
; | |
%% | |
int main(int argc, char **argv) | |
{ | |
yyparse(); | |
return 0; | |
} | |
int yyerror(char *s) | |
{ | |
fprintf(stderr, "error: %s\n", s); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment