parsinglemon

Lemon Parser - How can I set different associativity for unary minus and substraction?


expr ::= expr MINUS expr.
expr ::= MINUS expr.

I need to set different associativity for the 2 MINUS tokens. But I can't twice set associativity for MINUS.

%left PLUS MINUS. // + -
%right NOT MINUS. // ! - // error!

Solution

  • This is answered in the Lemon documentation, which provide an example of that specific requirement:

    The precedence of a grammar rule is equal to the precedence of the left-most terminal symbol in the rule for which a precedence is defined. This is normally what you want, but in those cases where you want the precedence of a grammar rule to be something different, you can specify an alternative precedence symbol by putting the symbol in square braces after the period at the end of the rule and before any C-code. For example:

       expr = MINUS expr.  [NOT]
    

    This rule has a precedence equal to that of the NOT symbol, not the MINUS symbol as would have been the case by default.

    The above example assumes you have a token NOT which you have placed in the correct order in your precedence list.