Support BEGIN blocks in B::Deparse (& more)
[p5sagit/p5-mst-13.2.git] / ext / B / B / Deparse.pm
index 53f2006..7d8e0b5 100644 (file)
@@ -8,17 +8,19 @@
 
 package B::Deparse;
 use Carp 'cluck', 'croak';
-use B qw(class main_root main_start main_cv svref_2object opnumber
+use B qw(class main_root main_start main_cv svref_2object opnumber cstring
         OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
         OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL
         OPpLVAL_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
         OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
+        OPpCONST_ARYBASE OPpEXISTS_SUB
         SVf_IOK SVf_NOK SVf_ROK SVf_POK
          CVf_METHOD CVf_LOCKED CVf_LVALUE
-        PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
+        PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE PMf_SKIPWHITE
         PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
 $VERSION = 0.60;
 use strict;
+use warnings ();
 
 # Changes between 0.50 and 0.51:
 # - fixed nulled leave with live enter in sort { }
@@ -93,13 +95,8 @@ use strict;
 # Todo:
 # - finish tr/// changes
 # - add option for even more parens (generalize \&foo change)
-# - {} around variables in strings ("${var}letters")
-#   base/lex.t 25-27
-#   comp/term.t 11
 # - left/right context
-# - recognize `use utf8', `use integer', etc
 # - treat top-level block specially for incremental output
-# - interpret high bit chars in string as utf8 \x{...} (when?)
 # - copy comments (look at real text with $^P?)
 # - avoid semis in one-statement blocks
 # - associativity of &&=, ||=, ?:
@@ -109,12 +106,9 @@ use strict;
 # - more style options: brace style, hex vs. octal, quotes, ...
 # - print big ints as hex/octal instead of decimal (heuristic?)
 # - handle `my $x if 0'?
-# - include values of variables (e.g. set in BEGIN)
 # - coordinate with Data::Dumper (both directions? see previous)
 # - version using op_next instead of op_first/sibling?
 # - avoid string copies (pass arrays, one big join?)
-# - auto-apply `-u'?
-# - -uPackage:: descend recursively?
 # - here-docs?
 # - <DATA>?
 
@@ -134,11 +128,14 @@ use strict;
 # curcv:
 # CV for current sub (or main program) being deparsed
 #
+# curcop:
+# COP for statement being deparsed
+#
 # curstash:
 # name of the current package for deparsed code
 #
 # subs_todo:
-# array of [cop_seq, GV, is_format?] for subs and formats we still
+# array of [cop_seq, CV, is_format?] for subs and formats we still
 # want to deparse
 #
 # protos_todo:
@@ -148,6 +145,10 @@ use strict;
 # keys are addresses of GVs for subs and formats we've already
 # deparsed (or at least put into subs_todo)
 #
+# subs_declared
+# keys are names of subs for which we've printed declarations.
+# That means we can omit parentheses from the arguments.
+#
 # parens: -p
 # linenums: -l
 # unquote: -q
@@ -215,25 +216,120 @@ sub null {
 
 sub todo {
     my $self = shift;
-    my($gv, $cv, $is_form) = @_;
+    my($cv, $is_form) = @_;
     my $seq;
     if (!null($cv->START) and is_state($cv->START)) {
        $seq = $cv->START->cop_seq;
     } else {
        $seq = 0;
     }
-    push @{$self->{'subs_todo'}}, [$seq, $gv, $is_form];
+    push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
 }
 
 sub next_todo {
     my $self = shift;
     my $ent = shift @{$self->{'subs_todo'}};
-    my $name = $self->gv_name($ent->[1]);
+    my $cv = $ent->[1];
+    my $gv = $cv->GV;
+    my $name = $self->gv_name($gv);
     if ($ent->[2]) {
        return "format $name =\n"
            . $self->deparse_format($ent->[1]->FORM). "\n";
     } else {
-       return "sub $name " . $self->deparse_sub($ent->[1]->CV);
+       $self->{'subs_declared'}{$name} = 1;
+       if ($name eq "BEGIN") {
+           my $use_dec = $self->begin_is_use($cv);
+           return $use_dec if defined ($use_dec);
+       }
+        return "sub $name " . $self->deparse_sub($cv);
+    }
+}
+
+# Return a "use" declaration for this BEGIN block, if appropriate
+sub begin_is_use {
+    my ($self, $cv) = @_;
+    my $root = $cv->ROOT;
+#require B::Debug;
+#B::walkoptree($cv->ROOT, "debug");
+    my $lineseq = $root->first;
+    return if $lineseq->name ne "lineseq";
+
+    my $req_op = $lineseq->first->sibling;
+    return if $req_op->name ne "require";
+
+    my $module;
+    if ($req_op->first->private & OPpCONST_BARE) {
+       # Actually it should always be a bareword
+       $module = $self->const_sv($req_op->first)->PV;
+       $module =~ s[/][::]g;
+       $module =~ s/.pm$//;
+    }
+    else {
+       $module = const($self->const_sv($req_op->first));
+    }
+
+    my $version;
+    my $version_op = $req_op->sibling;
+    return if class($version_op) eq "NULL";
+    if ($version_op->name eq "lineseq") {
+       # We have a version parameter; skip nextstate & pushmark
+       my $constop = $version_op->first->next->next;
+
+       return unless $self->const_sv($constop)->PV eq $module;
+       $constop = $constop->sibling;
+
+       $version = $self->const_sv($constop)->int_value;
+       $constop = $constop->sibling;
+       return if $constop->name ne "method_named";
+       return if $self->const_sv($constop)->PV ne "VERSION";
+    }
+
+    $lineseq = $version_op->sibling;
+    return if $lineseq->name ne "lineseq";
+    my $entersub = $lineseq->first->sibling;
+    if ($entersub->name eq "stub") {
+       return "use $module $version ();\n" if defined $version;
+       return "use $module ();\n";
+    }
+    return if $entersub->name ne "entersub";
+
+    # See if there are import arguments
+    my $args = '';
+
+    my $constop = $entersub->first->sibling; # Skip over pushmark
+    return unless $self->const_sv($constop)->PV eq $module;
+
+    # Pull out the arguments
+    for ($constop=$constop->sibling; $constop->name eq "const";
+               $constop = $constop->sibling) {
+       $args .= ", " if length($args);
+       $args .= $self->deparse($constop, 6);
+    }
+
+    my $use = 'use';
+    my $method_named = $constop;
+    return if $method_named->name ne "method_named";
+    my $method_name = $self->const_sv($method_named)->PV;
+
+    if ($method_name eq "unimport") {
+       $use = 'no';
+    }
+
+    # Certain pragmas are dealt with using hint bits,
+    # so we ignore them here
+    if ($module eq 'strict' || $module eq 'integer'
+       || $module eq 'bytes') {
+       return "";
+    }
+
+    if (defined $version && length $args) {
+       return "$use $module $version ($args);\n";
+    } elsif (defined $version) {
+       return "$use $module $version;\n";
+    } elsif (length $args) {
+       return "$use $module ($args);\n";
+    } else {
+       return "$use $module;\n";
     }
 }
 
@@ -261,14 +357,14 @@ sub walk_sub {
            if ($op->next->name eq "entersub") {
                return if $self->{'subs_done'}{$$gv}++;
                return if class($gv->CV) eq "SPECIAL";
-               $self->todo($gv, $gv->CV, 0);
+               $self->todo($gv->CV, 0);
                $self->walk_sub($gv->CV);
            } elsif ($op->next->name eq "enterwrite"
                     or ($op->next->name eq "rv2gv"
                         and $op->next->next->name eq "enterwrite")) {
                return if $self->{'forms_done'}{$$gv}++;
                return if class($gv->FORM) eq "SPECIAL";
-               $self->todo($gv, $gv->FORM, 1);
+               $self->todo($gv->FORM, 1);
                $self->walk_sub($gv->FORM);
            }
        }
@@ -276,17 +372,21 @@ sub walk_sub {
 }
 
 sub stash_subs {
-    my $self = shift;
-    my $pack = shift;
-    my(%stash, @ret);
-    { no strict 'refs'; %stash = svref_2object(\%{$pack . "::"})->ARRAY }
-    if ($pack eq "main") {
-       $pack = "";
-    } else {
-       $pack = $pack . "::";
+    my ($self, $pack) = @_;
+    my (@ret, $stash);
+    if (!defined $pack) {
+       $pack = '';
+       $stash = \%::;
     }
-    my($key, $val);
-    while (($key, $val) = each %stash) {
+    else {
+       $pack =~ s/(::)?$/::/;
+       no strict 'refs';
+       $stash = \%$pack;
+    }
+    my %stash = svref_2object($stash)->ARRAY;
+    while (my ($key, $val) = each %stash) {
+       next if $key eq 'main::';       # avoid infinite recursion
+       next if $key eq 'B::';          # don't automatically scan B
        my $class = class($val);
        if ($class eq "PV") {
            # Just a prototype
@@ -295,16 +395,20 @@ sub stash_subs {
            # Just a name
            push @{$self->{'protos_todo'}}, [$pack . $key, undef];          
        } elsif ($class eq "GV") {
-           if (class($val->CV) ne "SPECIAL") {
+           if (class(my $cv = $val->CV) ne "SPECIAL") {
+               next unless $cv->FILE eq $0 || $self->{'files'}{$cv->FILE};
                next if $self->{'subs_done'}{$$val}++;
-               $self->todo($val, $val->CV, 0);
+               $self->todo($val->CV, 0);
                $self->walk_sub($val->CV);
            }
            if (class($val->FORM) ne "SPECIAL") {
                next if $self->{'forms_done'}{$$val}++;
-               $self->todo($val, $val->FORM, 1);
+               $self->todo($val->FORM, 1);
                $self->walk_sub($val->FORM);
            }
+           if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
+               $self->stash_subs($pack . $key);
+           }
        }
     }
 }
@@ -346,14 +450,26 @@ sub new {
     my $class = shift;
     my $self = bless {}, $class;
     $self->{'subs_todo'} = [];
+    $self->{'files'} = {};
     $self->{'curstash'} = "main";
+    $self->{'curcop'} = undef;
     $self->{'cuddle'} = "\n";
     $self->{'indent_size'} = 4;
     $self->{'use_tabs'} = 0;
+    $self->{'expand'} = 0;
+    $self->{'unquote'} = 0;
+    $self->{'linenums'} = 0;
+    $self->{'parens'} = 0;
     $self->{'ex_const'} = "'???'";
+
+    $self->{'ambient_arybase'} = 0;
+    $self->{'ambient_warnings'} = "\0"x12;
+    $self->{'ambient_hints'} = 0;
+    $self->init();
+
     while (my $arg = shift @_) {
-       if (substr($arg, 0, 2) eq "-u") {
-           $self->stash_subs(substr($arg, 2));
+       if ($arg =~ /^-f(.*)/) {
+           $self->{'files'}{$1} = 1;
        } elsif ($arg eq "-p") {
            $self->{'parens'} = 1;
        } elsif ($arg eq "-l") {
@@ -369,11 +485,39 @@ sub new {
     return $self;
 }
 
+sub WARN_MASK () {
+    # Mask out the bits that C<use vars> uses
+    $warnings::Bits{all} | $warnings::DeadBits{all};
+}
+
+# Initialise the contextual information, either from
+# defaults provided with the ambient_pragmas method,
+# or from perl's own defaults otherwise.
+sub init {
+    my $self = shift;
+
+    $self->{'arybase'}  = $self->{'ambient_arybase'};
+    $self->{'warnings'} = $self->{'ambient_warnings'} & WARN_MASK;
+    $self->{'hints'}    = $self->{'ambient_hints'} & 0xFF;
+
+    # also a convenient place to clear out subs_declared
+    delete $self->{'subs_declared'};
+}
+
 sub compile {
     my(@args) = @_;
     return sub { 
        my $self = B::Deparse->new(@args);
-       $self->stash_subs("main");
+       my @BEGINs  = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
+       my @INITs   = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
+       my @ENDs    = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
+       for my $block (@BEGINs, @INITs, @ENDs) {
+           if ($block->FILE eq $0 || $self->{'files'}{$block->FILE}) {
+               $self->todo($block, 0);
+               $self->walk_sub($block);
+           }
+       }
+       $self->stash_subs();
        $self->{'curcv'} = main_cv;
        $self->walk_sub(main_cv, main_start);
        print $self->print_protos;
@@ -393,15 +537,120 @@ sub coderef2text {
     my $self = shift;
     my $sub = shift;
     croak "Usage: ->coderef2text(CODEREF)" unless ref($sub) eq "CODE";
+
+    $self->init();
     return $self->indent($self->deparse_sub(svref_2object($sub)));
 }
 
+sub ambient_pragmas {
+    my $self = shift;
+    my ($arybase, $hint_bits, $warning_bits) = (0, 0, "\0"x12);
+
+    while (@_ > 1) {
+       my $name = shift();
+       my $val  = shift();
+
+       if ($name eq 'strict') {
+           require strict;
+
+           if ($val eq 'none') {
+               $hint_bits &= ~strict::bits(qw/refs subs vars/);
+               next();
+           }
+
+           my @names;
+           if ($val eq "all") {
+               @names = qw/refs subs vars/;
+           }
+           elsif (ref $val) {
+               @names = @$val;
+           }
+           else {
+               @names = split' ', $val;
+           }
+           $hint_bits |= strict::bits(@names);
+       }
+
+       elsif ($name eq '$[') {
+           $arybase = $val;
+       }
+
+       elsif ($name eq 'integer'
+           || $name eq 'bytes'
+           || $name eq 'utf8') {
+           require "$name.pm";
+           if ($val) {
+               $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
+           }
+           else {
+               $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
+           }
+       }
+
+       elsif ($name eq 're') {
+           require re;
+           if ($val eq 'none') {
+               $hint_bits &= ~re::bits(qw/taint eval asciirange/);
+               next();
+           }
+
+           my @names;
+           if ($val eq 'all') {
+               @names = qw/taint eval asciirange/;
+           }
+           elsif (ref $val) {
+               @names = @$val;
+           }
+           else {
+               @names = split' ',$val;
+           }
+           $hint_bits |= re::bits(@names);
+       }
+
+       elsif ($name eq 'warnings') {
+           if ($val eq 'none') {
+               $warning_bits = "\0"x12;
+               next();
+           }
+
+           my @names;
+           if (ref $val) {
+               @names = @$val;
+           }
+           else {
+               @names = split/\s+/, $val;
+           }
+
+           $warning_bits |= warnings::bits(@names);
+       }
+
+       elsif ($name eq 'warning_bits') {
+           $warning_bits = $val;
+       }
+
+       elsif ($name eq 'hint_bits') {
+           $hint_bits = $val;
+       }
+
+       else {
+           croak "Unknown pragma type: $name";
+       }
+    }
+    if (@_) {
+       croak "The ambient_pragmas method expects an even number of args";
+    }
+
+    $self->{'ambient_arybase'} = $arybase;
+    $self->{'ambient_warnings'} = $warning_bits;
+    $self->{'ambient_hints'} = $hint_bits;
+}
+
 sub deparse {
     my $self = shift;
     my($op, $cx) = @_;
-#    cluck if class($op) eq "NULL";
-#    cluck unless $op;
-#    return $self->$ {\("pp_" . $op->name)}($op, $cx);
+
+    Carp::confess("Null op in deparse") if !defined($op)
+                                       || class($op) eq "NULL";
     my $meth = "pp_" . $op->name;
     return $self->$meth($op, $cx);
 }
@@ -438,6 +687,8 @@ sub deparse_sub {
     my $self = shift;
     my $cv = shift;
     my $proto = "";
+Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
+    local $self->{'curcop'} = $self->{'curcop'};
     if ($cv->FLAGS & SVf_POK) {
        $proto = "(". $cv->PV . ") ";
     }
@@ -449,7 +700,8 @@ sub deparse_sub {
     }
 
     local($self->{'curcv'}) = $cv;
-    local($self->{'curstash'}) = $self->{'curstash'};
+    local(@$self{qw'curstash warnings hints'})
+               = @$self{qw'curstash warnings hints'};
     if (not null $cv->ROOT) {
        # skip leavesub
        return $proto . "{\n\t" . 
@@ -459,8 +711,8 @@ sub deparse_sub {
     if ($$sv) {
        # uh-oh. inlinable sub... format it differently
        return $proto . "{ " . const($sv) . " }\n";
-    } else { # XSUB?
-       return $proto  . "{}\n";
+    } else { # XSUB? (or just a declaration)
+       return "$proto;\n";
     }
 }
 
@@ -469,7 +721,8 @@ sub deparse_format {
     my $form = shift;
     my @text;
     local($self->{'curcv'}) = $form;
-    local($self->{'curstash'}) = $self->{'curstash'};
+    local(@$self{qw'curstash warnings hints'})
+               = @$self{'curstash warnings hints'};
     my $op = $form->ROOT;
     my $kid;
     $op = $op->first->first; # skip leavewrite, lineseq
@@ -721,6 +974,7 @@ sub lineseq {
        $expr .= $self->deparse($ops[$i], 0);
        push @exprs, $expr if length $expr;
     }
+    for(@exprs[0..@exprs-1]) { s/;\n\z// }
     return join(";\n", @exprs);
 }
 
@@ -728,7 +982,9 @@ sub scopeop {
     my($real_block, $self, $op, $cx) = @_;
     my $kid;
     my @kids;
-    local($self->{'curstash'}) = $self->{'curstash'} if $real_block;
+
+    local(@$self{qw'curstash warnings hints'})
+               = @$self{qw'curstash warnings hints'} if $real_block;
     if ($real_block) {
        $kid = $op->first->sibling; # skip enter
        if (is_miniwhile($kid)) {
@@ -756,7 +1012,8 @@ sub scopeop {
     if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
        return "do { " . $self->lineseq(@kids) . " }";
     } else {
-       return $self->lineseq(@kids) . ";";
+       my $lineseq = $self->lineseq(@kids);
+       return (length ($lineseq) ? "$lineseq;" : "");
     }
 }
 
@@ -773,6 +1030,7 @@ BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
 sub gv_name {
     my $self = shift;
     my $gv = shift;
+Carp::confess() if $gv->isa("B::CV");
     my $stash = $gv->STASH->NAME;
     my $name = $gv->SAFENAME;
     if ($stash eq $self->{'curstash'} or $globalnames{$name}
@@ -788,17 +1046,55 @@ sub gv_name {
     return $stash . $name;
 }
 
-# Notice how subs and formats are inserted between statements here
-sub pp_nextstate {
-    my $self = shift;
-    my($op, $cx) = @_;
-    my @text;
-    @text = $op->label . ": " if $op->label;
+# Recurses down the tree, looking for a COP
+sub find_cop {
+    my ($self, $op) = @_;
+    if ($op->flags & OPf_KIDS) {
+       for (my $o=$op->first; $$o; $o=$o->sibling) {
+           return $o if is_state($o);
+           my $r = $self->find_cop($o);
+           return $r if defined $r;
+       }
+    }
+    return undef;
+}
+
+# Returns a list of subs which should be inserted before the COP
+sub cop_subs {
+    my ($self, $op, $out_seq) = @_;
     my $seq = $op->cop_seq;
+    # If we have nephews, then our sequence number indicates
+    # the cop_seq of the end of some sort of scope.
+    if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
+       and my $ncop = $self->find_cop($op->sibling)) {
+       $seq = $ncop->cop_seq;
+    }
+    $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
+    return $self->seq_subs($seq);
+}
+
+sub seq_subs {
+    my ($self, $seq) = @_;
+    my @text;
+#push @text, "# ($seq)\n";
+
     while (scalar(@{$self->{'subs_todo'}})
           and $seq > $self->{'subs_todo'}[0][0]) {
        push @text, $self->next_todo;
     }
+    return @text;
+}
+
+# Notice how subs and formats are inserted between statements here;
+# also $[ assignments and pragmas.
+sub pp_nextstate {
+    my $self = shift;
+    my($op, $cx) = @_;
+    $self->{'curcop'} = $op;
+    my @text;
+    @text = $op->label . ": " if $op->label;
+#push @text, "# ", $op->cop_seq, "\n";
+    push @text, $self->cop_subs($op);
     my $stash = $op->stashpv;
     if ($stash ne $self->{'curstash'}) {
        push @text, "package $stash;\n";
@@ -808,9 +1104,54 @@ sub pp_nextstate {
        push @text, "\f#line " . $op->line . 
          ' "' . $op->file, qq'"\n';
     }
+
+    if ($self->{'arybase'} != $op->arybase) {
+       push @text, '$[ = '. $op->arybase .";\n";
+       $self->{'arybase'} = $op->arybase;
+    }
+
+    my $warnings = $op->warnings;
+    my $warning_bits;
+    if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
+       $warning_bits = $warnings::Bits{"all"};
+    }
+    elsif ($warnings->isa("B::SPECIAL")) {
+        $warning_bits = "\0"x12;
+    }
+    else {
+       $warning_bits = $warnings->PV & WARN_MASK;
+    }
+
+    if ($self->{'warnings'} ne $warning_bits) {
+       push @text, declare_warnings($self->{'warnings'}, $warning_bits);
+       $self->{'warnings'} = $warning_bits;
+    }
+
+    if ($self->{'hints'} != $op->private) {
+       push @text, declare_hints($self->{'hints'}, $op->private);
+       $self->{'hints'} = $op->private;
+    }
+
     return join("", @text);
 }
 
+sub declare_warnings {
+    my ($from, $to) = @_;
+    if ($to eq warnings::bits("all")) {
+       return "use warnings;\n";
+    }
+    elsif ($to eq "\0"x12) {
+       return "no warnings;\n";
+    }
+    return "BEGIN {\${^WARNING_BITS} = ".cstring($to)."}\n";
+}
+
+sub declare_hints {
+    my ($from, $to) = @_;
+    my $bits = $to;
+    return sprintf "BEGIN {\$^H &= ~0xFF; \$^H |= %x}\n", $bits;
+}
+
 sub pp_dbstate { pp_nextstate(@_) }
 sub pp_setstate { pp_nextstate(@_) }
 
@@ -944,7 +1285,6 @@ sub pp_prototype { unop(@_, "prototype") }
 sub pp_close { unop(@_, "close") }
 sub pp_fileno { unop(@_, "fileno") }
 sub pp_umask { unop(@_, "umask") }
-sub pp_binmode { unop(@_, "binmode") }
 sub pp_untie { unop(@_, "untie") }
 sub pp_tied { unop(@_, "tied") }
 sub pp_dbmclose { unop(@_, "dbmclose") }
@@ -988,6 +1328,17 @@ sub pp_lock { unop(@_, "lock") }
 sub pp_exists {
     my $self = shift;
     my($op, $cx) = @_;
+    my $arg;
+    if ($op->private & OPpEXISTS_SUB) {
+       # Checking for the existence of a subroutine
+       return $self->maybe_parens_func("exists",
+                               $self->pp_rv2cv($op->first, 16), $cx, 16);
+    }
+    if ($op->flags & OPf_SPECIAL) {
+       # Array element, not hash element
+       return $self->maybe_parens_func("exists",
+                               $self->pp_aelem($op->first, 16), $cx, 16);
+    }
     return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
                                    $cx, 16);
 }
@@ -997,10 +1348,22 @@ sub pp_delete {
     my($op, $cx) = @_;
     my $arg;
     if ($op->private & OPpSLICE) {
+       if ($op->flags & OPf_SPECIAL) {
+           # Deleting from an array, not a hash
+           return $self->maybe_parens_func("delete",
+                                       $self->pp_aslice($op->first, 16),
+                                       $cx, 16);
+       }
        return $self->maybe_parens_func("delete",
                                        $self->pp_hslice($op->first, 16),
                                        $cx, 16);
     } else {
+       if ($op->flags & OPf_SPECIAL) {
+           # Deleting from an array, not a hash
+           return $self->maybe_parens_func("delete",
+                                       $self->pp_aelem($op->first, 16),
+                                       $cx, 16);
+       }
        return $self->maybe_parens_func("delete",
                                        $self->pp_helem($op->first, 16),
                                        $cx, 16);
@@ -1016,7 +1379,7 @@ sub pp_require {
        my $name = $self->const_sv($op->first)->PV;
        $name =~ s[/][::]g;
        $name =~ s/\.pm//g;
-       return "require($name)";
+       return "require $name";
     } else {   
        $self->unop($op, $cx, "require");
     }
@@ -1487,6 +1850,7 @@ sub pp_return { listop(@_, "return") }
 sub pp_open { listop(@_, "open") }
 sub pp_pipe_op { listop(@_, "pipe") }
 sub pp_tie { listop(@_, "tie") }
+sub pp_binmode { listop(@_, "binmode") }
 sub pp_dbmopen { listop(@_, "dbmopen") }
 sub pp_sselect { listop(@_, "select") }
 sub pp_select { listop(@_, "select") }
@@ -1733,11 +2097,13 @@ sub loop_common {
     my($op, $cx, $init) = @_;
     my $enter = $op->first;
     my $kid = $enter->sibling;
-    local($self->{'curstash'}) = $self->{'curstash'};
+    local(@$self{qw'curstash warnings hints'})
+               = @$self{qw'curstash warnings hints'};
     my $head = "";
     my $bare = 0;
     my $body;
     my $cond = undef;
+    my $out_seq = $self->{'curcop'}->cop_seq;;
     if ($kid->name eq "lineseq") { # bare or infinite loop 
        if (is_state $kid->last) { # infinite
            $head = "for (;;) "; # shorter than while (1)
@@ -1818,10 +2184,16 @@ sub loop_common {
              $self->deparse($cont, 0) . "\n\b}\cK";
        }
     } else {
+       return "" if !defined $body;
        $cont = "\cK";
        $body = $self->deparse($body, 0);
     }
-    return $head . "{\n\t" . $body . "\n\b}" . $cont;
+    $body .= "\n";
+    # If we have say C<{my $x=2; sub x{$x}}>, the sub must go inside
+    # the loop. So we insert any subs which are due here.
+    $body .= join"", $self->seq_subs($out_seq);
+
+    return $head . "{\n\t" . $body . "\b}" . $cont;
 }
 
 sub pp_leaveloop { loop_common(@_, "") }
@@ -1934,7 +2306,8 @@ sub pp_aelemfast {
     my $self = shift;
     my($op, $cx) = @_;
     my $gv = $self->gv_or_padgv($op);
-    return "\$" . $self->gv_name($gv) . "[" . $op->private . "]";
+    return "\$" . $self->gv_name($gv) . "[" .
+                 ($op->private + $self->{'arybase'}) . "]";
 }
 
 sub rv2x {
@@ -2015,6 +2388,25 @@ sub elem {
            $left . $self->deparse($idx, 1) . $right;
     }
     $idx = $self->deparse($idx, 1);
+
+    # Outer parens in an array index will confuse perl
+    # if we're interpolating in a regular expression, i.e.
+    # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
+    #
+    # If $self->{parens}, then an initial '(' will
+    # definitely be paired with a final ')'. If
+    # !$self->{parens}, the misleading parens won't
+    # have been added in the first place.
+    #
+    # [You might think that we could get "(...)...(...)"
+    # where the initial and final parens do not match
+    # each other. But we can't, because the above would
+    # only happen if there's an infix binop between the
+    # two pairs of parens, and *that* means that the whole
+    # expression would be parenthesized as well.]
+    #
+    $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
+
     return "\$" . $array . $left . $idx . $right;
 }
 
@@ -2258,8 +2650,13 @@ sub pp_entersub {
        my $arrow = is_subscriptable($kid->first) ? "" : "->";
        $kid = $self->deparse($kid, 24) . $arrow;
     }
+
+    # Doesn't matter how many prototypes there are, if
+    # they haven't happened yet!
+    my $declared = exists $self->{'subs_declared'}{$kid};
+
     my $args;
-    if (defined $proto and not $amper) {
+    if ($declared and defined $proto and not $amper) {
        ($amper, $args) = $self->check_proto($proto, @exprs);
        if ($amper eq "&") {
            $args = join(", ", map($self->deparse($_, 6), @exprs));
@@ -2274,7 +2671,22 @@ sub pp_entersub {
            return $prefix . $amper. $kid;
        }
     } else {
-       if (defined $proto and $proto eq "") {
+       # glob() invocations can be translated into calls of
+       # CORE::GLOBAL::glob with an second parameter, a number.
+       # Reverse this.
+       if ($kid eq "CORE::GLOBAL::glob") {
+           $kid = "glob";
+           $args =~ s/\s*,[^,]+$//;
+       }
+
+       # It's a syntax error to call CORE::GLOBAL::foo without a prefix,
+       # so it must have been translated from a keyword call. Translate
+       # it back.
+       $kid =~ s/^CORE::GLOBAL:://;
+
+        if (!$declared) {
+           return "$kid(" . $args . ")";
+       } elsif (defined $proto and $proto eq "") {
            return $kid;
        } elsif (defined $proto and $proto eq "\$") {
            return $self->maybe_parens_func($kid, $args, $cx, 16);
@@ -2305,8 +2717,9 @@ sub re_uninterp {
 }
 
 # character escapes, but not delimiters that might need to be escaped
-sub escape_str { # ASCII
+sub escape_str { # ASCII, UTF8
     my($str) = @_;
+    $str =~ s/(.)/ord($1)>255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
     $str =~ s/\a/\\a/g;
 #    $str =~ s/\cH/\\b/g; # \b means someting different in a regex 
     $str =~ s/\t/\\t/g;
@@ -2326,6 +2739,16 @@ sub unback {
     return $str;
 }
 
+# Remove backslashes which precede literal control characters,
+# to avoid creating ambiguity when we escape the latter.
+sub re_unback {
+    my($str) = @_;
+
+    # the insane complexity here is due to the behaviour of "\c\"
+    $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[\0-\031\177-\377])/$1$2/g;
+    return $str;
+}
+
 sub balanced_delim {
     my($str) = @_;
     my @str = split //, $str;
@@ -2373,11 +2796,13 @@ sub const {
     my $sv = shift;
     if (class($sv) eq "SPECIAL") {
        return ('undef', '1', '0')[$$sv-1]; # sv_undef, sv_yes, sv_no
+    } elsif (class($sv) eq "NULL") {
+       return 'undef';
     } elsif ($sv->FLAGS & SVf_IOK) {
        return $sv->int_value;
     } elsif ($sv->FLAGS & SVf_NOK) {
        return $sv->NV;
-    } elsif ($sv->FLAGS & SVf_ROK) {
+    } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
        return "\\(" . const($sv->RV) . ")"; # constant folded
     } else {
        my $str = $sv->PV;
@@ -2401,6 +2826,9 @@ sub const_sv {
 sub pp_const {
     my $self = shift;
     my($op, $cx) = @_;
+    if ($op->private & OPpCONST_ARYBASE) {
+        return '$[';
+    }
 #    if ($op->private & OPpCONST_BARE) { # trouble with `=>' autoquoting 
 #      return $self->const_sv($op)->PV;
 #    }
@@ -2415,13 +2843,17 @@ sub dq {
     my $op = shift;
     my $type = $op->name;
     if ($type eq "const") {
-       return uninterp(escape_str(unback($self->const_sv($op)->PV)));
+       return '$[' if $op->private & OPpCONST_ARYBASE;
+       return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
     } elsif ($type eq "concat") {
        my $first = $self->dq($op->first);
        my $last  = $self->dq($op->last);
        # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
-        if ($last =~ /^[{\[\w]/) {
-           $first =~ s/([%\$@])([A-Za-z_]\w*)$/${1}{$2}/;
+       if ($last =~ /^[A-Z\\\^\[\]_?]/) {
+           $first =~ s/([\$@])\^$/${1}{^}/;  # "${^}W" etc
+        }
+       elsif ($last =~ /^[{\[\w]/) {
+           $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/;
        }
        return $first . $last;
     } elsif ($type eq "uc") {
@@ -2710,9 +3142,19 @@ sub re_dq {
     my $op = shift;
     my $type = $op->name;
     if ($type eq "const") {
-       return uninterp($self->const_sv($op)->PV);
+       return '$[' if $op->private & OPpCONST_ARYBASE;
+       return re_uninterp(escape_str(re_unback($self->const_sv($op)->as_string)));
     } elsif ($type eq "concat") {
-       return $self->re_dq($op->first) . $self->re_dq($op->last);
+       my $first = $self->re_dq($op->first);
+       my $last  = $self->re_dq($op->last);
+       # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
+       if ($last =~ /^[A-Z\\\^\[\]_?]/) {
+           $first =~ s/([\$@])\^$/${1}{^}/;
+       }
+       elsif ($last =~ /^[{\[\w]/) {
+           $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/;
+       }
+       return $first . $last;
     } elsif ($type eq "uc") {
        return '\U' . $self->re_dq($op->first->sibling) . '\E';
     } elsif ($type eq "lc") {
@@ -2757,7 +3199,7 @@ sub matchop {
        $kid = $kid->sibling;
     }
     if (null $kid) {
-       $re = re_uninterp(escape_str($op->precomp));
+       $re = re_uninterp(escape_str(re_unback($op->precomp)));
     } else {
        $re = $self->deparse($kid, 1);
     }
@@ -2799,6 +3241,15 @@ sub pp_split {
     for (; !null($kid); $kid = $kid->sibling) {
        push @exprs, $self->deparse($kid, 6);
     }
+
+    # handle special case of split(), and split(" ") that compiles to /\s+/
+    $kid = $op->first;
+    if ($kid->flags & OPf_SPECIAL
+       && $exprs[0] eq '/\\s+/'
+       && $kid->pmflags & PMf_SKIPWHITE ) {
+           $exprs[0] = '" "';
+    }
+
     $expr = "split(" . join(", ", @exprs) . ")";
     if ($ary) {
        return $self->maybe_parens("$ary = $expr", $cx, 7);
@@ -2844,7 +3295,7 @@ sub pp_subst {
        }
     }
     if (null $kid) {
-       $re = re_uninterp(escape_str($op->precomp));
+       $re = re_uninterp(escape_str(re_unback($op->precomp)));
     } else {
        $re = $self->deparse($kid, 1);
     }
@@ -2947,19 +3398,14 @@ translation that B::Deparse usually does. On the other hand, note that
 C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value
 of $y into a string before doing the assignment.
 
-=item B<-u>I<PACKAGE>
+=item B<-f>I<FILE>
 
-Normally, B::Deparse deparses the main code of a program, all the subs
-called by the main program (and all the subs called by them,
-recursively), and any other subs in the main:: package. To include
-subs in other packages that aren't called directly, such as AUTOLOAD,
-DESTROY, other subs called automatically by perl, and methods (which
-aren't resolved to subs until runtime), use the B<-u> option. The
-argument to B<-u> is the name of a package, and should follow directly
-after the 'u'. Multiple B<-u> options may be given, separated by
-commas.  Note that unlike some other backends, B::Deparse doesn't
-(yet) try to guess automatically when B<-u> is needed -- you must
-invoke it yourself.
+Normally, B::Deparse deparses the main code of a program, and all the subs
+defined in the same file. To include subs defined in other files, pass the
+B<-f> option with the filename. You can pass the B<-f> option several times, to
+include more than one secondary file.  (Most of the time you don't want to
+use it at all.)  You can also use this option to include subs which are
+defined in the scope of a B<#line> directive with two parameters.
 
 =item B<-s>I<LETTERS>
 
@@ -3096,6 +3542,133 @@ after B<-MO=Deparse> should be given as separate strings. Some
 options, like B<-u>, don't make sense for a single subroutine, so
 don't pass them.
 
+=head2 ambient_pragmas
+
+    $deparse->ambient_pragmas(strict => 'all', '$[' => $[);
+
+The compilation of a subroutine can be affected by a few compiler
+directives, B<pragmas>. These are:
+
+=over 4
+
+=item *
+
+use strict;
+
+=item *
+
+use warnings;
+
+=item *
+
+Assigning to the special variable $[
+
+=item *
+
+use integer;
+
+=item *
+
+use bytes;
+
+=item *
+
+use utf8;
+
+=item *
+
+use re;
+
+=back
+
+Ordinarily, if you use B::Deparse on a subroutine which has
+been compiled in the presence of one or more of these pragmas,
+the output will include statements to turn on the appropriate
+directives. So if you then compile the code returned by coderef2text, 
+it will behave the same way as the subroutine which you deparsed.
+
+However, you may know that you intend to use the results in a
+particular context, where some pragmas are already in scope. In
+this case, you use the B<ambient_pragmas> method to describe the
+assumptions you wish to make.
+
+The parameters it accepts are:
+
+=over 4
+
+=item strict
+
+Takes a string, possibly containing several values separated
+by whitespace. The special values "all" and "none" mean what you'd
+expect.
+
+    $deparse->ambient_pragmas(strict => 'subs refs');
+
+=item $[
+
+Takes a number, the value of the array base $[.
+
+=item bytes
+
+=item utf8
+
+=item integer
+
+If the value is true, then the appropriate pragma is assumed to
+be in the ambient scope, otherwise not.
+
+=item re
+
+Takes a string, possibly containing a whitespace-separated list of
+values. The values "all" and "none" are special. It's also permissible
+to pass an array reference here.
+
+    $deparser->ambient_pragmas(re => 'eval');
+
+
+=item warnings
+
+Takes a string, possibly containing a whitespace-separated list of
+values. The values "all" and "none" are special, again. It's also
+permissible to pass an array reference here.
+
+    $deparser->ambient_pragmas(warnings => [qw[void io]]);
+
+If one of the values is the string "FATAL", then all the warnings
+in that list will be considered fatal, just as with the B<warnings>
+pragma itself. Should you need to specify that some warnings are
+fatal, and others are merely enabled, you can pass the B<warnings>
+parameter twice:
+
+    $deparser->ambient_pragmas(
+       warnings => 'all',
+       warnings => [FATAL => qw/void io/],
+    );
+
+See L<perllexwarn> for more information about lexical warnings. 
+
+=item hint_bits
+
+=item warning_bits
+
+These two parameters are used to specify the ambient pragmas in
+the format used by the special variables $^H and ${^WARNING_BITS}.
+
+They exist principally so that you can write code like:
+
+    { my ($hint_bits, $warning_bits);
+    BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
+    $deparser->ambient_pragmas (
+       hint_bits    => $hint_bits,
+       warning_bits => $warning_bits,
+       '$['         => 0 + $[
+    ); }
+
+which specifies that the ambient pragmas are exactly those which
+are in scope at the point of calling.
+
+=back
+
 =head2 coderef2text
 
     $body = $deparse->coderef2text(\&func)