note
blokhead
What you want is grammar <b>stratification</b> to give you precedence levels (as opposed to relying on rule matching order as you do now). Put the lowest precedence stuff at the top/outermost level of the grammar, and the highest-precendence stuff at the bottom/innermost level. This is one standard technique for writing grammars.
<p>
The basic structure of stratified rules is like this (at least for binary operations):
<code>
## for right-associative ops:
lower_prec_expr : higher_prec_expr lower_prec_op lower_prec_expr
| higher_prec expr
## for left-associative ops:
## warning: written this way, it is left-recursive.
lower_prec_expr : lower_prec_expr lower_prec_op higher_prec_expr
| higher_prec expr
</code>
You will have many layers of this type of thing (one for each level of precedence). You can think of it as the grammar matching the outermost expressions first (which have the lowest precedence, so are conceptually applied last), and then filling in the higher-precedence details later.
<p>
Here's an example for your purposes:
<code>
use Parse::RecDescent;
use Data::Dumper;
my $grammar = q{
startrule: logical_expr
logical_expr: comparison_expr logical_op logical_expr { [@item[1,2,3]] }
| comparison_expr
logical_op: /\\|\\||or|&&|and/
comparison_expr: paren_expr comparison_op comparison_expr { [@item[1,2,3]] }
| paren_expr
comparison_op: />=?|<=?|!=|==|le|ge|eq|ne|lt|gt/
paren_expr: '(' logical_expr ')' { $item[2] }
| atom
atom: /[A-Za-z_][A-Za-z0-9_]*/
};
my $parser = new Parse::RecDescent $grammar;
for (<DATA>) {
print $_;
print Dumper $parser->startrule($_);
print "============\n";
}
__DATA__
foo == bar || baz < bar
foo == bar || baz < bar || foo && bar
(foo || bar) || baz
</code>
This seems to output the kind of thing you want.
Notice how <tt>paren_expr</tt> must refer all the way back to the lowest-level precedence <tt>logical_expr</tt>!
<p>
<i>Postscript: Refer to <strike>the [isbn://0-201-10088-6|Dragon Book]</strike> or a similar parsing reference for more on stratification. (could have sworn the Dragon Book mentioned this, but it's not in the index)</i>
<p>
<b>Update:</b> [Limbic~Region] noticed that I had swapped left & right associativity in my examples. Now fixed.
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-137386">
<p>
blokhead
</div></div>
414823
414823