ratio

cli rational number calculator
git clone git://jb55.com/ratio
Log | Files | Refs | README | LICENSE

parser.y (1007B)


      1 %{
      2 
      3 #include <stdio.h>
      4 #include <gmp.h>
      5 #include <stdlib.h>
      6 
      7 extern int yylex();
      8 extern int yyparse();
      9 extern FILE* yyin;
     10 
     11 char buffer[255];
     12 
     13 void yyerror(const char* s);
     14 %}
     15 
     16 %union {
     17   mpq_t rval;
     18 }
     19 
     20 %token<rval> T_RATIO
     21 %token T_PLUS T_MINUS T_MULTIPLY T_DIVIDE T_LEFT T_RIGHT
     22 %token T_NEWLINE T_QUIT
     23 %left T_PLUS T_MINUS
     24 %left T_MULTIPLY T_DIVIDE
     25 
     26 %type<rval> expr
     27 
     28 %start calc
     29 
     30 %%
     31 
     32 calc:
     33     | calc line
     34 ;
     35 
     36 line: T_NEWLINE
     37     | expr T_NEWLINE { mpq_out_str(stdout, 10, $1); printf("\n"); }
     38 ;
     39 
     40 expr: T_RATIO               { mpq_set($$, $1); }
     41     | expr T_PLUS expr      { mpq_add($$, $1, $3); }
     42     | expr T_MINUS expr     { mpq_sub($$, $1, $3); }
     43     | expr T_MULTIPLY expr  { mpq_mul($$, $1, $3); }
     44     | expr T_DIVIDE expr    { mpq_div($$, $1, $3); }
     45     | T_LEFT expr T_RIGHT   { mpq_init($$); mpq_set($$, $2); }
     46 ;
     47 
     48 %%
     49 
     50 int main() {
     51   yyin = stdin;
     52 
     53   do {
     54     yyparse();
     55   } while(!feof(yyin));
     56 
     57   return 0;
     58 }
     59 
     60 void yyerror(const char* s) {
     61   fprintf(stderr, "Parse error: %s\n", s);
     62   exit(1);
     63 }