Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Transforming Syntax – Marpa parsing example
use strict; use warnings; use 5.010;
use Data::Dumper;
my $data = <<'END';
If ((Myvalue.xyz == 1) Or (Frmae_1.signal_1 == 1)) Then a = 1
Else a = 0;
END
my $ast = Parser->parse(\$data);
print Dumper $ast;
# Below is a class that wraps the Marpa Parser
package Parser;
use Marpa::R2;
my ($grammar);
sub parse {
my ($self, $ref) = @_;
my $recce = Marpa::R2::Scanless::R->new({ grammar => $grammar });
$recce->read($ref);
my $val = $recce->value // die "No parse found";
return $$val;
}
BEGIN {
$grammar = Marpa::R2::Scanless::G->new({
bless_package => 'Ast',
source => \<<'END SOURCE',
:default ::= action => [values]
:start ::= StatementList
:discard ~ ws
StatementList ::= <Expression>+ separator => <op semicolon> bless => Block
Expression ::=
('(') Expression (')') assoc => group action => ::first
| Number bless => Literal
|| Ident bless => Var
|| Expression '==' Expression bless => Binop
|| Expression '=' Expression bless => Binop
|| Expression 'Or' Expression bless => Binop
|| Conditional
Conditional ::=
('If') Expression ('Then') Expression
bless => Cond
| ('If') Expression ('Then') Expression ('Else') Expression
bless => Cond
Ident ~ ident
Number ~ <number int> | <number rat>
word ~ [\w]+
ident ~ word | ident '.' word
<number int> ~ [\d]+
<number rat> ~ <number int> '.' <number int>
ws ~ [\s]+
<op semicolon> ~ ';'
END SOURCE
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment