Maury Markowitz
Maury Markowitz

Reputation: 9283

optional parameters in bison

I'm toying with a BASIC interpreter in flex/bison based on gnbasic. I found a minor problem in the .y, bison complained about this code:

NEXT variable | NEXT {
    statement_t *new = mkstatement(NEXT);
    if (strlen($2) > 0) {
        new->parms.next = $2;
    }
  $$ = new;
}

It errored integer out of range: ‘$2’. I was quickly able to determine that it's because the second of the two forms, NEXT with no variable, doesn't have a $2. So that's easy, just separate this one out:

NEXT {
  statement_t *new = mkstatement(NEXT);
  $$ = new;
}

But is that the right solution? Is there some way I can leave these two combined and handle the optional parameter? I suspect this is not uncommon in most languages and that I'm missing the right terminology to ask Google.

Upvotes: 0

Views: 640

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126408

Your original code is equivalent to:

  NEXT variable { $$ = $1; }
| NEXT {
      statement_t *new = mkstatement(NEXT);
      if (strlen($2) > 0) {
          new->parms.next = $2;
      }
      $$ = new;
  }

-- every rule gets its own action; they are not 'shared' in any way between rules defined for the same non-terminal with |. If you want to factor common code between the two actions, you should write it as a function, and make each action just a call to your function.

Upvotes: 1

Related Questions