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