Skip to content

Instantly share code, notes, and snippets.

@jeffreykegler
Created December 18, 2017 05:51
Show Gist options
  • Save jeffreykegler/ab2d3a78197bda42e976ae2131f49841 to your computer and use it in GitHub Desktop.
Save jeffreykegler/ab2d3a78197bda42e976ae2131f49841 to your computer and use it in GitHub Desktop.
PEG style ranking
#!perl
use strict;
use warnings;
use 5.010;
use Data::Dumper;
use Marpa::R2;
sub My_Actions::dwim {
shift;
return $_[0] if scalar @_ == 1;
return join '', '(', @_, ')';
}
# This grammar tries to be equivalent to a PEG or Regex with ordered choice:
# List: Item*
# Item: VAR = VAR // VAR = // VAR
# In order to force that "order", this grammar specifies "rank"s.
use constant BNF => <<'BNF';
:default ::= action => My_Actions::dwim
:discard ~ ws; ws ~ [\s]+
List ::= Item rank => 2
List ::= List Item rank => 1
Item ::= VAR '=' VAR rank => 3
Item ::= VAR '=' rank => 2
Item ::= VAR rank => 1
VAR ~ [\w]+
BNF
local $Data::Dumper::Terse = 3;
my $g = Marpa::R2::Scanless::G->new({ source => \BNF });
sub all_parses {
my ($input) = @_;
my $r = Marpa::R2::Scanless::R->new({ grammar => $g, ranking_method => 'high_rule_only' });
$r->read(\$input);
# say "Earley set: $_\n", $r->show_progress($_) for 1 .. 6;
say "Input: $input";
my $i = 0;
while (my $value_ref = $r->value()) {
$i++;
say "Parse $i: ", Data::Dumper::Dumper($value_ref);
}
return $i;
}
all_parses("a = b");
all_parses("a = b c");
all_parses("a = b c = d");
all_parses("a = b c = d e");
all_parses("a = b c = d e =");
all_parses("a = b c = d e = f");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment