简体   繁体   中英

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.

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? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM