Browse Source

Add basic lexer and parser

main
raffitz 5 years ago
parent
commit
43fd5ee009
Signed by: raffitz
GPG Key ID: 0224483A6E6AC710
  1. 38
      lexer.l
  2. 45
      parser.y

38
lexer.l

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
%{
#include <stdio.h>
#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; }
%%

45
parser.y

@ -0,0 +1,45 @@ @@ -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 <exp> WEBDICE_TOKEN_CONST
%token <exp> 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 <exp> 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; }
;
%%
Loading…
Cancel
Save