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