use v5.12;
use  warnings;



package PkgWalker;

use B::Concise;
use Data::Dump;
use Scalar::Util qw/blessed/;
use PadWalker;



sub peek_sub {
    my $c_ref =shift;
    my @pkg_vars;
    my @pkg_dbg;
    my %peek_sub;
    

    my $next_seq="";
    my $last_var="";

    my $c_record = sub {
        my ($seq,$op_name,$var,$sigil) = @_;
        (my $full_name = $var) =~ s/^\*/$sigil/;
        $peek_sub{$var} = \( 
        push @pkg_vars, $full_name;
        push @pkg_dbg , [ @_ ];
    };


    B::Concise::add_callback(
        sub {
            my ($h, $op) = @_;
            my ($name,$seq) = ($h->{name},$h->{seq});
            my $var = $h->{svval};

            if ( blessed($op) eq "B::PADOP") {
                #ddx $op;
                #ddx $h->{arg};
                #ddx

                #ddx ($name,$seq);


                if    ($name eq "gvsv" ) {
                    #push @pkg_vars, [ $seq, $name, $var ,'$'];
                    $c_record->($seq, $name, $var ,'$');
                }
                elsif ($name eq "gv")   {
                    #ddx
                    $next_seq = ++$seq;
                    $last_var = $var;
                }
                else {
                    die "error at [$seq,$name,$var]";
                }
            }
            elsif (blessed($op) eq "B::UNOP" and $next_seq eq $seq) {
                #ddx $op;

                if    ($name eq "rv2hv") {
                    #push @pkg_vars, [$seq,$name,$last_var,'%'];
                    $c_record->($seq, $name, $last_var ,'%');
                }
                elsif ($name eq "rv2av") {
                    #push @pkg_vars, [$seq,$name,$last_var,'@'];
                    $c_record->($seq, $name, $last_var ,'@');
                }
                else {
                    die "error at [$seq,$name,$var,$last_var]";
                }
                $next_seq = $last_var = ""; # reset
            }
        }
       );

    my $walker = B::Concise::compile('-exec', '-concise',$c_ref); # 1
    B::Concise::walk_output(\my $buf);
    $walker->();			        # 1 renders

    #say $buf;                           #  TODO silence

    return \@pkg_vars,\@pkg_dbg;
}

package Other;

our $other="other";

package main;

use vars qw/$pkg $PKG_NOT/;
$pkg ="PKG";

our ($our,@our_arr,%our_hsh);
our $OUR_NOT="OUR_NOT";

my $my ="my";
my $MY_NOT ="MY_NOT";

sub test {
    %our_hsh=();
    "$my $our $pkg $1 $other @our_arr"
}
use Data::Dump;

ddx PkgWalker::peek_sub(\&test);

ddx PadWalker::peek_sub(\&test);
ddx PadWalker::closed_over(\&test);

sub hmp (&) {
    my $c_ref = shift;
    my ($a_pkg_vars) = PkgWalker::peek_sub($c_ref);
#    local 
}
