- or download this
term -> atom operator term
term -> '(' term ')'
term -> atom
operator -> '*' | '/'| '+' | '-'
atom -> \d+
- or download this
term ->
atom operator term
...
'2' '*' ('3' '+' term)
'2' '*' ('3' '+' (atom))
'2' '*' ('3' '+' ('4'))
- or download this
expression -> (term add_op)* term
term -> (factor mul_op)* factor
...
add_op -> '+' | '-'
mul_op -> '*' | '/'
atom -> \d+
- or download this
expression
term add_op term
...
(factor mulop factor) '+' ('4')
((atom) mulop (atom)) '+' ('4')
(('2') '*' ('3') ) '+' ('4')
- or download this
#!/usr/bin/perl
use strict;
...
[ 'AddOp', '+' ],
[ 'Number', '4' ]
];
- or download this
sub match {
my $expected_token = shift;
...
}
return 1;
}
- or download this
sub expression {
my @res = (term());
...
sub atom {
match('Number');
}
- or download this
my $parse_tree = expression();
print Dumper $parse_tree;
...
'+',
[ '4' ]
];
- or download this
# parse tree for '2 * (3+4)':
[
...
'*',
[ '3', '+', '4' ],
];
- or download this
my $parse_tree = expression();
match('EOF');
- or download this
sub execute {
my $tree = shift;
...
}
print execute($parse_tree), "\n";
- or download this
sub make_rule {
my ($operator, $next) = @_;
...
*term = make_rule('MulOp', \&factor);
*expression = make_rule('AddOp', \&term);
- or download this
grammar Arithmetic {
...
# match it:
$input ~~ Grammar.expression;
- or download this
rule factor {
| <atom>
| '(' <expression> [ ')' || <panic: Expected ')'> ]
}
- or download this
# this example mixes official Perl 6 syntax an PGE syntax,
# I don't really know if they are 100% compatible
...
rule expression is optable { ... }; # yes, '...' is valid Perl 6 ;-)
proto 'term:' is tighter('infix:*')
is parsed(&factor) { ... };
- or download this
ModernArithmetic is Arithmetc {
token infix:</> { '÷' } # different symbol, same rule name
}