Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Parsing syntax trees

by GrandFather (Saint)
on Dec 30, 2015 at 07:16 UTC ( [id://1151444]=note: print w/replies, xml ) Need Help??


in reply to Parsing syntax trees

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1151444]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-03-29 05:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found