This seems to work... I am guessing it is basically the shortcut way to do what
blokhead proposed... I was able to get it to return a little less depth in the tree, though it isn't quite perfect.
Here is my grammar, for posterity's sake.
my $grammar = <<'GRAMMAR'
{
use strict;
use warnings;
sub treeify {
my $t = shift;
# my($l,$r) = (shift,shift);
while(@_) {
my($l,$r) = (shift,shift);
$t = [ 'op',$l, (ref $t eq 'ARRAY' && !$#$t ? @$t : $t), (ref
+ $r eq 'ARRAY' && !$#$r ? @$r : $r) ]
}
return $t;
}
}
startrule: bin_op
bin_op: comp_op
# Lowest precendance.
comp_op: <leftop: add_op COMP add_op>
{ treeify(@{$item[1]}); }
add_op: <leftop: prod_op SUM prod_op >
{ treeify(@{$item[1]}); }
prod_op : <leftop: mod_op PROD mod_op >
{ treeify(@{$item[1]}); }
# Highest precendance.
mod_op : <leftop: term MOD term >
{ treeify(@{$item[1]}); }
SUM : '+' | '-'
PROD : '*' | '/'
MOD : '%'
COMP : />=?|<=?|!=|==?|le|ge|eq|ne|lt|gt/
term: function
| '(' bin_op ')' { $item[2] }
| number
| string
if: /if/i '(' list_bin_op list_bin_op bin_op ')' { ['func',@item[1,3
+..5]] }
concat: /concat/i '(' list_bin_op(s) bin_op ')' { ['func',$item[1],@
+{$item[3]},$item[4]] }
left: /left/i '(' list_bin_op bin_op ')' { ['func',@item[1,3,4]] }
right: /right/i '(' list_bin_op bin_op ')' { ['func',@item[1,3,4]] }
ifnull: /ifnull/i '(' list_bin_op bin_op ')' { ['func',@item[1,3,4]]
+ }
function: if | concat | left | right | ifnull
number: /[+-]?\d+/ { $item[1] }
string: { $_ = extract_quotelike($text); chop; substr($_,0,1,''); $_
+; } { [@item] }
#$thisparser->startrule($item[2],1,$type)
list_bin_op: bin_op ',' { $item[1] }
GRAMMAR
;
This is actually parsing MySQL-like statements, so there is a bit in there for some function definitions, seems to work, though. Thanks all!
- Ant
- Some of my
best work - (1 2 3)
-
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.