Richard
Richard

Reputation: 135

JavaCC: Nesting for-loops

The question I have is how would I go about creating a nested for-loop within JavaCC.

At the moment I have:

(
 < REPEAT >h=<NUMBER ><REPEAT >k=< NUMBER ><PRINT >t=< PHRASE ><ENDPRINT ><ENDREPEAT ><ENDREPEAT >
 {
   int hold = Integer.parseInt(h.image);
   int holdK = Integer.parseInt(k.image);

   for(int i =0; i < hold;i++)
   {
     for(int j =0; j < holdK;j++)
     {
       System.out.println(t.image);
     }
   }
 }
)

This will obviously allow for a single nested loop to work but how would I integrate an arbitrary amount of nested loops.

An example would be if the user wanted to create

for(int i =0; i < x;i++)
{
 print;
  for(int j=0; j<k;j++)
  {
  print;
  for(int l=0;l<f;l++)
   {
     print;
   }
  }
}

Any help will be appreciated. Thank you.

Upvotes: 0

Views: 396

Answers (1)

Theodore Norvell
Theodore Norvell

Reputation: 16241

You should start with a sensible grammar for your language. Since I don't know the language, I can only guess at what a sensible grammar would be, but it is likely something like this.

Command --> REPEAT NUMBER Block ENDREPEAT | PRINT Phrase ENDPRINT
Block --> { Command }

Second you should not try to interpret the language during parsing. Parse first, interpret later. This point is covered in the FAQ under 7.3 I'm writing a programming language interpreter; how do I deal with loops?.

Upvotes: 2

Related Questions