开发者

Creating multiple variables yacc

I am creating a compiler in yacc but I cannot find a way to allow the user to create multiple variables with individual identifiers. Currently they can assig开发者_StackOverflown a number to a word but all words have the same value. The code I'm using it:

...

%{
float var=0;
%}

...

exp: NUMBER 
   | WORD { $$ = var; }
   | exp '/' exp {  $$ = $1 / $3; }
   | ...


$$ will assign to the exp token the value var. So this is static.

If you want to parse some WORD and get its value, you should use $$ = $1 where $1 is the value of the first token of your rule (id est the WORD token)

Is that what you intended to do? I'm not sure about that, since you've done it right for the exp '/' exp ?

EDIT: To store each word in variable, I'd suggest you to use a table of floats. You will need to use a counter to increment the table index. But you should take care that the different words values will be stored in the matching order.

EDIT2: (Don't know if it will compile as is) I think it would look like :

exp: NUMBER
   | variable AFFECT exp { $$ = $3; var[ctr][0]="$1"; var[ctr][1]=$3; ctr++; }
   | variable { $$ = lookupVar($1); }

And define lookupVar to look for the string $1 within the table


Your code seems to be similar to mfcalc sample in bison manual.
Probably mfcalc sample will provide useful information, even if it isn't fully identical to your purpose.
mfcalc has a symbol table in order to keep the names of VAR(probably corresponds to WORD in your code).
Actually mfcalc enforces symbol name look-up in lexical analysis, and assigns a pointer to symbol record, to the semantic value of VAR.
In bison source code, the semantic value can be referred simply as like $1->value.var.
Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜