What you want is grammar
stratification 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.
The basic structure of stratified rules is like this (at least for binary operations):
## 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
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.
Here's an example for your purposes:
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
This seems to output the kind of thing you want.
Notice how
paren_expr must refer all the way back to the lowest-level precedence
logical_expr!
Postscript: Refer to the Dragon Book or a similar parsing reference for more on stratification. (could have sworn the Dragon Book mentioned this, but it's not in the index)
Update: Limbic~Region noticed that I had swapped left & right associativity in my examples. Now fixed.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.