#!/usr/bin/env perl

use strict;
use warnings;
use 5.01800;

use Marpa::R2;

my $source = <<'END_OF_SOURCE';
  :discard ~ ws; ws ~ [\s]+
  :default ::= action => ::array

  Top ::= List
  List ::= Item3 rank => 1 # 3
  List ::= Item1 rank => -9 # 1
  Item3 ::= VAR EqOp VAR action => main::concat3
  Item1 ::= JunkLine        action => main::junk
  JunkLine ::= GoodToken | JunkChar
  GoodToken ::= VAR | EqOp
  EqOp ~ '='
  VAR ~ [\w]+
  JunkChar ~ [^\s\x{A}\x{B}\x{C}\x{D}\x{2028}\x{2029}]
END_OF_SOURCE

my @tests = (
    [ 'a = 1' ],
    [ 'a' ],
);

my $grammar = Marpa::R2::Scanless::G->new( { source => \$source } );
my @results;
for my $test (@tests) {
    my ( $input, $output ) = @{$test};
    my $recce = Marpa::R2::Scanless::R->new(
        {
            grammar        => $grammar,
            ranking_method => 'high_rule_only'
        }
    );
    $recce->read( \$input );
    my $value_ref = $recce->value();
    if ( not defined $value_ref ) {
        die 'No parse';
    }
    push @results, ${$value_ref};
}
warn Data::Dumper->new([\@results],[qw(*results)])->Deepcopy(1)->Indent(1)->Maxdepth(3)->Sortkeys(1)->Dump(),q{ };
exit;

sub flatten {
    my ($array) = @_;

    # say STDERR 'flatten arg: ', Data::Dumper::Dumper($array);
    my $ref = ref $array;
    return [$array] if $ref ne 'ARRAY';
    my @flat = ();
  ELEMENT: for my $element ( @{$array} ) {
        my $ref = ref $element;
        if ( $ref ne 'ARRAY' ) {
            push @flat, $element;
            next ELEMENT;
        }
        my $flat_piece = flatten($element);
        push @flat, @{$flat_piece};
    }
    return \@flat;
}

sub junk {
    say {*STDERR} Data::Dumper->new([\@_],[qw(*_)])->Deepcopy(1)->Indent(1)->Maxdepth(3)->Sortkeys(1)->Dump(),('at '.(caller 0)[3]);
    my ( $pp, @args ) = @_;

    # say STDERR 'concat: ', Data::Dumper::Dumper(\@args);
    my $flat = flatten( \@args );
    return join '', 'junk: ', @{$flat};
}
sub concat3 {
    say {*STDERR} Data::Dumper->new([\@_],[qw(*_)])->Deepcopy(1)->Indent(1)->Maxdepth(3)->Sortkeys(1)->Dump(),('at '.(caller 0)[3]);
    my ( $pp, @args ) = @_;

    # say STDERR 'concat: ', Data::Dumper::Dumper(\@args);
    my $flat = flatten( \@args );
    return join '', @{$flat};
}

