Search code examples
bnf

How does the | affect a BNF grammar?


I'm working on a school project that requires me to parse a BNF grammar. I'm a little confused as to what role the pipe character (|) - which I believe means "or" - plays in a rule.

For example, if I had the following:

<a> ::= b c d | e f g

Which of the terminals is the | applied to? Using parentheses for grouping, which would describe how the "or" is applied?

(b c d) | (e f g)

(b c) (d) | (e) (f g)

Is the | applied to the entire set of terminals, or just the two next to the |?

And what if I had a set up like:

<a> ::= b | <c> <d>
<b> ::= e | f
<c> ::= g | h

Would it still be true if <c> and <d> refer to non-terminals? To what would the | be applied in this case?


Solution

  • In general,

    rule := a b c | d e f
    

    is grouped as

    rule := (a b c) | (d e f)
    

    This doesn't change whether or not you apply them to terminals or non-terminals.