javacc

How could I call several times a method based on the user input in JavaCC?


I have unsuccessfully tried to append several times a method group() that returns a string. My code works well only for the times I call the method, but fails to append the number of times the user calls group().

For instances, the following code would append the resulting string from the group() call three times. Then, when I type "end", description() would print the three strings appended in sb. "start" is the token used to initiate each group() call (start is used in group()).

TOKEN : 
{
  < START: "start" >
| < END: "end" >
}
String description() :
{
  StringBuffer sb = new StringBuffer();
}
{
  {
    sb.append(group());
    sb.append(group());
    sb.append(group());
  }
  < END >
  {
    return sb.toString();
  }
}

However, what I am really trying to achieve is that, if the user calls group() four times (using the token "start"), the description method would append for groups of strings. Essentially, it would append the number of strings based on the user's input. I have been told a useful way to do it is using (group())*. Nevertheless, I haven't gotten it to work.


Solution

  • Try something like this:

    String description() :
    {
      StringBuffer sb = new StringBuffer();
      Object o;
    }
    {
      (
        o=group() {sb.append(o);}
      )*
      <END>
      {
        return sb.toString();
      }
    }