I hadn't played with Marpa before so I thought I'd have a look:
#!/usr/bin/perl
use warnings;
use strict;
use Marpa::R2;
package Element;
sub newNode {
my ($value, $left, $right) = @_;
return bless {left => $left, right => $right, value => $value}, 'E
+lement';
}
sub doOp {
my @params = @_;
return newNode(@params[2, 1, 3],);
}
sub doConst {
my @params = @_;
return newNode($params[1]);
}
sub dump {
my ($node, $indent) = @_;
$indent //= '';
$node->{left}->dump("$indent ") if $node->{left};
print "$indent$node->{value}\n";
$node->{right}->dump("$indent ") if $node->{right};
}
package main;
my $syntax = <<'SYNTAX';
lexeme default = latm => 1
expression ::= expression '+' term action => doOp | term action => ::f
+irst
term ::= term '*' factor action => doOp | factor action => ::first
factor ::= constant action => doConst
constant ~ digits
digits ~ [\d]+
:discard ~ spaces
spaces ~ [\s]+
SYNTAX
my $grammar = Marpa::R2::Scanless::G->new({source => \$syntax});
my $input = '1 * 2 + 3 * 4';
my $root = $grammar->parse(\$input, 'Element');
($$root)->dump();
Prints:
1
*
2
+
3
*
4
No idea if that helps or not, but it was interesting to have a play.
Premature optimization is the root of all job security