bcalc

cli bitcoin unit calculator
git clone git://jb55.com/bcalc
Log | Files | Refs | README | LICENSE

parser.y (1486B)


      1 %{
      2 
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 
      6 #include "num.h"
      7 
      8 enum unit g_output_format;
      9 int g_print_unit;
     10 
     11 %}
     12 
     13 %union {
     14   int64_t intval;
     15   double floatval;
     16   struct lexunit lexunit;
     17   struct num num;
     18 }
     19 
     20 %token<intval> T_INT
     21 %token<floatval> T_FLOAT
     22 %token<lexunit> T_UNIT
     23 
     24 %token T_PLUS T_MINUS T_MULTIPLY T_DIVIDE T_LEFT T_RIGHT T_IN
     25 %token T_NEWLINE T_QUIT
     26 %left T_PLUS T_MINUS
     27 %left T_MULTIPLY T_DIVIDE
     28 
     29 %type<num> expr unit_number number mul_expr div_expr
     30 
     31 %start calc
     32 
     33 %%
     34 
     35 calc:
     36     | calc line
     37 ;
     38 
     39 line: T_NEWLINE
     40     | expr T_NEWLINE { num_print(&$1, g_output_format, NULL, g_print_unit); }
     41     | expr T_IN T_UNIT T_NEWLINE {
     42         num_print(&$1, $3.unit, $3.name, g_print_unit);
     43       }
     44     ;
     45 
     46 unit_number:
     47         T_INT T_UNIT     { num_init_int(&$$, $1, $2.unit); }
     48       | T_FLOAT T_UNIT   { num_init_float(&$$, $1, $2.unit); }
     49       ;
     50 
     51 
     52 number: T_INT    { num_init_int(&$$, $1, UNIT_NONE); }
     53       | T_FLOAT  { num_init_float(&$$, $1, UNIT_NONE); }
     54       ;
     55 
     56 mul_expr: number T_MULTIPLY expr    { num_mul(&$$, &$3, &$1); }
     57         | expr   T_MULTIPLY number  { num_mul(&$$, &$1, &$3); }
     58         ;
     59 
     60 div_expr: /* number T_DIVIDE expr   { num_div(&$$, &$1, &$3); } */
     61           expr   T_DIVIDE number { num_div(&$$, &$1, &$3); }
     62         ;
     63 
     64 expr: unit_number
     65     | expr T_PLUS expr      { num_add(&$$, &$1, &$3); }
     66     | expr T_MINUS expr     { num_sub(&$$, &$1, &$3); }
     67     | mul_expr
     68     | div_expr
     69     | T_LEFT expr T_RIGHT   { num_init(&$$); num_assign(&$$, &$2); }
     70 ;
     71 
     72 %%