This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
B::Concise: Two unused vars
[perl5.git] / dist / B-Deparse / Deparse.pm
CommitLineData
6e90668e 1# B::Deparse.pm
4ca8de37
SM
2# Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
3# All rights reserved.
6e90668e
SM
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
a798dbf2 10package B::Deparse;
ff97752d 11use Carp;
51a5edaf 12use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
bd0865ec 13 OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
2be95ceb 14 OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD
ce4e655d 15 OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
3ed82cfc 16 OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
e1dccc0d 17 OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER
2be95ceb 18 OPpSORT_REVERSE
d989cdac 19 SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
e95ab0c0 20 CVf_METHOD CVf_LVALUE
2be95ceb 21 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
ff0cf12f 22 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
3daac4da 23$VERSION = '1.16';
a798dbf2 24use strict;
2ae48fff 25use vars qw/$AUTOLOAD/;
34a48b4b 26use warnings ();
149758b3 27require feature;
a798dbf2 28
aa381260 29BEGIN {
ff0cf12f 30 # List version-specific constants here.
2be95ceb
NC
31 # Easiest way to keep this code portable between version looks to
32 # be to fake up a dummy constant that will never actually be true.
33 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
ff0cf12f 34 OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
b9bc576f 35 RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
24fcb59f 36 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
7d789282 37 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
ff0cf12f 38 eval { import B $_ };
2be95ceb
NC
39 no strict 'refs';
40 *{$_} = sub () {0} unless *{$_}{CODE};
41 }
aa381260
NC
42}
43
6e90668e
SM
44# Changes between 0.50 and 0.51:
45# - fixed nulled leave with live enter in sort { }
46# - fixed reference constants (\"str")
47# - handle empty programs gracefully
c4a6f826 48# - handle infinite loops (for (;;) {}, while (1) {})
e38ccfd9 49# - differentiate between 'for my $x ...' and 'my $x; for $x ...'
6e90668e
SM
50# - various minor cleanups
51# - moved globals into an object
e38ccfd9 52# - added '-u', like B::C
6e90668e
SM
53# - package declarations using cop_stash
54# - subs, formats and code sorted by cop_seq
f6f9bdb7 55# Changes between 0.51 and 0.52:
4d1ff10f 56# - added pp_threadsv (special variables under USE_5005THREADS)
f6f9bdb7 57# - added documentation
bd0865ec 58# Changes between 0.52 and 0.53:
9d2c6865 59# - many changes adding precedence contexts and associativity
e38ccfd9 60# - added '-p' and '-s' output style options
9d2c6865 61# - various other minor fixes
bd0865ec 62# Changes between 0.53 and 0.54:
e38ccfd9 63# - added support for new 'for (1..100)' optimization,
d7f5b6da 64# thanks to Gisle Aas
bd0865ec 65# Changes between 0.54 and 0.55:
90be192f
SM
66# - added support for new qr// construct
67# - added support for new pp_regcreset OP
bd0865ec 68# Changes between 0.55 and 0.56:
f5aa8f4e
SM
69# - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
70# - fixed $# on non-lexicals broken in last big rewrite
71# - added temporary fix for change in opcode of OP_STRINGIFY
e38ccfd9 72# - fixed problem in 0.54's for() patch in 'for (@ary)'
f5aa8f4e 73# - fixed precedence in conditional of ?:
e38ccfd9 74# - tweaked list paren elimination in 'my($x) = @_'
f5aa8f4e
SM
75# - made continue-block detection trickier wrt. null ops
76# - fixed various prototype problems in pp_entersub
77# - added support for sub prototypes that never get GVs
78# - added unquoting for special filehandle first arg in truncate
e38ccfd9 79# - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
f5aa8f4e 80# - added semicolons at the ends of blocks
e38ccfd9 81# - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
bd0865ec
GS
82# Changes between 0.56 and 0.561:
83# - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
84# - used new B.pm symbolic constants (done by Nick Ing-Simmons)
85# Changes between 0.561 and 0.57:
86# - stylistic changes to symbolic constant stuff
87# - handled scope in s///e replacement code
88# - added unquote option for expanding "" into concats, etc.
89# - split method and proto parts of pp_entersub into separate functions
90# - various minor cleanups
f4a44678
SM
91# Changes after 0.57:
92# - added parens in \&foo (patch by Albert Dvornik)
93# Changes between 0.57 and 0.58:
e38ccfd9 94# - fixed '0' statements that weren't being printed
f4a44678
SM
95# - added methods for use from other programs
96# (based on patches from James Duncan and Hugo van der Sanden)
97# - added -si and -sT to control indenting (also based on a patch from Hugo)
98# - added -sv to print something else instead of '???'
99# - preliminary version of utf8 tr/// handling
3ed82cfc
GS
100# Changes after 0.58:
101# - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
d989cdac 102# - added support for Hugo's new OP_SETSTATE (like nextstate)
3ed82cfc
GS
103# Changes between 0.58 and 0.59
104# - added support for Chip's OP_METHOD_NAMED
105# - added support for Ilya's OPpTARGET_MY optimization
e38ccfd9 106# - elided arrows before '()' subscripts when possible
58cccf98 107# Changes between 0.59 and 0.60
c4a6f826 108# - support for method attributes was added
58cccf98
SM
109# - some warnings fixed
110# - separate recognition of constant subs
c4a6f826 111# - rewrote continue block handling, now recognizing for loops
58cccf98 112# - added more control of expanding control structures
c7f67cde
RH
113# Changes between 0.60 and 0.61 (mostly by Robin Houston)
114# - many bug-fixes
115# - support for pragmas and 'use'
116# - support for the little-used $[ variable
117# - support for __DATA__ sections
118# - UTF8 support
119# - BEGIN, CHECK, INIT and END blocks
120# - scoping of subroutine declarations fixed
121# - compile-time output from the input program can be suppressed, so that the
122# output is just the deparsed code. (a change to O.pm in fact)
123# - our() declarations
124# - *all* the known bugs are now listed in the BUGS section
125# - comprehensive test mechanism (TEST -deparse)
9a58b761
RGS
126# Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
127# - bug-fixes
128# - new switch -P
129# - support for command-line switches (-l, -0, etc.)
d989cdac
SM
130# Changes between 0.63 and 0.64
131# - support for //, CHECK blocks, and assertions
132# - improved handling of foreach loops and lexicals
133# - option to use Data::Dumper for constants
134# - more bug fixes
135# - discovered lots more bugs not yet fixed
0d863452
RH
136#
137# ...
138#
139# Changes between 0.72 and 0.73
140# - support new switch constructs
6e90668e
SM
141
142# Todo:
2a9e2f8a
RH
143# (See also BUGS section at the end of this file)
144#
f4a44678
SM
145# - finish tr/// changes
146# - add option for even more parens (generalize \&foo change)
90be192f 147# - left/right context
58cccf98 148# - copy comments (look at real text with $^P?)
f5aa8f4e 149# - avoid semis in one-statement blocks
9d2c6865 150# - associativity of &&=, ||=, ?:
6e90668e
SM
151# - ',' => '=>' (auto-unquote?)
152# - break long lines ("\r" as discretionary break?)
f4a44678
SM
153# - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
154# - more style options: brace style, hex vs. octal, quotes, ...
155# - print big ints as hex/octal instead of decimal (heuristic?)
e38ccfd9 156# - handle 'my $x if 0'?
6e90668e
SM
157# - version using op_next instead of op_first/sibling?
158# - avoid string copies (pass arrays, one big join?)
9d2c6865 159# - here-docs?
6e90668e 160
d989cdac 161# Current test.deparse failures
d989cdac
SM
162# comp/hints 6 - location of BEGIN blocks wrt. block openings
163# run/switchI 1 - missing -I switches entirely
164# perl -Ifoo -e 'print @INC'
165# op/caller 2 - warning mask propagates backwards before warnings::register
166# 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
167# op/getpid 2 - can't assign to shared my() declaration (threads only)
168# 'my $x : shared = 5'
c4a6f826 169# op/override 7 - parens on overridden require change v-string interpretation
d989cdac
SM
170# 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
171# c.f. 'BEGIN { *f = sub {0} }; f 2'
172# op/pat 774 - losing Unicode-ness of Latin1-only strings
173# 'use charnames ":short"; $x="\N{latin:a with acute}"'
174# op/recurse 12 - missing parens on recursive call makes it look like method
175# 'sub f { f($x) }'
176# op/subst 90 - inconsistent handling of utf8 under "use utf8"
177# op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
178# op/tiehandle compile - "use strict" deparsed in the wrong place
179# uni/tr_ several
180# ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
181# ext/Data/Dumper/t/dumper compile
182# ext/DB_file/several
183# ext/Encode/several
184# ext/Ernno/Errno warnings
185# ext/IO/lib/IO/t/io_sel 23
186# ext/PerlIO/t/encoding compile
187# ext/POSIX/t/posix 6
188# ext/Socket/Socket 8
189# ext/Storable/t/croak compile
190# lib/Attribute/Handlers/t/multi compile
191# lib/bignum/ several
192# lib/charnames 35
193# lib/constant 32
194# lib/English 40
195# lib/ExtUtils/t/bytes 4
196# lib/File/DosGlob compile
197# lib/Filter/Simple/t/data 1
198# lib/Math/BigInt/t/constant 1
199# lib/Net/t/config Deparse-warning
200# lib/overload compile
201# lib/Switch/ several
202# lib/Symbol 4
203# lib/Test/Simple several
204# lib/Term/Complete
205# lib/Tie/File/t/29_downcopy 5
206# lib/vars 22
f5aa8f4e 207
6e90668e
SM
208# Object fields (were globals):
209#
210# avoid_local:
211# (local($a), local($b)) and local($a, $b) have the same internal
212# representation but the short form looks better. We notice we can
213# use a large-scale local when checking the list, but need to prevent
d989cdac 214# individual locals too. This hash holds the addresses of OPs that
6e90668e
SM
215# have already had their local-ness accounted for. The same thing
216# is done with my().
217#
218# curcv:
219# CV for current sub (or main program) being deparsed
220#
8510e997 221# curcvlex:
415d4c68
FC
222# Cached hash of lexical variables for curcv: keys are
223# names prefixed with "m" or "o" (representing my/our), and
8510e997
RH
224# each value is an array of pairs, indicating the cop_seq of scopes
225# in which a var of that name is valid.
226#
34a48b4b
RH
227# curcop:
228# COP for statement being deparsed
229#
6e90668e
SM
230# curstash:
231# name of the current package for deparsed code
232#
233# subs_todo:
34a48b4b 234# array of [cop_seq, CV, is_format?] for subs and formats we still
6e90668e
SM
235# want to deparse
236#
f5aa8f4e
SM
237# protos_todo:
238# as above, but [name, prototype] for subs that never got a GV
239#
6e90668e
SM
240# subs_done, forms_done:
241# keys are addresses of GVs for subs and formats we've already
242# deparsed (or at least put into subs_todo)
9d2c6865 243#
0ca62a8e
RH
244# subs_declared
245# keys are names of subs for which we've printed declarations.
4a1ac32e
FC
246# That means we can omit parentheses from the arguments. It also means we
247# need to put CORE:: on core functions of the same name.
0ca62a8e 248#
1d38190f
RGS
249# subs_deparsed
250# Keeps track of fully qualified names of all deparsed subs.
251#
9d2c6865 252# parens: -p
f5aa8f4e 253# linenums: -l
bd0865ec 254# unquote: -q
e38ccfd9 255# cuddle: ' ' or '\n', depending on -sC
f4a44678
SM
256# indent_size: -si
257# use_tabs: -sT
258# ex_const: -sv
9d2c6865
SM
259
260# A little explanation of how precedence contexts and associativity
261# work:
262#
263# deparse() calls each per-op subroutine with an argument $cx (short
264# for context, but not the same as the cx* in the perl core), which is
265# a number describing the op's parents in terms of precedence, whether
f5aa8f4e 266# they're inside an expression or at statement level, etc. (see
9d2c6865
SM
267# chart below). When ops with children call deparse on them, they pass
268# along their precedence. Fractional values are used to implement
e38ccfd9 269# associativity ('($x + $y) + $z' => '$x + $y + $y') and related
9d2c6865
SM
270# parentheses hacks. The major disadvantage of this scheme is that
271# it doesn't know about right sides and left sides, so say if you
272# assign a listop to a variable, it can't tell it's allowed to leave
273# the parens off the listop.
274
275# Precedences:
276# 26 [TODO] inside interpolation context ("")
277# 25 left terms and list operators (leftward)
278# 24 left ->
279# 23 nonassoc ++ --
280# 22 right **
281# 21 right ! ~ \ and unary + and -
282# 20 left =~ !~
283# 19 left * / % x
284# 18 left + - .
285# 17 left << >>
286# 16 nonassoc named unary operators
287# 15 nonassoc < > <= >= lt gt le ge
288# 14 nonassoc == != <=> eq ne cmp
289# 13 left &
290# 12 left | ^
291# 11 left &&
292# 10 left ||
293# 9 nonassoc .. ...
294# 8 right ?:
295# 7 right = += -= *= etc.
296# 6 left , =>
297# 5 nonassoc list operators (rightward)
298# 4 right not
299# 3 left and
300# 2 left or xor
301# 1 statement modifiers
d989cdac 302# 0.5 statements, but still print scopes as do { ... }
9d2c6865
SM
303# 0 statement level
304
305# Nonprinting characters with special meaning:
306# \cS - steal parens (see maybe_parens_unop)
307# \n - newline and indent
308# \t - increase indent
e38ccfd9 309# \b - decrease indent ('outdent')
f5aa8f4e 310# \f - flush left (no indent)
9d2c6865 311# \cK - kill following semicolon, if any
6e90668e
SM
312
313sub null {
314 my $op = shift;
315 return class($op) eq "NULL";
316}
317
318sub todo {
319 my $self = shift;
34a48b4b 320 my($cv, $is_form) = @_;
e31885a0 321 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
6e90668e 322 my $seq;
d989cdac
SM
323 if ($cv->OUTSIDE_SEQ) {
324 $seq = $cv->OUTSIDE_SEQ;
325 } elsif (!null($cv->START) and is_state($cv->START)) {
6e90668e
SM
326 $seq = $cv->START->cop_seq;
327 } else {
328 $seq = 0;
329 }
34a48b4b 330 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
1d38190f
RGS
331 unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
332 $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
333 }
6e90668e
SM
334}
335
336sub next_todo {
337 my $self = shift;
338 my $ent = shift @{$self->{'subs_todo'}};
34a48b4b
RH
339 my $cv = $ent->[1];
340 my $gv = $cv->GV;
341 my $name = $self->gv_name($gv);
6e90668e
SM
342 if ($ent->[2]) {
343 return "format $name =\n"
e31885a0 344 . $self->deparse_format($ent->[1]). "\n";
6e90668e 345 } else {
0ca62a8e 346 $self->{'subs_declared'}{$name} = 1;
34a48b4b
RH
347 if ($name eq "BEGIN") {
348 my $use_dec = $self->begin_is_use($cv);
d989cdac 349 if (defined ($use_dec) and $self->{'expand'} < 5) {
0e7fe0f0
RH
350 return () if 0 == length($use_dec);
351 return $use_dec;
352 }
34a48b4b 353 }
a0035eb8
RH
354 my $l = '';
355 if ($self->{'linenums'}) {
356 my $line = $gv->LINE;
357 my $file = $gv->FILE;
358 $l = "\n\f#line $line \"$file\"\n";
359 }
127212b2
DM
360 my $p = '';
361 if (class($cv->STASH) ne "SPECIAL") {
362 my $stash = $cv->STASH->NAME;
363 if ($stash ne $self->{'curstash'}) {
364 $p = "package $stash;\n";
365 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
366 $self->{'curstash'} = $stash;
367 }
8b2d6640 368 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
127212b2
DM
369 }
370 return "${p}${l}sub $name " . $self->deparse_sub($cv);
34a48b4b
RH
371 }
372}
373
374# Return a "use" declaration for this BEGIN block, if appropriate
375sub begin_is_use {
376 my ($self, $cv) = @_;
377 my $root = $cv->ROOT;
80dc0729 378 local @$self{qw'curcv curcvlex'} = ($cv);
34a48b4b
RH
379#require B::Debug;
380#B::walkoptree($cv->ROOT, "debug");
381 my $lineseq = $root->first;
382 return if $lineseq->name ne "lineseq";
383
384 my $req_op = $lineseq->first->sibling;
385 return if $req_op->name ne "require";
386
387 my $module;
388 if ($req_op->first->private & OPpCONST_BARE) {
389 # Actually it should always be a bareword
390 $module = $self->const_sv($req_op->first)->PV;
391 $module =~ s[/][::]g;
392 $module =~ s/.pm$//;
393 }
394 else {
d989cdac 395 $module = $self->const($self->const_sv($req_op->first), 6);
34a48b4b
RH
396 }
397
398 my $version;
399 my $version_op = $req_op->sibling;
400 return if class($version_op) eq "NULL";
401 if ($version_op->name eq "lineseq") {
402 # We have a version parameter; skip nextstate & pushmark
403 my $constop = $version_op->first->next->next;
404
405 return unless $self->const_sv($constop)->PV eq $module;
406 $constop = $constop->sibling;
a58644de 407 $version = $self->const_sv($constop);
d989cdac
SM
408 if (class($version) eq "IV") {
409 $version = $version->int_value;
410 } elsif (class($version) eq "NV") {
411 $version = $version->NV;
412 } elsif (class($version) ne "PVMG") {
413 # Includes PVIV and PVNV
a58644de
RGS
414 $version = $version->PV;
415 } else {
416 # version specified as a v-string
417 $version = 'v'.join '.', map ord, split //, $version->PV;
418 }
34a48b4b
RH
419 $constop = $constop->sibling;
420 return if $constop->name ne "method_named";
421 return if $self->const_sv($constop)->PV ne "VERSION";
422 }
423
424 $lineseq = $version_op->sibling;
425 return if $lineseq->name ne "lineseq";
426 my $entersub = $lineseq->first->sibling;
427 if ($entersub->name eq "stub") {
428 return "use $module $version ();\n" if defined $version;
429 return "use $module ();\n";
430 }
431 return if $entersub->name ne "entersub";
432
433 # See if there are import arguments
434 my $args = '';
435
6ec152c3
RH
436 my $svop = $entersub->first->sibling; # Skip over pushmark
437 return unless $self->const_sv($svop)->PV eq $module;
34a48b4b
RH
438
439 # Pull out the arguments
6ec152c3
RH
440 for ($svop=$svop->sibling; $svop->name ne "method_named";
441 $svop = $svop->sibling) {
34a48b4b 442 $args .= ", " if length($args);
6ec152c3 443 $args .= $self->deparse($svop, 6);
34a48b4b
RH
444 }
445
446 my $use = 'use';
6ec152c3 447 my $method_named = $svop;
34a48b4b
RH
448 return if $method_named->name ne "method_named";
449 my $method_name = $self->const_sv($method_named)->PV;
450
451 if ($method_name eq "unimport") {
452 $use = 'no';
453 }
454
455 # Certain pragmas are dealt with using hint bits,
456 # so we ignore them here
457 if ($module eq 'strict' || $module eq 'integer'
0ced6c29
RGS
458 || $module eq 'bytes' || $module eq 'warnings'
459 || $module eq 'feature') {
34a48b4b
RH
460 return "";
461 }
462
463 if (defined $version && length $args) {
464 return "$use $module $version ($args);\n";
465 } elsif (defined $version) {
466 return "$use $module $version;\n";
467 } elsif (length $args) {
468 return "$use $module ($args);\n";
469 } else {
470 return "$use $module;\n";
6e90668e
SM
471 }
472}
473
6e90668e 474sub stash_subs {
894e98ac 475 my ($self, $pack, $seen) = @_;
34a48b4b
RH
476 my (@ret, $stash);
477 if (!defined $pack) {
478 $pack = '';
479 $stash = \%::;
f5aa8f4e 480 }
34a48b4b
RH
481 else {
482 $pack =~ s/(::)?$/::/;
483 no strict 'refs';
d1dc589d 484 $stash = \%{"main::$pack"};
34a48b4b 485 }
894e98ac
FC
486 return
487 if ($seen ||= {})->{
488 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
489 }++;
34a48b4b
RH
490 my %stash = svref_2object($stash)->ARRAY;
491 while (my ($key, $val) = each %stash) {
f5aa8f4e
SM
492 my $class = class($val);
493 if ($class eq "PV") {
a0035eb8
RH
494 # Just a prototype. As an ugly but fairly effective way
495 # to find out if it belongs here is to see if the AUTOLOAD
496 # (if any) for the stash was defined in one of our files.
497 my $A = $stash{"AUTOLOAD"};
498 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
499 && class($A->CV) eq "CV") {
500 my $AF = $A->FILE;
501 next unless $AF eq $0 || exists $self->{'files'}{$AF};
502 }
f5aa8f4e 503 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
5b4ee549 504 } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
a0035eb8 505 # Just a name. As above.
5b4ee549
NC
506 # But skip proxy constant subroutines, as some form of perl-space
507 # visible code must have created them, be it a use statement, or
508 # some direct symbol-table manipulation code that we will Deparse
a0035eb8
RH
509 my $A = $stash{"AUTOLOAD"};
510 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
511 && class($A->CV) eq "CV") {
512 my $AF = $A->FILE;
513 next unless $AF eq $0 || exists $self->{'files'}{$AF};
514 }
d989cdac 515 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
f5aa8f4e 516 } elsif ($class eq "GV") {
34a48b4b 517 if (class(my $cv = $val->CV) ne "SPECIAL") {
f5aa8f4e 518 next if $self->{'subs_done'}{$$val}++;
e31885a0 519 next if $$val != ${$cv->GV}; # Ignore imposters
8510e997 520 $self->todo($cv, 0);
f5aa8f4e 521 }
e31885a0 522 if (class(my $cv = $val->FORM) ne "SPECIAL") {
f5aa8f4e 523 next if $self->{'forms_done'}{$$val}++;
e31885a0
RH
524 next if $$val != ${$cv->GV}; # Ignore imposters
525 $self->todo($cv, 1);
f5aa8f4e 526 }
34a48b4b 527 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
74cd21ba 528 $self->stash_subs($pack . $key, $seen);
34a48b4b 529 }
6e90668e
SM
530 }
531 }
532}
a798dbf2 533
f5aa8f4e
SM
534sub print_protos {
535 my $self = shift;
536 my $ar;
537 my @ret;
538 foreach $ar (@{$self->{'protos_todo'}}) {
539 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
540 push @ret, "sub " . $ar->[0] . "$proto;\n";
541 }
542 delete $self->{'protos_todo'};
543 return @ret;
544}
545
9d2c6865
SM
546sub style_opts {
547 my $self = shift;
548 my $opts = shift;
549 my $opt;
550 while (length($opt = substr($opts, 0, 1))) {
551 if ($opt eq "C") {
552 $self->{'cuddle'} = " ";
f4a44678
SM
553 $opts = substr($opts, 1);
554 } elsif ($opt eq "i") {
555 $opts =~ s/^i(\d+)//;
556 $self->{'indent_size'} = $1;
557 } elsif ($opt eq "T") {
558 $self->{'use_tabs'} = 1;
559 $opts = substr($opts, 1);
560 } elsif ($opt eq "v") {
561 $opts =~ s/^v([^.]*)(.|$)//;
562 $self->{'ex_const'} = $1;
9d2c6865 563 }
9d2c6865
SM
564 }
565}
566
f4a44678
SM
567sub new {
568 my $class = shift;
569 my $self = bless {}, $class;
f4a44678 570 $self->{'cuddle'} = "\n";
d989cdac
SM
571 $self->{'curcop'} = undef;
572 $self->{'curstash'} = "main";
573 $self->{'ex_const'} = "'???'";
793e2a70 574 $self->{'expand'} = 0;
d989cdac
SM
575 $self->{'files'} = {};
576 $self->{'indent_size'} = 4;
793e2a70
RH
577 $self->{'linenums'} = 0;
578 $self->{'parens'} = 0;
d989cdac
SM
579 $self->{'subs_todo'} = [];
580 $self->{'unquote'} = 0;
581 $self->{'use_dumper'} = 0;
582 $self->{'use_tabs'} = 0;
08c6f5ec 583
bc6b2ef6 584 $self->{'ambient_arybase'} = 0;
e31885a0 585 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
a0405c92 586 $self->{'ambient_hints'} = 0;
0ced6c29 587 $self->{'ambient_hinthash'} = undef;
08c6f5ec
RH
588 $self->init();
589
f4a44678 590 while (my $arg = shift @_) {
d989cdac
SM
591 if ($arg eq "-d") {
592 $self->{'use_dumper'} = 1;
593 require Data::Dumper;
594 } elsif ($arg =~ /^-f(.*)/) {
34a48b4b 595 $self->{'files'}{$1} = 1;
d989cdac
SM
596 } elsif ($arg eq "-l") {
597 $self->{'linenums'} = 1;
f4a44678
SM
598 } elsif ($arg eq "-p") {
599 $self->{'parens'} = 1;
acaaef34
RGS
600 } elsif ($arg eq "-P") {
601 $self->{'noproto'} = 1;
f4a44678
SM
602 } elsif ($arg eq "-q") {
603 $self->{'unquote'} = 1;
604 } elsif (substr($arg, 0, 2) eq "-s") {
605 $self->style_opts(substr $arg, 2);
58cccf98
SM
606 } elsif ($arg =~ /^-x(\d)$/) {
607 $self->{'expand'} = $1;
f4a44678
SM
608 }
609 }
610 return $self;
611}
612
810aef70
RH
613{
614 # Mask out the bits that L<warnings::register> uses
615 my $WARN_MASK;
616 BEGIN {
617 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
618 }
619 sub WARN_MASK () {
620 return $WARN_MASK;
621 }
34a48b4b
RH
622}
623
08c6f5ec
RH
624# Initialise the contextual information, either from
625# defaults provided with the ambient_pragmas method,
626# or from perl's own defaults otherwise.
627sub init {
628 my $self = shift;
629
bc6b2ef6 630 $self->{'arybase'} = $self->{'ambient_arybase'};
e31885a0
RH
631 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
632 ? $self->{'ambient_warnings'} & WARN_MASK
633 : undef;
d5ec2987 634 $self->{'hints'} = $self->{'ambient_hints'};
e412117e 635 $self->{'hints'} &= 0xFF if $] < 5.009;
0ced6c29 636 $self->{'hinthash'} = $self->{'ambient_hinthash'};
217aba5d
RH
637
638 # also a convenient place to clear out subs_declared
639 delete $self->{'subs_declared'};
08c6f5ec
RH
640}
641
a798dbf2 642sub compile {
6e90668e 643 my(@args) = @_;
d989cdac 644 return sub {
f4a44678 645 my $self = B::Deparse->new(@args);
d2bc402e
RGS
646 # First deparse command-line args
647 if (defined $^I) { # deparse -i
51a5edaf 648 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
d2bc402e
RGS
649 }
650 if ($^W) { # deparse -w
651 print qq(BEGIN { \$^W = $^W; }\n);
652 }
653 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
51a5edaf
RGS
654 my $fs = perlstring($/) || 'undef';
655 my $bs = perlstring($O::savebackslash) || 'undef';
d2bc402e
RGS
656 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
657 }
34a48b4b 658 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
676456c2
AG
659 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
660 ? B::unitcheck_av->ARRAY
661 : ();
ece599bd 662 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
34a48b4b
RH
663 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
664 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
676456c2 665 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
e31885a0 666 $self->todo($block, 0);
34a48b4b
RH
667 }
668 $self->stash_subs();
d989cdac
SM
669 local($SIG{"__DIE__"}) =
670 sub {
671 if ($self->{'curcop'}) {
672 my $cop = $self->{'curcop'};
673 my($line, $file) = ($cop->line, $cop->file);
674 print STDERR "While deparsing $file near line $line,\n";
675 }
676 };
6e90668e 677 $self->{'curcv'} = main_cv;
8510e997 678 $self->{'curcvlex'} = undef;
f5aa8f4e 679 print $self->print_protos;
6e90668e 680 @{$self->{'subs_todo'}} =
f4a44678 681 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
d989cdac 682 print $self->indent($self->deparse_root(main_root)), "\n"
f4a44678 683 unless null main_root;
6e90668e
SM
684 my @text;
685 while (scalar(@{$self->{'subs_todo'}})) {
686 push @text, $self->next_todo;
687 }
6f611a1a 688 print $self->indent(join("", @text)), "\n" if @text;
e31885a0
RH
689
690 # Print __DATA__ section, if necessary
691 no strict 'refs';
96c57f7e
RGS
692 my $laststash = defined $self->{'curcop'}
693 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
694 if (defined *{$laststash."::DATA"}{IO}) {
127212b2
DM
695 print "package $laststash;\n"
696 unless $laststash eq $self->{'curstash'};
e31885a0 697 print "__DATA__\n";
96c57f7e 698 print readline(*{$laststash."::DATA"});
e31885a0 699 }
a798dbf2 700 }
a798dbf2
MB
701}
702
f4a44678
SM
703sub coderef2text {
704 my $self = shift;
705 my $sub = shift;
0853f172 706 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
08c6f5ec
RH
707
708 $self->init();
f4a44678
SM
709 return $self->indent($self->deparse_sub(svref_2object($sub)));
710}
711
415d4c68 712my %strict_bits = do {
d1718a7c 713 local $^H;
415d4c68
FC
714 map +($_ => strict::bits($_)), qw/refs subs vars/
715};
716
08c6f5ec
RH
717sub ambient_pragmas {
718 my $self = shift;
bc6b2ef6 719 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
08c6f5ec
RH
720
721 while (@_ > 1) {
722 my $name = shift();
723 my $val = shift();
724
725 if ($name eq 'strict') {
726 require strict;
727
728 if ($val eq 'none') {
415d4c68 729 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
08c6f5ec
RH
730 next();
731 }
732
733 my @names;
734 if ($val eq "all") {
735 @names = qw/refs subs vars/;
736 }
737 elsif (ref $val) {
738 @names = @$val;
739 }
740 else {
a0405c92 741 @names = split' ', $val;
08c6f5ec 742 }
415d4c68 743 $hint_bits |= $strict_bits{$_} for @names;
08c6f5ec
RH
744 }
745
bc6b2ef6
Z
746 elsif ($name eq '$[') {
747 if (OPpCONST_ARYBASE) {
748 $arybase = $val;
749 } else {
750 croak "\$[ can't be non-zero on this perl" unless $val == 0;
751 }
752 }
753
a0405c92
RH
754 elsif ($name eq 'integer'
755 || $name eq 'bytes'
756 || $name eq 'utf8') {
757 require "$name.pm";
08c6f5ec 758 if ($val) {
a0405c92
RH
759 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
760 }
761 else {
762 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
763 }
764 }
765
766 elsif ($name eq 're') {
767 require re;
768 if ($val eq 'none') {
2570cdf1 769 $hint_bits &= ~re::bits(qw/taint eval/);
a0405c92
RH
770 next();
771 }
772
773 my @names;
774 if ($val eq 'all') {
2570cdf1 775 @names = qw/taint eval/;
a0405c92
RH
776 }
777 elsif (ref $val) {
778 @names = @$val;
08c6f5ec
RH
779 }
780 else {
a0405c92 781 @names = split' ',$val;
08c6f5ec 782 }
a0405c92 783 $hint_bits |= re::bits(@names);
08c6f5ec
RH
784 }
785
786 elsif ($name eq 'warnings') {
08c6f5ec 787 if ($val eq 'none') {
810aef70 788 $warning_bits = $warnings::NONE;
08c6f5ec
RH
789 next();
790 }
791
792 my @names;
793 if (ref $val) {
794 @names = @$val;
795 }
796 else {
797 @names = split/\s+/, $val;
798 }
799
810aef70 800 $warning_bits = $warnings::NONE if !defined ($warning_bits);
08c6f5ec
RH
801 $warning_bits |= warnings::bits(@names);
802 }
803
804 elsif ($name eq 'warning_bits') {
805 $warning_bits = $val;
806 }
807
808 elsif ($name eq 'hint_bits') {
809 $hint_bits = $val;
810 }
811
0ced6c29
RGS
812 elsif ($name eq '%^H') {
813 $hinthash = $val;
814 }
815
08c6f5ec
RH
816 else {
817 croak "Unknown pragma type: $name";
818 }
819 }
820 if (@_) {
821 croak "The ambient_pragmas method expects an even number of args";
822 }
823
bc6b2ef6 824 $self->{'ambient_arybase'} = $arybase;
08c6f5ec 825 $self->{'ambient_warnings'} = $warning_bits;
a0405c92 826 $self->{'ambient_hints'} = $hint_bits;
0ced6c29 827 $self->{'ambient_hinthash'} = $hinthash;
08c6f5ec
RH
828}
829
d989cdac 830# This method is the inner loop, so try to keep it simple
6e90668e
SM
831sub deparse {
832 my $self = shift;
d989cdac 833 my($op, $cx) = @_;
34a48b4b
RH
834
835 Carp::confess("Null op in deparse") if !defined($op)
836 || class($op) eq "NULL";
3f872cb9 837 my $meth = "pp_" . $op->name;
9d2c6865 838 return $self->$meth($op, $cx);
a798dbf2
MB
839}
840
6e90668e 841sub indent {
f4a44678 842 my $self = shift;
6e90668e
SM
843 my $txt = shift;
844 my @lines = split(/\n/, $txt);
845 my $leader = "";
f4a44678 846 my $level = 0;
6e90668e
SM
847 my $line;
848 for $line (@lines) {
f4a44678
SM
849 my $cmd = substr($line, 0, 1);
850 if ($cmd eq "\t" or $cmd eq "\b") {
851 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
852 if ($self->{'use_tabs'}) {
853 $leader = "\t" x ($level / 8) . " " x ($level % 8);
854 } else {
855 $leader = " " x $level;
856 }
6e90668e
SM
857 $line = substr($line, 1);
858 }
f5aa8f4e
SM
859 if (substr($line, 0, 1) eq "\f") {
860 $line = substr($line, 1); # no indent
861 } else {
862 $line = $leader . $line;
863 }
9d2c6865 864 $line =~ s/\cK;?//g;
6e90668e
SM
865 }
866 return join("\n", @lines);
867}
868
6e90668e
SM
869sub deparse_sub {
870 my $self = shift;
871 my $cv = shift;
872 my $proto = "";
ce4e655d 873Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
34a48b4b
RH
874Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
875 local $self->{'curcop'} = $self->{'curcop'};
6e90668e
SM
876 if ($cv->FLAGS & SVf_POK) {
877 $proto = "(". $cv->PV . ") ";
878 }
aa381260 879 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
6aaf4108
SC
880 $proto .= ": ";
881 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
aa381260 882 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
6aaf4108
SC
883 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
884 }
885
6e90668e 886 local($self->{'curcv'}) = $cv;
8510e997 887 local($self->{'curcvlex'});
0ced6c29
RGS
888 local(@$self{qw'curstash warnings hints hinthash'})
889 = @$self{qw'curstash warnings hints hinthash'};
ce4e655d 890 my $body;
6e90668e 891 if (not null $cv->ROOT) {
ce4e655d
RH
892 my $lineseq = $cv->ROOT->first;
893 if ($lineseq->name eq "lineseq") {
894 my @ops;
895 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
896 push @ops, $o;
897 }
898 $body = $self->lineseq(undef, @ops).";";
899 my $scope_en = $self->find_scope_en($lineseq);
900 if (defined $scope_en) {
901 my $subs = join"", $self->seq_subs($scope_en);
902 $body .= ";\n$subs" if length($subs);
903 }
904 }
905 else {
906 $body = $self->deparse($cv->ROOT->first, 0);
907 }
de3f1649 908 }
ce4e655d
RH
909 else {
910 my $sv = $cv->const_sv;
911 if ($$sv) {
912 # uh-oh. inlinable sub... format it differently
d989cdac 913 return $proto . "{ " . $self->const($sv, 0) . " }\n";
ce4e655d
RH
914 } else { # XSUB? (or just a declaration)
915 return "$proto;\n";
916 }
6e90668e 917 }
ce4e655d 918 return $proto ."{\n\t$body\n\b}" ."\n";
6e90668e
SM
919}
920
921sub deparse_format {
922 my $self = shift;
923 my $form = shift;
924 my @text;
925 local($self->{'curcv'}) = $form;
8510e997 926 local($self->{'curcvlex'});
67fc2416 927 local($self->{'in_format'}) = 1;
0ced6c29
RGS
928 local(@$self{qw'curstash warnings hints hinthash'})
929 = @$self{qw'curstash warnings hints hinthash'};
6e90668e
SM
930 my $op = $form->ROOT;
931 my $kid;
fb725297
RGS
932 return "\f." if $op->first->name eq 'stub'
933 || $op->first->name eq 'nextstate';
6e90668e
SM
934 $op = $op->first->first; # skip leavewrite, lineseq
935 while (not null $op) {
936 $op = $op->sibling; # skip nextstate
937 my @exprs;
938 $kid = $op->first->sibling; # skip pushmark
a5b0cd91 939 push @text, "\f".$self->const_sv($kid)->PV;
6e90668e
SM
940 $kid = $kid->sibling;
941 for (; not null $kid; $kid = $kid->sibling) {
9d2c6865 942 push @exprs, $self->deparse($kid, 0);
6e90668e 943 }
a5b0cd91 944 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
6e90668e
SM
945 $op = $op->sibling;
946 }
a5b0cd91 947 return join("", @text) . "\f.";
6e90668e
SM
948}
949
6e90668e 950sub is_scope {
a798dbf2 951 my $op = shift;
3f872cb9
GS
952 return $op->name eq "leave" || $op->name eq "scope"
953 || $op->name eq "lineseq"
d989cdac 954 || ($op->name eq "null" && class($op) eq "UNOP"
3f872cb9 955 && (is_scope($op->first) || $op->first->name eq "enter"));
6e90668e
SM
956}
957
958sub is_state {
3f872cb9
GS
959 my $name = $_[0]->name;
960 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
6e90668e
SM
961}
962
e38ccfd9 963sub is_miniwhile { # check for one-line loop ('foo() while $y--')
6e90668e 964 my $op = shift;
d989cdac 965 return (!null($op) and null($op->sibling)
3f872cb9
GS
966 and $op->name eq "null" and class($op) eq "UNOP"
967 and (($op->first->name =~ /^(and|or)$/
968 and $op->first->first->sibling->name eq "lineseq")
969 or ($op->first->name eq "lineseq"
6e90668e 970 and not null $op->first->first->sibling
3f872cb9 971 and $op->first->first->sibling->name eq "unstack")
6e90668e
SM
972 ));
973}
974
d989cdac
SM
975# Check if the op and its sibling are the initialization and the rest of a
976# for (..;..;..) { ... } loop
977sub is_for_loop {
978 my $op = shift;
979 # This OP might be almost anything, though it won't be a
980 # nextstate. (It's the initialization, so in the canonical case it
eae48c89
Z
981 # will be an sassign.) The sibling is (old style) a lineseq whose
982 # first child is a nextstate and whose second is a leaveloop, or
983 # (new style) an unstack whose sibling is a leaveloop.
d989cdac 984 my $lseq = $op->sibling;
eae48c89
Z
985 return 0 unless !is_state($op) and !null($lseq);
986 if ($lseq->name eq "lineseq") {
d989cdac
SM
987 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
988 && (my $sib = $lseq->first->sibling)) {
989 return (!null($sib) && $sib->name eq "leaveloop");
990 }
eae48c89
Z
991 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
992 my $sib = $lseq->sibling;
993 return $sib && !null($sib) && $sib->name eq "leaveloop";
d989cdac
SM
994 }
995 return 0;
996}
997
6e90668e
SM
998sub is_scalar {
999 my $op = shift;
3f872cb9
GS
1000 return ($op->name eq "rv2sv" or
1001 $op->name eq "padsv" or
1002 $op->name eq "gv" or # only in array/hash constructs
bd0865ec 1003 $op->flags & OPf_KIDS && !null($op->first)
3f872cb9 1004 && $op->first->name eq "gvsv");
6e90668e
SM
1005}
1006
9d2c6865
SM
1007sub maybe_parens {
1008 my $self = shift;
1009 my($text, $cx, $prec) = @_;
1010 if ($prec < $cx # unary ops nest just fine
1011 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1012 or $self->{'parens'})
1013 {
1014 $text = "($text)";
1015 # In a unop, let parent reuse our parens; see maybe_parens_unop
1016 $text = "\cS" . $text if $cx == 16;
1017 return $text;
1018 } else {
1019 return $text;
1020 }
1021}
1022
e38ccfd9 1023# same as above, but get around the 'if it looks like a function' rule
9d2c6865
SM
1024sub maybe_parens_unop {
1025 my $self = shift;
1026 my($name, $kid, $cx) = @_;
1027 if ($cx > 16 or $self->{'parens'}) {
a0035eb8
RH
1028 $kid = $self->deparse($kid, 1);
1029 if ($name eq "umask" && $kid =~ /^\d+$/) {
1030 $kid = sprintf("%#o", $kid);
1031 }
4a1ac32e 1032 return $self->keyword($name) . "($kid)";
9d2c6865
SM
1033 } else {
1034 $kid = $self->deparse($kid, 16);
a0035eb8
RH
1035 if ($name eq "umask" && $kid =~ /^\d+$/) {
1036 $kid = sprintf("%#o", $kid);
1037 }
4a1ac32e 1038 $name = $self->keyword($name);
9d2c6865
SM
1039 if (substr($kid, 0, 1) eq "\cS") {
1040 # use kid's parens
1041 return $name . substr($kid, 1);
1042 } elsif (substr($kid, 0, 1) eq "(") {
1043 # avoid looks-like-a-function trap with extra parens
e38ccfd9 1044 # ('+' can lead to ambiguities)
9d2c6865
SM
1045 return "$name(" . $kid . ")";
1046 } else {
1047 return "$name $kid";
1048 }
1049 }
1050}
1051
1052sub maybe_parens_func {
1053 my $self = shift;
1054 my($func, $text, $cx, $prec) = @_;
1055 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1056 return "$func($text)";
1057 } else {
1058 return "$func $text";
1059 }
1060}
1061
6e90668e
SM
1062sub maybe_local {
1063 my $self = shift;
9d2c6865 1064 my($op, $cx, $text) = @_;
ce4e655d
RH
1065 my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1066 if ($op->private & (OPpLVAL_INTRO|$our_intro)
1067 and not $self->{'avoid_local'}{$$op}) {
1068 my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
8e3542b6 1069 if( $our_local eq 'our' ) {
640d5d41
FC
1070 if ( $text !~ /^\W(\w+::)*\w+\z/
1071 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1072 ) {
1073 die "Unexpected our($text)\n";
1074 }
d989cdac 1075 $text =~ s/(\w+::)+//;
8e3542b6 1076 }
e8d3f51b 1077 if (want_scalar($op)) {
ce4e655d 1078 return "$our_local $text";
e8d3f51b 1079 } else {
ce4e655d 1080 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
e8d3f51b 1081 }
6e90668e
SM
1082 } else {
1083 return $text;
a798dbf2 1084 }
a798dbf2
MB
1085}
1086
3ed82cfc
GS
1087sub maybe_targmy {
1088 my $self = shift;
1089 my($op, $cx, $func, @args) = @_;
1090 if ($op->private & OPpTARGET_MY) {
1091 my $var = $self->padname($op->targ);
1092 my $val = $func->($self, $op, 7, @args);
1093 return $self->maybe_parens("$var = $val", $cx, 7);
1094 } else {
1095 return $func->($self, $op, $cx, @args);
1096 }
1097}
1098
6e90668e
SM
1099sub padname_sv {
1100 my $self = shift;
1101 my $targ = shift;
d989cdac 1102 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
6e90668e
SM
1103}
1104
1105sub maybe_my {
1106 my $self = shift;
9d2c6865 1107 my($op, $cx, $text) = @_;
4c1f658f 1108 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
80e3f4ad
FC
1109 my $my = $op->private & OPpPAD_STATE
1110 ? $self->keyword("state")
1111 : "my";
e8d3f51b 1112 if (want_scalar($op)) {
3462b4ac 1113 return "$my $text";
e8d3f51b 1114 } else {
3462b4ac 1115 return $self->maybe_parens_func($my, $text, $cx, 16);
e8d3f51b 1116 }
6e90668e
SM
1117 } else {
1118 return $text;
1119 }
1120}
1121
9d2c6865
SM
1122# The following OPs don't have functions:
1123
1124# pp_padany -- does not exist after parsing
9d2c6865 1125
2ae48fff
RGS
1126sub AUTOLOAD {
1127 if ($AUTOLOAD =~ s/^.*::pp_//) {
1128 warn "unexpected OP_".uc $AUTOLOAD;
1129 return "XXX";
1130 } else {
1131 die "Undefined subroutine $AUTOLOAD called";
1132 }
9d2c6865 1133}
6e90668e 1134
611c1e95
IZ
1135sub DESTROY {} # Do not AUTOLOAD
1136
ce4e655d
RH
1137# $root should be the op which represents the root of whatever
1138# we're sequencing here. If it's undefined, then we don't append
1139# any subroutine declarations to the deparsed ops, otherwise we
1140# append appropriate declarations.
58cccf98 1141sub lineseq {
ce4e655d 1142 my($self, $root, @ops) = @_;
58cccf98 1143 my($expr, @exprs);
ce4e655d
RH
1144
1145 my $out_cop = $self->{'curcop'};
1146 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1147 my $limit_seq;
1148 if (defined $root) {
1149 $limit_seq = $out_seq;
76df5e8f
DM
1150 my $nseq;
1151 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
ce4e655d
RH
1152 $limit_seq = $nseq if !defined($limit_seq)
1153 or defined($nseq) && $nseq < $limit_seq;
1154 }
1155 $limit_seq = $self->{'limit_seq'}
1156 if defined($self->{'limit_seq'})
1157 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1158 local $self->{'limit_seq'} = $limit_seq;
09d856fb
CK
1159
1160 $self->walk_lineseq($root, \@ops,
1161 sub { push @exprs, $_[0]} );
1162
ce4e655d
RH
1163 my $body = join(";\n", grep {length} @exprs);
1164 my $subs = "";
67fc2416 1165 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
ce4e655d
RH
1166 $subs = join "\n", $self->seq_subs($limit_seq);
1167 }
1168 return join(";\n", grep {length} $body, $subs);
6e90668e
SM
1169}
1170
58cccf98 1171sub scopeop {
d989cdac 1172 my($real_block, $self, $op, $cx) = @_;
58cccf98
SM
1173 my $kid;
1174 my @kids;
a0405c92 1175
0ced6c29
RGS
1176 local(@$self{qw'curstash warnings hints hinthash'})
1177 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
58cccf98
SM
1178 if ($real_block) {
1179 $kid = $op->first->sibling; # skip enter
1180 if (is_miniwhile($kid)) {
1181 my $top = $kid->first;
1182 my $name = $top->name;
1183 if ($name eq "and") {
1184 $name = "while";
1185 } elsif ($name eq "or") {
1186 $name = "until";
1187 } else { # no conditional -> while 1 or until 0
1188 return $self->deparse($top->first, 1) . " while 1";
1189 }
1190 my $cond = $top->first;
1191 my $body = $cond->sibling->first; # skip lineseq
1192 $cond = $self->deparse($cond, 1);
1193 $body = $self->deparse($body, 1);
1194 return "$body $name $cond";
6e90668e 1195 }
58cccf98
SM
1196 } else {
1197 $kid = $op->first;
1198 }
1199 for (; !null($kid); $kid = $kid->sibling) {
1200 push @kids, $kid;
6e90668e 1201 }
d989cdac 1202 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
ce4e655d 1203 return "do {\n\t" . $self->lineseq($op, @kids) . "\n\b}";
9d2c6865 1204 } else {
ce4e655d 1205 my $lineseq = $self->lineseq($op, @kids);
7a9b44b9 1206 return (length ($lineseq) ? "$lineseq;" : "");
6e90668e 1207 }
6e90668e
SM
1208}
1209
ce4e655d 1210sub pp_scope { scopeop(0, @_); }
58cccf98
SM
1211sub pp_lineseq { scopeop(0, @_); }
1212sub pp_leave { scopeop(1, @_); }
9d2c6865 1213
d989cdac
SM
1214# This is a special case of scopeop and lineseq, for the case of the
1215# main_root. The difference is that we print the output statements as
1216# soon as we get them, for the sake of impatient users.
1217sub deparse_root {
1218 my $self = shift;
1219 my($op) = @_;
0ced6c29
RGS
1220 local(@$self{qw'curstash warnings hints hinthash'})
1221 = @$self{qw'curstash warnings hints hinthash'};
d989cdac 1222 my @kids;
4ca8de37 1223 return if null $op->first; # Can happen, e.g., for Bytecode without -k
d989cdac
SM
1224 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1225 push @kids, $kid;
1226 }
09d856fb
CK
1227 $self->walk_lineseq($op, \@kids,
1228 sub { print $self->indent($_[0].';');
1229 print "\n" unless $_[1] == $#kids;
1230 });
1231}
1232
1233sub walk_lineseq {
1234 my ($self, $op, $kids, $callback) = @_;
1235 my @kids = @$kids;
d989cdac
SM
1236 for (my $i = 0; $i < @kids; $i++) {
1237 my $expr = "";
1238 if (is_state $kids[$i]) {
09d856fb 1239 $expr = $self->deparse($kids[$i++], 0);
d989cdac 1240 if ($i > $#kids) {
09d856fb 1241 $callback->($expr, $i);
d989cdac
SM
1242 last;
1243 }
1244 }
1245 if (is_for_loop($kids[$i])) {
eae48c89
Z
1246 $callback->($expr . $self->for_loop($kids[$i], 0),
1247 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
d989cdac
SM
1248 next;
1249 }
1250 $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1251 $expr =~ s/;\n?\z//;
09d856fb 1252 $callback->($expr, $i);
d989cdac
SM
1253 }
1254}
1255
6e90668e
SM
1256# The BEGIN {} is used here because otherwise this code isn't executed
1257# when you run B::Deparse on itself.
1258my %globalnames;
1259BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1260 "ENV", "ARGV", "ARGVOUT", "_"); }
1261
1262sub gv_name {
1263 my $self = shift;
1264 my $gv = shift;
b89b7257 1265 my $raw = shift;
c6e79e55 1266Carp::confess() unless ref($gv) eq "B::GV";
6e90668e 1267 my $stash = $gv->STASH->NAME;
b89b7257 1268 my $name = $raw ? $gv->NAME : $gv->SAFENAME;
8b2d6640
FC
1269 if ($stash eq 'main' && $name =~ /^::/) {
1270 $stash = '::';
1271 }
b861b87f
FC
1272 elsif (($stash eq 'main'
1273 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
8b2d6640
FC
1274 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1275 && ($stash eq 'main' || $name !~ /::/))
b861b87f 1276 )
9d2c6865 1277 {
6e90668e
SM
1278 $stash = "";
1279 } else {
1280 $stash = $stash . "::";
a798dbf2 1281 }
b89b7257 1282 if (!$raw and $name =~ /^(\^..|{)/) {
083bda02 1283 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
6e90668e
SM
1284 }
1285 return $stash . $name;
a798dbf2
MB
1286}
1287
8510e997 1288# Return the name to use for a stash variable.
415d4c68
FC
1289# If a lexical with the same name is in scope, or
1290# if strictures are enabled, it may need to be
8510e997
RH
1291# fully-qualified.
1292sub stash_variable {
bb8996b8 1293 my ($self, $prefix, $name, $cx) = @_;
8510e997
RH
1294
1295 return "$prefix$name" if $name =~ /::/;
1296
d989cdac 1297 unless ($prefix eq '$' || $prefix eq '@' || #'
8510e997
RH
1298 $prefix eq '%' || $prefix eq '$#') {
1299 return "$prefix$name";
1300 }
1301
61154ac0
FC
1302 if ($name =~ /^[^\w+-]$/) {
1303 if (defined $cx && $cx == 26) {
1304 if ($prefix eq '@') {
bb8996b8
HY
1305 return "$prefix\{$name}";
1306 }
61154ac0
FC
1307 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1308 }
1309 if ($prefix eq '$#') {
6ec73527 1310 return "\$#{$name}";
61154ac0 1311 }
6ec73527 1312 }
bb8996b8 1313
415d4c68 1314 return $prefix . $self->maybe_qualify($prefix, $name);
8510e997
RH
1315}
1316
be6cf5cf
FC
1317# Return just the name, without the prefix. It may be returned as a quoted
1318# string. The second return value is a boolean indicating that.
1319sub stash_variable_name {
1320 my($self, $prefix, $gv) = @_;
1321 my $name = $self->gv_name($gv, 1);
415d4c68 1322 $name = $self->maybe_qualify($prefix,$name);
be6cf5cf
FC
1323 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1324 $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1325 $name =~ /^(\^..|{)/ and $name = "{$name}";
1326 return $name, 0; # not quoted
1327 }
1328 else {
1329 single_delim("q", "'", $name), 1;
1330 }
1331}
1332
415d4c68
FC
1333sub maybe_qualify {
1334 my ($self,$prefix,$name) = @_;
1335 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1336 return $name if !$prefix || $name =~ /::/;
1337 return $self->{'curstash'}.'::'. $name
1338 if
36727b53
FC
1339 $name =~ /^(?!\d)\w/ # alphabetic
1340 && $v !~ /^\$[ab]\z/ # not $a or $b
415d4c68
FC
1341 && !$globalnames{$name} # not a global name
1342 && $self->{hints} & $strict_bits{vars} # strict vars
1343 && !$self->lex_in_scope($v,1) # no "our"
1344 or $self->lex_in_scope($v); # conflicts with "my" variable
1345 return $name;
1346}
1347
8510e997 1348sub lex_in_scope {
415d4c68
FC
1349 my ($self, $name, $our) = @_;
1350 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
8510e997
RH
1351 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1352
6ec152c3 1353 return 0 if !defined($self->{'curcop'});
8510e997
RH
1354 my $seq = $self->{'curcop'}->cop_seq;
1355 return 0 if !exists $self->{'curcvlex'}{$name};
1356 for my $a (@{$self->{'curcvlex'}{$name}}) {
1357 my ($st, $en) = @$a;
1358 return 1 if $seq > $st && $seq <= $en;
1359 }
1360 return 0;
1361}
1362
1363sub populate_curcvlex {
1364 my $self = shift;
ce4e655d 1365 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
7dafbf52
DM
1366 my $padlist = $cv->PADLIST;
1367 # an undef CV still in lexical chain
1368 next if class($padlist) eq "SPECIAL";
1369 my @padlist = $padlist->ARRAY;
8510e997
RH
1370 my @ns = $padlist[0]->ARRAY;
1371
1372 for (my $i=0; $i<@ns; ++$i) {
1373 next if class($ns[$i]) eq "SPECIAL";
0f2fe21d
RH
1374 if (class($ns[$i]) eq "PV") {
1375 # Probably that pesky lexical @_
1376 next;
1377 }
8510e997 1378 my $name = $ns[$i]->PVX;
7dafbf52
DM
1379 my ($seq_st, $seq_en) =
1380 ($ns[$i]->FLAGS & SVf_FAKE)
1381 ? (0, 999999)
809abb02 1382 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
8510e997 1383
415d4c68
FC
1384 push @{$self->{'curcvlex'}{
1385 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1386 }}, [$seq_st, $seq_en];
8510e997
RH
1387 }
1388 }
1389}
1390
ce4e655d
RH
1391sub find_scope_st { ((find_scope(@_))[0]); }
1392sub find_scope_en { ((find_scope(@_))[1]); }
1393
1394# Recurses down the tree, looking for pad variable introductions and COPs
1395sub find_scope {
1396 my ($self, $op, $scope_st, $scope_en) = @_;
ff97752d 1397 carp("Undefined op in find_scope") if !defined $op;
ce4e655d
RH
1398 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1399
b6b46d6f
AB
1400 my @queue = ($op);
1401 while(my $op = shift @queue ) {
1402 for (my $o=$op->first; $$o; $o=$o->sibling) {
1403 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1404 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1405 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1406 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1407 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1408 return ($scope_st, $scope_en);
1409 }
1410 elsif (is_state($o)) {
1411 my $c = $o->cop_seq;
1412 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1413 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1414 return ($scope_st, $scope_en);
1415 }
1416 elsif ($o->flags & OPf_KIDS) {
1417 unshift (@queue, $o);
1418 }
34a48b4b
RH
1419 }
1420 }
ce4e655d
RH
1421
1422 return ($scope_st, $scope_en);
34a48b4b
RH
1423}
1424
1425# Returns a list of subs which should be inserted before the COP
1426sub cop_subs {
1427 my ($self, $op, $out_seq) = @_;
1428 my $seq = $op->cop_seq;
1429 # If we have nephews, then our sequence number indicates
1430 # the cop_seq of the end of some sort of scope.
1431 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
ce4e655d
RH
1432 and my $nseq = $self->find_scope_st($op->sibling) ) {
1433 $seq = $nseq;
34a48b4b
RH
1434 }
1435 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1436 return $self->seq_subs($seq);
1437}
1438
1439sub seq_subs {
1440 my ($self, $seq) = @_;
1441 my @text;
1442#push @text, "# ($seq)\n";
1443
ce4e655d 1444 return "" if !defined $seq;
34a48b4b
RH
1445 while (scalar(@{$self->{'subs_todo'}})
1446 and $seq > $self->{'subs_todo'}[0][0]) {
1447 push @text, $self->next_todo;
1448 }
1449 return @text;
1450}
1451
95c04cde
NC
1452sub _features_from_bundle {
1453 my ($hints, $hh) = @_;
1873980a 1454 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
95c04cde
NC
1455 $hh->{$feature::feature{$_}} = 1;
1456 }
1457 return $hh;
1458}
1459
08c6f5ec 1460# Notice how subs and formats are inserted between statements here;
bc6b2ef6 1461# also $[ assignments and pragmas.
6e90668e
SM
1462sub pp_nextstate {
1463 my $self = shift;
9d2c6865 1464 my($op, $cx) = @_;
34a48b4b 1465 $self->{'curcop'} = $op;
6e90668e 1466 my @text;
34a48b4b 1467 push @text, $self->cop_subs($op);
11faa288 1468 my $stash = $op->stashpv;
6e90668e
SM
1469 if ($stash ne $self->{'curstash'}) {
1470 push @text, "package $stash;\n";
1471 $self->{'curstash'} = $stash;
1472 }
08c6f5ec 1473
bc6b2ef6
Z
1474 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1475 push @text, '$[ = '. $op->arybase .";\n";
1476 $self->{'arybase'} = $op->arybase;
1477 }
1478
7a9b44b9
RH
1479 my $warnings = $op->warnings;
1480 my $warning_bits;
1481 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
810aef70 1482 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
7a9b44b9 1483 }
e31885a0 1484 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
810aef70 1485 $warning_bits = $warnings::NONE;
7a9b44b9 1486 }
e31885a0
RH
1487 elsif ($warnings->isa("B::SPECIAL")) {
1488 $warning_bits = undef;
1489 }
7a9b44b9 1490 else {
34a48b4b 1491 $warning_bits = $warnings->PV & WARN_MASK;
7a9b44b9
RH
1492 }
1493
e31885a0
RH
1494 if (defined ($warning_bits) and
1495 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
08c6f5ec 1496 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
7a9b44b9
RH
1497 $self->{'warnings'} = $warning_bits;
1498 }
1499
2be95ceb 1500 my $hints = $] < 5.008009 ? $op->private : $op->hints;
0bb01b05 1501 my $old_hints = $self->{'hints'};
2be95ceb
NC
1502 if ($self->{'hints'} != $hints) {
1503 push @text, declare_hints($self->{'hints'}, $hints);
1504 $self->{'hints'} = $hints;
a0405c92
RH
1505 }
1506
0bb01b05
FC
1507 my $newhh;
1508 if ($] > 5.009) {
1509 $newhh = $op->hints_hash->HASH;
1510 }
1511
1512 if ($] >= 5.015006) {
1513 # feature bundle hints
149758b3
NC
1514 my $from = $old_hints & $feature::hint_mask;
1515 my $to = $ hints & $feature::hint_mask;
0bb01b05 1516 if ($from != $to) {
149758b3 1517 if ($to == $feature::hint_mask) {
0bb01b05
FC
1518 if ($self->{'hinthash'}) {
1519 delete $self->{'hinthash'}{$_}
1520 for grep /^feature_/, keys %{$self->{'hinthash'}};
1521 }
1522 else { $self->{'hinthash'} = {} }
95c04cde
NC
1523 $self->{'hinthash'}
1524 = _features_from_bundle($from, $self->{'hinthash'});
0bb01b05
FC
1525 }
1526 else {
1527 my $bundle =
1528 $feature::hint_bundles[$to >> $feature::hint_shift];
1529 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1530 push @text, "no feature;\n",
1531 "use feature ':$bundle';\n";
1532 }
1533 }
1534 }
1535
1536 if ($] > 5.009) {
1537 push @text, declare_hinthash(
1538 $self->{'hinthash'}, $newhh,
1539 $self->{indent_size}, $self->{hints},
1540 );
1541 $self->{'hinthash'} = $newhh;
0ced6c29
RGS
1542 }
1543
d989cdac
SM
1544 # This should go after of any branches that add statements, to
1545 # increase the chances that it refers to the same line it did in
1546 # the original program.
1547 if ($self->{'linenums'}) {
1548 push @text, "\f#line " . $op->line .
1549 ' "' . $op->file, qq'"\n';
1550 }
1551
98a1a137
Z
1552 push @text, $op->label . ": " if $op->label;
1553
6e90668e
SM
1554 return join("", @text);
1555}
1556
08c6f5ec
RH
1557sub declare_warnings {
1558 my ($from, $to) = @_;
e6f1f756 1559 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
a0405c92
RH
1560 return "use warnings;\n";
1561 }
e6f1f756 1562 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
a0405c92
RH
1563 return "no warnings;\n";
1564 }
51a5edaf 1565 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
a0405c92
RH
1566}
1567
1568sub declare_hints {
1569 my ($from, $to) = @_;
a0035eb8
RH
1570 my $use = $to & ~$from;
1571 my $no = $from & ~$to;
1572 my $decls = "";
1573 for my $pragma (hint_pragmas($use)) {
1574 $decls .= "use $pragma;\n";
1575 }
1576 for my $pragma (hint_pragmas($no)) {
1577 $decls .= "no $pragma;\n";
1578 }
1579 return $decls;
1580}
1581
493c23c6
NC
1582# Internal implementation hints that the core sets automatically, so don't need
1583# (or want) to be passed back to the user
1584my %ignored_hints = (
1585 'open<' => 1,
1586 'open>' => 1,
dca6062a 1587 ':' => 1,
1c74777c
FC
1588 'strict/refs' => 1,
1589 'strict/subs' => 1,
1590 'strict/vars' => 1,
2e8342de 1591);
493c23c6 1592
a8095af7
FC
1593my %rev_feature;
1594
0ced6c29 1595sub declare_hinthash {
0bb01b05 1596 my ($from, $to, $indent, $hints) = @_;
a8095af7 1597 my $doing_features =
149758b3 1598 ($hints & $feature::hint_mask) == $feature::hint_mask;
0ced6c29 1599 my @decls;
a8095af7
FC
1600 my @features;
1601 my @unfeatures; # bugs?
0bb01b05 1602 for my $key (sort keys %$to) {
493c23c6 1603 next if $ignored_hints{$key};
a8095af7
FC
1604 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1605 next if $is_feature and not $doing_features;
04be0204 1606 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
a8095af7 1607 push(@features, $key), next if $is_feature;
035146a3
FC
1608 push @decls,
1609 qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1610 . (
1611 defined $to->{$key}
1612 ? single_delim("q", "'", $to->{$key})
1613 : 'undef'
1614 )
04be0204 1615 . qq(;);
0ced6c29
RGS
1616 }
1617 }
0bb01b05 1618 for my $key (sort keys %$from) {
493c23c6 1619 next if $ignored_hints{$key};
a8095af7
FC
1620 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1621 next if $is_feature and not $doing_features;
0ced6c29 1622 if (!exists $to->{$key}) {
a8095af7 1623 push(@unfeatures, $key), next if $is_feature;
0ced6c29
RGS
1624 push @decls, qq(delete \$^H{'$key'};);
1625 }
1626 }
a8095af7
FC
1627 my @ret;
1628 if (@features || @unfeatures) {
a8095af7
FC
1629 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1630 }
1631 if (@features) {
1632 push @ret, "use feature "
1633 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1634 }
1635 if (@unfeatures) {
1636 push @ret, "no feature "
1637 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1638 . ";\n";
1639 }
1640 @decls and
1641 push @ret,
1642 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1643 return @ret;
0ced6c29
RGS
1644}
1645
a0035eb8
RH
1646sub hint_pragmas {
1647 my ($bits) = @_;
415d4c68 1648 my (@pragmas, @strict);
a0035eb8 1649 push @pragmas, "integer" if $bits & 0x1;
415d4c68
FC
1650 for (sort keys %strict_bits) {
1651 push @strict, "'$_'" if $bits & $strict_bits{$_};
1652 }
1653 if (@strict == keys %strict_bits) {
1654 push @pragmas, "strict";
1655 }
1656 elsif (@strict) {
1657 push @pragmas, "strict " . join ', ', @strict;
1658 }
a0035eb8
RH
1659 push @pragmas, "bytes" if $bits & 0x8;
1660 return @pragmas;
08c6f5ec
RH
1661}
1662
6e90668e 1663sub pp_dbstate { pp_nextstate(@_) }
3f872cb9 1664sub pp_setstate { pp_nextstate(@_) }
6e90668e
SM
1665
1666sub pp_unstack { return "" } # see also leaveloop
1667
80e3f4ad
FC
1668my %feature_keywords = (
1669 # keyword => 'feature',
1670 state => 'state',
1671 say => 'say',
1672 given => 'switch',
1673 when => 'switch',
1674 default => 'switch',
e36901c8 1675 break => 'switch',
7d789282 1676 evalbytes=>'evalbytes',
84ed0108 1677 __SUB__ => '__SUB__',
838f2281 1678 fc => 'fc',
80e3f4ad
FC
1679);
1680
4a1ac32e
FC
1681sub keyword {
1682 my $self = shift;
1683 my $name = shift;
1684 return $name if $name =~ /^CORE::/; # just in case
80e3f4ad 1685 if (exists $feature_keywords{$name}) {
223b1722 1686 my $hh;
149758b3
NC
1687 my $hints = $self->{hints} & $feature::hint_mask;
1688 if ($hints && $hints != $feature::hint_mask) {
1873980a 1689 $hh = _features_from_bundle($hints);
223b1722
FC
1690 }
1691 elsif ($hints) { $hh = $self->{'hinthash'} }
7d789282 1692 return "CORE::$name"
223b1722
FC
1693 if !$hh
1694 || !$hh->{"feature_$feature_keywords{$name}"}
80e3f4ad 1695 }
4a1ac32e 1696 if (
a598d0e5 1697 $name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
4a1ac32e
FC
1698 && !defined eval{prototype "CORE::$name"}
1699 ) { return $name }
1700 if (
1701 exists $self->{subs_declared}{$name}
1702 or
1703 exists &{"$self->{curstash}::$name"}
1704 ) {
1705 return "CORE::$name"
1706 }
1707 return $name;
1708}
1709
6e90668e
SM
1710sub baseop {
1711 my $self = shift;
9d2c6865 1712 my($op, $cx, $name) = @_;
4a1ac32e 1713 return $self->keyword($name);
6e90668e
SM
1714}
1715
e99ebc55
RH
1716sub pp_stub {
1717 my $self = shift;
1718 my($op, $cx, $name) = @_;
d989cdac 1719 if ($cx >= 1) {
e99ebc55
RH
1720 return "()";
1721 }
1722 else {
1723 return "();";
1724 }
1725}
6e90668e
SM
1726sub pp_wantarray { baseop(@_, "wantarray") }
1727sub pp_fork { baseop(@_, "fork") }
3ed82cfc
GS
1728sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1729sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1730sub pp_time { maybe_targmy(@_, \&baseop, "time") }
6e90668e
SM
1731sub pp_tms { baseop(@_, "times") }
1732sub pp_ghostent { baseop(@_, "gethostent") }
1733sub pp_gnetent { baseop(@_, "getnetent") }
1734sub pp_gprotoent { baseop(@_, "getprotoent") }
1735sub pp_gservent { baseop(@_, "getservent") }
1736sub pp_ehostent { baseop(@_, "endhostent") }
1737sub pp_enetent { baseop(@_, "endnetent") }
1738sub pp_eprotoent { baseop(@_, "endprotoent") }
1739sub pp_eservent { baseop(@_, "endservent") }
1740sub pp_gpwent { baseop(@_, "getpwent") }
1741sub pp_spwent { baseop(@_, "setpwent") }
1742sub pp_epwent { baseop(@_, "endpwent") }
1743sub pp_ggrent { baseop(@_, "getgrent") }
1744sub pp_sgrent { baseop(@_, "setgrent") }
1745sub pp_egrent { baseop(@_, "endgrent") }
1746sub pp_getlogin { baseop(@_, "getlogin") }
1747
1748sub POSTFIX () { 1 }
1749
9d2c6865
SM
1750# I couldn't think of a good short name, but this is the category of
1751# symbolic unary operators with interesting precedence
1752
1753sub pfixop {
1754 my $self = shift;
1755 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1756 my $kid = $op->first;
1757 $kid = $self->deparse($kid, $prec);
843b15cc
FC
1758 return $self->maybe_parens(($flags & POSTFIX)
1759 ? "$kid$name"
1760 # avoid confusion with filetests
1761 : $name eq '-'
1762 && $kid =~ /^[a-zA-Z](?!\w)/
1763 ? "$name($kid)"
1764 : "$name$kid",
9d2c6865
SM
1765 $cx, $prec);
1766}
1767
1768sub pp_preinc { pfixop(@_, "++", 23) }
1769sub pp_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
1770sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1771sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
9d2c6865
SM
1772sub pp_i_preinc { pfixop(@_, "++", 23) }
1773sub pp_i_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
1774sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1775sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
68cc8748 1776sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
9d2c6865 1777
3ed82cfc
GS
1778sub pp_negate { maybe_targmy(@_, \&real_negate) }
1779sub real_negate {
9d2c6865
SM
1780 my $self = shift;
1781 my($op, $cx) = @_;
3f872cb9 1782 if ($op->first->name =~ /^(i_)?negate$/) {
9d2c6865
SM
1783 # avoid --$x
1784 $self->pfixop($op, $cx, "-", 21.5);
1785 } else {
1786 $self->pfixop($op, $cx, "-", 21);
1787 }
1788}
1789sub pp_i_negate { pp_negate(@_) }
1790
1791sub pp_not {
1792 my $self = shift;
1793 my($op, $cx) = @_;
1794 if ($cx <= 4) {
1cabb3b3 1795 $self->listop($op, $cx, "not", $op->first);
9d2c6865
SM
1796 } else {
1797 $self->pfixop($op, $cx, "!", 21);
1798 }
1799}
1800
6e90668e
SM
1801sub unop {
1802 my $self = shift;
9c56d9ea 1803 my($op, $cx, $name, $nollafr) = @_;
6e90668e 1804 my $kid;
9d2c6865 1805 if ($op->flags & OPf_KIDS) {
aaf643ce 1806 $kid = $op->first;
1c85afce
YO
1807 if (not $name) {
1808 # this deals with 'boolkeys' right now
1809 return $self->deparse($kid,$cx);
1810 }
deb20ba3
RGS
1811 my $builtinname = $name;
1812 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1813 if (defined prototype($builtinname)
1814 && prototype($builtinname) =~ /^;?\*/
e31885a0
RH
1815 && $kid->name eq "rv2gv") {
1816 $kid = $kid->first;
1817 }
1818
9c56d9ea
FC
1819 if ($nollafr) {
1820 ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1821 return $self->maybe_parens(
1822 $self->keyword($name) . " $kid", $cx, 16
1823 );
1824 }
9d2c6865 1825 return $self->maybe_parens_unop($name, $kid, $cx);
6e90668e 1826 } else {
4d8ac5c7
FC
1827 return $self->maybe_parens(
1828 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1829 $cx, 16,
1830 );
6e90668e 1831 }
6e90668e
SM
1832}
1833
3ed82cfc
GS
1834sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1835sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1836sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1837sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
6e90668e
SM
1838sub pp_defined { unop(@_, "defined") }
1839sub pp_undef { unop(@_, "undef") }
1840sub pp_study { unop(@_, "study") }
6e90668e
SM
1841sub pp_ref { unop(@_, "ref") }
1842sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1843
3ed82cfc
GS
1844sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1845sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1846sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
6e90668e 1847sub pp_srand { unop(@_, "srand") }
3ed82cfc
GS
1848sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1849sub pp_log { maybe_targmy(@_, \&unop, "log") }
1850sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1851sub pp_int { maybe_targmy(@_, \&unop, "int") }
1852sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1853sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1854sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1855
1856sub pp_length { maybe_targmy(@_, \&unop, "length") }
1857sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1858sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
6e90668e
SM
1859
1860sub pp_each { unop(@_, "each") }
1861sub pp_values { unop(@_, "values") }
1862sub pp_keys { unop(@_, "keys") }
09dcfa7d 1863{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1c85afce
YO
1864sub pp_boolkeys {
1865 # no name because its an optimisation op that has no keyword
1866 unop(@_,"");
1867}
644741fd
NC
1868sub pp_aeach { unop(@_, "each") }
1869sub pp_avalues { unop(@_, "values") }
1870sub pp_akeys { unop(@_, "keys") }
6e90668e
SM
1871sub pp_pop { unop(@_, "pop") }
1872sub pp_shift { unop(@_, "shift") }
1873
1874sub pp_caller { unop(@_, "caller") }
1875sub pp_reset { unop(@_, "reset") }
1876sub pp_exit { unop(@_, "exit") }
1877sub pp_prototype { unop(@_, "prototype") }
1878
1879sub pp_close { unop(@_, "close") }
1880sub pp_fileno { unop(@_, "fileno") }
1881sub pp_umask { unop(@_, "umask") }
6e90668e
SM
1882sub pp_untie { unop(@_, "untie") }
1883sub pp_tied { unop(@_, "tied") }
1884sub pp_dbmclose { unop(@_, "dbmclose") }
1885sub pp_getc { unop(@_, "getc") }
1886sub pp_eof { unop(@_, "eof") }
1887sub pp_tell { unop(@_, "tell") }
1888sub pp_getsockname { unop(@_, "getsockname") }
1889sub pp_getpeername { unop(@_, "getpeername") }
1890
3ed82cfc
GS
1891sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1892sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
6e90668e 1893sub pp_readlink { unop(@_, "readlink") }
3ed82cfc 1894sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
6e90668e
SM
1895sub pp_readdir { unop(@_, "readdir") }
1896sub pp_telldir { unop(@_, "telldir") }
1897sub pp_rewinddir { unop(@_, "rewinddir") }
1898sub pp_closedir { unop(@_, "closedir") }
3ed82cfc 1899sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
6e90668e
SM
1900sub pp_localtime { unop(@_, "localtime") }
1901sub pp_gmtime { unop(@_, "gmtime") }
1902sub pp_alarm { unop(@_, "alarm") }
3ed82cfc 1903sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
6e90668e 1904
94bb57f9 1905sub pp_dofile {
9c56d9ea 1906 my $code = unop(@_, "do", 1); # llafr does not apply
8b46c09b 1907 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
94bb57f9
FC
1908 $code;
1909}
7d789282
FC
1910sub pp_entereval {
1911 unop(
1912 @_,
1913 $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
1914 )
1915}
6e90668e
SM
1916
1917sub pp_ghbyname { unop(@_, "gethostbyname") }
1918sub pp_gnbyname { unop(@_, "getnetbyname") }
1919sub pp_gpbyname { unop(@_, "getprotobyname") }
1920sub pp_shostent { unop(@_, "sethostent") }
1921sub pp_snetent { unop(@_, "setnetent") }
1922sub pp_sprotoent { unop(@_, "setprotoent") }
1923sub pp_sservent { unop(@_, "setservent") }
1924sub pp_gpwnam { unop(@_, "getpwnam") }
1925sub pp_gpwuid { unop(@_, "getpwuid") }
1926sub pp_ggrnam { unop(@_, "getgrnam") }
1927sub pp_ggrgid { unop(@_, "getgrgid") }
1928
1929sub pp_lock { unop(@_, "lock") }
1930
0d863452 1931sub pp_continue { unop(@_, "continue"); }
c08f093b 1932sub pp_break { unop(@_, "break"); }
0d863452
RH
1933
1934sub givwhen {
1935 my $self = shift;
1936 my($op, $cx, $givwhen) = @_;
1937
1938 my $enterop = $op->first;
1939 my ($head, $block);
1940 if ($enterop->flags & OPf_SPECIAL) {
80e3f4ad 1941 $head = $self->keyword("default");
0d863452
RH
1942 $block = $self->deparse($enterop->first, 0);
1943 }
1944 else {
1945 my $cond = $enterop->first;
1946 my $cond_str = $self->deparse($cond, 1);
1947 $head = "$givwhen ($cond_str)";
1948 $block = $self->deparse($cond->sibling, 0);
1949 }
1950
1951 return "$head {\n".
1952 "\t$block\n".
1953 "\b}\cK";
1954}
1955
80e3f4ad
FC
1956sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1957sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
0d863452 1958
6e90668e
SM
1959sub pp_exists {
1960 my $self = shift;
9d2c6865 1961 my($op, $cx) = @_;
34a48b4b
RH
1962 my $arg;
1963 if ($op->private & OPpEXISTS_SUB) {
1964 # Checking for the existence of a subroutine
1965 return $self->maybe_parens_func("exists",
1966 $self->pp_rv2cv($op->first, 16), $cx, 16);
1967 }
1968 if ($op->flags & OPf_SPECIAL) {
1969 # Array element, not hash element
1970 return $self->maybe_parens_func("exists",
1971 $self->pp_aelem($op->first, 16), $cx, 16);
1972 }
9d2c6865
SM
1973 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1974 $cx, 16);
6e90668e
SM
1975}
1976
6e90668e
SM
1977sub pp_delete {
1978 my $self = shift;
9d2c6865 1979 my($op, $cx) = @_;
6e90668e
SM
1980 my $arg;
1981 if ($op->private & OPpSLICE) {
34a48b4b
RH
1982 if ($op->flags & OPf_SPECIAL) {
1983 # Deleting from an array, not a hash
1984 return $self->maybe_parens_func("delete",
1985 $self->pp_aslice($op->first, 16),
1986 $cx, 16);
1987 }
9d2c6865
SM
1988 return $self->maybe_parens_func("delete",
1989 $self->pp_hslice($op->first, 16),
1990 $cx, 16);
6e90668e 1991 } else {
34a48b4b
RH
1992 if ($op->flags & OPf_SPECIAL) {
1993 # Deleting from an array, not a hash
1994 return $self->maybe_parens_func("delete",
1995 $self->pp_aelem($op->first, 16),
1996 $cx, 16);
1997 }
9d2c6865
SM
1998 return $self->maybe_parens_func("delete",
1999 $self->pp_helem($op->first, 16),
2000 $cx, 16);
6e90668e 2001 }
6e90668e
SM
2002}
2003
6e90668e
SM
2004sub pp_require {
2005 my $self = shift;
9d2c6865 2006 my($op, $cx) = @_;
d5889722 2007 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
3f872cb9 2008 if (class($op) eq "UNOP" and $op->first->name eq "const"
4c1f658f 2009 and $op->first->private & OPpCONST_BARE)
6e90668e 2010 {
18228111 2011 my $name = $self->const_sv($op->first)->PV;
6e90668e
SM
2012 $name =~ s[/][::]g;
2013 $name =~ s/\.pm//g;
41df74e3 2014 return $self->maybe_parens("$opname $name", $cx, 16);
6e90668e 2015 } else {
41df74e3
FC
2016 $self->unop(
2017 $op, $cx,
c75b4828
FC
2018 $op->first->name eq 'const'
2019 && $op->first->private & OPpCONST_NOVER
2020 ? "no"
2021 : $opname,
41df74e3
FC
2022 1, # llafr does not apply
2023 );
6e90668e
SM
2024 }
2025}
2026
d989cdac 2027sub pp_scalar {
9d2c6865 2028 my $self = shift;
d9002312 2029 my($op, $cx) = @_;
9d2c6865
SM
2030 my $kid = $op->first;
2031 if (not null $kid->sibling) {
2032 # XXX Was a here-doc
2033 return $self->dquote($op);
2034 }
2035 $self->unop(@_, "scalar");
2036}
2037
2038
6e90668e
SM
2039sub padval {
2040 my $self = shift;
2041 my $targ = shift;
d989cdac 2042 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
6e90668e
SM
2043}
2044
78c72037
NC
2045sub anon_hash_or_list {
2046 my $self = shift;
d9002312 2047 my($op, $cx) = @_;
78c72037
NC
2048
2049 my($pre, $post) = @{{"anonlist" => ["[","]"],
2050 "anonhash" => ["{","}"]}->{$op->name}};
2051 my($expr, @exprs);
2052 $op = $op->first->sibling; # skip pushmark
2053 for (; !null($op); $op = $op->sibling) {
2054 $expr = $self->deparse($op, 6);
2055 push @exprs, $expr;
2056 }
d9002312
SM
2057 if ($pre eq "{" and $cx < 1) {
2058 # Disambiguate that it's not a block
2059 $pre = "+{";
2060 }
78c72037
NC
2061 return $pre . join(", ", @exprs) . $post;
2062}
2063
2064sub pp_anonlist {
d9002312
SM
2065 my $self = shift;
2066 my ($op, $cx) = @_;
78c72037 2067 if ($op->flags & OPf_SPECIAL) {
d9002312 2068 return $self->anon_hash_or_list($op, $cx);
78c72037
NC
2069 }
2070 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2071 return 'XXX';
2072}
2073
2074*pp_anonhash = \&pp_anonlist;
2075
6e90668e
SM
2076sub pp_refgen {
2077 my $self = shift;
9d2c6865 2078 my($op, $cx) = @_;
6e90668e 2079 my $kid = $op->first;
3f872cb9 2080 if ($kid->name eq "null") {
6e90668e 2081 $kid = $kid->first;
35925e80 2082 if (!null($kid->sibling) and
3f872cb9 2083 $kid->sibling->name eq "anoncode") {
09d856fb 2084 return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
3f872cb9
GS
2085 } elsif ($kid->name eq "pushmark") {
2086 my $sib_name = $kid->sibling->name;
2087 if ($sib_name =~ /^(pad|rv2)[ah]v$/
c8c62db7
AD
2088 and not $kid->sibling->flags & OPf_REF)
2089 {
2090 # The @a in \(@a) isn't in ref context, but only when the
2091 # parens are there.
127212b2 2092 return "\\(" . $self->pp_list($op->first) . ")";
3f872cb9 2093 } elsif ($sib_name eq 'entersub') {
c8c62db7
AD
2094 my $text = $self->deparse($kid->sibling, 1);
2095 # Always show parens for \(&func()), but only with -p otherwise
2096 $text = "($text)" if $self->{'parens'}
2097 or $kid->sibling->private & OPpENTERSUB_AMPER;
2098 return "\\$text";
2099 }
2100 }
6e90668e 2101 }
9d2c6865 2102 $self->pfixop($op, $cx, "\\", 20);
6e90668e
SM
2103}
2104
09d856fb
CK
2105sub e_anoncode {
2106 my ($self, $info) = @_;
2107 my $text = $self->deparse_sub($info->{code});
2108 return "sub " . $text;
2109}
2110
6e90668e
SM
2111sub pp_srefgen { pp_refgen(@_) }
2112
2113sub pp_readline {
2114 my $self = shift;
9d2c6865 2115 my($op, $cx) = @_;
6e90668e 2116 my $kid = $op->first;
3f872cb9 2117 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
e31885a0
RH
2118 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2119 return $self->unop($op, $cx, "readline");
6e90668e
SM
2120}
2121
ad8caead
RGS
2122sub pp_rcatline {
2123 my $self = shift;
2124 my($op) = @_;
d989cdac 2125 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
ad8caead
RGS
2126}
2127
bd0865ec
GS
2128# Unary operators that can occur as pseudo-listops inside double quotes
2129sub dq_unop {
2130 my $self = shift;
2131 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2132 my $kid;
2133 if ($op->flags & OPf_KIDS) {
2134 $kid = $op->first;
2135 # If there's more than one kid, the first is an ex-pushmark.
2136 $kid = $kid->sibling if not null $kid->sibling;
2137 return $self->maybe_parens_unop($name, $kid, $cx);
2138 } else {
d989cdac 2139 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
bd0865ec
GS
2140 }
2141}
2142
2143sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2144sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2145sub pp_uc { dq_unop(@_, "uc") }
2146sub pp_lc { dq_unop(@_, "lc") }
3ed82cfc 2147sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
838f2281 2148sub pp_fc { dq_unop(@_, "fc") }
bd0865ec 2149
6e90668e
SM
2150sub loopex {
2151 my $self = shift;
9d2c6865 2152 my ($op, $cx, $name) = @_;
6e90668e 2153 if (class($op) eq "PVOP") {
41df74e3 2154 $name .= " " . $op->pv;
9d2c6865 2155 } elsif (class($op) eq "OP") {
41df74e3 2156 # no-op
6e90668e 2157 } elsif (class($op) eq "UNOP") {
1eb0b7be 2158 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
41df74e3 2159 $name .= " $kid";
6e90668e 2160 }
1eb0b7be 2161 return $self->maybe_parens($name, $cx, 7);
6e90668e
SM
2162}
2163
2164sub pp_last { loopex(@_, "last") }
2165sub pp_next { loopex(@_, "next") }
2166sub pp_redo { loopex(@_, "redo") }
2167sub pp_goto { loopex(@_, "goto") }
266da325 2168sub pp_dump { loopex(@_, "CORE::dump") }
6e90668e
SM
2169
2170sub ftst {
2171 my $self = shift;
9d2c6865 2172 my($op, $cx, $name) = @_;
6e90668e 2173 if (class($op) eq "UNOP") {
e38ccfd9 2174 # Genuine '-X' filetests are exempt from the LLAFR, but not
5830412d
FC
2175 # l?stat()
2176 if ($name =~ /^-/) {
2177 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2178 return $self->maybe_parens("$name $kid", $cx, 16);
2179 }
9d2c6865 2180 return $self->maybe_parens_unop($name, $op->first, $cx);
d989cdac 2181 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
9d2c6865 2182 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
6e90668e 2183 } else { # I don't think baseop filetests ever survive ck_ftst, but...
9d2c6865 2184 return $name;
6e90668e 2185 }
6e90668e
SM
2186}
2187
d989cdac
SM
2188sub pp_lstat { ftst(@_, "lstat") }
2189sub pp_stat { ftst(@_, "stat") }
2190sub pp_ftrread { ftst(@_, "-R") }
6e90668e 2191sub pp_ftrwrite { ftst(@_, "-W") }
d989cdac
SM
2192sub pp_ftrexec { ftst(@_, "-X") }
2193sub pp_fteread { ftst(@_, "-r") }
e31885a0 2194sub pp_ftewrite { ftst(@_, "-w") }
d989cdac
SM
2195sub pp_fteexec { ftst(@_, "-x") }
2196sub pp_ftis { ftst(@_, "-e") }
6e90668e
SM
2197sub pp_fteowned { ftst(@_, "-O") }
2198sub pp_ftrowned { ftst(@_, "-o") }
d989cdac
SM
2199sub pp_ftzero { ftst(@_, "-z") }
2200sub pp_ftsize { ftst(@_, "-s") }
2201sub pp_ftmtime { ftst(@_, "-M") }
2202sub pp_ftatime { ftst(@_, "-A") }
2203sub pp_ftctime { ftst(@_, "-C") }
2204sub pp_ftsock { ftst(@_, "-S") }
2205sub pp_ftchr { ftst(@_, "-c") }
2206sub pp_ftblk { ftst(@_, "-b") }
2207sub pp_ftfile { ftst(@_, "-f") }
2208sub pp_ftdir { ftst(@_, "-d") }
2209sub pp_ftpipe { ftst(@_, "-p") }
2210sub pp_ftlink { ftst(@_, "-l") }
2211sub pp_ftsuid { ftst(@_, "-u") }
2212sub pp_ftsgid { ftst(@_, "-g") }
2213sub pp_ftsvtx { ftst(@_, "-k") }
2214sub pp_fttty { ftst(@_, "-t") }
2215sub pp_fttext { ftst(@_, "-T") }
6e90668e
SM
2216sub pp_ftbinary { ftst(@_, "-B") }
2217
a798dbf2 2218sub SWAP_CHILDREN () { 1 }
6e90668e 2219sub ASSIGN () { 2 } # has OP= variant
7013e6ae 2220sub LIST_CONTEXT () { 4 } # Assignment is in list context
6e90668e 2221
9d2c6865
SM
2222my(%left, %right);
2223
2224sub assoc_class {
2225 my $op = shift;
3f872cb9
GS
2226 my $name = $op->name;
2227 if ($name eq "concat" and $op->first->name eq "concat") {
e38ccfd9 2228 # avoid spurious '=' -- see comment in pp_concat
3f872cb9 2229 return "concat";
9d2c6865 2230 }
3f872cb9
GS
2231 if ($name eq "null" and class($op) eq "UNOP"
2232 and $op->first->name =~ /^(and|x?or)$/
9d2c6865
SM
2233 and null $op->first->sibling)
2234 {
2235 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2236 # with a null that's used as the common end point of the two
2237 # flows of control. For precedence purposes, ignore it.
2238 # (COND_EXPRs have these too, but we don't bother with
2239 # their associativity).
2240 return assoc_class($op->first);
2241 }
2242 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2243}
2244
e38ccfd9 2245# Left associative operators, like '+', for which
9d2c6865
SM
2246# $a + $b + $c is equivalent to ($a + $b) + $c
2247
2248BEGIN {
3f872cb9
GS
2249 %left = ('multiply' => 19, 'i_multiply' => 19,
2250 'divide' => 19, 'i_divide' => 19,
2251 'modulo' => 19, 'i_modulo' => 19,
2252 'repeat' => 19,
2253 'add' => 18, 'i_add' => 18,
2254 'subtract' => 18, 'i_subtract' => 18,
2255 'concat' => 18,
2256 'left_shift' => 17, 'right_shift' => 17,
2257 'bit_and' => 13,
2258 'bit_or' => 12, 'bit_xor' => 12,
2259 'and' => 3,
2260 'or' => 2, 'xor' => 2,
9d2c6865
SM
2261 );
2262}
2263
2264sub deparse_binop_left {
2265 my $self = shift;
2266 my($op, $left, $prec) = @_;
58231d39 2267 if ($left{assoc_class($op)} && $left{assoc_class($left)}
9d2c6865
SM
2268 and $left{assoc_class($op)} == $left{assoc_class($left)})
2269 {
2270 return $self->deparse($left, $prec - .00001);
2271 } else {
2272 return $self->deparse($left, $prec);
2273 }
2274}
2275
e38ccfd9 2276# Right associative operators, like '=', for which
9d2c6865
SM
2277# $a = $b = $c is equivalent to $a = ($b = $c)
2278
2279BEGIN {
3f872cb9
GS
2280 %right = ('pow' => 22,
2281 'sassign=' => 7, 'aassign=' => 7,
2282 'multiply=' => 7, 'i_multiply=' => 7,
2283 'divide=' => 7, 'i_divide=' => 7,
2284 'modulo=' => 7, 'i_modulo=' => 7,
2285 'repeat=' => 7,
2286 'add=' => 7, 'i_add=' => 7,
2287 'subtract=' => 7, 'i_subtract=' => 7,
2288 'concat=' => 7,
2289 'left_shift=' => 7, 'right_shift=' => 7,
2290 'bit_and=' => 7,
2291 'bit_or=' => 7, 'bit_xor=' => 7,
2292 'andassign' => 7,
2293 'orassign' => 7,
9d2c6865
SM
2294 );
2295}
2296
2297sub deparse_binop_right {
2298 my $self = shift;
2299 my($op, $right, $prec) = @_;
58231d39 2300 if ($right{assoc_class($op)} && $right{assoc_class($right)}
9d2c6865
SM
2301 and $right{assoc_class($op)} == $right{assoc_class($right)})
2302 {
2303 return $self->deparse($right, $prec - .00001);
2304 } else {
2305 return $self->deparse($right, $prec);
2306 }
2307}
2308
a798dbf2 2309sub binop {
6e90668e 2310 my $self = shift;
9d2c6865 2311 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
a798dbf2
MB
2312 my $left = $op->first;
2313 my $right = $op->last;
9d2c6865
SM
2314 my $eq = "";
2315 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2316 $eq = "=";
2317 $prec = 7;
2318 }
a798dbf2
MB
2319 if ($flags & SWAP_CHILDREN) {
2320 ($left, $right) = ($right, $left);
2321 }
9d2c6865 2322 $left = $self->deparse_binop_left($op, $left, $prec);
90c0eb26
RH
2323 $left = "($left)" if $flags & LIST_CONTEXT
2324 && $left !~ /^(my|our|local|)[\@\(]/;
9d2c6865
SM
2325 $right = $self->deparse_binop_right($op, $right, $prec);
2326 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2327}
2328
3ed82cfc
GS
2329sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2330sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2331sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2332sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2333sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2334sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2335sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2336sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2337sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2338sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2339sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2340
2341sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2342sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2343sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2344sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2345sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
9d2c6865
SM
2346
2347sub pp_eq { binop(@_, "==", 14) }
2348sub pp_ne { binop(@_, "!=", 14) }
2349sub pp_lt { binop(@_, "<", 15) }
2350sub pp_gt { binop(@_, ">", 15) }
2351sub pp_ge { binop(@_, ">=", 15) }
2352sub pp_le { binop(@_, "<=", 15) }
2353sub pp_ncmp { binop(@_, "<=>", 14) }
2354sub pp_i_eq { binop(@_, "==", 14) }
2355sub pp_i_ne { binop(@_, "!=", 14) }
2356sub pp_i_lt { binop(@_, "<", 15) }
2357sub pp_i_gt { binop(@_, ">", 15) }
2358sub pp_i_ge { binop(@_, ">=", 15) }
2359sub pp_i_le { binop(@_, "<=", 15) }
2360sub pp_i_ncmp { binop(@_, "<=>", 14) }
2361
2362sub pp_seq { binop(@_, "eq", 14) }
2363sub pp_sne { binop(@_, "ne", 14) }
2364sub pp_slt { binop(@_, "lt", 15) }
2365sub pp_sgt { binop(@_, "gt", 15) }
2366sub pp_sge { binop(@_, "ge", 15) }
2367sub pp_sle { binop(@_, "le", 15) }
2368sub pp_scmp { binop(@_, "cmp", 14) }
2369
2370sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
7013e6ae 2371sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
6e90668e 2372
0d863452
RH
2373sub pp_smartmatch {
2374 my ($self, $op, $cx) = @_;
2375 if ($op->flags & OPf_SPECIAL) {
9210de83 2376 return $self->deparse($op->last, $cx);
0d863452
RH
2377 }
2378 else {
2379 binop(@_, "~~", 14);
2380 }
2381}
2382
e38ccfd9 2383# '.' is special because concats-of-concats are optimized to save copying
6e90668e 2384# by making all but the first concat stacked. The effect is as if the
e38ccfd9 2385# programmer had written '($a . $b) .= $c', except legal.
3ed82cfc
GS
2386sub pp_concat { maybe_targmy(@_, \&real_concat) }
2387sub real_concat {
6e90668e 2388 my $self = shift;
9d2c6865 2389 my($op, $cx) = @_;
6e90668e
SM
2390 my $left = $op->first;
2391 my $right = $op->last;
2392 my $eq = "";
9d2c6865 2393 my $prec = 18;
3f872cb9 2394 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
6e90668e 2395 $eq = "=";
9d2c6865 2396 $prec = 7;
6e90668e 2397 }
9d2c6865
SM
2398 $left = $self->deparse_binop_left($op, $left, $prec);
2399 $right = $self->deparse_binop_right($op, $right, $prec);
2400 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
6e90668e
SM
2401}
2402
e38ccfd9 2403# 'x' is weird when the left arg is a list
6e90668e
SM
2404sub pp_repeat {
2405 my $self = shift;
9d2c6865 2406 my($op, $cx) = @_;
6e90668e
SM
2407 my $left = $op->first;
2408 my $right = $op->last;
9d2c6865
SM
2409 my $eq = "";
2410 my $prec = 19;
2411 if ($op->flags & OPf_STACKED) {
2412 $eq = "=";
2413 $prec = 7;
2414 }
6e90668e
SM
2415 if (null($right)) { # list repeat; count is inside left-side ex-list
2416 my $kid = $left->first->sibling; # skip pushmark
2417 my @exprs;
2418 for (; !null($kid->sibling); $kid = $kid->sibling) {
9d2c6865 2419 push @exprs, $self->deparse($kid, 6);
6e90668e
SM
2420 }
2421 $right = $kid;
2422 $left = "(" . join(", ", @exprs). ")";
2423 } else {
9d2c6865 2424 $left = $self->deparse_binop_left($op, $left, $prec);
6e90668e 2425 }
9d2c6865
SM
2426 $right = $self->deparse_binop_right($op, $right, $prec);
2427 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
6e90668e
SM
2428}
2429
2430sub range {
2431 my $self = shift;
9d2c6865 2432 my ($op, $cx, $type) = @_;
6e90668e
SM
2433 my $left = $op->first;
2434 my $right = $left->sibling;
9d2c6865
SM
2435 $left = $self->deparse($left, 9);
2436 $right = $self->deparse($right, 9);
2437 return $self->maybe_parens("$left $type $right", $cx, 9);
6e90668e
SM
2438}
2439
2440sub pp_flop {
2441 my $self = shift;
9d2c6865 2442 my($op, $cx) = @_;
6e90668e
SM
2443 my $flip = $op->first;
2444 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
9d2c6865 2445 return $self->range($flip->first, $cx, $type);
6e90668e
SM
2446}
2447
2448# one-line while/until is handled in pp_leave
2449
2450sub logop {
2451 my $self = shift;
9d2c6865 2452 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
6e90668e
SM
2453 my $left = $op->first;
2454 my $right = $op->first->sibling;
d989cdac 2455 if ($cx < 1 and is_scope($right) and $blockname
58cccf98
SM
2456 and $self->{'expand'} < 7)
2457 { # if ($a) {$b}
9d2c6865
SM
2458 $left = $self->deparse($left, 1);
2459 $right = $self->deparse($right, 0);
2460 return "$blockname ($left) {\n\t$right\n\b}\cK";
d989cdac 2461 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
58cccf98 2462 and $self->{'expand'} < 7) { # $b if $a
9d2c6865
SM
2463 $right = $self->deparse($right, 1);
2464 $left = $self->deparse($left, 1);
2465 return "$right $blockname $left";
2466 } elsif ($cx > $lowprec and $highop) { # $a && $b
2467 $left = $self->deparse_binop_left($op, $left, $highprec);
2468 $right = $self->deparse_binop_right($op, $right, $highprec);
2469 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2470 } else { # $a and $b
2471 $left = $self->deparse_binop_left($op, $left, $lowprec);
2472 $right = $self->deparse_binop_right($op, $right, $lowprec);
d989cdac 2473 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
9d2c6865
SM
2474 }
2475}
2476
2477sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
f4a44678 2478sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
5b99f273 2479sub pp_dor { logop(@_, "//", 10) }
3ed82cfc
GS
2480
2481# xor is syntactically a logop, but it's really a binop (contrary to
2482# old versions of opcode.pl). Syntax is what matters here.
9d2c6865 2483sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
6e90668e
SM
2484
2485sub logassignop {
2486 my $self = shift;
9d2c6865 2487 my ($op, $cx, $opname) = @_;
6e90668e
SM
2488 my $left = $op->first;
2489 my $right = $op->first->sibling->first; # skip sassign
9d2c6865
SM
2490 $left = $self->deparse($left, 7);
2491 $right = $self->deparse($right, 7);
2492 return $self->maybe_parens("$left $opname $right", $cx, 7);
a798dbf2
MB
2493}
2494
6e90668e 2495sub pp_andassign { logassignop(@_, "&&=") }
c963b151
BD
2496sub pp_orassign { logassignop(@_, "||=") }
2497sub pp_dorassign { logassignop(@_, "//=") }
6e90668e 2498
b89b7257
FC
2499sub rv2gv_or_string {
2500 my($self,$op) = @_;
2501 if ($op->name eq "gv") { # could be open("open") or open("###")
be6cf5cf 2502 my($name,$quoted) =
1db94eeb 2503 $self->stash_variable_name("", $self->gv_or_padgv($op));
be6cf5cf 2504 $quoted ? $name : "*$name";
b89b7257
FC
2505 }
2506 else {
2507 $self->deparse($op, 6);
2508 }
2509}
2510
6e90668e
SM
2511sub listop {
2512 my $self = shift;
9c56d9ea 2513 my($op, $cx, $name, $kid, $nollafr) = @_;
9d2c6865
SM
2514 my(@exprs);
2515 my $parens = ($cx >= 5) || $self->{'parens'};
24fcb59f 2516 $kid ||= $op->first->sibling;
4d8ac5c7
FC
2517 # If there are no arguments, add final parentheses (or parenthesize the
2518 # whole thing if the llafr does not apply) to account for cases like
2519 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
2520 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2521 if (null $kid) {
2522 return $nollafr
2523 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2524 : $self->keyword($name) . '()' x (7 < $cx);
2525 }
e31885a0 2526 my $first;
fb725297 2527 $name = "socketpair" if $name eq "sockpair";
4a1ac32e 2528 my $fullname = $self->keyword($name);
b72c97e8
RGS
2529 my $proto = prototype("CORE::$name");
2530 if (defined $proto
2531 && $proto =~ /^;?\*/
2462c3cc 2532 && $kid->name eq "rv2gv" && !($kid->private & OPpLVAL_INTRO)) {
b89b7257 2533 $first = $self->rv2gv_or_string($kid->first);
e31885a0
RH
2534 }
2535 else {
2536 $first = $self->deparse($kid, 6);
2537 }
e99ebc55 2538 if ($name eq "chmod" && $first =~ /^\d+$/) {
a0035eb8 2539 $first = sprintf("%#o", $first);
e99ebc55 2540 }
9c56d9ea
FC
2541 $first = "+$first"
2542 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
9d2c6865
SM
2543 push @exprs, $first;
2544 $kid = $kid->sibling;
564cd6cb
FC
2545 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2546 && !($kid->private & OPpLVAL_INTRO)) {
b89b7257 2547 push @exprs, $first = $self->rv2gv_or_string($kid->first);
b72c97e8
RGS
2548 $kid = $kid->sibling;
2549 }
9d2c6865
SM
2550 for (; !null($kid); $kid = $kid->sibling) {
2551 push @exprs, $self->deparse($kid, 6);
2552 }
689e417f 2553 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
4a1ac32e
FC
2554 return "$exprs[0] = $fullname"
2555 . ($parens ? "($exprs[0])" : " $exprs[0]");
689e417f 2556 }
9c56d9ea
FC
2557 if ($parens && $nollafr) {
2558 return "($fullname " . join(", ", @exprs) . ")";
2559 } elsif ($parens) {
4a1ac32e 2560 return "$fullname(" . join(", ", @exprs) . ")";
9d2c6865 2561 } else {
4a1ac32e 2562 return "$fullname " . join(", ", @exprs);
6e90668e 2563 }
6e90668e 2564}
a798dbf2 2565
6e90668e 2566sub pp_bless { listop(@_, "bless") }
3ed82cfc 2567sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
24fcb59f
FC
2568sub pp_substr {
2569 my ($self,$op,$cx) = @_;
2570 if ($op->private & OPpSUBSTR_REPL_FIRST) {
2571 return
2572 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2573 . " = "
2574 . $self->deparse($op->first->sibling, 7);
2575 }
2576 maybe_local(@_, listop(@_, "substr"))
2577}
6e90668e 2578sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
3ed82cfc
GS
2579sub pp_index { maybe_targmy(@_, \&listop, "index") }
2580sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2581sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
6e90668e 2582sub pp_formline { listop(@_, "formline") } # see also deparse_format
3ed82cfc 2583sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
6e90668e
SM
2584sub pp_unpack { listop(@_, "unpack") }
2585sub pp_pack { listop(@_, "pack") }
3ed82cfc 2586sub pp_join { maybe_targmy(@_, \&listop, "join") }
6e90668e 2587sub pp_splice { listop(@_, "splice") }
3ed82cfc
GS
2588sub pp_push { maybe_targmy(@_, \&listop, "push") }
2589sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
6e90668e
SM
2590sub pp_reverse { listop(@_, "reverse") }
2591sub pp_warn { listop(@_, "warn") }
2592sub pp_die { listop(@_, "die") }
9c56d9ea 2593sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
6e90668e
SM
2594sub pp_open { listop(@_, "open") }
2595sub pp_pipe_op { listop(@_, "pipe") }
2596sub pp_tie { listop(@_, "tie") }
82bafd27 2597sub pp_binmode { listop(@_, "binmode") }
6e90668e
SM
2598sub pp_dbmopen { listop(@_, "dbmopen") }
2599sub pp_sselect { listop(@_, "select") }
2600sub pp_select { listop(@_, "select") }
2601sub pp_read { listop(@_, "read") }
2602sub pp_sysopen { listop(@_, "sysopen") }
2603sub pp_sysseek { listop(@_, "sysseek") }
2604sub pp_sysread { listop(@_, "sysread") }
2605sub pp_syswrite { listop(@_, "syswrite") }
2606sub pp_send { listop(@_, "send") }
2607sub pp_recv { listop(@_, "recv") }
2608sub pp_seek { listop(@_, "seek") }
6e90668e
SM
2609sub pp_fcntl { listop(@_, "fcntl") }
2610sub pp_ioctl { listop(@_, "ioctl") }
3ed82cfc 2611sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
6e90668e
SM
2612sub pp_socket { listop(@_, "socket") }
2613sub pp_sockpair { listop(@_, "sockpair") }
2614sub pp_bind { listop(@_, "bind") }
2615sub pp_connect { listop(@_, "connect") }
2616sub pp_listen { listop(@_, "listen") }
2617sub pp_accept { listop(@_, "accept") }
2618sub pp_shutdown { listop(@_, "shutdown") }
2619sub pp_gsockopt { listop(@_, "getsockopt") }
2620sub pp_ssockopt { listop(@_, "setsockopt") }
3ed82cfc
GS
2621sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2622sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2623sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2624sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2625sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2626sub pp_link { maybe_targmy(@_, \&listop, "link") }
2627sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2628sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
6e90668e
SM
2629sub pp_open_dir { listop(@_, "opendir") }
2630sub pp_seekdir { listop(@_, "seekdir") }
3ed82cfc
GS
2631sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2632sub pp_system { maybe_targmy(@_, \&listop, "system") }
2633sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2634sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2635sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2636sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2637sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
6e90668e
SM
2638sub pp_shmget { listop(@_, "shmget") }
2639sub pp_shmctl { listop(@_, "shmctl") }
2640sub pp_shmread { listop(@_, "shmread") }
2641sub pp_shmwrite { listop(@_, "shmwrite") }
2642sub pp_msgget { listop(@_, "msgget") }
2643sub pp_msgctl { listop(@_, "msgctl") }
2644sub pp_msgsnd { listop(@_, "msgsnd") }
2645sub pp_msgrcv { listop(@_, "msgrcv") }
2646sub pp_semget { listop(@_, "semget") }
2647sub pp_semctl { listop(@_, "semctl") }
2648sub pp_semop { listop(@_, "semop") }
2649sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2650sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2651sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2652sub pp_gsbyname { listop(@_, "getservbyname") }
2653sub pp_gsbyport { listop(@_, "getservbyport") }
2654sub pp_syscall { listop(@_, "syscall") }
2655
2656sub pp_glob {
2657 my $self = shift;
9d2c6865 2658 my($op, $cx) = @_;
6e90668e 2659 my $text = $self->dq($op->first->sibling); # skip pushmark
a32fbbd8
FC
2660 my $keyword =
2661 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
6e90668e 2662 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
a32fbbd8
FC
2663 or $keyword =~ /^CORE::/
2664 or $text =~ /[<>]/) {
2665 return "$keyword(" . single_delim('qq', '"', $text) . ')';
6e90668e
SM
2666 } else {
2667 return '<' . $text . '>';
2668 }
2669}
2670
f5aa8f4e
SM
2671# Truncate is special because OPf_SPECIAL makes a bareword first arg
2672# be a filehandle. This could probably be better fixed in the core
2673# by moving the GV lookup into ck_truc.
2674
2675sub pp_truncate {
2676 my $self = shift;
2677 my($op, $cx) = @_;
2678 my(@exprs);
2679 my $parens = ($cx >= 5) || $self->{'parens'};
2680 my $kid = $op->first->sibling;
acba1d67 2681 my $fh;
f5aa8f4e
SM
2682 if ($op->flags & OPf_SPECIAL) {
2683 # $kid is an OP_CONST
18228111 2684 $fh = $self->const_sv($kid)->PV;
f5aa8f4e
SM
2685 } else {
2686 $fh = $self->deparse($kid, 6);
2687 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2688 }
2689 my $len = $self->deparse($kid->sibling, 6);
4a1ac32e 2690 my $name = $self->keyword('truncate');
f5aa8f4e 2691 if ($parens) {
4a1ac32e 2692 return "$name($fh, $len)";
f5aa8f4e 2693 } else {
4a1ac32e 2694 return "$name $fh, $len";
f5aa8f4e 2695 }
f5aa8f4e
SM
2696}
2697
6e90668e
SM
2698sub indirop {
2699 my $self = shift;
9d2c6865 2700 my($op, $cx, $name) = @_;
6e90668e 2701 my($expr, @exprs);
521795fe 2702 my $firstkid = my $kid = $op->first->sibling;
6e90668e
SM
2703 my $indir = "";
2704 if ($op->flags & OPf_STACKED) {
2705 $indir = $kid;
2706 $indir = $indir->first; # skip rv2gv
2707 if (is_scope($indir)) {
9d2c6865 2708 $indir = "{" . $self->deparse($indir, 0) . "}";
d989cdac 2709 $indir = "{;}" if $indir eq "{}";
c73811ab
RH
2710 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2711 $indir = $self->const_sv($indir)->PV;
6e90668e 2712 } else {
9d2c6865 2713 $indir = $self->deparse($indir, 24);
6e90668e
SM
2714 }
2715 $indir = $indir . " ";
2716 $kid = $kid->sibling;
2717 }
7e80da18 2718 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3ac6e0f9 2719 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
7e80da18
RH
2720 : '{$a <=> $b} ';
2721 }
3ac6e0f9 2722 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
7e80da18
RH
2723 $indir = '{$b cmp $a} ';
2724 }
6e90668e 2725 for (; !null($kid); $kid = $kid->sibling) {
521795fe 2726 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
6e90668e
SM
2727 push @exprs, $expr;
2728 }
4a1ac32e 2729 my $name2;
3ac6e0f9 2730 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
4a1ac32e 2731 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3ac6e0f9 2732 }
4a1ac32e 2733 else { $name2 = $self->keyword($name) }
2b6e98cb 2734 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3ac6e0f9 2735 return "$exprs[0] = $name2 $indir $exprs[0]";
2b6e98cb
DM
2736 }
2737
d989cdac 2738 my $args = $indir . join(", ", @exprs);
521795fe 2739 if ($indir ne "" && $name eq "sort") {
d989cdac
SM
2740 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2741 # give bareword warnings in that case. Therefore if context
2742 # requires, we'll put parens around the outside "(sort f 1, 2,
2743 # 3)". Unfortunately, we'll currently think the parens are
3c4b39be 2744 # necessary more often that they really are, because we don't
d989cdac
SM
2745 # distinguish which side of an assignment we're on.
2746 if ($cx >= 5) {
3ac6e0f9 2747 return "($name2 $args)";
d989cdac 2748 } else {
3ac6e0f9 2749 return "$name2 $args";
d989cdac 2750 }
521795fe
FC
2751 } elsif (
2752 !$indir && $name eq "sort"
2753 && $op->first->sibling->name eq 'entersub'
2754 ) {
2755 # We cannot say sort foo(bar), as foo will be interpreted as a
2756 # comparison routine. We have to say sort(...) in that case.
2757 return "$name2($args)";
d989cdac 2758 } else {
3ac6e0f9 2759 return $self->maybe_parens_func($name2, $args, $cx, 5);
d989cdac
SM
2760 }
2761
6e90668e
SM
2762}
2763
2764sub pp_prtf { indirop(@_, "printf") }
2765sub pp_print { indirop(@_, "print") }
9b08e3d3 2766sub pp_say { indirop(@_, "say") }
6e90668e
SM
2767sub pp_sort { indirop(@_, "sort") }
2768
2769sub mapop {
2770 my $self = shift;
9d2c6865 2771 my($op, $cx, $name) = @_;
6e90668e
SM
2772 my($expr, @exprs);
2773 my $kid = $op->first; # this is the (map|grep)start
2774 $kid = $kid->first->sibling; # skip a pushmark
2775 my $code = $kid->first; # skip a null
2776 if (is_scope $code) {
f4a44678 2777 $code = "{" . $self->deparse($code, 0) . "} ";
6e90668e 2778 } else {
9d2c6865 2779 $code = $self->deparse($code, 24) . ", ";
6e90668e
SM
2780 }
2781 $kid = $kid->sibling;
2782 for (; !null($kid); $kid = $kid->sibling) {
9d2c6865 2783 $expr = $self->deparse($kid, 6);
9a58b761 2784 push @exprs, $expr if defined $expr;
6e90668e 2785 }
9d2c6865 2786 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
6e90668e
SM
2787}
2788
d989cdac
SM
2789sub pp_mapwhile { mapop(@_, "map") }
2790sub pp_grepwhile { mapop(@_, "grep") }
11e09183
SP
2791sub pp_mapstart { baseop(@_, "map") }
2792sub pp_grepstart { baseop(@_, "grep") }
6e90668e
SM
2793
2794sub pp_list {
2795 my $self = shift;
9d2c6865 2796 my($op, $cx) = @_;
6e90668e
SM
2797 my($expr, @exprs);
2798 my $kid = $op->first->sibling; # skip pushmark
958ed56b 2799 return '' if class($kid) eq 'NULL';
6e90668e 2800 my $lop;
3462b4ac 2801 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
6e90668e
SM
2802 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2803 # This assumes that no other private flags equal 128, and that
2804 # OPs that store things other than flags in their op_private,
2805 # like OP_AELEMFAST, won't be immediate children of a list.
b8e103fc
RH
2806 #
2807 # OP_ENTERSUB can break this logic, so check for it.
2808 # I suspect that open and exit can too.
2809
2810 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
ce4e655d 2811 or $lop->name eq "undef")
b8e103fc
RH
2812 or $lop->name eq "entersub"
2813 or $lop->name eq "exit"
2814 or $lop->name eq "open")
6e90668e
SM
2815 {
2816 $local = ""; # or not
2817 last;
2818 }
3462b4ac
RGS
2819 if ($lop->name =~ /^pad[ash]v$/) {
2820 if ($lop->private & OPpPAD_STATE) { # state()
2821 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2822 $local = "state";
2823 } else { # my()
2824 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2825 $local = "my";
2826 }
b8e103fc
RH
2827 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2828 && $lop->private & OPpOUR_INTRO
2829 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2830 && $lop->first->private & OPpOUR_INTRO) { # our()
3462b4ac 2831 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
ce4e655d 2832 $local = "our";
3ac6e0f9
RGS
2833 } elsif ($lop->name ne "undef"
2834 # specifically avoid the "reverse sort" optimisation,
2835 # where "reverse" is nullified
36d57d93 2836 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
3ac6e0f9
RGS
2837 {
2838 # local()
3462b4ac 2839 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
6e90668e
SM
2840 $local = "local";
2841 }
2842 }
2843 $local = "" if $local eq "either"; # no point if it's all undefs
f5aa8f4e 2844 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
6e90668e
SM
2845 for (; !null($kid); $kid = $kid->sibling) {
2846 if ($local) {
3f872cb9 2847 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
6e90668e
SM
2848 $lop = $kid->first;
2849 } else {
2850 $lop = $kid;
2851 }
2852 $self->{'avoid_local'}{$$lop}++;
9d2c6865 2853 $expr = $self->deparse($kid, 6);
6e90668e
SM
2854 delete $self->{'avoid_local'}{$$lop};
2855 } else {
9d2c6865 2856 $expr = $self->deparse($kid, 6);
6e90668e
SM
2857 }
2858 push @exprs, $expr;
2859 }
9d2c6865
SM
2860 if ($local) {
2861 return "$local(" . join(", ", @exprs) . ")";
2862 } else {
2863 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2864 }
6e90668e
SM
2865}
2866
6f611a1a
GS
2867sub is_ifelse_cont {
2868 my $op = shift;
2869 return ($op->name eq "null" and class($op) eq "UNOP"
2870 and $op->first->name =~ /^(and|cond_expr)$/
2871 and is_scope($op->first->first->sibling));
2872}
2873
6e90668e
SM
2874sub pp_cond_expr {
2875 my $self = shift;
9d2c6865 2876 my($op, $cx) = @_;
6e90668e
SM
2877 my $cond = $op->first;
2878 my $true = $cond->sibling;
2879 my $false = $true->sibling;
9d2c6865 2880 my $cuddle = $self->{'cuddle'};
d989cdac 2881 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
58cccf98
SM
2882 (is_scope($false) || is_ifelse_cont($false))
2883 and $self->{'expand'} < 7) {
f5aa8f4e 2884 $cond = $self->deparse($cond, 8);
cfaba469 2885 $true = $self->deparse($true, 6);
9d2c6865
SM
2886 $false = $self->deparse($false, 8);
2887 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
6f611a1a
GS
2888 }
2889
f5aa8f4e 2890 $cond = $self->deparse($cond, 1);
d989cdac 2891 $true = $self->deparse($true, 0);
6f611a1a
GS
2892 my $head = "if ($cond) {\n\t$true\n\b}";
2893 my @elsifs;
2894 while (!null($false) and is_ifelse_cont($false)) {
2895 my $newop = $false->first;
2896 my $newcond = $newop->first;
2897 my $newtrue = $newcond->sibling;
2898 $false = $newtrue->sibling; # last in chain is OP_AND => no else
7ecdd211
PJ
2899 if ($newcond->name eq "lineseq")
2900 {
2901 # lineseq to ensure correct line numbers in elsif()
2902 # Bug #37302 fixed by change #33710.
2903 $newcond = $newcond->first->sibling;
2904 }
6f611a1a
GS
2905 $newcond = $self->deparse($newcond, 1);
2906 $newtrue = $self->deparse($newtrue, 0);
2907 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2908 }
d989cdac 2909 if (!null($false)) {
6f611a1a
GS
2910 $false = $cuddle . "else {\n\t" .
2911 $self->deparse($false, 0) . "\n\b}\cK";
2912 } else {
2913 $false = "\cK";
6e90668e 2914 }
d989cdac 2915 return $head . join($cuddle, "", @elsifs) . $false;
6e90668e
SM
2916}
2917
95562366
NC
2918sub pp_once {
2919 my ($self, $op, $cx) = @_;
2920 my $cond = $op->first;
2921 my $true = $cond->sibling;
2922
2923 return $self->deparse($true, $cx);
2924}
2925
58cccf98 2926sub loop_common {
6e90668e 2927 my $self = shift;
58cccf98 2928 my($op, $cx, $init) = @_;
6e90668e
SM
2929 my $enter = $op->first;
2930 my $kid = $enter->sibling;
0ced6c29
RGS
2931 local(@$self{qw'curstash warnings hints hinthash'})
2932 = @$self{qw'curstash warnings hints hinthash'};
6e90668e 2933 my $head = "";
9d2c6865 2934 my $bare = 0;
58cccf98
SM
2935 my $body;
2936 my $cond = undef;
d989cdac 2937 if ($kid->name eq "lineseq") { # bare or infinite loop
241416b8 2938 if ($kid->last->name eq "unstack") { # infinite
e99ebc55 2939 $head = "while (1) "; # Can't use for(;;) if there's a continue
58cccf98 2940 $cond = "";
9d2c6865
SM
2941 } else {
2942 $bare = 1;
6e90668e 2943 }
58cccf98 2944 $body = $kid;
3f872cb9 2945 } elsif ($enter->name eq "enteriter") { # foreach
6e90668e
SM
2946 my $ary = $enter->first->sibling; # first was pushmark
2947 my $var = $ary->sibling;
36d57d93
RGS
2948 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2949 # "reverse" was optimised away
aae53c41 2950 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
36d57d93 2951 } elsif ($enter->flags & OPf_STACKED
f5aa8f4e
SM
2952 and not null $ary->first->sibling->sibling)
2953 {
d7f5b6da
SM
2954 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2955 $self->deparse($ary->first->sibling->sibling, 9);
d8d95777
GA
2956 } else {
2957 $ary = $self->deparse($ary, 1);
2958 }
6e90668e 2959 if (null $var) {
823eff14
NC
2960 if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2961 # thread special var, under 5005threads
9d2c6865 2962 $var = $self->pp_threadsv($enter, 1);
f6f9bdb7 2963 } else { # regular my() variable
9d2c6865 2964 $var = $self->pp_padsv($enter, 1);
6e90668e 2965 }
3f872cb9 2966 } elsif ($var->name eq "rv2gv") {
9d2c6865 2967 $var = $self->pp_rv2sv($var, 1);
241416b8
DM
2968 if ($enter->private & OPpOUR_INTRO) {
2969 # our declarations don't have package names
2970 $var =~ s/^(.).*::/$1/;
2971 $var = "our $var";
2972 }
3f872cb9 2973 } elsif ($var->name eq "gv") {
9d2c6865 2974 $var = "\$" . $self->deparse($var, 1);
6e90668e 2975 }
58cccf98 2976 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
afb60448 2977 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
cf24a840
SM
2978 confess unless $var eq '$_';
2979 $body = $body->first;
2980 return $self->deparse($body, 2) . " foreach ($ary)";
2981 }
2982 $head = "foreach $var ($ary) ";
3f872cb9 2983 } elsif ($kid->name eq "null") { # while/until
6e90668e 2984 $kid = $kid->first;
58cccf98
SM
2985 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2986 $cond = $self->deparse($kid->first, 1);
2987 $head = "$name ($cond) ";
2988 $body = $kid->first->sibling;
3f872cb9 2989 } elsif ($kid->name eq "stub") { # bare and empty
9d2c6865 2990 return "{;}"; # {} could be a hashref
6e90668e 2991 }
58cccf98 2992 # If there isn't a continue block, then the next pointer for the loop
241416b8 2993 # will point to the unstack, which is kid's last child, except
58cccf98 2994 # in a bare loop, when it will point to the leaveloop. When neither of
241416b8 2995 # these conditions hold, then the second-to-last child is the continue
58cccf98
SM
2996 # block (or the last in a bare loop).
2997 my $cont_start = $enter->nextop;
2998 my $cont;
241416b8 2999 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
58cccf98
SM
3000 if ($bare) {
3001 $cont = $body->last;
3002 } else {
3003 $cont = $body->first;
241416b8 3004 while (!null($cont->sibling->sibling)) {
58cccf98
SM
3005 $cont = $cont->sibling;
3006 }
3007 }
3008 my $state = $body->first;
3009 my $cuddle = $self->{'cuddle'};
3010 my @states;
3011 for (; $$state != $$cont; $state = $state->sibling) {
3012 push @states, $state;
3013 }
ce4e655d 3014 $body = $self->lineseq(undef, @states);
58cccf98
SM
3015 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3016 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3017 $cont = "\cK";
3018 } else {
3019 $cont = $cuddle . "continue {\n\t" .
3020 $self->deparse($cont, 0) . "\n\b}\cK";
6e90668e 3021 }
6e90668e 3022 } else {
7a9b44b9 3023 return "" if !defined $body;
c73811ab
RH
3024 if (length $init) {
3025 $head = "for ($init; $cond;) ";
3026 }
9d2c6865 3027 $cont = "\cK";
58cccf98 3028 $body = $self->deparse($body, 0);
6e90668e 3029 }
ce4e655d 3030 $body =~ s/;?$/;\n/;
34a48b4b
RH
3031
3032 return $head . "{\n\t" . $body . "\b}" . $cont;
58cccf98
SM
3033}
3034
09d856fb 3035sub pp_leaveloop { shift->loop_common(@_, "") }
58cccf98
SM
3036
3037sub for_loop {
3038 my $self = shift;
3039 my($op, $cx) = @_;
3040 my $init = $self->deparse($op, 1);
eae48c89
Z
3041 my $s = $op->sibling;
3042 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3043 return $self->loop_common($ll, $cx, $init);
6e90668e
SM
3044}
3045
3046sub pp_leavetry {
3047 my $self = shift;
9d2c6865 3048 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
bd0865ec 3049}
6e90668e 3050
a3ba843f
FC
3051BEGIN { for (qw[ const stringify rv2sv list glob ]) {
3052 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
3053}}
f5aa8f4e 3054
a798dbf2 3055sub pp_null {
6e90668e 3056 my $self = shift;
d989cdac 3057 my($op, $cx) = @_;
6e90668e 3058 if (class($op) eq "OP") {
f4a44678
SM
3059 # old value is lost
3060 return $self->{'ex_const'} if $op->targ == OP_CONST;
3f872cb9 3061 } elsif ($op->first->name eq "pushmark") {
9d2c6865 3062 return $self->pp_list($op, $cx);
3f872cb9 3063 } elsif ($op->first->name eq "enter") {
9d2c6865 3064 return $self->pp_leave($op, $cx);
31c6271a
RD
3065 } elsif ($op->first->name eq "leave") {
3066 return $self->pp_leave($op->first, $cx);
3067 } elsif ($op->first->name eq "scope") {
3068 return $self->pp_scope($op->first, $cx);
bd0865ec 3069 } elsif ($op->targ == OP_STRINGIFY) {
6f611a1a 3070 return $self->dquote($op, $cx);
f4002a4b
FC
3071 } elsif ($op->targ == OP_GLOB) {
3072 return $self->pp_glob(
3073 $op->first # entersub
3074 ->first # ex-list
3075 ->first # pushmark
3076 ->sibling, # glob
3077 $cx
3078 );
6e90668e 3079 } elsif (!null($op->first->sibling) and
3f872cb9 3080 $op->first->sibling->name eq "readline" and
6e90668e 3081 $op->first->sibling->flags & OPf_STACKED) {
9d2c6865
SM
3082 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3083 . $self->deparse($op->first->sibling, 7),
3084 $cx, 7);
6e90668e 3085 } elsif (!null($op->first->sibling) and
3f872cb9 3086 $op->first->sibling->name eq "trans" and
6e90668e 3087 $op->first->sibling->flags & OPf_STACKED) {
9d2c6865
SM
3088 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3089 . $self->deparse($op->first->sibling, 20),
3090 $cx, 20);
d989cdac
SM
3091 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3092 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
ad8caead
RGS
3093 } elsif (!null($op->first->sibling) and
3094 $op->first->sibling->name eq "null" and
3095 class($op->first->sibling) eq "UNOP" and
3096 $op->first->sibling->first->flags & OPf_STACKED and
3097 $op->first->sibling->first->name eq "rcatline") {
3098 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3099 . $self->deparse($op->first->sibling, 18),
3100 $cx, 18);
6e90668e 3101 } else {
9d2c6865 3102 return $self->deparse($op->first, $cx);
6e90668e 3103 }
a798dbf2
MB
3104}
3105
6e90668e
SM
3106sub padname {
3107 my $self = shift;
3108 my $targ = shift;
68223ea3 3109 return $self->padname_sv($targ)->PVX;
6e90668e
SM
3110}
3111
3112sub padany {
3113 my $self = shift;
3114 my $op = shift;
3115 return substr($self->padname($op->targ), 1); # skip $/@/%
3116}
3117
3118sub pp_padsv {
3119 my $self = shift;
9d2c6865
SM
3120 my($op, $cx) = @_;
3121 return $self->maybe_my($op, $cx, $self->padname($op->targ));
6e90668e
SM
3122}
3123
3124sub pp_padav { pp_padsv(@_) }
3125sub pp_padhv { pp_padsv(@_) }
3126
e0ab66ad 3127my @threadsv_names = B::threadsv_names;
f6f9bdb7
SM
3128sub pp_threadsv {
3129 my $self = shift;
9d2c6865
SM
3130 my($op, $cx) = @_;
3131 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
d989cdac 3132}
f6f9bdb7 3133
6f611a1a 3134sub gv_or_padgv {
18228111
GS
3135 my $self = shift;
3136 my $op = shift;
6f611a1a
GS
3137 if (class($op) eq "PADOP") {
3138 return $self->padval($op->padix);
3139 } else { # class($op) eq "SVOP"
3140 return $op->gv;
18228111 3141 }
18228111
GS
3142}
3143
6e90668e
SM
3144sub pp_gvsv {
3145 my $self = shift;
9d2c6865 3146 my($op, $cx) = @_;
6f611a1a 3147 my $gv = $self->gv_or_padgv($op);
8510e997 3148 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
bb8996b8 3149 $self->gv_name($gv), $cx));
6e90668e
SM
3150}
3151
3152sub pp_gv {
3153 my $self = shift;
9d2c6865 3154 my($op, $cx) = @_;
6f611a1a 3155 my $gv = $self->gv_or_padgv($op);
18228111 3156 return $self->gv_name($gv);
6e90668e
SM
3157}
3158
93bad3fd
NC
3159sub pp_aelemfast_lex {
3160 my $self = shift;
3161 my($op, $cx) = @_;
3162 my $name = $self->padname($op->targ);
3163 $name =~ s/^@/\$/;
bc6b2ef6 3164 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
93bad3fd
NC
3165}
3166
6e90668e
SM
3167sub pp_aelemfast {
3168 my $self = shift;
9d2c6865 3169 my($op, $cx) = @_;
93bad3fd
NC
3170 # optimised PADAV, pre 5.15
3171 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
ce4e655d 3172
93bad3fd 3173 my $gv = $self->gv_or_padgv($op);
be6cf5cf
FC
3174 my($name,$quoted) = $self->stash_variable_name('@',$gv);
3175 $name = $quoted ? "$name->" : '$' . $name;
bc6b2ef6 3176 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
6e90668e
SM
3177}
3178
3179sub rv2x {
3180 my $self = shift;
9d2c6865 3181 my($op, $cx, $type) = @_;
90c0eb26
RH
3182
3183 if (class($op) eq 'NULL' || !$op->can("first")) {
ff97752d 3184 carp("Unexpected op in pp_rv2x");
90c0eb26
RH
3185 return 'XXX';
3186 }
6e90668e 3187 my $kid = $op->first;
d989cdac 3188 if ($kid->name eq "gv") {
bb8996b8 3189 return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
d989cdac
SM
3190 } elsif (is_scalar $kid) {
3191 my $str = $self->deparse($kid, 0);
3192 if ($str =~ /^\$([^\w\d])\z/) {
3193 # "$$+" isn't a legal way to write the scalar dereference
3194 # of $+, since the lexer can't tell you aren't trying to
3195 # do something like "$$ + 1" to get one more than your
3196 # PID. Either "${$+}" or "$${+}" are workable
3197 # disambiguations, but if the programmer did the former,
3198 # they'd be in the "else" clause below rather than here.
3199 # It's not clear if this should somehow be unified with
3200 # the code in dq and re_dq that also adds lexer
3201 # disambiguation braces.
3202 $str = '$' . "{$1}"; #'
3203 }
3204 return $type . $str;
3205 } else {
3206 return $type . "{" . $self->deparse($kid, 0) . "}";
3207 }
6e90668e
SM
3208}
3209
3210sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3211sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3212sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3213
3214# skip rv2av
3215sub pp_av2arylen {
3216 my $self = shift;
9d2c6865 3217 my($op, $cx) = @_;
3f872cb9 3218 if ($op->first->name eq "padav") {
9d2c6865 3219 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
6e90668e 3220 } else {
f5aa8f4e
SM
3221 return $self->maybe_local($op, $cx,
3222 $self->rv2x($op->first, $cx, '$#'));
6e90668e
SM
3223 }
3224}
3225
3226# skip down to the old, ex-rv2cv
90c0eb26
RH
3227sub pp_rv2cv {
3228 my ($self, $op, $cx) = @_;
3229 if (!null($op->first) && $op->first->name eq 'null' &&
3230 $op->first->targ eq OP_LIST)
3231 {
3232 return $self->rv2x($op->first->first->sibling, $cx, "&")
3233 }
3234 else {
3235 return $self->rv2x($op, $cx, "")
3236 }
3237}
6e90668e 3238
d989cdac
SM
3239sub list_const {
3240 my $self = shift;
3241 my($cx, @list) = @_;
3242 my @a = map $self->const($_, 6), @list;
3243 if (@a == 0) {
3244 return "()";
3245 } elsif (@a == 1) {
3246 return $a[0];
3247 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3248 # collapse (-1,0,1,2) into (-1..2)
3249 my ($s, $e) = @a[0,-1];
3250 my $i = $s;
3251 return $self->maybe_parens("$s..$e", $cx, 9)
3252 unless grep $i++ != $_, @a;
3253 }
3254 return $self->maybe_parens(join(", ", @a), $cx, 6);
3255}
3256
6e90668e
SM
3257sub pp_rv2av {
3258 my $self = shift;
9d2c6865 3259 my($op, $cx) = @_;
6e90668e 3260 my $kid = $op->first;
3f872cb9 3261 if ($kid->name eq "const") { # constant list
18228111 3262 my $av = $self->const_sv($kid);
d989cdac 3263 return $self->list_const($cx, $av->ARRAY);
6e90668e 3264 } else {
9d2c6865 3265 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
6e90668e
SM
3266 }
3267 }
3268
3ed82cfc
GS
3269sub is_subscriptable {
3270 my $op = shift;
3271 if ($op->name =~ /^[ahg]elem/) {
3272 return 1;
3273 } elsif ($op->name eq "entersub") {
3274 my $kid = $op->first;
3275 return 0 unless null $kid->sibling;
3276 $kid = $kid->first;
3277 $kid = $kid->sibling until null $kid->sibling;
3278 return 0 if is_scope($kid);
3279 $kid = $kid->first;
3280 return 0 if $kid->name eq "gv";
3281 return 0 if is_scalar($kid);
3282 return is_subscriptable($kid);
3283 } else {
3284 return 0;
3285 }
3286}
6e90668e 3287
21b7468a
BL
3288sub elem_or_slice_array_name
3289{
6e90668e 3290 my $self = shift;
21b7468a
BL
3291 my ($array, $left, $padname, $allow_arrow) = @_;
3292
3f872cb9 3293 if ($array->name eq $padname) {
21b7468a 3294 return $self->padany($array);
6e90668e 3295 } elsif (is_scope($array)) { # ${expr}[0]
21b7468a 3296 return "{" . $self->deparse($array, 0) . "}";
ce4e655d 3297 } elsif ($array->name eq "gv") {
10e8e32b
FC
3298 ($array, my $quoted) =
3299 $self->stash_variable_name(
3300 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3301 );
3302 if (!$allow_arrow && $quoted) {
3303 # This cannot happen.
3304 die "Invalid variable name $array for slice";
ce4e655d 3305 }
10e8e32b 3306 return $quoted ? "$array->" : $array;
21b7468a
BL
3307 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3308 return $self->deparse($array, 24);
6e90668e 3309 } else {
21b7468a 3310 return undef;
6e90668e 3311 }
21b7468a
BL
3312}
3313
3314sub elem_or_slice_single_index
3315{
3316 my $self = shift;
3317 my ($idx) = @_;
3318
9d2c6865 3319 $idx = $self->deparse($idx, 1);
7a9b44b9
RH
3320
3321 # Outer parens in an array index will confuse perl
3322 # if we're interpolating in a regular expression, i.e.
3323 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3324 #
3325 # If $self->{parens}, then an initial '(' will
3326 # definitely be paired with a final ')'. If
3327 # !$self->{parens}, the misleading parens won't
3328 # have been added in the first place.
3329 #
3330 # [You might think that we could get "(...)...(...)"
3331 # where the initial and final parens do not match
3332 # each other. But we can't, because the above would
3333 # only happen if there's an infix binop between the
3334 # two pairs of parens, and *that* means that the whole
3335 # expression would be parenthesized as well.]
3336 #
3337 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3338
098251bc
RH
3339 # Hash-element braces will autoquote a bareword inside themselves.
3340 # We need to make sure that C<$hash{warn()}> doesn't come out as
3341 # C<$hash{warn}>, which has a quite different meaning. Currently
3342 # B::Deparse will always quote strings, even if the string was a
3343 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3344 # for constant strings.) So we can cheat slightly here - if we see
3345 # a bareword, we know that it is supposed to be a function call.
3346 #
3347 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3348
21b7468a
BL
3349 return $idx;
3350}
3351
3352sub elem {
3353 my $self = shift;
3354 my ($op, $cx, $left, $right, $padname) = @_;
3355 my($array, $idx) = ($op->first, $op->first->sibling);
3356
3357 $idx = $self->elem_or_slice_single_index($idx);
3358
3359 unless ($array->name eq $padname) { # Maybe this has been fixed
3360 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3361 }
3362 if (my $array_name=$self->elem_or_slice_array_name
3363 ($array, $left, $padname, 1)) {
10e8e32b
FC
3364 return ($array_name =~ /->\z/ ? $array_name : "\$" . $array_name)
3365 . $left . $idx . $right;
21b7468a
BL
3366 } else {
3367 # $x[20][3]{hi} or expr->[20]
3368 my $arrow = is_subscriptable($array) ? "" : "->";
3369 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3370 }
3371
6e90668e
SM
3372}
3373
3f872cb9
GS
3374sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3375sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
6e90668e
SM
3376
3377sub pp_gelem {
3378 my $self = shift;
9d2c6865 3379 my($op, $cx) = @_;
6e90668e
SM
3380 my($glob, $part) = ($op->first, $op->last);
3381 $glob = $glob->first; # skip rv2gv
3f872cb9 3382 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
9d2c6865
SM
3383 my $scope = is_scope($glob);
3384 $glob = $self->deparse($glob, 0);
3385 $part = $self->deparse($part, 1);
6e90668e
SM
3386 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3387}
3388
3389sub slice {
3390 my $self = shift;
9d2c6865 3391 my ($op, $cx, $left, $right, $regname, $padname) = @_;
6e90668e
SM
3392 my $last;
3393 my(@elems, $kid, $array, $list);
3394 if (class($op) eq "LISTOP") {
3395 $last = $op->last;
3396 } else { # ex-hslice inside delete()
3397 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3398 $last = $kid;
3399 }
3400 $array = $last;
3401 $array = $array->first
3f872cb9 3402 if $array->name eq $regname or $array->name eq "null";
21b7468a 3403 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
6e90668e 3404 $kid = $op->first->sibling; # skip pushmark
3f872cb9 3405 if ($kid->name eq "list") {
6e90668e
SM
3406 $kid = $kid->first->sibling; # skip list, pushmark
3407 for (; !null $kid; $kid = $kid->sibling) {