0

I am implementing a parser based on javacc which will be able to GW Basic programs.

I implemented for loop like this

void forloop(Token line):
{
    Token toV;
    Token toI;
    Token step;
    Token next;
    Token var;
}
{
    <FOR> var=<VARIABLE> "=" Expression() { instructions.add("STORE " + var.image); } <TO> toV=<INTEGER> <STEP> step=<INTEGER> 
    {   
        instructions.add("LABEL "+labelsCntr);
        instructions.add("LOAD "+var.image);
        instructions.add("CONST "+toV.image);
        instructions.add("SUB");
        instructions.add("CONST 0");

    }
    ( Line() )*
    next = <INTEGER> <NEXT> <VARIABLE>
    {
        instructions.add("LINE "+next.image);
        instructions.add("LOAD "+step.image);
        instructions.add("LOAD "+var.image);
        instructions.add("ADD");
        instructions.add("JMP LABEL "+(labelsCntr));

        labelsCntr++;

    }    
}

But it does not work.

How can I implement for loop so that it works.

Or where I am doing wrong.

Thanks in advance.

arnold
  • 1,682
  • 8
  • 24
  • 31

1 Answers1

2

There are two things I don't see in your machine code that I would have expected. One is a conditional jump out of the loop. When the variable exceeds toV, control should jump to the first instruction after the loop. Second I don't see where the var is changed. At the end of the loop you add the value of the variable to the step value, but you don't store the result back into the variable.

There are also a few checks I expect need to be done at compile time that are missing: That the variable in the NEXT statement matches that in the VAR and that the step is positive.

Theodore Norvell
  • 15,366
  • 6
  • 31
  • 45