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