Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Parsing syntax trees

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


in reply to Parsing syntax trees

or using Tree::Binary:

#!/usr/bin/perl use warnings; use strict; use Marpa::R2; use Tree::Binary; package Construct; sub newNode { my ($value, $left, $right) = @_; my $node = Tree::Binary->new($value); $node->setLeft($left) if $left; $node->setRight($right) if $right; return $node; } sub doOp { my @params = @_; return newNode(@params[2, 1, 3],); } sub doConst { my @params = @_; return newNode($params[1]); } 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, 'Construct'); ($$root)->traverse(sub {print " " x $_[0]->{_depth}, $_[0]->getNodeVa +lue(), "\n"});

Prints:

+ * 1 2 * 3 4
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://1151455]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2024-03-28 11:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found