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