0

Let's say I had an EBNF like this:

<Expr> -> <Term> {( + | - ) <Term>}

The {} brackets mean choose zero or more, so how would I know when I have just <Term> vs something like <Term> + <Term> + <Term> when I'm reading the line character by character?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
dtgee
  • 1,272
  • 2
  • 15
  • 30

1 Answers1

1

Assuming you have a recursive descent parser, what you want to do is look ahead one token. If you've just read a <Term> and the next token is + or - then you follow this production. If it's not, then this <Expr> production is complete and you return to the caller.

To implement this in code, you want something like a global lookaheadToken variable. You can use that token to make decisions on how to proceed with parsing before you actually commit to a particular production and consume the token.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578