0

I was writing a simple compiler to execute MOV and ADD instructions. Here is part of my yacc code...

            %{
              char *name
              extern char *yytext
            %}

        %token MOV ADD    /*name of instructions returned from lexer*/
        %token REG ACC OP  /*REG implies Register names such as R0-R7, ACC implies name of accumulator such as A-F, OP implies operand such as 0-9*/
        %type <val> mov_inst add_instr
        %type <string> reg REG
        %type <index>  acc ACC

       %%
        program: instr  {printf("The value of %s is:%d\n", name, $1);}
        instr: add_instr;
        add_instr: ADD acc OP  {$$ = mem[$2] = mem[$2] + $3;}
           | ADD acc reg  {$$ = mem[$2] = mem[$2] + regmem[regIdx];}
           ;
       acc: ACC {$$ = mem[$1]; name = strdup(yytext);}
       reg: REG {$$ = strdup(yytext); name = $1;}
          ;

Here for the instruction of type

               ADD B 5; result should be printed as  
           "The value of B is 5" which is working fine. 

SIMILARLY for

              ADD B R1 -> it should be 
              "The value of B is 8" (say R1=3);

But Iam getting is as

               "The value of R1 is 8" 

its printing the name R1 instead of B. Iam not sure why!
I need to get B inplace of R1 in the result

          "The value of R1 is 8" should be like "The value of B is 8"

any suggestions!!!

Shilpa
  • 15
  • 6
  • 1
    Possible duplicate of [Why does this bison code produce unexpected output?](http://stackoverflow.com/questions/13151570/why-does-this-bison-code-produce-unexpected-output) – rici Oct 19 '16 at 14:04
  • Just quickly looking at this you have declared `name` as a global and it is altered by both `acc: ACC` and `reg: REG` – Michael Petch Oct 19 '16 at 21:26
  • 1
    @MichaelPetch Yes I agree. I tried altering only reg:REG and it worked as I expected. Thanks :) – Shilpa Oct 20 '16 at 04:18

0 Answers0