Search code examples
parsingabnf

Does the order of rules in ABNF matter?


Does the order of rules in Augmented Backus-Naur Form matter?

In particular, are

a = b
b = c

and

b = c
a = b

the same?

What about

a = b
a =/ c

and

a =/ c
a = b

?

Would it be possible to have a rule using =/ without a rule of the same name using =?


Solution

  • Kind of. While it may make no difference regarding the result, you should always define your rule-sets in a way that the rules it depends on itself are already defined. When you are matching elements with certain rules, the order of the rules does of course influence the result.

    ABNF doesn't allow you to redefine rule-sets at a later point, so it must always be the same. (ABNF is not a programing language, rules are not variables)

    a = b
    b = c
    

    The example above would make no sense. In this short example it's apparent what this is supposed to mean, but in a long RFC these lines could be separated by a wall of text.

    b = c
    a = b
    

    Are those the same?

    Yes, rules are not variables - but I'd recommend the second notation/order

    a = b
    a =/ c
    

    =/ defines an incremental alternative, or as specifically defined in the RFC:

    That is, an initial rule may match one or more alternatives, with later rule definitions adding to the set of alternatives.

    There are cases where it might not matter, but it can't be assumed to always the case.

    In your case it's the same as writing

    a = b / c
    

    =/ shouldn't come before = for reasons of readability (and logic).

    Would it be possible to have a rule using =/ without a rule of the same name using =?

    Not really, no. a /= b would simply be a = b then.