Search code examples
javabnf

how to represent Java-style OR in BNF?


Good day. I was wondering, if I wanted to do a Backus-Naur form representing for example an if-else clause in Java, how would I go about using OR and AND for multiple conditions? I know that AND can be simply represented with &&, and OR with ||. But as vertical lines are already part of BNF syntax, I would like to know if this is allowed anyways.


Solution

  • From: https://users-cs.au.dk/amoeller/RegAut/JavaBNF.html

    <conditional or expression> ::= <conditional and expression> | <conditional or expression> || <conditional and expression>
    
    <conditional and expression> ::= <inclusive or expression> | <conditional and expression> && <inclusive or expression>
    

    Logical or is pretty unambiguous because you have two ||, but you can always represent literals in bold, or another font or quotes.

    Another example here: https://users-cs.au.dk/amoeller/RegAut/JavaBNF.html uses bold and a fixed width font for literals.

    Wiki shows quotes which is safest if you don't have multiple fonts available:

    <expression> ::= <list> | <list> <opt-whitespace> "|" <opt-whitespace> <expression>