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