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