Multiple Variable Calculator Flex/Bison -


i'm writing calculator in flex/bison allows variables. right have 1 variable (x) can use. want able use more x. (rather a-z). can help? here's have far:

calculator.y

%{     #include <stdio.h>     #include <math.h>     void yyerror(char *);     int yylex(void);     int symbol; %}  %token integer variable %left '+' '-' '*' '/' '^'  %%  program:     program statement '\n'     | /* null */     ; statement:     expression          { printf("%d\n", $1); }     | variable '=' expression   { symbol = $3; }     ; expression:         integer      | variable          { $$ = symbol; }     | '-' expression        { $$ = -$2; }     | expression '+' expression { $$ = $1 + $3; }     | expression '-' expression { $$ = $1 - $3; }     | expression '*' expression { $$ = $1 * $3; }     | expression '/' expression { $$ = $1 / $3; }     | expression '^' expression { $$ = pow($1, $3); }     | '(' expression ')'        { $$ = $2; }     ;  %%  void yyerror(char *s) {     fprintf(stderr, "%s\n", s); } int main(void) {     yyparse(); } 

calculator.l

    /* calculator */ %{     #include "y.tab.h"     #include <math.h>     #include <stdlib.h>     void yyerror(char *); %}  %%  [x] {         yylval = *yytext - 'a';         return variable;     }  [0-9]+ {          yylval = atoi(yytext);         return integer;        }  [-+*/^()=\n] { return *yytext; }  [ \t]   ; /* skip whitespace */  .          yyerror("unknown character");  %%  int yywrap(void) {     return 1; } 

your lexer needs recognize [a-z] instead of [x].

in grammar, need define array int variables[26];

in rule(s) variable assigned, assign variables[$1] (for example) , variable referenced, use $$ = variables[$1]; (for example). check n in $n correct value.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -