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