See Re: Left-associative binary operators in Parse::RecDescent for my preferred technique of doing precedence in grammars (stratification). You have one layer (stratum) for each precedence levels. Your grammar's starting rule is at the lowest precedence and the subrules increase in precedence. Finally, at the bottom level (of highest precedence), you have the rule for parenthesized expressions which recurses back to the top level (of lowest precedence). But this is unambiguous, because of the parentheses in this recursion rule.

P::RD may have other bells & whistles to help with precedence, but this is the only way I can ever remember to do precedence correctly, and it works with any kind of parser (although you may have to factor out left-recursion in right-associative operators).

Update: BTW, you can string together all operations of the same precedence level, which is probably more efficient. I.e, parse (a+b)*c*d*e*(f+g) into a shallow parse tree whose root has 5 children, instead of having a deeper parse tree whose nodes always have 2 children. However, for simplicity/uniformity it's often nice to always know that each node of the parse tree is a simple binary operation.

blokhead


In reply to Re: Order of Precedence in Parse::RecDescent grammar by blokhead
in thread Order of Precedence in Parse::RecDescent grammar by suaveant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.