Skip to content

Instantly share code, notes, and snippets.

@awwaiid
Created April 11, 2011 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awwaiid/913757 to your computer and use it in GitHub Desktop.
Save awwaiid/913757 to your computer and use it in GitHub Desktop.
# Original API
my $grammar = Marpa::Grammar->new(
{ start => 'Expression',
actions => 'My_Actions',
default_action => 'first_arg',
rules => [
{ lhs => 'Expression', rhs => [qw/Term/] },
{ lhs => 'Term', rhs => [qw/Factor/] },
{ lhs => 'Factor', rhs => [qw/Number/] },
{ lhs => 'Term', rhs => [qw/Term Add Term/], action => 'do_add' },
{ lhs => 'Factor',
rhs => [qw/Factor Multiply Factor/],
action => 'do_multiply'
},
],
}
);
$grammar->precompute();
my $recce = Marpa::Recognizer->new( { grammar => $grammar } );
my @tokens = (
[ 'Number', 42 ],
[ 'Multiply', ],
[ 'Number', 1 ],
[ 'Add', ],
[ 'Number', 7 ],
);
$recce->tokens( \@tokens );
sub My_Actions::do_add {
my ( undef, $t1, undef, $t2 ) = @_;
return $t1 + $t2;
}
sub My_Actions::do_multiply {
my ( undef, $t1, undef, $t2 ) = @_;
return $t1 * $t2;
}
sub My_Actions::first_arg { shift; return shift; }
my $value_ref = $recce->value;
my $value = $value_ref ? ${$value_ref} : 'No Parse';
################################################
# Fancy shmancy API
# Looks like this is already partially done with "Short Form Rule Descriptors"
################################################
# Implies ->precompute and makes a recognizer
# 'start' defaults to first rule ('Expression')
# actions don't need a namespace
my $parser = Marpa::Sweet->new(
default_action => \&first_arg,
rules => [
Expression => 'Term',
Term => 'Factor',
Factor => 'Number',
Term => [qw/ Term Add Term /] => \&do_add,
Factor => [qw/ Factor Multiply Factor /] => \&do_multiply,
]
);
sub first_arg { shift; return shift; }
sub do_add {
my ( undef, $t1, undef, $t2 ) = @_;
return $t1 + $t2;
}
sub do_multiply {
my ( undef, $t1, undef, $t2 ) = @_;
return $t1 * $t2;
}
# Tokens are the already-tokenized input, as a series of Token/value pairs. In
# streaming mode, you could call this lots of times, giving it whatever tokens
# you have so far (and you'd get back some stuff).
$parser->parse_tokens(
Number => 42,
Multiply => undef,
Number => 1,
Add => undef,
Number => 7,
);
# Implies ->end_input maybe? Call multiple times to get multiple parses.
my $parse_result = $parser->value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment