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