<p>I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:</p>

<pre><code>%token &lt;int&gt; INT
%token &lt;string&gt; ID
%token MINUS

%start expr
%type &lt;expr&gt; expr

%nonassoc INT ID
%left MINUS
%left APPLY

%%

expr: INT
    { ExprInt $1 }
| ID
    { ExprId $1 }
| expr MINUS expr
    { ExprSub($1, $3) }
| MINUS expr
    { ExprNeg $2 }
| expr expr %prec APPLY
    { ExprApply($1, $2) };
</code></pre>

<p>The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?</p>

[{'answer_id': 24589, 'author': 'James A. Rosen', 'author_id': 1190, 'author_profile': 'https://Stackoverflow.com/users/1190', 'pm_score': 4, 'selected': True, 'text': "<p>Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.</p>\n\n<ol>\n<li>split <code>expr</code> into <code>simple_expr</code> and <code>expr_with_prefix</code></li>\n<li>allow only <code>simple_expr</code> or <code>(expr_with_prefix)</code> in an APPLY</li>\n</ol>\n\n<p>The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that.</p>\n\n<p>You're going to have the same problem with 'a b c': is it <code>a(b(c))</code> or <code>(a(b))(c)</code>?  You'll need to also break off <code>applied_expression</code> and required <code>(applied_expression)</code> in the grammar.</p>\n\n<p>I think this will do it, but I'm not sure:</p>\n\n<pre><code>expr := INT\n      | parenthesized_expr\n      | expr MINUS expr\n\nparenthesized_expr := ( expr )\n                    | ( applied_expr )\n                    | ( expr_with_prefix )\n\napplied_expr := expr expr\n\nexpr_with_prefix := MINUS expr\n</code></pre>\n"}, {'answer_id': 7678584, 'author': 'Chris Dodd', 'author_id': 16406, 'author_profile': 'https://Stackoverflow.com/users/16406', 'pm_score': 0, 'selected': False, 'text': '<p>Well, this simplest answer is to just ignore it and let the default reduce/reduce resolution handle it -- reduce the rule that appears first in the grammar.  In this case, that means reducing <code>expr MINUS expr</code> in preference to <code>MINUS expr</code>, which is exactly what you want.  After seeing <code>a-b</code>, you want to parse it as a binary minus, rather than a unary minus and then an apply.</p>\n'}]
['https://Stackoverflow.com/questions/24516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1891/']