diff --git a/lexer.l b/lexer.l new file mode 100644 index 0000000..62489f5 --- /dev/null +++ b/lexer.l @@ -0,0 +1,38 @@ +%{ + +#include +#include "expression.h" +#include "parser.tab.h" + +%} + +%% + +"\n" { return WEBDICE_TOKEN_EOL; } +-?[0-9]+ { + int64_t aux; + + sscanf(yytext,"%ld",&aux); + yylval.exp.constant.id = WEBDICE_CONST; + yylval.exp.constant.value = aux; + return WEBDICE_TOKEN_CONST; + } +-?[0-9]+d[0-9]+ { + int64_t count,type; + + sscanf(yytext,"%ldd%ld",&count,&type); + yylval.exp.roll.id = WEBDICE_ROLL; + yylval.exp.roll.count = count; + yylval.exp.roll.type = type; + return WEBDICE_TOKEN_ROLL; + } +"(" { return WEBDICE_TOKEN_LPAREN; } +")" { return WEBDICE_TOKEN_RPAREN; } +"*" { return WEBDICE_TOKEN_MUL; } +"/" { return WEBDICE_TOKEN_DIV; } +"+" { return WEBDICE_TOKEN_ADD; } +"-" { return WEBDICE_TOKEN_SUB; } +[ \t]+ {} +. { fprintf(stderr,"%s",yytext); return WEBDICE_TOKEN_EOL; } + +%% diff --git a/parser.y b/parser.y new file mode 100644 index 0000000..bbaff25 --- /dev/null +++ b/parser.y @@ -0,0 +1,45 @@ +%{ +#include "expression.h" + +int yylex(); +int yyerror(char*); + +%} + +%parse-param {union expression** root}; + +%union { + union expression* exp; +} + +%token WEBDICE_TOKEN_EOL +%token WEBDICE_TOKEN_CONST +%token WEBDICE_TOKEN_ROLL +%token WEBDICE_TOKEN_LPAREN +%token WEBDICE_TOKEN_RPAREN + +%left WEBDICE_TOKEN_ADD +%left WEBDICE_TOKEN_SUB +%left WEBDICE_TOKEN_MUL +%left WEBDICE_TOKEN_DIV + +%type expression + +%start lines + +%% +expression: expression WEBDICE_TOKEN_ADD expression { $$ = webdice_add($1,$3); } + | expression WEBDICE_TOKEN_SUB expression { $$ = webdice_sub($1,$3); } + | expression WEBDICE_TOKEN_MUL expression { $$ = webdice_mul($1,$3); } + | expression WEBDICE_TOKEN_DIV expression { $$ = webdice_div($1,$3); } + | WEBDICE_TOKEN_CONST { $$ = $1; } + | WEBDICE_TOKEN_ROLL { $$ = $1; } + | WEBDICE_TOKEN_LPAREN expression WEBDICE_TOKEN_RPAREN { $$ = $2; } + ; + +lines: + | lines WEBDICE_TOKEN_EOL { (*root) = NULL; } + | lines expression WEBDICE_TOKEN_EOL { (*root) = $2; } + ; + +%%