This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
In B::Deparse::_features_from_bundle(), don't call feature::current_bundle()
[perl5.git] / dist / B-Deparse / Deparse.pm
1 # B::Deparse.pm
2 # Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
3 # All rights reserved.
4 # This module is free software; you can redistribute and/or modify
5 # it under the same terms as Perl itself.
6
7 # This is based on the module of the same name by Malcolm Beattie,
8 # but essentially none of his code remains.
9
10 package B::Deparse;
11 use Carp;
12 use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
13          OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
14          OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD
15          OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
16          OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
17          OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER
18          OPpSORT_REVERSE
19          SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
20          CVf_METHOD CVf_LVALUE
21          PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
22          PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
23 $VERSION = '1.13';
24 use strict;
25 use vars qw/$AUTOLOAD/;
26 use warnings ();
27 require feature;
28
29 BEGIN {
30     # List version-specific constants here.
31     # Easiest way to keep this code portable between version looks to
32     # be to fake up a dummy constant that will never actually be true.
33     foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
34                 OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
35                 RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
36                 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
37                 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
38         eval { import B $_ };
39         no strict 'refs';
40         *{$_} = sub () {0} unless *{$_}{CODE};
41     }
42 }
43
44 # Changes between 0.50 and 0.51:
45 # - fixed nulled leave with live enter in sort { }
46 # - fixed reference constants (\"str")
47 # - handle empty programs gracefully
48 # - handle infinite loops (for (;;) {}, while (1) {})
49 # - differentiate between 'for my $x ...' and 'my $x; for $x ...'
50 # - various minor cleanups
51 # - moved globals into an object
52 # - added '-u', like B::C
53 # - package declarations using cop_stash
54 # - subs, formats and code sorted by cop_seq
55 # Changes between 0.51 and 0.52:
56 # - added pp_threadsv (special variables under USE_5005THREADS)
57 # - added documentation
58 # Changes between 0.52 and 0.53:
59 # - many changes adding precedence contexts and associativity
60 # - added '-p' and '-s' output style options
61 # - various other minor fixes
62 # Changes between 0.53 and 0.54:
63 # - added support for new 'for (1..100)' optimization,
64 #   thanks to Gisle Aas
65 # Changes between 0.54 and 0.55:
66 # - added support for new qr// construct
67 # - added support for new pp_regcreset OP
68 # Changes between 0.55 and 0.56:
69 # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
70 # - fixed $# on non-lexicals broken in last big rewrite
71 # - added temporary fix for change in opcode of OP_STRINGIFY
72 # - fixed problem in 0.54's for() patch in 'for (@ary)'
73 # - fixed precedence in conditional of ?:
74 # - tweaked list paren elimination in 'my($x) = @_'
75 # - made continue-block detection trickier wrt. null ops
76 # - fixed various prototype problems in pp_entersub
77 # - added support for sub prototypes that never get GVs
78 # - added unquoting for special filehandle first arg in truncate
79 # - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
80 # - added semicolons at the ends of blocks
81 # - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
82 # Changes between 0.56 and 0.561:
83 # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
84 # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
85 # Changes between 0.561 and 0.57:
86 # - stylistic changes to symbolic constant stuff
87 # - handled scope in s///e replacement code
88 # - added unquote option for expanding "" into concats, etc.
89 # - split method and proto parts of pp_entersub into separate functions
90 # - various minor cleanups
91 # Changes after 0.57:
92 # - added parens in \&foo (patch by Albert Dvornik)
93 # Changes between 0.57 and 0.58:
94 # - fixed '0' statements that weren't being printed
95 # - added methods for use from other programs
96 #   (based on patches from James Duncan and Hugo van der Sanden)
97 # - added -si and -sT to control indenting (also based on a patch from Hugo)
98 # - added -sv to print something else instead of '???'
99 # - preliminary version of utf8 tr/// handling
100 # Changes after 0.58:
101 # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
102 # - added support for Hugo's new OP_SETSTATE (like nextstate)
103 # Changes between 0.58 and 0.59
104 # - added support for Chip's OP_METHOD_NAMED
105 # - added support for Ilya's OPpTARGET_MY optimization
106 # - elided arrows before '()' subscripts when possible
107 # Changes between 0.59 and 0.60
108 # - support for method attributes was added
109 # - some warnings fixed
110 # - separate recognition of constant subs
111 # - rewrote continue block handling, now recognizing for loops
112 # - added more control of expanding control structures
113 # Changes between 0.60 and 0.61 (mostly by Robin Houston)
114 # - many bug-fixes
115 # - support for pragmas and 'use'
116 # - support for the little-used $[ variable
117 # - support for __DATA__ sections
118 # - UTF8 support
119 # - BEGIN, CHECK, INIT and END blocks
120 # - scoping of subroutine declarations fixed
121 # - compile-time output from the input program can be suppressed, so that the
122 #   output is just the deparsed code. (a change to O.pm in fact)
123 # - our() declarations
124 # - *all* the known bugs are now listed in the BUGS section
125 # - comprehensive test mechanism (TEST -deparse)
126 # Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
127 # - bug-fixes
128 # - new switch -P
129 # - support for command-line switches (-l, -0, etc.)
130 # Changes between 0.63 and 0.64
131 # - support for //, CHECK blocks, and assertions
132 # - improved handling of foreach loops and lexicals
133 # - option to use Data::Dumper for constants
134 # - more bug fixes
135 # - discovered lots more bugs not yet fixed
136 #
137 # ...
138 #
139 # Changes between 0.72 and 0.73
140 # - support new switch constructs
141
142 # Todo:
143 #  (See also BUGS section at the end of this file)
144 #
145 # - finish tr/// changes
146 # - add option for even more parens (generalize \&foo change)
147 # - left/right context
148 # - copy comments (look at real text with $^P?)
149 # - avoid semis in one-statement blocks
150 # - associativity of &&=, ||=, ?:
151 # - ',' => '=>' (auto-unquote?)
152 # - break long lines ("\r" as discretionary break?)
153 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
154 # - more style options: brace style, hex vs. octal, quotes, ...
155 # - print big ints as hex/octal instead of decimal (heuristic?)
156 # - handle 'my $x if 0'?
157 # - version using op_next instead of op_first/sibling?
158 # - avoid string copies (pass arrays, one big join?)
159 # - here-docs?
160
161 # Current test.deparse failures
162 # comp/hints 6 - location of BEGIN blocks wrt. block openings
163 # run/switchI 1 - missing -I switches entirely
164 #    perl -Ifoo -e 'print @INC'
165 # op/caller 2 - warning mask propagates backwards before warnings::register
166 #    'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
167 # op/getpid 2 - can't assign to shared my() declaration (threads only)
168 #    'my $x : shared = 5'
169 # op/override 7 - parens on overridden require change v-string interpretation
170 #    'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
171 #    c.f. 'BEGIN { *f = sub {0} }; f 2'
172 # op/pat 774 - losing Unicode-ness of Latin1-only strings
173 #    'use charnames ":short"; $x="\N{latin:a with acute}"'
174 # op/recurse 12 - missing parens on recursive call makes it look like method
175 #    'sub f { f($x) }'
176 # op/subst 90 - inconsistent handling of utf8 under "use utf8"
177 # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
178 # op/tiehandle compile - "use strict" deparsed in the wrong place
179 # uni/tr_ several
180 # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
181 # ext/Data/Dumper/t/dumper compile
182 # ext/DB_file/several
183 # ext/Encode/several
184 # ext/Ernno/Errno warnings
185 # ext/IO/lib/IO/t/io_sel 23
186 # ext/PerlIO/t/encoding compile
187 # ext/POSIX/t/posix 6
188 # ext/Socket/Socket 8
189 # ext/Storable/t/croak compile
190 # lib/Attribute/Handlers/t/multi compile
191 # lib/bignum/ several
192 # lib/charnames 35
193 # lib/constant 32
194 # lib/English 40
195 # lib/ExtUtils/t/bytes 4
196 # lib/File/DosGlob compile
197 # lib/Filter/Simple/t/data 1
198 # lib/Math/BigInt/t/constant 1
199 # lib/Net/t/config Deparse-warning
200 # lib/overload compile
201 # lib/Switch/ several
202 # lib/Symbol 4
203 # lib/Test/Simple several
204 # lib/Term/Complete
205 # lib/Tie/File/t/29_downcopy 5
206 # lib/vars 22
207
208 # Object fields (were globals):
209 #
210 # avoid_local:
211 # (local($a), local($b)) and local($a, $b) have the same internal
212 # representation but the short form looks better. We notice we can
213 # use a large-scale local when checking the list, but need to prevent
214 # individual locals too. This hash holds the addresses of OPs that
215 # have already had their local-ness accounted for. The same thing
216 # is done with my().
217 #
218 # curcv:
219 # CV for current sub (or main program) being deparsed
220 #
221 # curcvlex:
222 # Cached hash of lexical variables for curcv: keys are
223 # names prefixed with "m" or "o" (representing my/our), and
224 # each value is an array of pairs, indicating the cop_seq of scopes
225 # in which a var of that name is valid.
226 #
227 # curcop:
228 # COP for statement being deparsed
229 #
230 # curstash:
231 # name of the current package for deparsed code
232 #
233 # subs_todo:
234 # array of [cop_seq, CV, is_format?] for subs and formats we still
235 # want to deparse
236 #
237 # protos_todo:
238 # as above, but [name, prototype] for subs that never got a GV
239 #
240 # subs_done, forms_done:
241 # keys are addresses of GVs for subs and formats we've already
242 # deparsed (or at least put into subs_todo)
243 #
244 # subs_declared
245 # keys are names of subs for which we've printed declarations.
246 # That means we can omit parentheses from the arguments. It also means we
247 # need to put CORE:: on core functions of the same name.
248 #
249 # subs_deparsed
250 # Keeps track of fully qualified names of all deparsed subs.
251 #
252 # parens: -p
253 # linenums: -l
254 # unquote: -q
255 # cuddle: ' ' or '\n', depending on -sC
256 # indent_size: -si
257 # use_tabs: -sT
258 # ex_const: -sv
259
260 # A little explanation of how precedence contexts and associativity
261 # work:
262 #
263 # deparse() calls each per-op subroutine with an argument $cx (short
264 # for context, but not the same as the cx* in the perl core), which is
265 # a number describing the op's parents in terms of precedence, whether
266 # they're inside an expression or at statement level, etc.  (see
267 # chart below). When ops with children call deparse on them, they pass
268 # along their precedence. Fractional values are used to implement
269 # associativity ('($x + $y) + $z' => '$x + $y + $y') and related
270 # parentheses hacks. The major disadvantage of this scheme is that
271 # it doesn't know about right sides and left sides, so say if you
272 # assign a listop to a variable, it can't tell it's allowed to leave
273 # the parens off the listop.
274
275 # Precedences:
276 # 26             [TODO] inside interpolation context ("")
277 # 25 left        terms and list operators (leftward)
278 # 24 left        ->
279 # 23 nonassoc    ++ --
280 # 22 right       **
281 # 21 right       ! ~ \ and unary + and -
282 # 20 left        =~ !~
283 # 19 left        * / % x
284 # 18 left        + - .
285 # 17 left        << >>
286 # 16 nonassoc    named unary operators
287 # 15 nonassoc    < > <= >= lt gt le ge
288 # 14 nonassoc    == != <=> eq ne cmp
289 # 13 left        &
290 # 12 left        | ^
291 # 11 left        &&
292 # 10 left        ||
293 #  9 nonassoc    ..  ...
294 #  8 right       ?:
295 #  7 right       = += -= *= etc.
296 #  6 left        , =>
297 #  5 nonassoc    list operators (rightward)
298 #  4 right       not
299 #  3 left        and
300 #  2 left        or xor
301 #  1             statement modifiers
302 #  0.5           statements, but still print scopes as do { ... }
303 #  0             statement level
304
305 # Nonprinting characters with special meaning:
306 # \cS - steal parens (see maybe_parens_unop)
307 # \n - newline and indent
308 # \t - increase indent
309 # \b - decrease indent ('outdent')
310 # \f - flush left (no indent)
311 # \cK - kill following semicolon, if any
312
313 sub null {
314     my $op = shift;
315     return class($op) eq "NULL";
316 }
317
318 sub todo {
319     my $self = shift;
320     my($cv, $is_form) = @_;
321     return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
322     my $seq;
323     if ($cv->OUTSIDE_SEQ) {
324         $seq = $cv->OUTSIDE_SEQ;
325     } elsif (!null($cv->START) and is_state($cv->START)) {
326         $seq = $cv->START->cop_seq;
327     } else {
328         $seq = 0;
329     }
330     push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
331     unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
332         $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
333     }
334 }
335
336 sub next_todo {
337     my $self = shift;
338     my $ent = shift @{$self->{'subs_todo'}};
339     my $cv = $ent->[1];
340     my $gv = $cv->GV;
341     my $name = $self->gv_name($gv);
342     if ($ent->[2]) {
343         return "format $name =\n"
344             . $self->deparse_format($ent->[1]). "\n";
345     } else {
346         $self->{'subs_declared'}{$name} = 1;
347         if ($name eq "BEGIN") {
348             my $use_dec = $self->begin_is_use($cv);
349             if (defined ($use_dec) and $self->{'expand'} < 5) {
350                 return () if 0 == length($use_dec);
351                 return $use_dec;
352             }
353         }
354         my $l = '';
355         if ($self->{'linenums'}) {
356             my $line = $gv->LINE;
357             my $file = $gv->FILE;
358             $l = "\n\f#line $line \"$file\"\n";
359         }
360         my $p = '';
361         if (class($cv->STASH) ne "SPECIAL") {
362             my $stash = $cv->STASH->NAME;
363             if ($stash ne $self->{'curstash'}) {
364                 $p = "package $stash;\n";
365                 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
366                 $self->{'curstash'} = $stash;
367             }
368             $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
369         }
370         return "${p}${l}sub $name " . $self->deparse_sub($cv);
371     }
372 }
373
374 # Return a "use" declaration for this BEGIN block, if appropriate
375 sub begin_is_use {
376     my ($self, $cv) = @_;
377     my $root = $cv->ROOT;
378     local @$self{qw'curcv curcvlex'} = ($cv);
379 #require B::Debug;
380 #B::walkoptree($cv->ROOT, "debug");
381     my $lineseq = $root->first;
382     return if $lineseq->name ne "lineseq";
383
384     my $req_op = $lineseq->first->sibling;
385     return if $req_op->name ne "require";
386
387     my $module;
388     if ($req_op->first->private & OPpCONST_BARE) {
389         # Actually it should always be a bareword
390         $module = $self->const_sv($req_op->first)->PV;
391         $module =~ s[/][::]g;
392         $module =~ s/.pm$//;
393     }
394     else {
395         $module = $self->const($self->const_sv($req_op->first), 6);
396     }
397
398     my $version;
399     my $version_op = $req_op->sibling;
400     return if class($version_op) eq "NULL";
401     if ($version_op->name eq "lineseq") {
402         # We have a version parameter; skip nextstate & pushmark
403         my $constop = $version_op->first->next->next;
404
405         return unless $self->const_sv($constop)->PV eq $module;
406         $constop = $constop->sibling;
407         $version = $self->const_sv($constop);
408         if (class($version) eq "IV") {
409             $version = $version->int_value;
410         } elsif (class($version) eq "NV") {
411             $version = $version->NV;
412         } elsif (class($version) ne "PVMG") {
413             # Includes PVIV and PVNV
414             $version = $version->PV;
415         } else {
416             # version specified as a v-string
417             $version = 'v'.join '.', map ord, split //, $version->PV;
418         }
419         $constop = $constop->sibling;
420         return if $constop->name ne "method_named";
421         return if $self->const_sv($constop)->PV ne "VERSION";
422     }
423
424     $lineseq = $version_op->sibling;
425     return if $lineseq->name ne "lineseq";
426     my $entersub = $lineseq->first->sibling;
427     if ($entersub->name eq "stub") {
428         return "use $module $version ();\n" if defined $version;
429         return "use $module ();\n";
430     }
431     return if $entersub->name ne "entersub";
432
433     # See if there are import arguments
434     my $args = '';
435
436     my $svop = $entersub->first->sibling; # Skip over pushmark
437     return unless $self->const_sv($svop)->PV eq $module;
438
439     # Pull out the arguments
440     for ($svop=$svop->sibling; $svop->name ne "method_named";
441                 $svop = $svop->sibling) {
442         $args .= ", " if length($args);
443         $args .= $self->deparse($svop, 6);
444     }
445
446     my $use = 'use';
447     my $method_named = $svop;
448     return if $method_named->name ne "method_named";
449     my $method_name = $self->const_sv($method_named)->PV;
450
451     if ($method_name eq "unimport") {
452         $use = 'no';
453     }
454
455     # Certain pragmas are dealt with using hint bits,
456     # so we ignore them here
457     if ($module eq 'strict' || $module eq 'integer'
458         || $module eq 'bytes' || $module eq 'warnings'
459         || $module eq 'feature') {
460         return "";
461     }
462
463     if (defined $version && length $args) {
464         return "$use $module $version ($args);\n";
465     } elsif (defined $version) {
466         return "$use $module $version;\n";
467     } elsif (length $args) {
468         return "$use $module ($args);\n";
469     } else {
470         return "$use $module;\n";
471     }
472 }
473
474 sub stash_subs {
475     my ($self, $pack, $seen) = @_;
476     my (@ret, $stash);
477     if (!defined $pack) {
478         $pack = '';
479         $stash = \%::;
480     }
481     else {
482         $pack =~ s/(::)?$/::/;
483         no strict 'refs';
484         $stash = \%{"main::$pack"};
485     }
486     return
487         if ($seen ||= {})->{
488             $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
489            }++;
490     my %stash = svref_2object($stash)->ARRAY;
491     while (my ($key, $val) = each %stash) {
492         my $class = class($val);
493         if ($class eq "PV") {
494             # Just a prototype. As an ugly but fairly effective way
495             # to find out if it belongs here is to see if the AUTOLOAD
496             # (if any) for the stash was defined in one of our files.
497             my $A = $stash{"AUTOLOAD"};
498             if (defined ($A) && class($A) eq "GV" && defined($A->CV)
499                 && class($A->CV) eq "CV") {
500                 my $AF = $A->FILE;
501                 next unless $AF eq $0 || exists $self->{'files'}{$AF};
502             }
503             push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
504         } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
505             # Just a name. As above.
506             # But skip proxy constant subroutines, as some form of perl-space
507             # visible code must have created them, be it a use statement, or
508             # some direct symbol-table manipulation code that we will Deparse
509             my $A = $stash{"AUTOLOAD"};
510             if (defined ($A) && class($A) eq "GV" && defined($A->CV)
511                 && class($A->CV) eq "CV") {
512                 my $AF = $A->FILE;
513                 next unless $AF eq $0 || exists $self->{'files'}{$AF};
514             }
515             push @{$self->{'protos_todo'}}, [$pack . $key, undef];
516         } elsif ($class eq "GV") {
517             if (class(my $cv = $val->CV) ne "SPECIAL") {
518                 next if $self->{'subs_done'}{$$val}++;
519                 next if $$val != ${$cv->GV};   # Ignore imposters
520                 $self->todo($cv, 0);
521             }
522             if (class(my $cv = $val->FORM) ne "SPECIAL") {
523                 next if $self->{'forms_done'}{$$val}++;
524                 next if $$val != ${$cv->GV};   # Ignore imposters
525                 $self->todo($cv, 1);
526             }
527             if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
528                 $self->stash_subs($pack . $key, $seen);
529             }
530         }
531     }
532 }
533
534 sub print_protos {
535     my $self = shift;
536     my $ar;
537     my @ret;
538     foreach $ar (@{$self->{'protos_todo'}}) {
539         my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
540         push @ret, "sub " . $ar->[0] .  "$proto;\n";
541     }
542     delete $self->{'protos_todo'};
543     return @ret;
544 }
545
546 sub style_opts {
547     my $self = shift;
548     my $opts = shift;
549     my $opt;
550     while (length($opt = substr($opts, 0, 1))) {
551         if ($opt eq "C") {
552             $self->{'cuddle'} = " ";
553             $opts = substr($opts, 1);
554         } elsif ($opt eq "i") {
555             $opts =~ s/^i(\d+)//;
556             $self->{'indent_size'} = $1;
557         } elsif ($opt eq "T") {
558             $self->{'use_tabs'} = 1;
559             $opts = substr($opts, 1);
560         } elsif ($opt eq "v") {
561             $opts =~ s/^v([^.]*)(.|$)//;
562             $self->{'ex_const'} = $1;
563         }
564     }
565 }
566
567 sub new {
568     my $class = shift;
569     my $self = bless {}, $class;
570     $self->{'cuddle'} = "\n";
571     $self->{'curcop'} = undef;
572     $self->{'curstash'} = "main";
573     $self->{'ex_const'} = "'???'";
574     $self->{'expand'} = 0;
575     $self->{'files'} = {};
576     $self->{'indent_size'} = 4;
577     $self->{'linenums'} = 0;
578     $self->{'parens'} = 0;
579     $self->{'subs_todo'} = [];
580     $self->{'unquote'} = 0;
581     $self->{'use_dumper'} = 0;
582     $self->{'use_tabs'} = 0;
583
584     $self->{'ambient_arybase'} = 0;
585     $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
586     $self->{'ambient_hints'} = 0;
587     $self->{'ambient_hinthash'} = undef;
588     $self->init();
589
590     while (my $arg = shift @_) {
591         if ($arg eq "-d") {
592             $self->{'use_dumper'} = 1;
593             require Data::Dumper;
594         } elsif ($arg =~ /^-f(.*)/) {
595             $self->{'files'}{$1} = 1;
596         } elsif ($arg eq "-l") {
597             $self->{'linenums'} = 1;
598         } elsif ($arg eq "-p") {
599             $self->{'parens'} = 1;
600         } elsif ($arg eq "-P") {
601             $self->{'noproto'} = 1;
602         } elsif ($arg eq "-q") {
603             $self->{'unquote'} = 1;
604         } elsif (substr($arg, 0, 2) eq "-s") {
605             $self->style_opts(substr $arg, 2);
606         } elsif ($arg =~ /^-x(\d)$/) {
607             $self->{'expand'} = $1;
608         }
609     }
610     return $self;
611 }
612
613 {
614     # Mask out the bits that L<warnings::register> uses
615     my $WARN_MASK;
616     BEGIN {
617         $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
618     }
619     sub WARN_MASK () {
620         return $WARN_MASK;
621     }
622 }
623
624 # Initialise the contextual information, either from
625 # defaults provided with the ambient_pragmas method,
626 # or from perl's own defaults otherwise.
627 sub init {
628     my $self = shift;
629
630     $self->{'arybase'}  = $self->{'ambient_arybase'};
631     $self->{'warnings'} = defined ($self->{'ambient_warnings'})
632                                 ? $self->{'ambient_warnings'} & WARN_MASK
633                                 : undef;
634     $self->{'hints'}    = $self->{'ambient_hints'};
635     $self->{'hints'} &= 0xFF if $] < 5.009;
636     $self->{'hinthash'} = $self->{'ambient_hinthash'};
637
638     # also a convenient place to clear out subs_declared
639     delete $self->{'subs_declared'};
640 }
641
642 sub compile {
643     my(@args) = @_;
644     return sub {
645         my $self = B::Deparse->new(@args);
646         # First deparse command-line args
647         if (defined $^I) { # deparse -i
648             print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
649         }
650         if ($^W) { # deparse -w
651             print qq(BEGIN { \$^W = $^W; }\n);
652         }
653         if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
654             my $fs = perlstring($/) || 'undef';
655             my $bs = perlstring($O::savebackslash) || 'undef';
656             print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
657         }
658         my @BEGINs  = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
659         my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
660             ? B::unitcheck_av->ARRAY
661             : ();
662         my @CHECKs  = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
663         my @INITs   = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
664         my @ENDs    = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
665         for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
666             $self->todo($block, 0);
667         }
668         $self->stash_subs();
669         local($SIG{"__DIE__"}) =
670           sub {
671               if ($self->{'curcop'}) {
672                   my $cop = $self->{'curcop'};
673                   my($line, $file) = ($cop->line, $cop->file);
674                   print STDERR "While deparsing $file near line $line,\n";
675               }
676             };
677         $self->{'curcv'} = main_cv;
678         $self->{'curcvlex'} = undef;
679         print $self->print_protos;
680         @{$self->{'subs_todo'}} =
681           sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
682         print $self->indent($self->deparse_root(main_root)), "\n"
683           unless null main_root;
684         my @text;
685         while (scalar(@{$self->{'subs_todo'}})) {
686             push @text, $self->next_todo;
687         }
688         print $self->indent(join("", @text)), "\n" if @text;
689
690         # Print __DATA__ section, if necessary
691         no strict 'refs';
692         my $laststash = defined $self->{'curcop'}
693             ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
694         if (defined *{$laststash."::DATA"}{IO}) {
695             print "package $laststash;\n"
696                 unless $laststash eq $self->{'curstash'};
697             print "__DATA__\n";
698             print readline(*{$laststash."::DATA"});
699         }
700     }
701 }
702
703 sub coderef2text {
704     my $self = shift;
705     my $sub = shift;
706     croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
707
708     $self->init();
709     return $self->indent($self->deparse_sub(svref_2object($sub)));
710 }
711
712 my %strict_bits = do {
713     local %^H;
714     map +($_ => strict::bits($_)), qw/refs subs vars/
715 };
716
717 sub ambient_pragmas {
718     my $self = shift;
719     my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
720
721     while (@_ > 1) {
722         my $name = shift();
723         my $val  = shift();
724
725         if ($name eq 'strict') {
726             require strict;
727
728             if ($val eq 'none') {
729                 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
730                 next();
731             }
732
733             my @names;
734             if ($val eq "all") {
735                 @names = qw/refs subs vars/;
736             }
737             elsif (ref $val) {
738                 @names = @$val;
739             }
740             else {
741                 @names = split' ', $val;
742             }
743             $hint_bits |= $strict_bits{$_} for @names;
744         }
745
746         elsif ($name eq '$[') {
747             if (OPpCONST_ARYBASE) {
748                 $arybase = $val;
749             } else {
750                 croak "\$[ can't be non-zero on this perl" unless $val == 0;
751             }
752         }
753
754         elsif ($name eq 'integer'
755             || $name eq 'bytes'
756             || $name eq 'utf8') {
757             require "$name.pm";
758             if ($val) {
759                 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
760             }
761             else {
762                 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
763             }
764         }
765
766         elsif ($name eq 're') {
767             require re;
768             if ($val eq 'none') {
769                 $hint_bits &= ~re::bits(qw/taint eval/);
770                 next();
771             }
772
773             my @names;
774             if ($val eq 'all') {
775                 @names = qw/taint eval/;
776             }
777             elsif (ref $val) {
778                 @names = @$val;
779             }
780             else {
781                 @names = split' ',$val;
782             }
783             $hint_bits |= re::bits(@names);
784         }
785
786         elsif ($name eq 'warnings') {
787             if ($val eq 'none') {
788                 $warning_bits = $warnings::NONE;
789                 next();
790             }
791
792             my @names;
793             if (ref $val) {
794                 @names = @$val;
795             }
796             else {
797                 @names = split/\s+/, $val;
798             }
799
800             $warning_bits = $warnings::NONE if !defined ($warning_bits);
801             $warning_bits |= warnings::bits(@names);
802         }
803
804         elsif ($name eq 'warning_bits') {
805             $warning_bits = $val;
806         }
807
808         elsif ($name eq 'hint_bits') {
809             $hint_bits = $val;
810         }
811
812         elsif ($name eq '%^H') {
813             $hinthash = $val;
814         }
815
816         else {
817             croak "Unknown pragma type: $name";
818         }
819     }
820     if (@_) {
821         croak "The ambient_pragmas method expects an even number of args";
822     }
823
824     $self->{'ambient_arybase'} = $arybase;
825     $self->{'ambient_warnings'} = $warning_bits;
826     $self->{'ambient_hints'} = $hint_bits;
827     $self->{'ambient_hinthash'} = $hinthash;
828 }
829
830 # This method is the inner loop, so try to keep it simple
831 sub deparse {
832     my $self = shift;
833     my($op, $cx) = @_;
834
835     Carp::confess("Null op in deparse") if !defined($op)
836                                         || class($op) eq "NULL";
837     my $meth = "pp_" . $op->name;
838     return $self->$meth($op, $cx);
839 }
840
841 sub indent {
842     my $self = shift;
843     my $txt = shift;
844     my @lines = split(/\n/, $txt);
845     my $leader = "";
846     my $level = 0;
847     my $line;
848     for $line (@lines) {
849         my $cmd = substr($line, 0, 1);
850         if ($cmd eq "\t" or $cmd eq "\b") {
851             $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
852             if ($self->{'use_tabs'}) {
853                 $leader = "\t" x ($level / 8) . " " x ($level % 8);
854             } else {
855                 $leader = " " x $level;
856             }
857             $line = substr($line, 1);
858         }
859         if (substr($line, 0, 1) eq "\f") {
860             $line = substr($line, 1); # no indent
861         } else {
862             $line = $leader . $line;
863         }
864         $line =~ s/\cK;?//g;
865     }
866     return join("\n", @lines);
867 }
868
869 sub deparse_sub {
870     my $self = shift;
871     my $cv = shift;
872     my $proto = "";
873 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
874 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
875     local $self->{'curcop'} = $self->{'curcop'};
876     if ($cv->FLAGS & SVf_POK) {
877         $proto = "(". $cv->PV . ") ";
878     }
879     if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
880         $proto .= ": ";
881         $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
882         $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
883         $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
884     }
885
886     local($self->{'curcv'}) = $cv;
887     local($self->{'curcvlex'});
888     local(@$self{qw'curstash warnings hints hinthash'})
889                 = @$self{qw'curstash warnings hints hinthash'};
890     my $body;
891     if (not null $cv->ROOT) {
892         my $lineseq = $cv->ROOT->first;
893         if ($lineseq->name eq "lineseq") {
894             my @ops;
895             for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
896                 push @ops, $o;
897             }
898             $body = $self->lineseq(undef, @ops).";";
899             my $scope_en = $self->find_scope_en($lineseq);
900             if (defined $scope_en) {
901                 my $subs = join"", $self->seq_subs($scope_en);
902                 $body .= ";\n$subs" if length($subs);
903             }
904         }
905         else {
906             $body = $self->deparse($cv->ROOT->first, 0);
907         }
908     }
909     else {
910         my $sv = $cv->const_sv;
911         if ($$sv) {
912             # uh-oh. inlinable sub... format it differently
913             return $proto . "{ " . $self->const($sv, 0) . " }\n";
914         } else { # XSUB? (or just a declaration)
915             return "$proto;\n";
916         }
917     }
918     return $proto ."{\n\t$body\n\b}" ."\n";
919 }
920
921 sub deparse_format {
922     my $self = shift;
923     my $form = shift;
924     my @text;
925     local($self->{'curcv'}) = $form;
926     local($self->{'curcvlex'});
927     local($self->{'in_format'}) = 1;
928     local(@$self{qw'curstash warnings hints hinthash'})
929                 = @$self{qw'curstash warnings hints hinthash'};
930     my $op = $form->ROOT;
931     my $kid;
932     return "\f." if $op->first->name eq 'stub'
933                 || $op->first->name eq 'nextstate';
934     $op = $op->first->first; # skip leavewrite, lineseq
935     while (not null $op) {
936         $op = $op->sibling; # skip nextstate
937         my @exprs;
938         $kid = $op->first->sibling; # skip pushmark
939         push @text, "\f".$self->const_sv($kid)->PV;
940         $kid = $kid->sibling;
941         for (; not null $kid; $kid = $kid->sibling) {
942             push @exprs, $self->deparse($kid, 0);
943         }
944         push @text, "\f".join(", ", @exprs)."\n" if @exprs;
945         $op = $op->sibling;
946     }
947     return join("", @text) . "\f.";
948 }
949
950 sub is_scope {
951     my $op = shift;
952     return $op->name eq "leave" || $op->name eq "scope"
953       || $op->name eq "lineseq"
954         || ($op->name eq "null" && class($op) eq "UNOP"
955             && (is_scope($op->first) || $op->first->name eq "enter"));
956 }
957
958 sub is_state {
959     my $name = $_[0]->name;
960     return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
961 }
962
963 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
964     my $op = shift;
965     return (!null($op) and null($op->sibling)
966             and $op->name eq "null" and class($op) eq "UNOP"
967             and (($op->first->name =~ /^(and|or)$/
968                   and $op->first->first->sibling->name eq "lineseq")
969                  or ($op->first->name eq "lineseq"
970                      and not null $op->first->first->sibling
971                      and $op->first->first->sibling->name eq "unstack")
972                  ));
973 }
974
975 # Check if the op and its sibling are the initialization and the rest of a
976 # for (..;..;..) { ... } loop
977 sub is_for_loop {
978     my $op = shift;
979     # This OP might be almost anything, though it won't be a
980     # nextstate. (It's the initialization, so in the canonical case it
981     # will be an sassign.) The sibling is (old style) a lineseq whose
982     # first child is a nextstate and whose second is a leaveloop, or
983     # (new style) an unstack whose sibling is a leaveloop.
984     my $lseq = $op->sibling;
985     return 0 unless !is_state($op) and !null($lseq);
986     if ($lseq->name eq "lineseq") {
987         if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
988             && (my $sib = $lseq->first->sibling)) {
989             return (!null($sib) && $sib->name eq "leaveloop");
990         }
991     } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
992         my $sib = $lseq->sibling;
993         return $sib && !null($sib) && $sib->name eq "leaveloop";
994     }
995     return 0;
996 }
997
998 sub is_scalar {
999     my $op = shift;
1000     return ($op->name eq "rv2sv" or
1001             $op->name eq "padsv" or
1002             $op->name eq "gv" or # only in array/hash constructs
1003             $op->flags & OPf_KIDS && !null($op->first)
1004               && $op->first->name eq "gvsv");
1005 }
1006
1007 sub maybe_parens {
1008     my $self = shift;
1009     my($text, $cx, $prec) = @_;
1010     if ($prec < $cx              # unary ops nest just fine
1011         or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1012         or $self->{'parens'})
1013     {
1014         $text = "($text)";
1015         # In a unop, let parent reuse our parens; see maybe_parens_unop
1016         $text = "\cS" . $text if $cx == 16;
1017         return $text;
1018     } else {
1019         return $text;
1020     }
1021 }
1022
1023 # same as above, but get around the 'if it looks like a function' rule
1024 sub maybe_parens_unop {
1025     my $self = shift;
1026     my($name, $kid, $cx) = @_;
1027     if ($cx > 16 or $self->{'parens'}) {
1028         $kid =  $self->deparse($kid, 1);
1029         if ($name eq "umask" && $kid =~ /^\d+$/) {
1030             $kid = sprintf("%#o", $kid);
1031         }
1032         return $self->keyword($name) . "($kid)";
1033     } else {
1034         $kid = $self->deparse($kid, 16);
1035         if ($name eq "umask" && $kid =~ /^\d+$/) {
1036             $kid = sprintf("%#o", $kid);
1037         }
1038         $name = $self->keyword($name);
1039         if (substr($kid, 0, 1) eq "\cS") {
1040             # use kid's parens
1041             return $name . substr($kid, 1);
1042         } elsif (substr($kid, 0, 1) eq "(") {
1043             # avoid looks-like-a-function trap with extra parens
1044             # ('+' can lead to ambiguities)
1045             return "$name(" . $kid  . ")";
1046         } else {
1047             return "$name $kid";
1048         }
1049     }
1050 }
1051
1052 sub maybe_parens_func {
1053     my $self = shift;
1054     my($func, $text, $cx, $prec) = @_;
1055     if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1056         return "$func($text)";
1057     } else {
1058         return "$func $text";
1059     }
1060 }
1061
1062 sub maybe_local {
1063     my $self = shift;
1064     my($op, $cx, $text) = @_;
1065     my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1066     if ($op->private & (OPpLVAL_INTRO|$our_intro)
1067         and not $self->{'avoid_local'}{$$op}) {
1068         my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1069         if( $our_local eq 'our' ) {
1070             if ( $text !~ /^\W(\w+::)*\w+\z/
1071              and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1072             ) {
1073                 die "Unexpected our($text)\n";
1074             }
1075             $text =~ s/(\w+::)+//;
1076         }
1077         if (want_scalar($op)) {
1078             return "$our_local $text";
1079         } else {
1080             return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1081         }
1082     } else {
1083         return $text;
1084     }
1085 }
1086
1087 sub maybe_targmy {
1088     my $self = shift;
1089     my($op, $cx, $func, @args) = @_;
1090     if ($op->private & OPpTARGET_MY) {
1091         my $var = $self->padname($op->targ);
1092         my $val = $func->($self, $op, 7, @args);
1093         return $self->maybe_parens("$var = $val", $cx, 7);
1094     } else {
1095         return $func->($self, $op, $cx, @args);
1096     }
1097 }
1098
1099 sub padname_sv {
1100     my $self = shift;
1101     my $targ = shift;
1102     return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1103 }
1104
1105 sub maybe_my {
1106     my $self = shift;
1107     my($op, $cx, $text) = @_;
1108     if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1109         my $my = $op->private & OPpPAD_STATE
1110             ? $self->keyword("state")
1111             : "my";
1112         if (want_scalar($op)) {
1113             return "$my $text";
1114         } else {
1115             return $self->maybe_parens_func($my, $text, $cx, 16);
1116         }
1117     } else {
1118         return $text;
1119     }
1120 }
1121
1122 # The following OPs don't have functions:
1123
1124 # pp_padany -- does not exist after parsing
1125
1126 sub AUTOLOAD {
1127     if ($AUTOLOAD =~ s/^.*::pp_//) {
1128         warn "unexpected OP_".uc $AUTOLOAD;
1129         return "XXX";
1130     } else {
1131         die "Undefined subroutine $AUTOLOAD called";
1132     }
1133 }
1134
1135 sub DESTROY {}  #       Do not AUTOLOAD
1136
1137 # $root should be the op which represents the root of whatever
1138 # we're sequencing here. If it's undefined, then we don't append
1139 # any subroutine declarations to the deparsed ops, otherwise we
1140 # append appropriate declarations.
1141 sub lineseq {
1142     my($self, $root, @ops) = @_;
1143     my($expr, @exprs);
1144
1145     my $out_cop = $self->{'curcop'};
1146     my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1147     my $limit_seq;
1148     if (defined $root) {
1149         $limit_seq = $out_seq;
1150         my $nseq;
1151         $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1152         $limit_seq = $nseq if !defined($limit_seq)
1153                            or defined($nseq) && $nseq < $limit_seq;
1154     }
1155     $limit_seq = $self->{'limit_seq'}
1156         if defined($self->{'limit_seq'})
1157         && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1158     local $self->{'limit_seq'} = $limit_seq;
1159
1160     $self->walk_lineseq($root, \@ops,
1161                        sub { push @exprs, $_[0]} );
1162
1163     my $body = join(";\n", grep {length} @exprs);
1164     my $subs = "";
1165     if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1166         $subs = join "\n", $self->seq_subs($limit_seq);
1167     }
1168     return join(";\n", grep {length} $body, $subs);
1169 }
1170
1171 sub scopeop {
1172     my($real_block, $self, $op, $cx) = @_;
1173     my $kid;
1174     my @kids;
1175
1176     local(@$self{qw'curstash warnings hints hinthash'})
1177                 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1178     if ($real_block) {
1179         $kid = $op->first->sibling; # skip enter
1180         if (is_miniwhile($kid)) {
1181             my $top = $kid->first;
1182             my $name = $top->name;
1183             if ($name eq "and") {
1184                 $name = "while";
1185             } elsif ($name eq "or") {
1186                 $name = "until";
1187             } else { # no conditional -> while 1 or until 0
1188                 return $self->deparse($top->first, 1) . " while 1";
1189             }
1190             my $cond = $top->first;
1191             my $body = $cond->sibling->first; # skip lineseq
1192             $cond = $self->deparse($cond, 1);
1193             $body = $self->deparse($body, 1);
1194             return "$body $name $cond";
1195         }
1196     } else {
1197         $kid = $op->first;
1198     }
1199     for (; !null($kid); $kid = $kid->sibling) {
1200         push @kids, $kid;
1201     }
1202     if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1203         return "do {\n\t" . $self->lineseq($op, @kids) . "\n\b}";
1204     } else {
1205         my $lineseq = $self->lineseq($op, @kids);
1206         return (length ($lineseq) ? "$lineseq;" : "");
1207     }
1208 }
1209
1210 sub pp_scope { scopeop(0, @_); }
1211 sub pp_lineseq { scopeop(0, @_); }
1212 sub pp_leave { scopeop(1, @_); }
1213
1214 # This is a special case of scopeop and lineseq, for the case of the
1215 # main_root. The difference is that we print the output statements as
1216 # soon as we get them, for the sake of impatient users.
1217 sub deparse_root {
1218     my $self = shift;
1219     my($op) = @_;
1220     local(@$self{qw'curstash warnings hints hinthash'})
1221       = @$self{qw'curstash warnings hints hinthash'};
1222     my @kids;
1223     return if null $op->first; # Can happen, e.g., for Bytecode without -k
1224     for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1225         push @kids, $kid;
1226     }
1227     $self->walk_lineseq($op, \@kids,
1228                         sub { print $self->indent($_[0].';');
1229                               print "\n" unless $_[1] == $#kids;
1230                           });
1231 }
1232
1233 sub walk_lineseq {
1234     my ($self, $op, $kids, $callback) = @_;
1235     my @kids = @$kids;
1236     for (my $i = 0; $i < @kids; $i++) {
1237         my $expr = "";
1238         if (is_state $kids[$i]) {
1239             $expr = $self->deparse($kids[$i++], 0);
1240             if ($i > $#kids) {
1241                 $callback->($expr, $i);
1242                 last;
1243             }
1244         }
1245         if (is_for_loop($kids[$i])) {
1246             $callback->($expr . $self->for_loop($kids[$i], 0),
1247                 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1248             next;
1249         }
1250         $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1251         $expr =~ s/;\n?\z//;
1252         $callback->($expr, $i);
1253     }
1254 }
1255
1256 # The BEGIN {} is used here because otherwise this code isn't executed
1257 # when you run B::Deparse on itself.
1258 my %globalnames;
1259 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1260             "ENV", "ARGV", "ARGVOUT", "_"); }
1261
1262 sub gv_name {
1263     my $self = shift;
1264     my $gv = shift;
1265     my $raw = shift;
1266 Carp::confess() unless ref($gv) eq "B::GV";
1267     my $stash = $gv->STASH->NAME;
1268     my $name = $raw ? $gv->NAME : $gv->SAFENAME;
1269     if ($stash eq 'main' && $name =~ /^::/) {
1270         $stash = '::';
1271     }
1272     elsif (($stash eq 'main'
1273             && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1274         or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1275             && ($stash eq 'main' || $name !~ /::/))
1276           )
1277     {
1278         $stash = "";
1279     } else {
1280         $stash = $stash . "::";
1281     }
1282     if (!$raw and $name =~ /^(\^..|{)/) {
1283         $name = "{$name}";       # ${^WARNING_BITS}, etc and ${
1284     }
1285     return $stash . $name;
1286 }
1287
1288 # Return the name to use for a stash variable.
1289 # If a lexical with the same name is in scope, or
1290 # if strictures are enabled, it may need to be
1291 # fully-qualified.
1292 sub stash_variable {
1293     my ($self, $prefix, $name, $cx) = @_;
1294
1295     return "$prefix$name" if $name =~ /::/;
1296
1297     unless ($prefix eq '$' || $prefix eq '@' || #'
1298             $prefix eq '%' || $prefix eq '$#') {
1299         return "$prefix$name";
1300     }
1301
1302     if ($name =~ /^[^\w+-]$/) {
1303       if (defined $cx && $cx == 26) {
1304         if ($prefix eq '@') {
1305             return "$prefix\{$name}";
1306         }
1307         elsif ($name eq '#') { return '${#}' } #  "${#}a" vs "$#a"
1308       }
1309       if ($prefix eq '$#') {
1310         return "\$#{$name}";
1311       }
1312     }
1313
1314     return $prefix . $self->maybe_qualify($prefix, $name);
1315 }
1316
1317 # Return just the name, without the prefix.  It may be returned as a quoted
1318 # string.  The second return value is a boolean indicating that.
1319 sub stash_variable_name {
1320     my($self, $prefix, $gv) = @_;
1321     my $name = $self->gv_name($gv, 1);
1322     $name = $self->maybe_qualify($prefix,$name);
1323     if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1324         $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1325         $name =~ /^(\^..|{)/ and $name = "{$name}";
1326         return $name, 0; # not quoted
1327     }
1328     else {
1329         single_delim("q", "'", $name), 1;
1330     }
1331 }
1332
1333 sub maybe_qualify {
1334     my ($self,$prefix,$name) = @_;
1335     my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1336     return $name if !$prefix || $name =~ /::/;
1337     return $self->{'curstash'}.'::'. $name
1338         if
1339             $name =~ /^(?!\d)\w/         # alphabetic
1340          && $v    !~ /^\$[ab]\z/         # not $a or $b
1341          && !$globalnames{$name}         # not a global name
1342          && $self->{hints} & $strict_bits{vars}  # strict vars
1343          && !$self->lex_in_scope($v,1)   # no "our"
1344       or $self->lex_in_scope($v);        # conflicts with "my" variable
1345     return $name;
1346 }
1347
1348 sub lex_in_scope {
1349     my ($self, $name, $our) = @_;
1350     substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1351     $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1352
1353     return 0 if !defined($self->{'curcop'});
1354     my $seq = $self->{'curcop'}->cop_seq;
1355     return 0 if !exists $self->{'curcvlex'}{$name};
1356     for my $a (@{$self->{'curcvlex'}{$name}}) {
1357         my ($st, $en) = @$a;
1358         return 1 if $seq > $st && $seq <= $en;
1359     }
1360     return 0;
1361 }
1362
1363 sub populate_curcvlex {
1364     my $self = shift;
1365     for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1366         my $padlist = $cv->PADLIST;
1367         # an undef CV still in lexical chain
1368         next if class($padlist) eq "SPECIAL";
1369         my @padlist = $padlist->ARRAY;
1370         my @ns = $padlist[0]->ARRAY;
1371
1372         for (my $i=0; $i<@ns; ++$i) {
1373             next if class($ns[$i]) eq "SPECIAL";
1374             if (class($ns[$i]) eq "PV") {
1375                 # Probably that pesky lexical @_
1376                 next;
1377             }
1378             my $name = $ns[$i]->PVX;
1379             my ($seq_st, $seq_en) =
1380                 ($ns[$i]->FLAGS & SVf_FAKE)
1381                     ? (0, 999999)
1382                     : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1383
1384             push @{$self->{'curcvlex'}{
1385                         ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1386                   }}, [$seq_st, $seq_en];
1387         }
1388     }
1389 }
1390
1391 sub find_scope_st { ((find_scope(@_))[0]); }
1392 sub find_scope_en { ((find_scope(@_))[1]); }
1393
1394 # Recurses down the tree, looking for pad variable introductions and COPs
1395 sub find_scope {
1396     my ($self, $op, $scope_st, $scope_en) = @_;
1397     carp("Undefined op in find_scope") if !defined $op;
1398     return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1399
1400     my @queue = ($op);
1401     while(my $op = shift @queue ) {
1402         for (my $o=$op->first; $$o; $o=$o->sibling) {
1403             if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1404                 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1405                 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1406                 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1407                 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1408                 return ($scope_st, $scope_en);
1409             }
1410             elsif (is_state($o)) {
1411                 my $c = $o->cop_seq;
1412                 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1413                 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1414                 return ($scope_st, $scope_en);
1415             }
1416             elsif ($o->flags & OPf_KIDS) {
1417                 unshift (@queue, $o);
1418             }
1419         }
1420     }
1421
1422     return ($scope_st, $scope_en);
1423 }
1424
1425 # Returns a list of subs which should be inserted before the COP
1426 sub cop_subs {
1427     my ($self, $op, $out_seq) = @_;
1428     my $seq = $op->cop_seq;
1429     # If we have nephews, then our sequence number indicates
1430     # the cop_seq of the end of some sort of scope.
1431     if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1432         and my $nseq = $self->find_scope_st($op->sibling) ) {
1433         $seq = $nseq;
1434     }
1435     $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1436     return $self->seq_subs($seq);
1437 }
1438
1439 sub seq_subs {
1440     my ($self, $seq) = @_;
1441     my @text;
1442 #push @text, "# ($seq)\n";
1443
1444     return "" if !defined $seq;
1445     while (scalar(@{$self->{'subs_todo'}})
1446            and $seq > $self->{'subs_todo'}[0][0]) {
1447         push @text, $self->next_todo;
1448     }
1449     return @text;
1450 }
1451
1452 sub _features_from_bundle {
1453     my ($hints, $hh) = @_;
1454     foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
1455         $hh->{$feature::feature{$_}} = 1;
1456     }
1457     return $hh;
1458 }
1459
1460 # Notice how subs and formats are inserted between statements here;
1461 # also $[ assignments and pragmas.
1462 sub pp_nextstate {
1463     my $self = shift;
1464     my($op, $cx) = @_;
1465     $self->{'curcop'} = $op;
1466     my @text;
1467     push @text, $self->cop_subs($op);
1468     my $stash = $op->stashpv;
1469     if ($stash ne $self->{'curstash'}) {
1470         push @text, "package $stash;\n";
1471         $self->{'curstash'} = $stash;
1472     }
1473
1474     if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1475         push @text, '$[ = '. $op->arybase .";\n";
1476         $self->{'arybase'} = $op->arybase;
1477     }
1478
1479     my $warnings = $op->warnings;
1480     my $warning_bits;
1481     if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1482         $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1483     }
1484     elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1485         $warning_bits = $warnings::NONE;
1486     }
1487     elsif ($warnings->isa("B::SPECIAL")) {
1488         $warning_bits = undef;
1489     }
1490     else {
1491         $warning_bits = $warnings->PV & WARN_MASK;
1492     }
1493
1494     if (defined ($warning_bits) and
1495        !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1496         push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1497         $self->{'warnings'} = $warning_bits;
1498     }
1499
1500     my $hints = $] < 5.008009 ? $op->private : $op->hints;
1501     my $old_hints = $self->{'hints'};
1502     if ($self->{'hints'} != $hints) {
1503         push @text, declare_hints($self->{'hints'}, $hints);
1504         $self->{'hints'} = $hints;
1505     }
1506
1507     my $newhh;
1508     if ($] > 5.009) {
1509         $newhh = $op->hints_hash->HASH;
1510     }
1511
1512     if ($] >= 5.015006) {
1513         # feature bundle hints
1514         my $from = $old_hints & $feature::hint_mask;
1515         my $to   = $    hints & $feature::hint_mask;
1516         if ($from != $to) {
1517             if ($to == $feature::hint_mask) {
1518                 if ($self->{'hinthash'}) {
1519                     delete $self->{'hinthash'}{$_}
1520                         for grep /^feature_/, keys %{$self->{'hinthash'}};
1521                 }
1522                 else { $self->{'hinthash'} = {} }
1523                 $self->{'hinthash'}
1524                     = _features_from_bundle($from, $self->{'hinthash'});
1525             }
1526             else {
1527                 my $bundle =
1528                     $feature::hint_bundles[$to >> $feature::hint_shift];
1529                 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1530                 push @text, "no feature;\n",
1531                             "use feature ':$bundle';\n";
1532             }
1533         }
1534     }
1535
1536     if ($] > 5.009) {
1537         push @text, declare_hinthash(
1538             $self->{'hinthash'}, $newhh,
1539             $self->{indent_size}, $self->{hints},
1540         );
1541         $self->{'hinthash'} = $newhh;
1542     }
1543
1544     # This should go after of any branches that add statements, to
1545     # increase the chances that it refers to the same line it did in
1546     # the original program.
1547     if ($self->{'linenums'}) {
1548         push @text, "\f#line " . $op->line .
1549           ' "' . $op->file, qq'"\n';
1550     }
1551
1552     push @text, $op->label . ": " if $op->label;
1553
1554     return join("", @text);
1555 }
1556
1557 sub declare_warnings {
1558     my ($from, $to) = @_;
1559     if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1560         return "use warnings;\n";
1561     }
1562     elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1563         return "no warnings;\n";
1564     }
1565     return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1566 }
1567
1568 sub declare_hints {
1569     my ($from, $to) = @_;
1570     my $use = $to   & ~$from;
1571     my $no  = $from & ~$to;
1572     my $decls = "";
1573     for my $pragma (hint_pragmas($use)) {
1574         $decls .= "use $pragma;\n";
1575     }
1576     for my $pragma (hint_pragmas($no)) {
1577         $decls .= "no $pragma;\n";
1578     }
1579     return $decls;
1580 }
1581
1582 # Internal implementation hints that the core sets automatically, so don't need
1583 # (or want) to be passed back to the user
1584 my %ignored_hints = (
1585     'open<' => 1,
1586     'open>' => 1,
1587     ':'     => 1,
1588     'strict/refs' => 1,
1589     'strict/subs' => 1,
1590     'strict/vars' => 1,
1591 );
1592
1593 my %rev_feature;
1594
1595 sub declare_hinthash {
1596     my ($from, $to, $indent, $hints) = @_;
1597     my $doing_features =
1598         ($hints & $feature::hint_mask) == $feature::hint_mask;
1599     my @decls;
1600     my @features;
1601     my @unfeatures; # bugs?
1602     for my $key (sort keys %$to) {
1603         next if $ignored_hints{$key};
1604         my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1605         next if $is_feature and not $doing_features;
1606         if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1607             push(@features, $key), next if $is_feature;
1608             push @decls,
1609                 qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1610               . (
1611                    defined $to->{$key}
1612                         ? single_delim("q", "'", $to->{$key})
1613                         : 'undef'
1614                 )
1615               . qq(;);
1616         }
1617     }
1618     for my $key (sort keys %$from) {
1619         next if $ignored_hints{$key};
1620         my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1621         next if $is_feature and not $doing_features;
1622         if (!exists $to->{$key}) {
1623             push(@unfeatures, $key), next if $is_feature;
1624             push @decls, qq(delete \$^H{'$key'};);
1625         }
1626     }
1627     my @ret;
1628     if (@features || @unfeatures) {
1629         if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1630     }
1631     if (@features) {
1632         push @ret, "use feature "
1633                  . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1634     }
1635     if (@unfeatures) {
1636         push @ret, "no feature "
1637                  . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1638                  . ";\n";
1639     }
1640     @decls and
1641         push @ret,
1642              join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1643     return @ret;
1644 }
1645
1646 sub hint_pragmas {
1647     my ($bits) = @_;
1648     my (@pragmas, @strict);
1649     push @pragmas, "integer" if $bits & 0x1;
1650     for (sort keys %strict_bits) {
1651         push @strict, "'$_'" if $bits & $strict_bits{$_};
1652     }
1653     if (@strict == keys %strict_bits) {
1654         push @pragmas, "strict";
1655     }
1656     elsif (@strict) {
1657         push @pragmas, "strict " . join ', ', @strict;
1658     }
1659     push @pragmas, "bytes" if $bits & 0x8;
1660     return @pragmas;
1661 }
1662
1663 sub pp_dbstate { pp_nextstate(@_) }
1664 sub pp_setstate { pp_nextstate(@_) }
1665
1666 sub pp_unstack { return "" } # see also leaveloop
1667
1668 my %feature_keywords = (
1669   # keyword => 'feature',
1670     state   => 'state',
1671     say     => 'say',
1672     given   => 'switch',
1673     when    => 'switch',
1674     default => 'switch',
1675     break   => 'switch',
1676     evalbytes=>'evalbytes',
1677     __SUB__ => '__SUB__',
1678    fc       => 'fc',
1679 );
1680
1681 sub keyword {
1682     my $self = shift;
1683     my $name = shift;
1684     return $name if $name =~ /^CORE::/; # just in case
1685     if (exists $feature_keywords{$name}) {
1686         my $hh;
1687         my $hints = $self->{hints} & $feature::hint_mask;
1688         if ($hints && $hints != $feature::hint_mask) {
1689             $hh = _features_from_bundle($hints);
1690         }
1691         elsif ($hints) { $hh = $self->{'hinthash'} }
1692         return "CORE::$name"
1693          if !$hh
1694          || !$hh->{"feature_$feature_keywords{$name}"}
1695     }
1696     if (
1697       $name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1698        && !defined eval{prototype "CORE::$name"}
1699     ) { return $name }
1700     if (
1701         exists $self->{subs_declared}{$name}
1702          or
1703         exists &{"$self->{curstash}::$name"}
1704     ) {
1705         return "CORE::$name"
1706     }
1707     return $name;
1708 }
1709
1710 sub baseop {
1711     my $self = shift;
1712     my($op, $cx, $name) = @_;
1713     return $self->keyword($name);
1714 }
1715
1716 sub pp_stub {
1717     my $self = shift;
1718     my($op, $cx, $name) = @_;
1719     if ($cx >= 1) {
1720         return "()";
1721     }
1722     else {
1723         return "();";
1724     }
1725 }
1726 sub pp_wantarray { baseop(@_, "wantarray") }
1727 sub pp_fork { baseop(@_, "fork") }
1728 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1729 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1730 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1731 sub pp_tms { baseop(@_, "times") }
1732 sub pp_ghostent { baseop(@_, "gethostent") }
1733 sub pp_gnetent { baseop(@_, "getnetent") }
1734 sub pp_gprotoent { baseop(@_, "getprotoent") }
1735 sub pp_gservent { baseop(@_, "getservent") }
1736 sub pp_ehostent { baseop(@_, "endhostent") }
1737 sub pp_enetent { baseop(@_, "endnetent") }
1738 sub pp_eprotoent { baseop(@_, "endprotoent") }
1739 sub pp_eservent { baseop(@_, "endservent") }
1740 sub pp_gpwent { baseop(@_, "getpwent") }
1741 sub pp_spwent { baseop(@_, "setpwent") }
1742 sub pp_epwent { baseop(@_, "endpwent") }
1743 sub pp_ggrent { baseop(@_, "getgrent") }
1744 sub pp_sgrent { baseop(@_, "setgrent") }
1745 sub pp_egrent { baseop(@_, "endgrent") }
1746 sub pp_getlogin { baseop(@_, "getlogin") }
1747
1748 sub POSTFIX () { 1 }
1749
1750 # I couldn't think of a good short name, but this is the category of
1751 # symbolic unary operators with interesting precedence
1752
1753 sub pfixop {
1754     my $self = shift;
1755     my($op, $cx, $name, $prec, $flags) = (@_, 0);
1756     my $kid = $op->first;
1757     $kid = $self->deparse($kid, $prec);
1758     return $self->maybe_parens(($flags & POSTFIX)
1759                                  ? "$kid$name"
1760                                    # avoid confusion with filetests
1761                                  : $name eq '-'
1762                                    && $kid =~ /^[a-zA-Z](?!\w)/
1763                                         ? "$name($kid)"
1764                                         : "$name$kid",
1765                                $cx, $prec);
1766 }
1767
1768 sub pp_preinc { pfixop(@_, "++", 23) }
1769 sub pp_predec { pfixop(@_, "--", 23) }
1770 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1771 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1772 sub pp_i_preinc { pfixop(@_, "++", 23) }
1773 sub pp_i_predec { pfixop(@_, "--", 23) }
1774 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1775 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1776 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1777
1778 sub pp_negate { maybe_targmy(@_, \&real_negate) }
1779 sub real_negate {
1780     my $self = shift;
1781     my($op, $cx) = @_;
1782     if ($op->first->name =~ /^(i_)?negate$/) {
1783         # avoid --$x
1784         $self->pfixop($op, $cx, "-", 21.5);
1785     } else {
1786         $self->pfixop($op, $cx, "-", 21);       
1787     }
1788 }
1789 sub pp_i_negate { pp_negate(@_) }
1790
1791 sub pp_not {
1792     my $self = shift;
1793     my($op, $cx) = @_;
1794     if ($cx <= 4) {
1795         $self->listop($op, $cx, "not", $op->first);
1796     } else {
1797         $self->pfixop($op, $cx, "!", 21);       
1798     }
1799 }
1800
1801 sub unop {
1802     my $self = shift;
1803     my($op, $cx, $name, $nollafr) = @_;
1804     my $kid;
1805     if ($op->flags & OPf_KIDS) {
1806         $kid = $op->first;
1807         if (not $name) {
1808             # this deals with 'boolkeys' right now
1809             return $self->deparse($kid,$cx);
1810         }
1811         my $builtinname = $name;
1812         $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1813         if (defined prototype($builtinname)
1814            && prototype($builtinname) =~ /^;?\*/
1815            && $kid->name eq "rv2gv") {
1816             $kid = $kid->first;
1817         }
1818
1819         if ($nollafr) {
1820             ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1821             return $self->maybe_parens(
1822                         $self->keyword($name) . " $kid", $cx, 16
1823                    );
1824         }   
1825         return $self->maybe_parens_unop($name, $kid, $cx);
1826     } else {
1827         return $self->maybe_parens(
1828             $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1829             $cx, 16,
1830         );
1831     }
1832 }
1833
1834 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1835 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1836 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1837 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1838 sub pp_defined { unop(@_, "defined") }
1839 sub pp_undef { unop(@_, "undef") }
1840 sub pp_study { unop(@_, "study") }
1841 sub pp_ref { unop(@_, "ref") }
1842 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1843
1844 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1845 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1846 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1847 sub pp_srand { unop(@_, "srand") }
1848 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1849 sub pp_log { maybe_targmy(@_, \&unop, "log") }
1850 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1851 sub pp_int { maybe_targmy(@_, \&unop, "int") }
1852 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1853 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1854 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1855
1856 sub pp_length { maybe_targmy(@_, \&unop, "length") }
1857 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1858 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1859
1860 sub pp_each { unop(@_, "each") }
1861 sub pp_values { unop(@_, "values") }
1862 sub pp_keys { unop(@_, "keys") }
1863 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1864 sub pp_boolkeys { 
1865     # no name because its an optimisation op that has no keyword
1866     unop(@_,"");
1867 }
1868 sub pp_aeach { unop(@_, "each") }
1869 sub pp_avalues { unop(@_, "values") }
1870 sub pp_akeys { unop(@_, "keys") }
1871 sub pp_pop { unop(@_, "pop") }
1872 sub pp_shift { unop(@_, "shift") }
1873
1874 sub pp_caller { unop(@_, "caller") }
1875 sub pp_reset { unop(@_, "reset") }
1876 sub pp_exit { unop(@_, "exit") }
1877 sub pp_prototype { unop(@_, "prototype") }
1878
1879 sub pp_close { unop(@_, "close") }
1880 sub pp_fileno { unop(@_, "fileno") }
1881 sub pp_umask { unop(@_, "umask") }
1882 sub pp_untie { unop(@_, "untie") }
1883 sub pp_tied { unop(@_, "tied") }
1884 sub pp_dbmclose { unop(@_, "dbmclose") }
1885 sub pp_getc { unop(@_, "getc") }
1886 sub pp_eof { unop(@_, "eof") }
1887 sub pp_tell { unop(@_, "tell") }
1888 sub pp_getsockname { unop(@_, "getsockname") }
1889 sub pp_getpeername { unop(@_, "getpeername") }
1890
1891 sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1892 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1893 sub pp_readlink { unop(@_, "readlink") }
1894 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1895 sub pp_readdir { unop(@_, "readdir") }
1896 sub pp_telldir { unop(@_, "telldir") }
1897 sub pp_rewinddir { unop(@_, "rewinddir") }
1898 sub pp_closedir { unop(@_, "closedir") }
1899 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1900 sub pp_localtime { unop(@_, "localtime") }
1901 sub pp_gmtime { unop(@_, "gmtime") }
1902 sub pp_alarm { unop(@_, "alarm") }
1903 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1904
1905 sub pp_dofile {
1906     my $code = unop(@_, "do", 1); # llafr does not apply
1907     if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
1908     $code;
1909 }
1910 sub pp_entereval {
1911     unop(
1912       @_,
1913       $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
1914     )
1915 }
1916
1917 sub pp_ghbyname { unop(@_, "gethostbyname") }
1918 sub pp_gnbyname { unop(@_, "getnetbyname") }
1919 sub pp_gpbyname { unop(@_, "getprotobyname") }
1920 sub pp_shostent { unop(@_, "sethostent") }
1921 sub pp_snetent { unop(@_, "setnetent") }
1922 sub pp_sprotoent { unop(@_, "setprotoent") }
1923 sub pp_sservent { unop(@_, "setservent") }
1924 sub pp_gpwnam { unop(@_, "getpwnam") }
1925 sub pp_gpwuid { unop(@_, "getpwuid") }
1926 sub pp_ggrnam { unop(@_, "getgrnam") }
1927 sub pp_ggrgid { unop(@_, "getgrgid") }
1928
1929 sub pp_lock { unop(@_, "lock") }
1930
1931 sub pp_continue { unop(@_, "continue"); }
1932 sub pp_break { unop(@_, "break"); }
1933
1934 sub givwhen {
1935     my $self = shift;
1936     my($op, $cx, $givwhen) = @_;
1937
1938     my $enterop = $op->first;
1939     my ($head, $block);
1940     if ($enterop->flags & OPf_SPECIAL) {
1941         $head = $self->keyword("default");
1942         $block = $self->deparse($enterop->first, 0);
1943     }
1944     else {
1945         my $cond = $enterop->first;
1946         my $cond_str = $self->deparse($cond, 1);
1947         $head = "$givwhen ($cond_str)";
1948         $block = $self->deparse($cond->sibling, 0);
1949     }
1950
1951     return "$head {\n".
1952         "\t$block\n".
1953         "\b}\cK";
1954 }
1955
1956 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1957 sub pp_leavewhen  { givwhen(@_, $_[0]->keyword("when")); }
1958
1959 sub pp_exists {
1960     my $self = shift;
1961     my($op, $cx) = @_;
1962     my $arg;
1963     if ($op->private & OPpEXISTS_SUB) {
1964         # Checking for the existence of a subroutine
1965         return $self->maybe_parens_func("exists",
1966                                 $self->pp_rv2cv($op->first, 16), $cx, 16);
1967     }
1968     if ($op->flags & OPf_SPECIAL) {
1969         # Array element, not hash element
1970         return $self->maybe_parens_func("exists",
1971                                 $self->pp_aelem($op->first, 16), $cx, 16);
1972     }
1973     return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1974                                     $cx, 16);
1975 }
1976
1977 sub pp_delete {
1978     my $self = shift;
1979     my($op, $cx) = @_;
1980     my $arg;
1981     if ($op->private & OPpSLICE) {
1982         if ($op->flags & OPf_SPECIAL) {
1983             # Deleting from an array, not a hash
1984             return $self->maybe_parens_func("delete",
1985                                         $self->pp_aslice($op->first, 16),
1986                                         $cx, 16);
1987         }
1988         return $self->maybe_parens_func("delete",
1989                                         $self->pp_hslice($op->first, 16),
1990                                         $cx, 16);
1991     } else {
1992         if ($op->flags & OPf_SPECIAL) {
1993             # Deleting from an array, not a hash
1994             return $self->maybe_parens_func("delete",
1995                                         $self->pp_aelem($op->first, 16),
1996                                         $cx, 16);
1997         }
1998         return $self->maybe_parens_func("delete",
1999                                         $self->pp_helem($op->first, 16),
2000                                         $cx, 16);
2001     }
2002 }
2003
2004 sub pp_require {
2005     my $self = shift;
2006     my($op, $cx) = @_;
2007     my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2008     if (class($op) eq "UNOP" and $op->first->name eq "const"
2009         and $op->first->private & OPpCONST_BARE)
2010     {
2011         my $name = $self->const_sv($op->first)->PV;
2012         $name =~ s[/][::]g;
2013         $name =~ s/\.pm//g;
2014         return $self->maybe_parens("$opname $name", $cx, 16);
2015     } else {    
2016         $self->unop(
2017             $op, $cx,
2018             $op->first->name eq 'const'
2019              && $op->first->private & OPpCONST_NOVER
2020                  ? "no"
2021                  : $opname,
2022             1, # llafr does not apply
2023         );
2024     }
2025 }
2026
2027 sub pp_scalar {
2028     my $self = shift;
2029     my($op, $cx) = @_;
2030     my $kid = $op->first;
2031     if (not null $kid->sibling) {
2032         # XXX Was a here-doc
2033         return $self->dquote($op);
2034     }
2035     $self->unop(@_, "scalar");
2036 }
2037
2038
2039 sub padval {
2040     my $self = shift;
2041     my $targ = shift;
2042     return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2043 }
2044
2045 sub anon_hash_or_list {
2046     my $self = shift;
2047     my($op, $cx) = @_;
2048
2049     my($pre, $post) = @{{"anonlist" => ["[","]"],
2050                          "anonhash" => ["{","}"]}->{$op->name}};
2051     my($expr, @exprs);
2052     $op = $op->first->sibling; # skip pushmark
2053     for (; !null($op); $op = $op->sibling) {
2054         $expr = $self->deparse($op, 6);
2055         push @exprs, $expr;
2056     }
2057     if ($pre eq "{" and $cx < 1) {
2058         # Disambiguate that it's not a block
2059         $pre = "+{";
2060     }
2061     return $pre . join(", ", @exprs) . $post;
2062 }
2063
2064 sub pp_anonlist {
2065     my $self = shift;
2066     my ($op, $cx) = @_;
2067     if ($op->flags & OPf_SPECIAL) {
2068         return $self->anon_hash_or_list($op, $cx);
2069     }
2070     warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2071     return 'XXX';
2072 }
2073
2074 *pp_anonhash = \&pp_anonlist;
2075
2076 sub pp_refgen {
2077     my $self = shift;   
2078     my($op, $cx) = @_;
2079     my $kid = $op->first;
2080     if ($kid->name eq "null") {
2081         $kid = $kid->first;
2082         if (!null($kid->sibling) and
2083                  $kid->sibling->name eq "anoncode") {
2084             return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
2085         } elsif ($kid->name eq "pushmark") {
2086             my $sib_name = $kid->sibling->name;
2087             if ($sib_name =~ /^(pad|rv2)[ah]v$/
2088                 and not $kid->sibling->flags & OPf_REF)
2089             {
2090                 # The @a in \(@a) isn't in ref context, but only when the
2091                 # parens are there.
2092                 return "\\(" . $self->pp_list($op->first) . ")";
2093             } elsif ($sib_name eq 'entersub') {
2094                 my $text = $self->deparse($kid->sibling, 1);
2095                 # Always show parens for \(&func()), but only with -p otherwise
2096                 $text = "($text)" if $self->{'parens'}
2097                                  or $kid->sibling->private & OPpENTERSUB_AMPER;
2098                 return "\\$text";
2099             }
2100         }
2101     }
2102     $self->pfixop($op, $cx, "\\", 20);
2103 }
2104
2105 sub e_anoncode {
2106     my ($self, $info) = @_;
2107     my $text = $self->deparse_sub($info->{code});
2108     return "sub " . $text;
2109 }
2110
2111 sub pp_srefgen { pp_refgen(@_) }
2112
2113 sub pp_readline {
2114     my $self = shift;
2115     my($op, $cx) = @_;
2116     my $kid = $op->first;
2117     $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
2118     return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2119     return $self->unop($op, $cx, "readline");
2120 }
2121
2122 sub pp_rcatline {
2123     my $self = shift;
2124     my($op) = @_;
2125     return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2126 }
2127
2128 # Unary operators that can occur as pseudo-listops inside double quotes
2129 sub dq_unop {
2130     my $self = shift;
2131     my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2132     my $kid;
2133     if ($op->flags & OPf_KIDS) {
2134        $kid = $op->first;
2135        # If there's more than one kid, the first is an ex-pushmark.
2136        $kid = $kid->sibling if not null $kid->sibling;
2137        return $self->maybe_parens_unop($name, $kid, $cx);
2138     } else {
2139        return $name .  ($op->flags & OPf_SPECIAL ? "()" : "");
2140     }
2141 }
2142
2143 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2144 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2145 sub pp_uc { dq_unop(@_, "uc") }
2146 sub pp_lc { dq_unop(@_, "lc") }
2147 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2148 sub pp_fc { dq_unop(@_, "fc") }
2149
2150 sub loopex {
2151     my $self = shift;
2152     my ($op, $cx, $name) = @_;
2153     if (class($op) eq "PVOP") {
2154         $name .= " " . $op->pv;
2155     } elsif (class($op) eq "OP") {
2156         # no-op
2157     } elsif (class($op) eq "UNOP") {
2158         (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2159         $name .= " $kid";
2160     }
2161     return $self->maybe_parens($name, $cx, 16);
2162 }
2163
2164 sub pp_last { loopex(@_, "last") }
2165 sub pp_next { loopex(@_, "next") }
2166 sub pp_redo { loopex(@_, "redo") }
2167 sub pp_goto { loopex(@_, "goto") }
2168 sub pp_dump { loopex(@_, "CORE::dump") }
2169
2170 sub ftst {
2171     my $self = shift;
2172     my($op, $cx, $name) = @_;
2173     if (class($op) eq "UNOP") {
2174         # Genuine '-X' filetests are exempt from the LLAFR, but not
2175         # l?stat()
2176         if ($name =~ /^-/) {
2177             (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2178             return $self->maybe_parens("$name $kid", $cx, 16);
2179         }
2180         return $self->maybe_parens_unop($name, $op->first, $cx);
2181     } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2182         return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2183     } else { # I don't think baseop filetests ever survive ck_ftst, but...
2184         return $name;
2185     }
2186 }
2187
2188 sub pp_lstat    { ftst(@_, "lstat") }
2189 sub pp_stat     { ftst(@_, "stat") }
2190 sub pp_ftrread  { ftst(@_, "-R") }
2191 sub pp_ftrwrite { ftst(@_, "-W") }
2192 sub pp_ftrexec  { ftst(@_, "-X") }
2193 sub pp_fteread  { ftst(@_, "-r") }
2194 sub pp_ftewrite { ftst(@_, "-w") }
2195 sub pp_fteexec  { ftst(@_, "-x") }
2196 sub pp_ftis     { ftst(@_, "-e") }
2197 sub pp_fteowned { ftst(@_, "-O") }
2198 sub pp_ftrowned { ftst(@_, "-o") }
2199 sub pp_ftzero   { ftst(@_, "-z") }
2200 sub pp_ftsize   { ftst(@_, "-s") }
2201 sub pp_ftmtime  { ftst(@_, "-M") }
2202 sub pp_ftatime  { ftst(@_, "-A") }
2203 sub pp_ftctime  { ftst(@_, "-C") }
2204 sub pp_ftsock   { ftst(@_, "-S") }
2205 sub pp_ftchr    { ftst(@_, "-c") }
2206 sub pp_ftblk    { ftst(@_, "-b") }
2207 sub pp_ftfile   { ftst(@_, "-f") }
2208 sub pp_ftdir    { ftst(@_, "-d") }
2209 sub pp_ftpipe   { ftst(@_, "-p") }
2210 sub pp_ftlink   { ftst(@_, "-l") }
2211 sub pp_ftsuid   { ftst(@_, "-u") }
2212 sub pp_ftsgid   { ftst(@_, "-g") }
2213 sub pp_ftsvtx   { ftst(@_, "-k") }
2214 sub pp_fttty    { ftst(@_, "-t") }
2215 sub pp_fttext   { ftst(@_, "-T") }
2216 sub pp_ftbinary { ftst(@_, "-B") }
2217
2218 sub SWAP_CHILDREN () { 1 }
2219 sub ASSIGN () { 2 } # has OP= variant
2220 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2221
2222 my(%left, %right);
2223
2224 sub assoc_class {
2225     my $op = shift;
2226     my $name = $op->name;
2227     if ($name eq "concat" and $op->first->name eq "concat") {
2228         # avoid spurious '=' -- see comment in pp_concat
2229         return "concat";
2230     }
2231     if ($name eq "null" and class($op) eq "UNOP"
2232         and $op->first->name =~ /^(and|x?or)$/
2233         and null $op->first->sibling)
2234     {
2235         # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2236         # with a null that's used as the common end point of the two
2237         # flows of control. For precedence purposes, ignore it.
2238         # (COND_EXPRs have these too, but we don't bother with
2239         # their associativity).
2240         return assoc_class($op->first);
2241     }
2242     return $name . ($op->flags & OPf_STACKED ? "=" : "");
2243 }
2244
2245 # Left associative operators, like '+', for which
2246 # $a + $b + $c is equivalent to ($a + $b) + $c
2247
2248 BEGIN {
2249     %left = ('multiply' => 19, 'i_multiply' => 19,
2250              'divide' => 19, 'i_divide' => 19,
2251              'modulo' => 19, 'i_modulo' => 19,
2252              'repeat' => 19,
2253              'add' => 18, 'i_add' => 18,
2254              'subtract' => 18, 'i_subtract' => 18,
2255              'concat' => 18,
2256              'left_shift' => 17, 'right_shift' => 17,
2257              'bit_and' => 13,
2258              'bit_or' => 12, 'bit_xor' => 12,
2259              'and' => 3,
2260              'or' => 2, 'xor' => 2,
2261             );
2262 }
2263
2264 sub deparse_binop_left {
2265     my $self = shift;
2266     my($op, $left, $prec) = @_;
2267     if ($left{assoc_class($op)} && $left{assoc_class($left)}
2268         and $left{assoc_class($op)} == $left{assoc_class($left)})
2269     {
2270         return $self->deparse($left, $prec - .00001);
2271     } else {
2272         return $self->deparse($left, $prec);    
2273     }
2274 }
2275
2276 # Right associative operators, like '=', for which
2277 # $a = $b = $c is equivalent to $a = ($b = $c)
2278
2279 BEGIN {
2280     %right = ('pow' => 22,
2281               'sassign=' => 7, 'aassign=' => 7,
2282               'multiply=' => 7, 'i_multiply=' => 7,
2283               'divide=' => 7, 'i_divide=' => 7,
2284               'modulo=' => 7, 'i_modulo=' => 7,
2285               'repeat=' => 7,
2286               'add=' => 7, 'i_add=' => 7,
2287               'subtract=' => 7, 'i_subtract=' => 7,
2288               'concat=' => 7,
2289               'left_shift=' => 7, 'right_shift=' => 7,
2290               'bit_and=' => 7,
2291               'bit_or=' => 7, 'bit_xor=' => 7,
2292               'andassign' => 7,
2293               'orassign' => 7,
2294              );
2295 }
2296
2297 sub deparse_binop_right {
2298     my $self = shift;
2299     my($op, $right, $prec) = @_;
2300     if ($right{assoc_class($op)} && $right{assoc_class($right)}
2301         and $right{assoc_class($op)} == $right{assoc_class($right)})
2302     {
2303         return $self->deparse($right, $prec - .00001);
2304     } else {
2305         return $self->deparse($right, $prec);   
2306     }
2307 }
2308
2309 sub binop {
2310     my $self = shift;
2311     my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2312     my $left = $op->first;
2313     my $right = $op->last;
2314     my $eq = "";
2315     if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2316         $eq = "=";
2317         $prec = 7;
2318     }
2319     if ($flags & SWAP_CHILDREN) {
2320         ($left, $right) = ($right, $left);
2321     }
2322     $left = $self->deparse_binop_left($op, $left, $prec);
2323     $left = "($left)" if $flags & LIST_CONTEXT
2324                 && $left !~ /^(my|our|local|)[\@\(]/;
2325     $right = $self->deparse_binop_right($op, $right, $prec);
2326     return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2327 }
2328
2329 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2330 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2331 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18,  ASSIGN) }
2332 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2333 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2334 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2335 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2336 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2337 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2338 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2339 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2340
2341 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2342 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2343 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2344 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2345 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2346
2347 sub pp_eq { binop(@_, "==", 14) }
2348 sub pp_ne { binop(@_, "!=", 14) }
2349 sub pp_lt { binop(@_, "<", 15) }
2350 sub pp_gt { binop(@_, ">", 15) }
2351 sub pp_ge { binop(@_, ">=", 15) }
2352 sub pp_le { binop(@_, "<=", 15) }
2353 sub pp_ncmp { binop(@_, "<=>", 14) }
2354 sub pp_i_eq { binop(@_, "==", 14) }
2355 sub pp_i_ne { binop(@_, "!=", 14) }
2356 sub pp_i_lt { binop(@_, "<", 15) }
2357 sub pp_i_gt { binop(@_, ">", 15) }
2358 sub pp_i_ge { binop(@_, ">=", 15) }
2359 sub pp_i_le { binop(@_, "<=", 15) }
2360 sub pp_i_ncmp { binop(@_, "<=>", 14) }
2361
2362 sub pp_seq { binop(@_, "eq", 14) }
2363 sub pp_sne { binop(@_, "ne", 14) }
2364 sub pp_slt { binop(@_, "lt", 15) }
2365 sub pp_sgt { binop(@_, "gt", 15) }
2366 sub pp_sge { binop(@_, "ge", 15) }
2367 sub pp_sle { binop(@_, "le", 15) }
2368 sub pp_scmp { binop(@_, "cmp", 14) }
2369
2370 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2371 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2372
2373 sub pp_smartmatch {
2374     my ($self, $op, $cx) = @_;
2375     if ($op->flags & OPf_SPECIAL) {
2376         return $self->deparse($op->last, $cx);
2377     }
2378     else {
2379         binop(@_, "~~", 14);
2380     }
2381 }
2382
2383 # '.' is special because concats-of-concats are optimized to save copying
2384 # by making all but the first concat stacked. The effect is as if the
2385 # programmer had written '($a . $b) .= $c', except legal.
2386 sub pp_concat { maybe_targmy(@_, \&real_concat) }
2387 sub real_concat {
2388     my $self = shift;
2389     my($op, $cx) = @_;
2390     my $left = $op->first;
2391     my $right = $op->last;
2392     my $eq = "";
2393     my $prec = 18;
2394     if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2395         $eq = "=";
2396         $prec = 7;
2397     }
2398     $left = $self->deparse_binop_left($op, $left, $prec);
2399     $right = $self->deparse_binop_right($op, $right, $prec);
2400     return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2401 }
2402
2403 # 'x' is weird when the left arg is a list
2404 sub pp_repeat {
2405     my $self = shift;
2406     my($op, $cx) = @_;
2407     my $left = $op->first;
2408     my $right = $op->last;
2409     my $eq = "";
2410     my $prec = 19;
2411     if ($op->flags & OPf_STACKED) {
2412         $eq = "=";
2413         $prec = 7;
2414     }
2415     if (null($right)) { # list repeat; count is inside left-side ex-list
2416         my $kid = $left->first->sibling; # skip pushmark
2417         my @exprs;
2418         for (; !null($kid->sibling); $kid = $kid->sibling) {
2419             push @exprs, $self->deparse($kid, 6);
2420         }
2421         $right = $kid;
2422         $left = "(" . join(", ", @exprs). ")";
2423     } else {
2424         $left = $self->deparse_binop_left($op, $left, $prec);
2425     }
2426     $right = $self->deparse_binop_right($op, $right, $prec);
2427     return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2428 }
2429
2430 sub range {
2431     my $self = shift;
2432     my ($op, $cx, $type) = @_;
2433     my $left = $op->first;
2434     my $right = $left->sibling;
2435     $left = $self->deparse($left, 9);
2436     $right = $self->deparse($right, 9);
2437     return $self->maybe_parens("$left $type $right", $cx, 9);
2438 }
2439
2440 sub pp_flop {
2441     my $self = shift;
2442     my($op, $cx) = @_;
2443     my $flip = $op->first;
2444     my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2445     return $self->range($flip->first, $cx, $type);
2446 }
2447
2448 # one-line while/until is handled in pp_leave
2449
2450 sub logop {
2451     my $self = shift;
2452     my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2453     my $left = $op->first;
2454     my $right = $op->first->sibling;
2455     if ($cx < 1 and is_scope($right) and $blockname
2456         and $self->{'expand'} < 7)
2457     { # if ($a) {$b}
2458         $left = $self->deparse($left, 1);
2459         $right = $self->deparse($right, 0);
2460         return "$blockname ($left) {\n\t$right\n\b}\cK";
2461     } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2462              and $self->{'expand'} < 7) { # $b if $a
2463         $right = $self->deparse($right, 1);
2464         $left = $self->deparse($left, 1);
2465         return "$right $blockname $left";
2466     } elsif ($cx > $lowprec and $highop) { # $a && $b
2467         $left = $self->deparse_binop_left($op, $left, $highprec);
2468         $right = $self->deparse_binop_right($op, $right, $highprec);
2469         return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2470     } else { # $a and $b
2471         $left = $self->deparse_binop_left($op, $left, $lowprec);
2472         $right = $self->deparse_binop_right($op, $right, $lowprec);
2473         return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2474     }
2475 }
2476
2477 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2478 sub pp_or  { logop(@_, "or",  2, "||", 10, "unless") }
2479 sub pp_dor { logop(@_, "//", 10) }
2480
2481 # xor is syntactically a logop, but it's really a binop (contrary to
2482 # old versions of opcode.pl). Syntax is what matters here.
2483 sub pp_xor { logop(@_, "xor", 2, "",   0,  "") }
2484
2485 sub logassignop {
2486     my $self = shift;
2487     my ($op, $cx, $opname) = @_;
2488     my $left = $op->first;
2489     my $right = $op->first->sibling->first; # skip sassign
2490     $left = $self->deparse($left, 7);
2491     $right = $self->deparse($right, 7);
2492     return $self->maybe_parens("$left $opname $right", $cx, 7);
2493 }
2494
2495 sub pp_andassign { logassignop(@_, "&&=") }
2496 sub pp_orassign  { logassignop(@_, "||=") }
2497 sub pp_dorassign { logassignop(@_, "//=") }
2498
2499 sub rv2gv_or_string {
2500     my($self,$op) = @_;
2501     if ($op->name eq "gv") { # could be open("open") or open("###")
2502         my($name,$quoted) =
2503             $self->stash_variable_name(undef,$self->gv_or_padgv($op));
2504         $quoted ? $name : "*$name";
2505     }
2506     else {
2507         $self->deparse($op, 6);
2508     }
2509 }
2510
2511 sub listop {
2512     my $self = shift;
2513     my($op, $cx, $name, $kid, $nollafr) = @_;
2514     my(@exprs);
2515     my $parens = ($cx >= 5) || $self->{'parens'};
2516     $kid ||= $op->first->sibling;
2517     # If there are no arguments, add final parentheses (or parenthesize the
2518     # whole thing if the llafr does not apply) to account for cases like
2519     # (return)+1 or setpgrp()+1.  When the llafr does not apply, we use a
2520     # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2521     if (null $kid) {
2522         return $nollafr
2523                 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2524                 : $self->keyword($name) . '()' x (7 < $cx);
2525     }
2526     my $first;
2527     $name = "socketpair" if $name eq "sockpair";
2528     my $fullname = $self->keyword($name);
2529     my $proto = prototype("CORE::$name");
2530     if (defined $proto
2531         && $proto =~ /^;?\*/
2532         && $kid->name eq "rv2gv" && !($kid->private & OPpLVAL_INTRO)) {
2533         $first = $self->rv2gv_or_string($kid->first);
2534     }
2535     else {
2536         $first = $self->deparse($kid, 6);
2537     }
2538     if ($name eq "chmod" && $first =~ /^\d+$/) {
2539         $first = sprintf("%#o", $first);
2540     }
2541     $first = "+$first"
2542         if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
2543     push @exprs, $first;
2544     $kid = $kid->sibling;
2545     if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2546          && !($kid->private & OPpLVAL_INTRO)) {
2547         push @exprs, $first = $self->rv2gv_or_string($kid->first);
2548         $kid = $kid->sibling;
2549     }
2550     for (; !null($kid); $kid = $kid->sibling) {
2551         push @exprs, $self->deparse($kid, 6);
2552     }
2553     if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2554         return "$exprs[0] = $fullname"
2555                  . ($parens ? "($exprs[0])" : " $exprs[0]");
2556     }
2557     if ($parens && $nollafr) {
2558         return "($fullname " . join(", ", @exprs) . ")";
2559     } elsif ($parens) {
2560         return "$fullname(" . join(", ", @exprs) . ")";
2561     } else {
2562         return "$fullname " . join(", ", @exprs);
2563     }
2564 }
2565
2566 sub pp_bless { listop(@_, "bless") }
2567 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2568 sub pp_substr {
2569     my ($self,$op,$cx) = @_;
2570     if ($op->private & OPpSUBSTR_REPL_FIRST) {
2571         return
2572            listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2573          . " = "
2574          . $self->deparse($op->first->sibling, 7);
2575     }
2576     maybe_local(@_, listop(@_, "substr"))
2577 }
2578 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2579 sub pp_index { maybe_targmy(@_, \&listop, "index") }
2580 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2581 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2582 sub pp_formline { listop(@_, "formline") } # see also deparse_format
2583 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2584 sub pp_unpack { listop(@_, "unpack") }
2585 sub pp_pack { listop(@_, "pack") }
2586 sub pp_join { maybe_targmy(@_, \&listop, "join") }
2587 sub pp_splice { listop(@_, "splice") }
2588 sub pp_push { maybe_targmy(@_, \&listop, "push") }
2589 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2590 sub pp_reverse { listop(@_, "reverse") }
2591 sub pp_warn { listop(@_, "warn") }
2592 sub pp_die { listop(@_, "die") }
2593 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
2594 sub pp_open { listop(@_, "open") }
2595 sub pp_pipe_op { listop(@_, "pipe") }
2596 sub pp_tie { listop(@_, "tie") }
2597 sub pp_binmode { listop(@_, "binmode") }
2598 sub pp_dbmopen { listop(@_, "dbmopen") }
2599 sub pp_sselect { listop(@_, "select") }
2600 sub pp_select { listop(@_, "select") }
2601 sub pp_read { listop(@_, "read") }
2602 sub pp_sysopen { listop(@_, "sysopen") }
2603 sub pp_sysseek { listop(@_, "sysseek") }
2604 sub pp_sysread { listop(@_, "sysread") }
2605 sub pp_syswrite { listop(@_, "syswrite") }
2606 sub pp_send { listop(@_, "send") }
2607 sub pp_recv { listop(@_, "recv") }
2608 sub pp_seek { listop(@_, "seek") }
2609 sub pp_fcntl { listop(@_, "fcntl") }
2610 sub pp_ioctl { listop(@_, "ioctl") }
2611 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2612 sub pp_socket { listop(@_, "socket") }
2613 sub pp_sockpair { listop(@_, "sockpair") }
2614 sub pp_bind { listop(@_, "bind") }
2615 sub pp_connect { listop(@_, "connect") }
2616 sub pp_listen { listop(@_, "listen") }
2617 sub pp_accept { listop(@_, "accept") }
2618 sub pp_shutdown { listop(@_, "shutdown") }
2619 sub pp_gsockopt { listop(@_, "getsockopt") }
2620 sub pp_ssockopt { listop(@_, "setsockopt") }
2621 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2622 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2623 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2624 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2625 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2626 sub pp_link { maybe_targmy(@_, \&listop, "link") }
2627 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2628 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2629 sub pp_open_dir { listop(@_, "opendir") }
2630 sub pp_seekdir { listop(@_, "seekdir") }
2631 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2632 sub pp_system { maybe_targmy(@_, \&listop, "system") }
2633 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2634 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2635 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2636 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2637 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2638 sub pp_shmget { listop(@_, "shmget") }
2639 sub pp_shmctl { listop(@_, "shmctl") }
2640 sub pp_shmread { listop(@_, "shmread") }
2641 sub pp_shmwrite { listop(@_, "shmwrite") }
2642 sub pp_msgget { listop(@_, "msgget") }
2643 sub pp_msgctl { listop(@_, "msgctl") }
2644 sub pp_msgsnd { listop(@_, "msgsnd") }
2645 sub pp_msgrcv { listop(@_, "msgrcv") }
2646 sub pp_semget { listop(@_, "semget") }
2647 sub pp_semctl { listop(@_, "semctl") }
2648 sub pp_semop { listop(@_, "semop") }
2649 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2650 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2651 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2652 sub pp_gsbyname { listop(@_, "getservbyname") }
2653 sub pp_gsbyport { listop(@_, "getservbyport") }
2654 sub pp_syscall { listop(@_, "syscall") }
2655
2656 sub pp_glob {
2657     my $self = shift;
2658     my($op, $cx) = @_;
2659     my $text = $self->dq($op->first->sibling);  # skip pushmark
2660     my $keyword =
2661         $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
2662     if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2663         or $keyword =~ /^CORE::/
2664         or $text =~ /[<>]/) {
2665         return "$keyword(" . single_delim('qq', '"', $text) . ')';
2666     } else {
2667         return '<' . $text . '>';
2668     }
2669 }
2670
2671 # Truncate is special because OPf_SPECIAL makes a bareword first arg
2672 # be a filehandle. This could probably be better fixed in the core
2673 # by moving the GV lookup into ck_truc.
2674
2675 sub pp_truncate {
2676     my $self = shift;
2677     my($op, $cx) = @_;
2678     my(@exprs);
2679     my $parens = ($cx >= 5) || $self->{'parens'};
2680     my $kid = $op->first->sibling;
2681     my $fh;
2682     if ($op->flags & OPf_SPECIAL) {
2683         # $kid is an OP_CONST
2684         $fh = $self->const_sv($kid)->PV;
2685     } else {
2686         $fh = $self->deparse($kid, 6);
2687         $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2688     }
2689     my $len = $self->deparse($kid->sibling, 6);
2690     my $name = $self->keyword('truncate');
2691     if ($parens) {
2692         return "$name($fh, $len)";
2693     } else {
2694         return "$name $fh, $len";
2695     }
2696 }
2697
2698 sub indirop {
2699     my $self = shift;
2700     my($op, $cx, $name) = @_;
2701     my($expr, @exprs);
2702     my $firstkid = my $kid = $op->first->sibling;
2703     my $indir = "";
2704     if ($op->flags & OPf_STACKED) {
2705         $indir = $kid;
2706         $indir = $indir->first; # skip rv2gv
2707         if (is_scope($indir)) {
2708             $indir = "{" . $self->deparse($indir, 0) . "}";
2709             $indir = "{;}" if $indir eq "{}";
2710         } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2711             $indir = $self->const_sv($indir)->PV;
2712         } else {
2713             $indir = $self->deparse($indir, 24);
2714         }
2715         $indir = $indir . " ";
2716         $kid = $kid->sibling;
2717     }
2718     if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2719         $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2720                                                   : '{$a <=> $b} ';
2721     }
2722     elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2723         $indir = '{$b cmp $a} ';
2724     }
2725     for (; !null($kid); $kid = $kid->sibling) {
2726         $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
2727         push @exprs, $expr;
2728     }
2729     my $name2;
2730     if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2731         $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2732     }
2733     else { $name2 = $self->keyword($name) }
2734     if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2735         return "$exprs[0] = $name2 $indir $exprs[0]";
2736     }
2737
2738     my $args = $indir . join(", ", @exprs);
2739     if ($indir ne "" && $name eq "sort") {
2740         # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2741         # give bareword warnings in that case. Therefore if context
2742         # requires, we'll put parens around the outside "(sort f 1, 2,
2743         # 3)". Unfortunately, we'll currently think the parens are
2744         # necessary more often that they really are, because we don't
2745         # distinguish which side of an assignment we're on.
2746         if ($cx >= 5) {
2747             return "($name2 $args)";
2748         } else {
2749             return "$name2 $args";
2750         }
2751     } elsif (
2752         !$indir && $name eq "sort"
2753       && $op->first->sibling->name eq 'entersub'
2754     ) {
2755         # We cannot say sort foo(bar), as foo will be interpreted as a
2756         # comparison routine.  We have to say sort(...) in that case.
2757         return "$name2($args)";
2758     } else {
2759         return $self->maybe_parens_func($name2, $args, $cx, 5);
2760     }
2761
2762 }
2763
2764 sub pp_prtf { indirop(@_, "printf") }
2765 sub pp_print { indirop(@_, "print") }
2766 sub pp_say  { indirop(@_, "say") }
2767 sub pp_sort { indirop(@_, "sort") }
2768
2769 sub mapop {
2770     my $self = shift;
2771     my($op, $cx, $name) = @_;
2772     my($expr, @exprs);
2773     my $kid = $op->first; # this is the (map|grep)start
2774     $kid = $kid->first->sibling; # skip a pushmark
2775     my $code = $kid->first; # skip a null
2776     if (is_scope $code) {
2777         $code = "{" . $self->deparse($code, 0) . "} ";
2778     } else {
2779         $code = $self->deparse($code, 24) . ", ";
2780     }
2781     $kid = $kid->sibling;
2782     for (; !null($kid); $kid = $kid->sibling) {
2783         $expr = $self->deparse($kid, 6);
2784         push @exprs, $expr if defined $expr;
2785     }
2786     return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2787 }
2788
2789 sub pp_mapwhile { mapop(@_, "map") }
2790 sub pp_grepwhile { mapop(@_, "grep") }
2791 sub pp_mapstart { baseop(@_, "map") }
2792 sub pp_grepstart { baseop(@_, "grep") }
2793
2794 sub pp_list {
2795     my $self = shift;
2796     my($op, $cx) = @_;
2797     my($expr, @exprs);
2798     my $kid = $op->first->sibling; # skip pushmark
2799     return '' if class($kid) eq 'NULL';
2800     my $lop;
2801     my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2802     for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2803         # This assumes that no other private flags equal 128, and that
2804         # OPs that store things other than flags in their op_private,
2805         # like OP_AELEMFAST, won't be immediate children of a list.
2806         #
2807         # OP_ENTERSUB can break this logic, so check for it.
2808         # I suspect that open and exit can too.
2809
2810         if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2811                 or $lop->name eq "undef")
2812             or $lop->name eq "entersub"
2813             or $lop->name eq "exit"
2814             or $lop->name eq "open")
2815         {
2816             $local = ""; # or not
2817             last;
2818         }
2819         if ($lop->name =~ /^pad[ash]v$/) {
2820             if ($lop->private & OPpPAD_STATE) { # state()
2821                 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2822                 $local = "state";
2823             } else { # my()
2824                 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2825                 $local = "my";
2826             }
2827         } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2828                         && $lop->private & OPpOUR_INTRO
2829                 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2830                         && $lop->first->private & OPpOUR_INTRO) { # our()
2831             ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2832             $local = "our";
2833         } elsif ($lop->name ne "undef"
2834                 # specifically avoid the "reverse sort" optimisation,
2835                 # where "reverse" is nullified
2836                 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
2837         {
2838             # local()
2839             ($local = "", last) if $local =~ /^(?:my|our|state)$/;
2840             $local = "local";
2841         }
2842     }
2843     $local = "" if $local eq "either"; # no point if it's all undefs
2844     return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2845     for (; !null($kid); $kid = $kid->sibling) {
2846         if ($local) {
2847             if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2848                 $lop = $kid->first;
2849             } else {
2850                 $lop = $kid;
2851             }
2852             $self->{'avoid_local'}{$$lop}++;
2853             $expr = $self->deparse($kid, 6);
2854             delete $self->{'avoid_local'}{$$lop};
2855         } else {
2856             $expr = $self->deparse($kid, 6);
2857         }
2858         push @exprs, $expr;
2859     }
2860     if ($local) {
2861         return "$local(" . join(", ", @exprs) . ")";
2862     } else {
2863         return $self->maybe_parens( join(", ", @exprs), $cx, 6);        
2864     }
2865 }
2866
2867 sub is_ifelse_cont {
2868     my $op = shift;
2869     return ($op->name eq "null" and class($op) eq "UNOP"
2870             and $op->first->name =~ /^(and|cond_expr)$/
2871             and is_scope($op->first->first->sibling));
2872 }
2873
2874 sub pp_cond_expr {
2875     my $self = shift;
2876     my($op, $cx) = @_;
2877     my $cond = $op->first;
2878     my $true = $cond->sibling;
2879     my $false = $true->sibling;
2880     my $cuddle = $self->{'cuddle'};
2881     unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
2882             (is_scope($false) || is_ifelse_cont($false))
2883             and $self->{'expand'} < 7) {
2884         $cond = $self->deparse($cond, 8);
2885         $true = $self->deparse($true, 6);
2886         $false = $self->deparse($false, 8);
2887         return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2888     }
2889
2890     $cond = $self->deparse($cond, 1);
2891     $true = $self->deparse($true, 0);
2892     my $head = "if ($cond) {\n\t$true\n\b}";
2893     my @elsifs;
2894     while (!null($false) and is_ifelse_cont($false)) {
2895         my $newop = $false->first;
2896         my $newcond = $newop->first;
2897         my $newtrue = $newcond->sibling;
2898         $false = $newtrue->sibling; # last in chain is OP_AND => no else
2899         if ($newcond->name eq "lineseq")
2900         {
2901             # lineseq to ensure correct line numbers in elsif()
2902             # Bug #37302 fixed by change #33710.
2903             $newcond = $newcond->first->sibling;
2904         }
2905         $newcond = $self->deparse($newcond, 1);
2906         $newtrue = $self->deparse($newtrue, 0);
2907         push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2908     }
2909     if (!null($false)) {
2910         $false = $cuddle . "else {\n\t" .
2911           $self->deparse($false, 0) . "\n\b}\cK";
2912     } else {
2913         $false = "\cK";
2914     }
2915     return $head . join($cuddle, "", @elsifs) . $false;
2916 }
2917
2918 sub pp_once {
2919     my ($self, $op, $cx) = @_;
2920     my $cond = $op->first;
2921     my $true = $cond->sibling;
2922
2923     return $self->deparse($true, $cx);
2924 }
2925
2926 sub loop_common {
2927     my $self = shift;
2928     my($op, $cx, $init) = @_;
2929     my $enter = $op->first;
2930     my $kid = $enter->sibling;
2931     local(@$self{qw'curstash warnings hints hinthash'})
2932                 = @$self{qw'curstash warnings hints hinthash'};
2933     my $head = "";
2934     my $bare = 0;
2935     my $body;
2936     my $cond = undef;
2937     if ($kid->name eq "lineseq") { # bare or infinite loop
2938         if ($kid->last->name eq "unstack") { # infinite
2939             $head = "while (1) "; # Can't use for(;;) if there's a continue
2940             $cond = "";
2941         } else {
2942             $bare = 1;
2943         }
2944         $body = $kid;
2945     } elsif ($enter->name eq "enteriter") { # foreach
2946         my $ary = $enter->first->sibling; # first was pushmark
2947         my $var = $ary->sibling;
2948         if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2949             # "reverse" was optimised away
2950             $ary = listop($self, $ary->first->sibling, 1, 'reverse');
2951         } elsif ($enter->flags & OPf_STACKED
2952             and not null $ary->first->sibling->sibling)
2953         {
2954             $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2955               $self->deparse($ary->first->sibling->sibling, 9);
2956         } else {
2957             $ary = $self->deparse($ary, 1);
2958         }
2959         if (null $var) {
2960             if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2961                 # thread special var, under 5005threads
2962                 $var = $self->pp_threadsv($enter, 1);
2963             } else { # regular my() variable
2964                 $var = $self->pp_padsv($enter, 1);
2965             }
2966         } elsif ($var->name eq "rv2gv") {
2967             $var = $self->pp_rv2sv($var, 1);
2968             if ($enter->private & OPpOUR_INTRO) {
2969                 # our declarations don't have package names
2970                 $var =~ s/^(.).*::/$1/;
2971                 $var = "our $var";
2972             }
2973         } elsif ($var->name eq "gv") {
2974             $var = "\$" . $self->deparse($var, 1);
2975         }
2976         $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
2977         if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
2978             confess unless $var eq '$_';
2979             $body = $body->first;
2980             return $self->deparse($body, 2) . " foreach ($ary)";
2981         }
2982         $head = "foreach $var ($ary) ";
2983     } elsif ($kid->name eq "null") { # while/until
2984         $kid = $kid->first;
2985         my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2986         $cond = $self->deparse($kid->first, 1);
2987         $head = "$name ($cond) ";
2988         $body = $kid->first->sibling;
2989     } elsif ($kid->name eq "stub") { # bare and empty
2990         return "{;}"; # {} could be a hashref
2991     }
2992     # If there isn't a continue block, then the next pointer for the loop
2993     # will point to the unstack, which is kid's last child, except
2994     # in a bare loop, when it will point to the leaveloop. When neither of
2995     # these conditions hold, then the second-to-last child is the continue
2996     # block (or the last in a bare loop).
2997     my $cont_start = $enter->nextop;
2998     my $cont;
2999     if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3000         if ($bare) {
3001             $cont = $body->last;
3002         } else {
3003             $cont = $body->first;
3004             while (!null($cont->sibling->sibling)) {
3005                 $cont = $cont->sibling;
3006             }
3007         }
3008         my $state = $body->first;
3009         my $cuddle = $self->{'cuddle'};
3010         my @states;
3011         for (; $$state != $$cont; $state = $state->sibling) {
3012             push @states, $state;
3013         }
3014         $body = $self->lineseq(undef, @states);
3015         if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3016             $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3017             $cont = "\cK";
3018         } else {
3019             $cont = $cuddle . "continue {\n\t" .
3020               $self->deparse($cont, 0) . "\n\b}\cK";
3021         }
3022     } else {
3023         return "" if !defined $body;
3024         if (length $init) {
3025             $head = "for ($init; $cond;) ";
3026         }
3027         $cont = "\cK";
3028         $body = $self->deparse($body, 0);
3029     }
3030     $body =~ s/;?$/;\n/;
3031
3032     return $head . "{\n\t" . $body . "\b}" . $cont;
3033 }
3034
3035 sub pp_leaveloop { shift->loop_common(@_, "") }
3036
3037 sub for_loop {
3038     my $self = shift;
3039     my($op, $cx) = @_;
3040     my $init = $self->deparse($op, 1);
3041     my $s = $op->sibling;
3042     my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3043     return $self->loop_common($ll, $cx, $init);
3044 }
3045
3046 sub pp_leavetry {
3047     my $self = shift;
3048     return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3049 }
3050
3051 BEGIN { for (qw[ const stringify rv2sv list glob ]) {
3052     eval "sub OP_\U$_ () { " . opnumber($_) . "}"
3053 }}
3054
3055 sub pp_null {
3056     my $self = shift;
3057     my($op, $cx) = @_;
3058     if (class($op) eq "OP") {
3059         # old value is lost
3060         return $self->{'ex_const'} if $op->targ == OP_CONST;
3061     } elsif ($op->first->name eq "pushmark") {
3062         return $self->pp_list($op, $cx);
3063     } elsif ($op->first->name eq "enter") {
3064         return $self->pp_leave($op, $cx);
3065     } elsif ($op->first->name eq "leave") {
3066         return $self->pp_leave($op->first, $cx);
3067     } elsif ($op->first->name eq "scope") {
3068         return $self->pp_scope($op->first, $cx);
3069     } elsif ($op->targ == OP_STRINGIFY) {
3070         return $self->dquote($op, $cx);
3071     } elsif ($op->targ == OP_GLOB) {
3072         return $self->pp_glob(
3073                  $op->first    # entersub
3074                     ->first    # ex-list
3075                     ->first    # pushmark
3076                     ->sibling, # glob
3077                  $cx
3078                );
3079     } elsif (!null($op->first->sibling) and
3080              $op->first->sibling->name eq "readline" and
3081              $op->first->sibling->flags & OPf_STACKED) {
3082         return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3083                                    . $self->deparse($op->first->sibling, 7),
3084                                    $cx, 7);
3085     } elsif (!null($op->first->sibling) and
3086              $op->first->sibling->name eq "trans" and
3087              $op->first->sibling->flags & OPf_STACKED) {
3088         return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3089                                    . $self->deparse($op->first->sibling, 20),
3090                                    $cx, 20);
3091     } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3092         return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
3093     } elsif (!null($op->first->sibling) and
3094              $op->first->sibling->name eq "null" and
3095              class($op->first->sibling) eq "UNOP" and
3096              $op->first->sibling->first->flags & OPf_STACKED and
3097              $op->first->sibling->first->name eq "rcatline") {
3098         return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3099                                    . $self->deparse($op->first->sibling, 18),
3100                                    $cx, 18);
3101     } else {
3102         return $self->deparse($op->first, $cx);
3103     }
3104 }
3105
3106 sub padname {
3107     my $self = shift;
3108     my $targ = shift;
3109     return $self->padname_sv($targ)->PVX;
3110 }
3111
3112 sub padany {
3113     my $self = shift;
3114     my $op = shift;
3115     return substr($self->padname($op->targ), 1); # skip $/@/%
3116 }
3117
3118 sub pp_padsv {
3119     my $self = shift;
3120     my($op, $cx) = @_;
3121     return $self->maybe_my($op, $cx, $self->padname($op->targ));
3122 }
3123
3124 sub pp_padav { pp_padsv(@_) }
3125 sub pp_padhv { pp_padsv(@_) }
3126
3127 my @threadsv_names = B::threadsv_names;
3128 sub pp_threadsv {
3129     my $self = shift;
3130     my($op, $cx) = @_;
3131     return $self->maybe_local($op, $cx, "\$" .  $threadsv_names[$op->targ]);
3132 }
3133
3134 sub gv_or_padgv {
3135     my $self = shift;
3136     my $op = shift;
3137     if (class($op) eq "PADOP") {
3138         return $self->padval($op->padix);
3139     } else { # class($op) eq "SVOP"
3140         return $op->gv;
3141     }
3142 }
3143
3144 sub pp_gvsv {
3145     my $self = shift;
3146     my($op, $cx) = @_;
3147     my $gv = $self->gv_or_padgv($op);
3148     return $self->maybe_local($op, $cx, $self->stash_variable("\$",
3149                                  $self->gv_name($gv), $cx));
3150 }
3151
3152 sub pp_gv {
3153     my $self = shift;
3154     my($op, $cx) = @_;
3155     my $gv = $self->gv_or_padgv($op);
3156     return $self->gv_name($gv);
3157 }
3158
3159 sub pp_aelemfast_lex {
3160     my $self = shift;
3161     my($op, $cx) = @_;
3162     my $name = $self->padname($op->targ);
3163     $name =~ s/^@/\$/;
3164     return $name . "[" .  ($op->private + $self->{'arybase'}) . "]";
3165 }
3166
3167 sub pp_aelemfast {
3168     my $self = shift;
3169     my($op, $cx) = @_;
3170     # optimised PADAV, pre 5.15
3171     return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
3172
3173     my $gv = $self->gv_or_padgv($op);
3174     my($name,$quoted) = $self->stash_variable_name('@',$gv);
3175     $name = $quoted ? "$name->" : '$' . $name;
3176     return $name . "[" .  ($op->private + $self->{'arybase'}) . "]";
3177 }
3178
3179 sub rv2x {
3180     my $self = shift;
3181     my($op, $cx, $type) = @_;
3182
3183     if (class($op) eq 'NULL' || !$op->can("first")) {
3184         carp("Unexpected op in pp_rv2x");
3185         return 'XXX';
3186     }
3187     my $kid = $op->first;
3188     if ($kid->name eq "gv") {
3189         return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
3190     } elsif (is_scalar $kid) {
3191         my $str = $self->deparse($kid, 0);
3192         if ($str =~ /^\$([^\w\d])\z/) {
3193             # "$$+" isn't a legal way to write the scalar dereference
3194             # of $+, since the lexer can't tell you aren't trying to
3195             # do something like "$$ + 1" to get one more than your
3196             # PID. Either "${$+}" or "$${+}" are workable
3197             # disambiguations, but if the programmer did the former,
3198             # they'd be in the "else" clause below rather than here.
3199             # It's not clear if this should somehow be unified with
3200             # the code in dq and re_dq that also adds lexer
3201             # disambiguation braces.
3202             $str = '$' . "{$1}"; #'
3203         }
3204         return $type . $str;
3205     } else {
3206         return $type . "{" . $self->deparse($kid, 0) . "}";
3207     }
3208 }
3209
3210 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3211 sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3212 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3213
3214 # skip rv2av
3215 sub pp_av2arylen {
3216     my $self = shift;
3217     my($op, $cx) = @_;
3218     if ($op->first->name eq "padav") {
3219         return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3220     } else {
3221         return $self->maybe_local($op, $cx,
3222                                   $self->rv2x($op->first, $cx, '$#'));
3223     }
3224 }
3225
3226 # skip down to the old, ex-rv2cv
3227 sub pp_rv2cv {
3228     my ($self, $op, $cx) = @_;
3229     if (!null($op->first) && $op->first->name eq 'null' &&
3230         $op->first->targ eq OP_LIST)
3231     {
3232         return $self->rv2x($op->first->first->sibling, $cx, "&")
3233     }
3234     else {
3235         return $self->rv2x($op, $cx, "")
3236     }
3237 }
3238
3239 sub list_const {
3240     my $self = shift;
3241     my($cx, @list) = @_;
3242     my @a = map $self->const($_, 6), @list;
3243     if (@a == 0) {
3244         return "()";
3245     } elsif (@a == 1) {
3246         return $a[0];
3247     } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3248         # collapse (-1,0,1,2) into (-1..2)
3249         my ($s, $e) = @a[0,-1];
3250         my $i = $s;
3251         return $self->maybe_parens("$s..$e", $cx, 9)
3252           unless grep $i++ != $_, @a;
3253     }
3254     return $self->maybe_parens(join(", ", @a), $cx, 6);
3255 }
3256
3257 sub pp_rv2av {
3258     my $self = shift;
3259     my($op, $cx) = @_;
3260     my $kid = $op->first;
3261     if ($kid->name eq "const") { # constant list
3262         my $av = $self->const_sv($kid);
3263         return $self->list_const($cx, $av->ARRAY);
3264     } else {
3265         return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3266     }
3267  }
3268
3269 sub is_subscriptable {
3270     my $op = shift;
3271     if ($op->name =~ /^[ahg]elem/) {
3272         return 1;
3273     } elsif ($op->name eq "entersub") {
3274         my $kid = $op->first;
3275         return 0 unless null $kid->sibling;
3276         $kid = $kid->first;
3277         $kid = $kid->sibling until null $kid->sibling;
3278         return 0 if is_scope($kid);
3279         $kid = $kid->first;
3280         return 0 if $kid->name eq "gv";
3281         return 0 if is_scalar($kid);
3282         return is_subscriptable($kid);  
3283     } else {
3284         return 0;
3285     }
3286 }
3287
3288 sub elem_or_slice_array_name
3289 {
3290     my $self = shift;
3291     my ($array, $left, $padname, $allow_arrow) = @_;
3292
3293     if ($array->name eq $padname) {
3294         return $self->padany($array);
3295     } elsif (is_scope($array)) { # ${expr}[0]
3296         return "{" . $self->deparse($array, 0) . "}";
3297     } elsif ($array->name eq "gv") {
3298         ($array, my $quoted) =
3299             $self->stash_variable_name(
3300                 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3301             );
3302         if (!$allow_arrow && $quoted) {
3303             # This cannot happen.
3304             die "Invalid variable name $array for slice";
3305         }
3306         return $quoted ? "$array->" : $array;
3307     } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3308         return $self->deparse($array, 24);
3309     } else {
3310         return undef;
3311     }
3312 }
3313
3314 sub elem_or_slice_single_index
3315 {
3316     my $self = shift;
3317     my ($idx) = @_;
3318
3319     $idx = $self->deparse($idx, 1);
3320
3321     # Outer parens in an array index will confuse perl
3322     # if we're interpolating in a regular expression, i.e.
3323     # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3324     #
3325     # If $self->{parens}, then an initial '(' will
3326     # definitely be paired with a final ')'. If
3327     # !$self->{parens}, the misleading parens won't
3328     # have been added in the first place.
3329     #
3330     # [You might think that we could get "(...)...(...)"
3331     # where the initial and final parens do not match
3332     # each other. But we can't, because the above would
3333     # only happen if there's an infix binop between the
3334     # two pairs of parens, and *that* means that the whole
3335     # expression would be parenthesized as well.]
3336     #
3337     $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3338
3339     # Hash-element braces will autoquote a bareword inside themselves.
3340     # We need to make sure that C<$hash{warn()}> doesn't come out as
3341     # C<$hash{warn}>, which has a quite different meaning. Currently
3342     # B::Deparse will always quote strings, even if the string was a
3343     # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3344     # for constant strings.) So we can cheat slightly here - if we see
3345     # a bareword, we know that it is supposed to be a function call.
3346     #
3347     $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3348
3349     return $idx;
3350 }
3351
3352 sub elem {
3353     my $self = shift;
3354     my ($op, $cx, $left, $right, $padname) = @_;
3355     my($array, $idx) = ($op->first, $op->first->sibling);
3356
3357     $idx = $self->elem_or_slice_single_index($idx);
3358
3359     unless ($array->name eq $padname) { # Maybe this has been fixed     
3360         $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3361     }
3362     if (my $array_name=$self->elem_or_slice_array_name
3363             ($array, $left, $padname, 1)) {
3364         return ($array_name =~ /->\z/ ? $array_name : "\$" . $array_name)
3365               . $left . $idx . $right;
3366     } else {
3367         # $x[20][3]{hi} or expr->[20]
3368         my $arrow = is_subscriptable($array) ? "" : "->";
3369         return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3370     }
3371
3372 }
3373
3374 sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3375 sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3376
3377 sub pp_gelem {
3378     my $self = shift;
3379     my($op, $cx) = @_;
3380     my($glob, $part) = ($op->first, $op->last);
3381     $glob = $glob->first; # skip rv2gv
3382     $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3383     my $scope = is_scope($glob);
3384     $glob = $self->deparse($glob, 0);
3385     $part = $self->deparse($part, 1);
3386     return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3387 }
3388
3389 sub slice {
3390     my $self = shift;
3391     my ($op, $cx, $left, $right, $regname, $padname) = @_;
3392     my $last;
3393     my(@elems, $kid, $array, $list);
3394     if (class($op) eq "LISTOP") {
3395         $last = $op->last;
3396     } else { # ex-hslice inside delete()
3397         for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3398         $last = $kid;
3399     }
3400     $array = $last;
3401     $array = $array->first
3402         if $array->name eq $regname or $array->name eq "null";
3403     $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3404     $kid = $op->first->sibling; # skip pushmark
3405     if ($kid->name eq "list") {
3406         $kid = $kid->first->sibling; # skip list, pushmark
3407         for (; !null $kid; $kid = $kid->sibling) {
3408             push @elems, $self->deparse($kid, 6);
3409         }
3410         $list = join(", ", @elems);
3411     } else {
3412         $list = $self->elem_or_slice_single_index($kid);
3413     }
3414     return "\@" . $array . $left . $list . $right;
3415 }
3416
3417 sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3418 sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3419
3420 sub pp_lslice {
3421     my $self = shift;
3422     my($op, $cx) = @_;
3423     my $idx = $op->first;
3424     my $list = $op->last;
3425     my(@elems, $kid);
3426     $list = $self->deparse($list, 1);
3427     $idx = $self->deparse($idx, 1);
3428     return "($list)" . "[$idx]";
3429 }
3430
3431 sub want_scalar {
3432     my $op = shift;
3433     return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3434 }
3435
3436 sub want_list {
3437     my $op = shift;
3438     return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3439 }
3440
3441 sub _method {
3442     my $self = shift;
3443     my($op, $cx) = @_;
3444     my $kid = $op->first->sibling; # skip pushmark
3445     my($meth, $obj, @exprs);
3446     if ($kid->name eq "list" and want_list $kid) {
3447         # When an indirect object isn't a bareword but the args are in
3448         # parens, the parens aren't part of the method syntax (the LLAFR
3449         # doesn't apply), but they make a list with OPf_PARENS set that
3450         # doesn't get flattened by the append_elem that adds the method,
3451         # making a (object, arg1, arg2, ...) list where the object
3452         # usually is. This can be distinguished from
3453         # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3454         # object) because in the later the list is in scalar context
3455         # as the left side of -> always is, while in the former
3456         # the list is in list context as method arguments always are.
3457         # (Good thing there aren't method prototypes!)
3458         $meth = $kid->sibling;
3459         $kid = $kid->first->sibling; # skip pushmark
3460         $obj = $kid;
3461         $kid = $kid->sibling;
3462         for (; not null $kid; $kid = $kid->sibling) {
3463             push @exprs, $kid;
3464         }
3465     } else {
3466         $obj = $kid;
3467         $kid = $kid->sibling;
3468         for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3469               $kid = $kid->sibling) {
3470             push @exprs, $kid
3471         }
3472         $meth = $kid;
3473     }
3474
3475     if ($meth->name eq "method_named") {
3476         $meth = $self->const_sv($meth)->PV;
3477     } else {
3478         $meth = $meth->first;
3479         if ($meth->name eq "const") {
3480             # As of 5.005_58, this case is probably obsoleted by the
3481             # method_named case above
3482             $meth = $self->const_sv($meth)->PV; # needs to be bare
3483         }
3484     }
3485
3486     return { method => $meth, variable_method => ref($meth),
3487              object => $obj, args => \@exprs  },
3488            $cx;
3489 }
3490
3491 # compat function only
3492 sub method {
3493     my $self = shift;
3494     my $info = $self->_method(@_);
3495     return $self->e_method( $self->_method(@_) );
3496 }
3497
3498 sub e_method {
3499     my ($self, $info, $cx) = @_;
3500     my $obj = $self->deparse($info->{object}, 24);
3501
3502     my $meth = $info->{method};
3503     $meth = $self->deparse($meth, 1) if $info->{variable_method};
3504     my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3505     if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
3506         # method { $object }
3507         # This must be deparsed this way to preserve list context
3508         # of $object.
3509         my $need_paren = $cx >= 6;
3510         return '(' x $need_paren
3511              . $meth . substr($obj,2) # chop off the "do"
3512              . " $args"
3513              . ')' x $need_paren;
3514     }
3515     my $kid = $obj . "->" . $meth;
3516     if (length $args) {
3517         return $kid . "(" . $args . ")"; # parens mandatory
3518     } else {
3519         return $kid;
3520     }
3521 }
3522
3523 # returns "&" if the prototype doesn't match the args,
3524 # or ("", $args_after_prototype_demunging) if it does.
3525 sub check_proto {
3526     my $self = shift;
3527     return "&" if $self->{'noproto'};
3528     my($proto, @args) = @_;
3529     my($arg, $real);
3530     my $doneok = 0;
3531     my @reals;
3532     # An unbackslashed @ or % gobbles up the rest of the args
3533     1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3534     while ($proto) {
3535         $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)//;
3536         my $chr = $1;
3537         if ($chr eq "") {
3538             return "&" if @args;
3539         } elsif ($chr eq ";") {
3540             $doneok = 1;
3541         } elsif ($chr eq "@" or $chr eq "%") {
3542             push @reals, map($self->deparse($_, 6), @args);
3543             @args = ();
3544         } else {
3545             $arg = shift @args;
3546             last unless $arg;
3547             if ($chr eq "\$" || $chr eq "_") {
3548                 if (want_scalar $arg) {
3549                     push @reals, $self->deparse($arg, 6);
3550                 } else {
3551                     return "&";
3552                 }
3553             } elsif ($chr eq "&") {
3554                 if ($arg->name =~ /^(s?refgen|undef)$/) {
3555                     push @reals, $self->deparse($arg, 6);
3556                 } else {
3557                     return "&";
3558                 }
3559             } elsif ($chr eq "*") {
3560                 if ($arg->name =~ /^s?refgen$/
3561                     and $arg->first->first->name eq "rv2gv")
3562                   {
3563                       $real = $arg->first->first; # skip refgen, null
3564                       if ($real->first->name eq "gv") {
3565                           push @reals, $self->deparse($real, 6);
3566                       } else {
3567                           push @reals, $self->deparse($real->first, 6);
3568                       }
3569                   } else {
3570                       return "&";
3571                   }
3572             } elsif (substr($chr, 0, 1) eq "\\") {
3573                 $chr =~ tr/\\[]//d;
3574                 if ($arg->name =~ /^s?refgen$/ and
3575                     !null($real = $arg->first) and
3576                     ($chr =~ /\$/ && is_scalar($real->first)
3577                      or ($chr =~ /@/
3578                          && class($real->first->sibling) ne 'NULL'
3579                          && $real->first->sibling->name
3580                          =~ /^(rv2|pad)av$/)
3581                      or ($chr =~ /%/
3582                          && class($real->first->sibling) ne 'NULL'
3583                          && $real->first->sibling->name
3584                          =~ /^(rv2|pad)hv$/)
3585                      #or ($chr =~ /&/ # This doesn't work
3586                      #   && $real->first->name eq "rv2cv")
3587                      or ($chr =~ /\*/
3588                          && $real->first->name eq "rv2gv")))
3589                   {
3590                       push @reals, $self->deparse($real, 6);
3591                   } else {
3592                       return "&";
3593                   }
3594             }
3595        }
3596     }
3597     return "&" if $proto and !$doneok; # too few args and no ';'
3598     return "&" if @args;               # too many args
3599     return ("", join ", ", @reals);
3600 }
3601
3602 sub pp_entersub {
3603     my $self = shift;
3604     my($op, $cx) = @_;
3605     return $self->e_method($self->_method($op, $cx))
3606         unless null $op->first->sibling;
3607     my $prefix = "";
3608     my $amper = "";
3609     my($kid, @exprs);
3610     if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3611         $prefix = "do ";
3612     } elsif ($op->private & OPpENTERSUB_AMPER) {
3613         $amper = "&";
3614     }
3615     $kid = $op->first;
3616     $kid = $kid->first->sibling; # skip ex-list, pushmark
3617     for (; not null $kid->sibling; $kid = $kid->sibling) {
3618         push @exprs, $kid;
3619     }
3620     my $simple = 0;
3621     my $proto = undef;
3622     if (is_scope($kid)) {
3623         $amper = "&";
3624         $kid = "{" . $self->deparse($kid, 0) . "}";
3625     } elsif ($kid->first->name eq "gv") {
3626         my $gv = $self->gv_or_padgv($kid->first);
3627         if (class($gv->CV) ne "SPECIAL") {
3628             $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3629         }
3630         $simple = 1; # only calls of named functions can be prototyped
3631         $kid = $self->deparse($kid, 24);
3632         if (!$amper) {
3633             if ($kid eq 'main::') {
3634                 $kid = '::';
3635             } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3636                 $kid = single_delim("q", "'", $kid) . '->';
3637             }
3638         }
3639     } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3640         $amper = "&";
3641         $kid = $self->deparse($kid, 24);
3642     } else {
3643         $prefix = "";
3644         my $arrow = is_subscriptable($kid->first) ? "" : "->";
3645         $kid = $self->deparse($kid, 24) . $arrow;
3646     }
3647
3648     # Doesn't matter how many prototypes there are, if
3649     # they haven't happened yet!
3650     my $declared;
3651     {
3652         no strict 'refs';
3653         no warnings 'uninitialized';
3654         $declared = exists $self->{'subs_declared'}{$kid}
3655             || (
3656                  defined &{ ${$self->{'curstash'}."::"}{$kid} }
3657                  && !exists
3658                      $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3659                  && defined prototype $self->{'curstash'}."::".$kid
3660                );
3661         if (!$declared && defined($proto)) {
3662             # Avoid "too early to check prototype" warning
3663             ($amper, $proto) = ('&');
3664         }
3665     }
3666
3667     my $args;
3668     if ($declared and defined $proto and not $amper) {
3669         ($amper, $args) = $self->check_proto($proto, @exprs);
3670         if ($amper eq "&") {
3671             $args = join(", ", map($self->deparse($_, 6), @exprs));
3672         }
3673     } else {
3674         $args = join(", ", map($self->deparse($_, 6), @exprs));
3675     }
3676     if ($prefix or $amper) {
3677         if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
3678         if ($op->flags & OPf_STACKED) {
3679             return $prefix . $amper . $kid . "(" . $args . ")";
3680         } else {
3681             return $prefix . $amper. $kid;
3682         }
3683     } else {
3684         # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3685         # so it must have been translated from a keyword call. Translate
3686         # it back.
3687         $kid =~ s/^CORE::GLOBAL:://;
3688
3689         my $dproto = defined($proto) ? $proto : "undefined";
3690         if (!$declared) {
3691             return "$kid(" . $args . ")";
3692         } elsif ($dproto eq "") {
3693             return $kid;
3694         } elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3695             # is_scalar is an excessively conservative test here:
3696             # really, we should be comparing to the precedence of the
3697             # top operator of $exprs[0] (ala unop()), but that would
3698             # take some major code restructuring to do right.
3699             return $self->maybe_parens_func($kid, $args, $cx, 16);
3700         } elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3701             return $self->maybe_parens_func($kid, $args, $cx, 5);
3702         } else {
3703             return "$kid(" . $args . ")";
3704         }
3705     }
3706 }
3707
3708 sub pp_enterwrite { unop(@_, "write") }
3709
3710 # escape things that cause interpolation in double quotes,
3711 # but not character escapes
3712 sub uninterp {
3713     my($str) = @_;
3714     $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3715     return $str;
3716 }
3717
3718 {
3719 my $bal;
3720 BEGIN {
3721     use re "eval";
3722     # Matches any string which is balanced with respect to {braces}
3723     $bal = qr(
3724       (?:
3725         [^\\{}]
3726       | \\\\
3727       | \\[{}]
3728       | \{(??{$bal})\}
3729       )*
3730     )x;
3731 }
3732
3733 # the same, but treat $|, $), $( and $ at the end of the string differently
3734 sub re_uninterp {
3735     my($str) = @_;
3736
3737     $str =~ s/
3738           ( ^|\G                  # $1
3739           | [^\\]
3740           )
3741
3742           (                       # $2
3743             (?:\\\\)*
3744           )
3745
3746           (                       # $3
3747             (\(\?\??\{$bal\}\))   # $4
3748           | [\$\@]
3749             (?!\||\)|\(|$)
3750           | \\[uUlLQE]
3751           )
3752
3753         /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3754
3755     return $str;
3756 }
3757
3758 # This is for regular expressions with the /x modifier
3759 # We have to leave comments unmangled.
3760 sub re_uninterp_extended {
3761     my($str) = @_;
3762
3763     $str =~ s/
3764           ( ^|\G                  # $1
3765           | [^\\]
3766           )
3767
3768           (                       # $2
3769             (?:\\\\)*
3770           )
3771
3772           (                       # $3
3773             ( \(\?\??\{$bal\}\)   # $4  (skip over (?{}) and (??{}) blocks)
3774             | \#[^\n]*            #     (skip over comments)
3775             )
3776           | [\$\@]
3777             (?!\||\)|\(|$|\s)
3778           | \\[uUlLQE]
3779           )
3780
3781         /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3782
3783     return $str;
3784 }
3785 }
3786
3787 my %unctrl = # portable to to EBCDIC
3788     (
3789      "\c@" => '\c@',    # unused
3790      "\cA" => '\cA',
3791      "\cB" => '\cB',
3792      "\cC" => '\cC',
3793      "\cD" => '\cD',
3794      "\cE" => '\cE',
3795      "\cF" => '\cF',
3796      "\cG" => '\cG',
3797      "\cH" => '\cH',
3798      "\cI" => '\cI',
3799      "\cJ" => '\cJ',
3800      "\cK" => '\cK',
3801      "\cL" => '\cL',
3802      "\cM" => '\cM',
3803      "\cN" => '\cN',
3804      "\cO" => '\cO',
3805      "\cP" => '\cP',
3806      "\cQ" => '\cQ',
3807      "\cR" => '\cR',
3808      "\cS" => '\cS',
3809      "\cT" => '\cT',
3810      "\cU" => '\cU',
3811      "\cV" => '\cV',
3812      "\cW" => '\cW',
3813      "\cX" => '\cX',
3814      "\cY" => '\cY',
3815      "\cZ" => '\cZ',
3816      "\c[" => '\c[',    # unused
3817      "\c\\" => '\c\\',  # unused
3818      "\c]" => '\c]',    # unused
3819      "\c_" => '\c_',    # unused
3820     );
3821
3822 # character escapes, but not delimiters that might need to be escaped
3823 sub escape_str { # ASCII, UTF8
3824     my($str) = @_;
3825     $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3826     $str =~ s/\a/\\a/g;
3827 #    $str =~ s/\cH/\\b/g; # \b means something different in a regex
3828     $str =~ s/\t/\\t/g;
3829     $str =~ s/\n/\\n/g;
3830     $str =~ s/\e/\\e/g;
3831     $str =~ s/\f/\\f/g;
3832     $str =~ s/\r/\\r/g;
3833     $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
3834     $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
3835     return $str;
3836 }
3837
3838 # For regexes with the /x modifier.
3839 # Leave whitespace unmangled.
3840 sub escape_extended_re {
3841     my($str) = @_;
3842     $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3843     $str =~ s/([[:^print:]])/
3844         ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
3845     $str =~ s/\n/\n\f/g;
3846     return $str;
3847 }
3848
3849 # Don't do this for regexen
3850 sub unback {
3851     my($str) = @_;
3852     $str =~ s/\\/\\\\/g;
3853     return $str;
3854 }
3855
3856 # Remove backslashes which precede literal control characters,
3857 # to avoid creating ambiguity when we escape the latter.
3858 sub re_unback {
3859     my($str) = @_;
3860
3861     # the insane complexity here is due to the behaviour of "\c\"
3862     $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
3863     return $str;
3864 }
3865
3866 sub balanced_delim {
3867     my($str) = @_;
3868     my @str = split //, $str;
3869     my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
3870     for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
3871         ($open, $close) = @$ar;
3872         $fail = 0; $cnt = 0; $last_bs = 0;
3873         for $c (@str) {
3874             if ($c eq $open) {
3875                 $fail = 1 if $last_bs;
3876                 $cnt++;
3877             } elsif ($c eq $close) {
3878                 $fail = 1 if $last_bs;
3879                 $cnt--;
3880                 if ($cnt < 0) {
3881                     # qq()() isn't ")("
3882                     $fail = 1;
3883                     last;
3884                 }
3885             }
3886             $last_bs = $c eq '\\';
3887         }
3888         $fail = 1 if $cnt != 0;
3889         return ($open, "$open$str$close") if not $fail;
3890     }
3891     return ("", $str);
3892 }
3893
3894 sub single_delim {
3895     my($q, $default, $str) = @_;
3896     return "$default$str$default" if $default and index($str, $default) == -1;
3897     if ($q ne 'qr') {
3898         (my $succeed, $str) = balanced_delim($str);
3899         return "$q$str" if $succeed;
3900     }
3901     for my $delim ('/', '"', '#') {
3902         return "$q$delim" . $str . $delim if index($str, $delim) == -1;
3903     }
3904     if ($default) {
3905         $str =~ s/$default/\\$default/g;
3906         return "$default$str$default";
3907     } else {
3908         $str =~ s[/][\\/]g;
3909         return "$q/$str/";
3910     }
3911 }
3912
3913 my $max_prec;
3914 BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
3915
3916 # Split a floating point number into an integer mantissa and a binary
3917 # exponent. Assumes you've already made sure the number isn't zero or
3918 # some weird infinity or NaN.
3919 sub split_float {
3920     my($f) = @_;
3921     my $exponent = 0;
3922     if ($f == int($f)) {
3923         while ($f % 2 == 0) {
3924             $f /= 2;
3925             $exponent++;
3926         }
3927     } else {
3928         while ($f != int($f)) {
3929             $f *= 2;
3930             $exponent--;
3931         }
3932     }
3933     my $mantissa = sprintf("%.0f", $f);
3934     return ($mantissa, $exponent);
3935 }
3936
3937 sub const {
3938     my $self = shift;
3939     my($sv, $cx) = @_;
3940     if ($self->{'use_dumper'}) {
3941         return $self->const_dumper($sv, $cx);
3942     }
3943     if (class($sv) eq "SPECIAL") {
3944         # sv_undef, sv_yes, sv_no
3945         return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
3946     }
3947     if (class($sv) eq "NULL") {
3948        return 'undef';
3949     }
3950     # convert a version object into the "v1.2.3" string in its V magic
3951     if ($sv->FLAGS & SVs_RMG) {
3952         for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3953             return $mg->PTR if $mg->TYPE eq 'V';
3954         }
3955     }
3956
3957     if ($sv->FLAGS & SVf_IOK) {
3958         my $str = $sv->int_value;
3959         $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
3960         return $str;
3961     } elsif ($sv->FLAGS & SVf_NOK) {
3962         my $nv = $sv->NV;
3963         if ($nv == 0) {
3964             if (pack("F", $nv) eq pack("F", 0)) {
3965                 # positive zero
3966                 return "0";
3967             } else {
3968                 # negative zero
3969                 return $self->maybe_parens("-.0", $cx, 21);
3970             }
3971         } elsif (1/$nv == 0) {
3972             if ($nv > 0) {
3973                 # positive infinity
3974                 return $self->maybe_parens("9**9**9", $cx, 22);
3975             } else {
3976                 # negative infinity
3977                 return $self->maybe_parens("-9**9**9", $cx, 21);
3978             }
3979         } elsif ($nv != $nv) {
3980             # NaN
3981             if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
3982                 # the normal kind
3983                 return "sin(9**9**9)";
3984             } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
3985                 # the inverted kind
3986                 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
3987             } else {
3988                 # some other kind
3989                 my $hex = unpack("h*", pack("F", $nv));
3990                 return qq'unpack("F", pack("h*", "$hex"))';
3991             }
3992         }
3993         # first, try the default stringification
3994         my $str = "$nv";
3995         if ($str != $nv) {
3996             # failing that, try using more precision
3997             $str = sprintf("%.${max_prec}g", $nv);
3998 #           if (pack("F", $str) ne pack("F", $nv)) {
3999             if ($str != $nv) {
4000                 # not representable in decimal with whatever sprintf()
4001                 # and atof() Perl is using here.
4002                 my($mant, $exp) = split_float($nv);
4003                 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
4004             }
4005         }
4006         $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
4007         return $str;
4008     } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
4009         my $ref = $sv->RV;
4010         if (class($ref) eq "AV") {
4011             return "[" . $self->list_const(2, $ref->ARRAY) . "]";
4012         } elsif (class($ref) eq "HV") {
4013             my %hash = $ref->ARRAY;
4014             my @elts;
4015             for my $k (sort keys %hash) {
4016                 push @elts, "$k => " . $self->const($hash{$k}, 6);
4017             }
4018             return "{" . join(", ", @elts) . "}";
4019         } elsif (class($ref) eq "CV") {
4020             BEGIN {
4021                 if ($] > 5.0150051) {
4022                     require overloading;
4023                     unimport overloading;
4024                 }
4025             }
4026             if ($] > 5.0150051 && $self->{curcv} &&
4027                  $self->{curcv}->object_2svref == $ref->object_2svref) {
4028                 return $self->keyword("__SUB__");
4029             }
4030             return "sub " . $self->deparse_sub($ref);
4031         }
4032         if ($ref->FLAGS & SVs_SMG) {
4033             for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4034                 if ($mg->TYPE eq 'r') {
4035                     my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
4036                     return single_delim("qr", "", $re);
4037                 }
4038             }
4039         }
4040         
4041         return $self->maybe_parens("\\" . $self->const($ref, 20), $cx, 20);
4042     } elsif ($sv->FLAGS & SVf_POK) {
4043         my $str = $sv->PV;
4044         if ($str =~ /[[:^print:]]/) {
4045             return single_delim("qq", '"', uninterp escape_str unback $str);
4046         } else {
4047             return single_delim("q", "'", unback $str);
4048         }
4049     } else {
4050         return "undef";
4051     }
4052 }
4053
4054 sub const_dumper {
4055     my $self = shift;
4056     my($sv, $cx) = @_;
4057     my $ref = $sv->object_2svref();
4058     my $dumper = Data::Dumper->new([$$ref], ['$v']);
4059     $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
4060     my $str = $dumper->Dump();
4061     if ($str =~ /^\$v/) {
4062         return '${my ' . $str . ' \$v}';
4063     } else {
4064         return $str;
4065     }
4066 }
4067
4068 sub const_sv {
4069     my $self = shift;
4070     my $op = shift;
4071     my $sv = $op->sv;
4072     # the constant could be in the pad (under useithreads)
4073     $sv = $self->padval($op->targ) unless $$sv;
4074     return $sv;
4075 }
4076
4077 sub pp_const {
4078     my $self = shift;
4079     my($op, $cx) = @_;
4080     if ($op->private & OPpCONST_ARYBASE) {
4081         return '$[';
4082     }
4083 #    if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
4084 #       return $self->const_sv($op)->PV;
4085 #    }
4086     my $sv = $self->const_sv($op);
4087     return $self->const($sv, $cx);
4088 }
4089
4090 sub dq {
4091     my $self = shift;
4092     my $op = shift;
4093     my $type = $op->name;
4094     if ($type eq "const") {
4095         return '$[' if $op->private & OPpCONST_ARYBASE;
4096         return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
4097     } elsif ($type eq "concat") {
4098         my $first = $self->dq($op->first);
4099         my $last  = $self->dq($op->last);
4100
4101         # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
4102         ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4103             $first =~ s/([\$@])\^$/${1}{^}/)  # "${^}W" etc
4104             || ($last =~ /^[:'{\[\w_]/ && #'
4105                 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4106
4107         return $first . $last;
4108     } elsif ($type eq "uc") {
4109         return '\U' . $self->dq($op->first->sibling) . '\E';
4110     } elsif ($type eq "lc") {
4111         return '\L' . $self->dq($op->first->sibling) . '\E';
4112     } elsif ($type eq "ucfirst") {
4113         return '\u' . $self->dq($op->first->sibling);
4114     } elsif ($type eq "lcfirst") {
4115         return '\l' . $self->dq($op->first->sibling);
4116     } elsif ($type eq "quotemeta") {
4117         return '\Q' . $self->dq($op->first->sibling) . '\E';
4118     } elsif ($type eq "fc") {
4119         return '\F' . $self->dq($op->first->sibling) . '\E';
4120     } elsif ($type eq "join") {
4121         return $self->deparse($op->last, 26); # was join($", @ary)
4122     } else {
4123         return $self->deparse($op, 26);
4124     }
4125 }
4126
4127 sub pp_backtick {
4128     my $self = shift;
4129     my($op, $cx) = @_;
4130     # skip pushmark if it exists (readpipe() vs ``)
4131     my $child = $op->first->sibling->isa('B::NULL')
4132         ? $op->first : $op->first->sibling;
4133     if ($self->pure_string($child)) {
4134         return single_delim("qx", '`', $self->dq($child, 1));
4135     }
4136     unop($self, @_, "readpipe");
4137 }
4138
4139 sub dquote {
4140     my $self = shift;
4141     my($op, $cx) = @_;
4142     my $kid = $op->first->sibling; # skip ex-stringify, pushmark
4143     return $self->deparse($kid, $cx) if $self->{'unquote'};
4144     $self->maybe_targmy($kid, $cx,
4145                         sub {single_delim("qq", '"', $self->dq($_[1]))});
4146 }
4147
4148 # OP_STRINGIFY is a listop, but it only ever has one arg
4149 sub pp_stringify { maybe_targmy(@_, \&dquote) }
4150
4151 # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
4152 # note that tr(from)/to/ is OK, but not tr/from/(to)
4153 sub double_delim {
4154     my($from, $to) = @_;
4155     my($succeed, $delim);
4156     if ($from !~ m[/] and $to !~ m[/]) {
4157         return "/$from/$to/";
4158     } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
4159         if (($succeed, $to) = balanced_delim($to) and $succeed) {
4160             return "$from$to";
4161         } else {
4162             for $delim ('/', '"', '#') { # note no "'" -- s''' is special
4163                 return "$from$delim$to$delim" if index($to, $delim) == -1;
4164             }
4165             $to =~ s[/][\\/]g;
4166             return "$from/$to/";
4167         }
4168     } else {
4169         for $delim ('/', '"', '#') { # note no '
4170             return "$delim$from$delim$to$delim"
4171                 if index($to . $from, $delim) == -1;
4172         }
4173         $from =~ s[/][\\/]g;
4174         $to =~ s[/][\\/]g;
4175         return "/$from/$to/";   
4176     }
4177 }
4178
4179 # Only used by tr///, so backslashes hyphens
4180 sub pchr { # ASCII
4181     my($n) = @_;
4182     if ($n == ord '\\') {
4183         return '\\\\';
4184     } elsif ($n == ord "-") {
4185         return "\\-";
4186     } elsif ($n >= ord(' ') and $n <= ord('~')) {
4187         return chr($n);
4188     } elsif ($n == ord "\a") {
4189         return '\\a';
4190     } elsif ($n == ord "\b") {
4191         return '\\b';
4192     } elsif ($n == ord "\t") {
4193         return '\\t';
4194     } elsif ($n == ord "\n") {
4195         return '\\n';
4196     } elsif ($n == ord "\e") {
4197         return '\\e';
4198     } elsif ($n == ord "\f") {
4199         return '\\f';
4200     } elsif ($n == ord "\r") {
4201         return '\\r';
4202     } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
4203         return '\\c' . chr(ord("@") + $n);
4204     } else {
4205 #       return '\x' . sprintf("%02x", $n);
4206         return '\\' . sprintf("%03o", $n);
4207     }
4208 }
4209
4210 sub collapse {
4211     my(@chars) = @_;
4212     my($str, $c, $tr) = ("");
4213     for ($c = 0; $c < @chars; $c++) {
4214         $tr = $chars[$c];
4215         $str .= pchr($tr);
4216         if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
4217             $chars[$c + 2] == $tr + 2)
4218         {
4219             for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
4220               {}
4221             $str .= "-";
4222             $str .= pchr($chars[$c]);
4223         }
4224     }
4225     return $str;
4226 }
4227
4228 sub tr_decode_byte {
4229     my($table, $flags) = @_;
4230     my(@table) = unpack("s*", $table);
4231     splice @table, 0x100, 1;   # Number of subsequent elements
4232     my($c, $tr, @from, @to, @delfrom, $delhyphen);
4233     if ($table[ord "-"] != -1 and
4234         $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4235     {
4236         $tr = $table[ord "-"];
4237         $table[ord "-"] = -1;
4238         if ($tr >= 0) {
4239             @from = ord("-");
4240             @to = $tr;
4241         } else { # -2 ==> delete
4242             $delhyphen = 1;
4243         }
4244     }
4245     for ($c = 0; $c < @table; $c++) {
4246         $tr = $table[$c];
4247         if ($tr >= 0) {
4248             push @from, $c; push @to, $tr;
4249         } elsif ($tr == -2) {
4250             push @delfrom, $c;
4251         }
4252     }
4253     @from = (@from, @delfrom);
4254     if ($flags & OPpTRANS_COMPLEMENT) {
4255         my @newfrom = ();
4256         my %from;
4257         @from{@from} = (1) x @from;
4258         for ($c = 0; $c < 256; $c++) {
4259             push @newfrom, $c unless $from{$c};
4260         }
4261         @from = @newfrom;
4262     }
4263     unless ($flags & OPpTRANS_DELETE || !@to) {
4264         pop @to while $#to and $to[$#to] == $to[$#to -1];
4265     }
4266     my($from, $to);
4267     $from = collapse(@from);
4268     $to = collapse(@to);
4269     $from .= "-" if $delhyphen;
4270     return ($from, $to);
4271 }
4272
4273 sub tr_chr {
4274     my $x = shift;
4275     if ($x == ord "-") {
4276         return "\\-";
4277     } elsif ($x == ord "\\") {
4278         return "\\\\";
4279     } else {
4280         return chr $x;
4281     }
4282 }
4283
4284 # XXX This doesn't yet handle all cases correctly either
4285
4286 sub tr_decode_utf8 {
4287     my($swash_hv, $flags) = @_;
4288     my %swash = $swash_hv->ARRAY;
4289     my $final = undef;
4290     $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4291     my $none = $swash{"NONE"}->IV;
4292     my $extra = $none + 1;
4293     my(@from, @delfrom, @to);
4294     my $line;
4295     foreach $line (split /\n/, $swash{'LIST'}->PV) {
4296         my($min, $max, $result) = split(/\t/, $line);
4297         $min = hex $min;
4298         if (length $max) {
4299             $max = hex $max;
4300         } else {
4301             $max = $min;
4302         }
4303         $result = hex $result;
4304         if ($result == $extra) {
4305             push @delfrom, [$min, $max];
4306         } else {
4307             push @from, [$min, $max];
4308             push @to, [$result, $result + $max - $min];
4309         }
4310     }
4311     for my $i (0 .. $#from) {
4312         if ($from[$i][0] == ord '-') {
4313             unshift @from, splice(@from, $i, 1);
4314             unshift @to, splice(@to, $i, 1);
4315             last;
4316         } elsif ($from[$i][1] == ord '-') {
4317             $from[$i][1]--;
4318             $to[$i][1]--;
4319             unshift @from, ord '-';
4320             unshift @to, ord '-';
4321             last;
4322         }
4323     }
4324     for my $i (0 .. $#delfrom) {
4325         if ($delfrom[$i][0] == ord '-') {
4326             push @delfrom, splice(@delfrom, $i, 1);
4327             last;
4328         } elsif ($delfrom[$i][1] == ord '-') {
4329             $delfrom[$i][1]--;
4330             push @delfrom, ord '-';
4331             last;
4332         }
4333     }
4334     if (defined $final and $to[$#to][1] != $final) {
4335         push @to, [$final, $final];
4336     }
4337     push @from, @delfrom;
4338     if ($flags & OPpTRANS_COMPLEMENT) {
4339         my @newfrom;
4340         my $next = 0;
4341         for my $i (0 .. $#from) {
4342             push @newfrom, [$next, $from[$i][0] - 1];
4343             $next = $from[$i][1] + 1;
4344         }
4345         @from = ();
4346         for my $range (@newfrom) {
4347             if ($range->[0] <= $range->[1]) {
4348                 push @from, $range;
4349             }
4350         }
4351     }
4352     my($from, $to, $diff);
4353     for my $chunk (@from) {
4354         $diff = $chunk->[1] - $chunk->[0];
4355         if ($diff > 1) {
4356             $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4357         } elsif ($diff ==