Skip to content

Instantly share code, notes, and snippets.

@AlexDenisov
Last active January 1, 2016 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlexDenisov/8169300 to your computer and use it in GitHub Desktop.
Save AlexDenisov/8169300 to your computer and use it in GitHub Desktop.
Flex/Bison studying.
%{
#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 */ }
%%
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
%{
#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