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