parsingbisonyacccontext-free-grammarlalr

Why a rule for each operation in Bison


While searching for Bison grammars, i found this example of C grammar:

https://www.lysator.liu.se/c/ANSI-C-grammar-y.html

logical_and_expression
    : inclusive_or_expression
    | logical_and_expression AND_OP inclusive_or_expression
    ;
logical_or_expression
    : logical_and_expression
    | logical_or_expression OR_OP logical_and_expression
    ;

I didn't understand the reason for a rule for each logical operation. Is there an advantage over this construction below?

binary_expression:
    : object // imagine it can be bool, int, real ...
    | binary_expression AND_OP binary_expression
    | binary_expression OR_OP binary_expression
    ;

Solution

  • The grammar you quote is unambiguous.

    The one you suggest is ambiguous, although yacc/bison allow you to use precedence rules to resolve the ambiguities.

    There are some advantages to using a grammar which makes operator precedence explicit:

    On the other hand, precedence rules do have some advantages:

    The total size of the grammar is not really affected by using precedence rules. As mentioned, the precedence rules avoid the need for unit productions, but every unit production corresponds to one precedence declaration so the total number of lines is the same. There are fewer non-terminals, but non-terminals cost little; the major annoyance in yacc/bison is declaring all the semantic types, but that is easy to automate.