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