This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
add Porting/bench.pl
[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);
59f8d31d 24$VERSION = '1.31';
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 326BEGIN { for (qw[ const stringify rv2sv list glob pushmark null aelem
34b54951 327 custom nextstate dbstate ]) {
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
7d6c333c 566 for ($svop=$svop->sibling; index($svop->name, "method_") != 0;
6ec152c3 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 978 my $txt = shift;
4b1385ee
FC
979 # Handle semicolons after sub declarations. There will be a \0 marker
980 # after each sequence of subs. This:
981 # sub {
982 # ....
983 # }
984 # \0;
985 # needs to have the "\n\0;" removed, but the \n should be left if the
986 # semicolon is not followed by one.
987 $txt =~ s/(?<=\})(\n?)\0;(\n?)/$1 || $2 ? "\n" : ""/egg;
988 # Remove any remaining markers
989 $txt =~ y/\0//d;
6e90668e
SM
990 my @lines = split(/\n/, $txt);
991 my $leader = "";
f4a44678 992 my $level = 0;
6e90668e
SM
993 my $line;
994 for $line (@lines) {
f4a44678
SM
995 my $cmd = substr($line, 0, 1);
996 if ($cmd eq "\t" or $cmd eq "\b") {
997 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
998 if ($self->{'use_tabs'}) {
999 $leader = "\t" x ($level / 8) . " " x ($level % 8);
1000 } else {
1001 $leader = " " x $level;
1002 }
6e90668e
SM
1003 $line = substr($line, 1);
1004 }
f2734596 1005 if (index($line, "\f") > 0) {
1006 $line =~ s/\f/\n/;
1007 }
f5aa8f4e
SM
1008 if (substr($line, 0, 1) eq "\f") {
1009 $line = substr($line, 1); # no indent
1010 } else {
1011 $line = $leader . $line;
1012 }
9d2c6865 1013 $line =~ s/\cK;?//g;
6e90668e
SM
1014 }
1015 return join("\n", @lines);
1016}
1017
6e90668e
SM
1018sub deparse_sub {
1019 my $self = shift;
1020 my $cv = shift;
1021 my $proto = "";
ce4e655d 1022Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
34a48b4b
RH
1023Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1024 local $self->{'curcop'} = $self->{'curcop'};
6e90668e
SM
1025 if ($cv->FLAGS & SVf_POK) {
1026 $proto = "(". $cv->PV . ") ";
1027 }
aa381260 1028 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
6aaf4108
SC
1029 $proto .= ": ";
1030 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
aa381260 1031 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
6aaf4108
SC
1032 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
1033 }
1034
6e90668e 1035 local($self->{'curcv'}) = $cv;
8510e997 1036 local($self->{'curcvlex'});
0ced6c29
RGS
1037 local(@$self{qw'curstash warnings hints hinthash'})
1038 = @$self{qw'curstash warnings hints hinthash'};
ce4e655d 1039 my $body;
a7fd8ef6
DM
1040 my $root = $cv->ROOT;
1041 local $B::overlay = {};
1042 if (not null $root) {
1043 $self->pessimise($root, $cv->START);
1044 my $lineseq = $root->first;
ce4e655d
RH
1045 if ($lineseq->name eq "lineseq") {
1046 my @ops;
1047 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
1048 push @ops, $o;
1049 }
93a8ff62 1050 $body = $self->lineseq(undef, 0, @ops).";";
ce4e655d
RH
1051 my $scope_en = $self->find_scope_en($lineseq);
1052 if (defined $scope_en) {
1053 my $subs = join"", $self->seq_subs($scope_en);
1054 $body .= ";\n$subs" if length($subs);
1055 }
1056 }
1057 else {
a7fd8ef6 1058 $body = $self->deparse($root->first, 0);
ce4e655d 1059 }
de3f1649 1060 }
ce4e655d
RH
1061 else {
1062 my $sv = $cv->const_sv;
1063 if ($$sv) {
1064 # uh-oh. inlinable sub... format it differently
d989cdac 1065 return $proto . "{ " . $self->const($sv, 0) . " }\n";
ce4e655d
RH
1066 } else { # XSUB? (or just a declaration)
1067 return "$proto;\n";
1068 }
6e90668e 1069 }
ce4e655d 1070 return $proto ."{\n\t$body\n\b}" ."\n";
6e90668e
SM
1071}
1072
1073sub deparse_format {
1074 my $self = shift;
1075 my $form = shift;
1076 my @text;
1077 local($self->{'curcv'}) = $form;
8510e997 1078 local($self->{'curcvlex'});
67fc2416 1079 local($self->{'in_format'}) = 1;
0ced6c29
RGS
1080 local(@$self{qw'curstash warnings hints hinthash'})
1081 = @$self{qw'curstash warnings hints hinthash'};
6e90668e 1082 my $op = $form->ROOT;
a7fd8ef6
DM
1083 local $B::overlay = {};
1084 $self->pessimise($op, $form->START);
6e90668e 1085 my $kid;
fb725297
RGS
1086 return "\f." if $op->first->name eq 'stub'
1087 || $op->first->name eq 'nextstate';
6e90668e
SM
1088 $op = $op->first->first; # skip leavewrite, lineseq
1089 while (not null $op) {
1090 $op = $op->sibling; # skip nextstate
1091 my @exprs;
1092 $kid = $op->first->sibling; # skip pushmark
a5b0cd91 1093 push @text, "\f".$self->const_sv($kid)->PV;
6e90668e
SM
1094 $kid = $kid->sibling;
1095 for (; not null $kid; $kid = $kid->sibling) {
93a8ff62 1096 push @exprs, $self->deparse($kid, -1);
31c26a0a 1097 $exprs[-1] =~ s/;\z//;
6e90668e 1098 }
a5b0cd91 1099 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
6e90668e
SM
1100 $op = $op->sibling;
1101 }
a5b0cd91 1102 return join("", @text) . "\f.";
6e90668e
SM
1103}
1104
6e90668e 1105sub is_scope {
a798dbf2 1106 my $op = shift;
3f872cb9
GS
1107 return $op->name eq "leave" || $op->name eq "scope"
1108 || $op->name eq "lineseq"
d989cdac 1109 || ($op->name eq "null" && class($op) eq "UNOP"
3f872cb9 1110 && (is_scope($op->first) || $op->first->name eq "enter"));
6e90668e
SM
1111}
1112
1113sub is_state {
3f872cb9
GS
1114 my $name = $_[0]->name;
1115 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
6e90668e
SM
1116}
1117
e38ccfd9 1118sub is_miniwhile { # check for one-line loop ('foo() while $y--')
6e90668e 1119 my $op = shift;
d989cdac 1120 return (!null($op) and null($op->sibling)
3f872cb9
GS
1121 and $op->name eq "null" and class($op) eq "UNOP"
1122 and (($op->first->name =~ /^(and|or)$/
1123 and $op->first->first->sibling->name eq "lineseq")
1124 or ($op->first->name eq "lineseq"
6e90668e 1125 and not null $op->first->first->sibling
3f872cb9 1126 and $op->first->first->sibling->name eq "unstack")
6e90668e
SM
1127 ));
1128}
1129
d989cdac
SM
1130# Check if the op and its sibling are the initialization and the rest of a
1131# for (..;..;..) { ... } loop
1132sub is_for_loop {
1133 my $op = shift;
1134 # This OP might be almost anything, though it won't be a
1135 # nextstate. (It's the initialization, so in the canonical case it
eae48c89
Z
1136 # will be an sassign.) The sibling is (old style) a lineseq whose
1137 # first child is a nextstate and whose second is a leaveloop, or
1138 # (new style) an unstack whose sibling is a leaveloop.
d989cdac 1139 my $lseq = $op->sibling;
eae48c89
Z
1140 return 0 unless !is_state($op) and !null($lseq);
1141 if ($lseq->name eq "lineseq") {
d989cdac
SM
1142 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1143 && (my $sib = $lseq->first->sibling)) {
1144 return (!null($sib) && $sib->name eq "leaveloop");
1145 }
eae48c89
Z
1146 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1147 my $sib = $lseq->sibling;
1148 return $sib && !null($sib) && $sib->name eq "leaveloop";
d989cdac
SM
1149 }
1150 return 0;
1151}
1152
6e90668e
SM
1153sub is_scalar {
1154 my $op = shift;
3f872cb9
GS
1155 return ($op->name eq "rv2sv" or
1156 $op->name eq "padsv" or
1157 $op->name eq "gv" or # only in array/hash constructs
bd0865ec 1158 $op->flags & OPf_KIDS && !null($op->first)
3f872cb9 1159 && $op->first->name eq "gvsv");
6e90668e
SM
1160}
1161
9d2c6865
SM
1162sub maybe_parens {
1163 my $self = shift;
1164 my($text, $cx, $prec) = @_;
1165 if ($prec < $cx # unary ops nest just fine
1166 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1167 or $self->{'parens'})
1168 {
1169 $text = "($text)";
1170 # In a unop, let parent reuse our parens; see maybe_parens_unop
1171 $text = "\cS" . $text if $cx == 16;
1172 return $text;
1173 } else {
1174 return $text;
1175 }
1176}
1177
e38ccfd9 1178# same as above, but get around the 'if it looks like a function' rule
9d2c6865
SM
1179sub maybe_parens_unop {
1180 my $self = shift;
1181 my($name, $kid, $cx) = @_;
1182 if ($cx > 16 or $self->{'parens'}) {
a0035eb8
RH
1183 $kid = $self->deparse($kid, 1);
1184 if ($name eq "umask" && $kid =~ /^\d+$/) {
1185 $kid = sprintf("%#o", $kid);
1186 }
4a1ac32e 1187 return $self->keyword($name) . "($kid)";
9d2c6865
SM
1188 } else {
1189 $kid = $self->deparse($kid, 16);
a0035eb8
RH
1190 if ($name eq "umask" && $kid =~ /^\d+$/) {
1191 $kid = sprintf("%#o", $kid);
1192 }
4a1ac32e 1193 $name = $self->keyword($name);
9d2c6865
SM
1194 if (substr($kid, 0, 1) eq "\cS") {
1195 # use kid's parens
1196 return $name . substr($kid, 1);
1197 } elsif (substr($kid, 0, 1) eq "(") {
1198 # avoid looks-like-a-function trap with extra parens
e38ccfd9 1199 # ('+' can lead to ambiguities)
9d2c6865
SM
1200 return "$name(" . $kid . ")";
1201 } else {
1202 return "$name $kid";
1203 }
1204 }
1205}
1206
1207sub maybe_parens_func {
1208 my $self = shift;
1209 my($func, $text, $cx, $prec) = @_;
1210 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1211 return "$func($text)";
1212 } else {
1213 return "$func $text";
1214 }
1215}
1216
56cd2ef8
FC
1217sub find_our_type {
1218 my ($self, $name) = @_;
1219 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
5afbd733 1220 my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0;
56cd2ef8
FC
1221 for my $a (@{$self->{'curcvlex'}{"o$name"}}) {
1222 my ($st, undef, $padname) = @$a;
5afbd733 1223 if ($st >= $seq && $padname->FLAGS & SVpad_TYPED) {
56cd2ef8
FC
1224 return $padname->SvSTASH->NAME;
1225 }
1226 }
1227 return '';
1228}
1229
6e90668e
SM
1230sub maybe_local {
1231 my $self = shift;
9d2c6865 1232 my($op, $cx, $text) = @_;
c8ec376c 1233 my $name = $op->name;
9187b6e4
FC
1234 my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign
1235 |lv(?:av)?ref)$/x)
de183bbb
FC
1236 ? OPpOUR_INTRO
1237 : 0;
1238 my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO;
c8ec376c
FC
1239 # The @a in \(@a) isn't in ref context, but only when the
1240 # parens are there.
1241 my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/
1242 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
de183bbb 1243 if ((my $priv = $op->private) & ($lval_intro|$our_intro)) {
f3515641 1244 my @our_local;
de183bbb 1245 push @our_local, "local" if $priv & $lval_intro;
f3515641 1246 push @our_local, "our" if $priv & $our_intro;
3188a821 1247 my $our_local = join " ", map $self->keyword($_), @our_local;
f3515641 1248 if( $our_local[-1] eq 'our' ) {
640d5d41
FC
1249 if ( $text !~ /^\W(\w+::)*\w+\z/
1250 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1251 ) {
1252 die "Unexpected our($text)\n";
1253 }
d989cdac 1254 $text =~ s/(\w+::)+//;
56cd2ef8
FC
1255
1256 if (my $type = $self->find_our_type($text)) {
1257 $our_local .= ' ' . $type;
1258 }
8e3542b6 1259 }
c8ec376c
FC
1260 return $need_parens ? "($text)" : $text
1261 if $self->{'avoid_local'}{$$op};
1262 if ($need_parens) {
1263 return "$our_local($text)";
1264 } elsif (want_scalar($op)) {
ce4e655d 1265 return "$our_local $text";
e8d3f51b 1266 } else {
ce4e655d 1267 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
e8d3f51b 1268 }
6e90668e 1269 } else {
c8ec376c 1270 return $need_parens ? "($text)" : $text;
a798dbf2 1271 }
a798dbf2
MB
1272}
1273
3ed82cfc
GS
1274sub maybe_targmy {
1275 my $self = shift;
1276 my($op, $cx, $func, @args) = @_;
1277 if ($op->private & OPpTARGET_MY) {
1278 my $var = $self->padname($op->targ);
1279 my $val = $func->($self, $op, 7, @args);
1280 return $self->maybe_parens("$var = $val", $cx, 7);
1281 } else {
1282 return $func->($self, $op, $cx, @args);
1283 }
1284}
1285
6e90668e
SM
1286sub padname_sv {
1287 my $self = shift;
1288 my $targ = shift;
d989cdac 1289 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
6e90668e
SM
1290}
1291
1292sub maybe_my {
1293 my $self = shift;
8db6f480 1294 my($op, $cx, $text, $padname, $forbid_parens) = @_;
c8ec376c
FC
1295 # The @a in \(@a) isn't in ref context, but only when the
1296 # parens are there.
1297 my $need_parens = !$forbid_parens && $self->{'in_refgen'}
1298 && $op->name =~ /[ah]v\z/
1299 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
4c1f658f 1300 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
bcff4148
FC
1301 # Check $padname->FLAGS for statehood, rather than $op->private,
1302 # because enteriter ops do not carry the flag.
3188a821 1303 my $my =
bcff4148 1304 $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my");
56cd2ef8
FC
1305 if ($padname->FLAGS & SVpad_TYPED) {
1306 $my .= ' ' . $padname->SvSTASH->NAME;
1307 }
c8ec376c
FC
1308 if ($need_parens) {
1309 return "$my($text)";
1310 } elsif ($forbid_parens || want_scalar($op)) {
3462b4ac 1311 return "$my $text";
e8d3f51b 1312 } else {
3462b4ac 1313 return $self->maybe_parens_func($my, $text, $cx, 16);
e8d3f51b 1314 }
6e90668e 1315 } else {
c8ec376c 1316 return $need_parens ? "($text)" : $text;
6e90668e
SM
1317 }
1318}
1319
9d2c6865
SM
1320# The following OPs don't have functions:
1321
1322# pp_padany -- does not exist after parsing
9d2c6865 1323
2ae48fff
RGS
1324sub AUTOLOAD {
1325 if ($AUTOLOAD =~ s/^.*::pp_//) {
5e8c3db2
FC
1326 warn "unexpected OP_".
1327 ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD);
2ae48fff
RGS
1328 return "XXX";
1329 } else {
1330 die "Undefined subroutine $AUTOLOAD called";
1331 }
9d2c6865 1332}
6e90668e 1333
611c1e95
IZ
1334sub DESTROY {} # Do not AUTOLOAD
1335
ce4e655d
RH
1336# $root should be the op which represents the root of whatever
1337# we're sequencing here. If it's undefined, then we don't append
1338# any subroutine declarations to the deparsed ops, otherwise we
1339# append appropriate declarations.
58cccf98 1340sub lineseq {
93a8ff62 1341 my($self, $root, $cx, @ops) = @_;
58cccf98 1342 my($expr, @exprs);
ce4e655d
RH
1343
1344 my $out_cop = $self->{'curcop'};
1345 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1346 my $limit_seq;
1347 if (defined $root) {
1348 $limit_seq = $out_seq;
76df5e8f
DM
1349 my $nseq;
1350 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
ce4e655d
RH
1351 $limit_seq = $nseq if !defined($limit_seq)
1352 or defined($nseq) && $nseq < $limit_seq;
1353 }
1354 $limit_seq = $self->{'limit_seq'}
1355 if defined($self->{'limit_seq'})
1356 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1357 local $self->{'limit_seq'} = $limit_seq;
09d856fb
CK
1358
1359 $self->walk_lineseq($root, \@ops,
1360 sub { push @exprs, $_[0]} );
1361
93a8ff62
FC
1362 my $sep = $cx ? '; ' : ";\n";
1363 my $body = join($sep, grep {length} @exprs);
ce4e655d 1364 my $subs = "";
67fc2416 1365 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
ce4e655d
RH
1366 $subs = join "\n", $self->seq_subs($limit_seq);
1367 }
93a8ff62 1368 return join($sep, grep {length} $body, $subs);
6e90668e
SM
1369}
1370
58cccf98 1371sub scopeop {
d989cdac 1372 my($real_block, $self, $op, $cx) = @_;
58cccf98
SM
1373 my $kid;
1374 my @kids;
a0405c92 1375
0ced6c29
RGS
1376 local(@$self{qw'curstash warnings hints hinthash'})
1377 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
58cccf98
SM
1378 if ($real_block) {
1379 $kid = $op->first->sibling; # skip enter
1380 if (is_miniwhile($kid)) {
1381 my $top = $kid->first;
1382 my $name = $top->name;
1383 if ($name eq "and") {
7741ceed 1384 $name = $self->keyword("while");
58cccf98 1385 } elsif ($name eq "or") {
7741ceed 1386 $name = $self->keyword("until");
58cccf98 1387 } else { # no conditional -> while 1 or until 0
7741ceed
FC
1388 return $self->deparse($top->first, 1) . " "
1389 . $self->keyword("while") . " 1";
58cccf98
SM
1390 }
1391 my $cond = $top->first;
1392 my $body = $cond->sibling->first; # skip lineseq
1393 $cond = $self->deparse($cond, 1);
1394 $body = $self->deparse($body, 1);
1395 return "$body $name $cond";
6e90668e 1396 }
58cccf98
SM
1397 } else {
1398 $kid = $op->first;
1399 }
1400 for (; !null($kid); $kid = $kid->sibling) {
1401 push @kids, $kid;
6e90668e 1402 }
d989cdac 1403 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
73582821 1404 my $body = $self->lineseq($op, 0, @kids);
3188a821
FC
1405 return is_lexical_subs(@kids)
1406 ? $body
1407 : ($self->lex_in_scope("&do") ? "CORE::do" : "do")
1408 . " {\n\t$body\n\b}";
9d2c6865 1409 } else {
93a8ff62 1410 my $lineseq = $self->lineseq($op, $cx, @kids);
7a9b44b9 1411 return (length ($lineseq) ? "$lineseq;" : "");
6e90668e 1412 }
6e90668e
SM
1413}
1414
ce4e655d 1415sub pp_scope { scopeop(0, @_); }
58cccf98
SM
1416sub pp_lineseq { scopeop(0, @_); }
1417sub pp_leave { scopeop(1, @_); }
9d2c6865 1418
d989cdac
SM
1419# This is a special case of scopeop and lineseq, for the case of the
1420# main_root. The difference is that we print the output statements as
1421# soon as we get them, for the sake of impatient users.
1422sub deparse_root {
1423 my $self = shift;
1424 my($op) = @_;
0ced6c29
RGS
1425 local(@$self{qw'curstash warnings hints hinthash'})
1426 = @$self{qw'curstash warnings hints hinthash'};
d989cdac 1427 my @kids;
4ca8de37 1428 return if null $op->first; # Can happen, e.g., for Bytecode without -k
d989cdac
SM
1429 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1430 push @kids, $kid;
1431 }
09d856fb 1432 $self->walk_lineseq($op, \@kids,
4b1385ee
FC
1433 sub { return unless length $_[0];
1434 print $self->indent($_[0] =~ s/\0\z//
1435 ? $_[0]
1436 : $_[0].';');
1437 print "\n"
1438 unless $_[1] == $#kids or $_[0] =~ /\n\z/;
09d856fb
CK
1439 });
1440}
1441
1442sub walk_lineseq {
1443 my ($self, $op, $kids, $callback) = @_;
1444 my @kids = @$kids;
d989cdac
SM
1445 for (my $i = 0; $i < @kids; $i++) {
1446 my $expr = "";
1447 if (is_state $kids[$i]) {
09d856fb 1448 $expr = $self->deparse($kids[$i++], 0);
d989cdac 1449 if ($i > $#kids) {
09d856fb 1450 $callback->($expr, $i);
d989cdac
SM
1451 last;
1452 }
1453 }
1454 if (is_for_loop($kids[$i])) {
eae48c89
Z
1455 $callback->($expr . $self->for_loop($kids[$i], 0),
1456 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
d989cdac
SM
1457 next;
1458 }
6b6b21da 1459 my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2);
34b54951 1460 $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise
6b6b21da 1461 $expr .= $expr2;
d989cdac 1462 $expr =~ s/;\n?\z//;
09d856fb 1463 $callback->($expr, $i);
d989cdac
SM
1464 }
1465}
1466
6e90668e
SM
1467# The BEGIN {} is used here because otherwise this code isn't executed
1468# when you run B::Deparse on itself.
1469my %globalnames;
1470BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1471 "ENV", "ARGV", "ARGVOUT", "_"); }
1472
1473sub gv_name {
1474 my $self = shift;
1475 my $gv = shift;
b89b7257 1476 my $raw = shift;
32cc5cd1
FC
1477#Carp::confess() unless ref($gv) eq "B::GV";
1478 my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0;
1479 my $stash = ($cv || $gv)->STASH->NAME;
1480 my $name = $raw
1481 ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME
1482 : $cv
1483 ? B::safename($cv->NAME_HEK || $cv->GV->NAME)
1484 : $gv->SAFENAME;
8b2d6640
FC
1485 if ($stash eq 'main' && $name =~ /^::/) {
1486 $stash = '::';
1487 }
b861b87f
FC
1488 elsif (($stash eq 'main'
1489 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
8b2d6640
FC
1490 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1491 && ($stash eq 'main' || $name !~ /::/))
b861b87f 1492 )
9d2c6865 1493 {
6e90668e
SM
1494 $stash = "";
1495 } else {
1496 $stash = $stash . "::";
a798dbf2 1497 }
b89b7257 1498 if (!$raw and $name =~ /^(\^..|{)/) {
083bda02 1499 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
6e90668e
SM
1500 }
1501 return $stash . $name;
a798dbf2
MB
1502}
1503
8510e997 1504# Return the name to use for a stash variable.
415d4c68
FC
1505# If a lexical with the same name is in scope, or
1506# if strictures are enabled, it may need to be
8510e997
RH
1507# fully-qualified.
1508sub stash_variable {
bb8996b8 1509 my ($self, $prefix, $name, $cx) = @_;
8510e997
RH
1510
1511 return "$prefix$name" if $name =~ /::/;
1512
d989cdac 1513 unless ($prefix eq '$' || $prefix eq '@' || #'
8510e997
RH
1514 $prefix eq '%' || $prefix eq '$#') {
1515 return "$prefix$name";
1516 }
1517
61154ac0
FC
1518 if ($name =~ /^[^\w+-]$/) {
1519 if (defined $cx && $cx == 26) {
1520 if ($prefix eq '@') {
bb8996b8
HY
1521 return "$prefix\{$name}";
1522 }
61154ac0
FC
1523 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1524 }
1525 if ($prefix eq '$#') {
6ec73527 1526 return "\$#{$name}";
61154ac0 1527 }
6ec73527 1528 }
bb8996b8 1529
415d4c68 1530 return $prefix . $self->maybe_qualify($prefix, $name);
8510e997
RH
1531}
1532
be6cf5cf
FC
1533# Return just the name, without the prefix. It may be returned as a quoted
1534# string. The second return value is a boolean indicating that.
1535sub stash_variable_name {
1536 my($self, $prefix, $gv) = @_;
1537 my $name = $self->gv_name($gv, 1);
415d4c68 1538 $name = $self->maybe_qualify($prefix,$name);
be6cf5cf
FC
1539 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1540 $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1541 $name =~ /^(\^..|{)/ and $name = "{$name}";
1542 return $name, 0; # not quoted
1543 }
1544 else {
7741ceed 1545 single_delim("q", "'", $name, $self), 1;
be6cf5cf
FC
1546 }
1547}
1548
415d4c68
FC
1549sub maybe_qualify {
1550 my ($self,$prefix,$name) = @_;
1551 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1552 return $name if !$prefix || $name =~ /::/;
1553 return $self->{'curstash'}.'::'. $name
1554 if
36727b53
FC
1555 $name =~ /^(?!\d)\w/ # alphabetic
1556 && $v !~ /^\$[ab]\z/ # not $a or $b
415d4c68
FC
1557 && !$globalnames{$name} # not a global name
1558 && $self->{hints} & $strict_bits{vars} # strict vars
1559 && !$self->lex_in_scope($v,1) # no "our"
1560 or $self->lex_in_scope($v); # conflicts with "my" variable
1561 return $name;
1562}
1563
8510e997 1564sub lex_in_scope {
415d4c68
FC
1565 my ($self, $name, $our) = @_;
1566 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
8510e997
RH
1567 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1568
6ec152c3 1569 return 0 if !defined($self->{'curcop'});
8510e997
RH
1570 my $seq = $self->{'curcop'}->cop_seq;
1571 return 0 if !exists $self->{'curcvlex'}{$name};
1572 for my $a (@{$self->{'curcvlex'}{$name}}) {
1573 my ($st, $en) = @$a;
1574 return 1 if $seq > $st && $seq <= $en;
1575 }
1576 return 0;
1577}
1578
1579sub populate_curcvlex {
1580 my $self = shift;
ce4e655d 1581 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
7dafbf52
DM
1582 my $padlist = $cv->PADLIST;
1583 # an undef CV still in lexical chain
1584 next if class($padlist) eq "SPECIAL";
1585 my @padlist = $padlist->ARRAY;
8510e997
RH
1586 my @ns = $padlist[0]->ARRAY;
1587
1588 for (my $i=0; $i<@ns; ++$i) {
1589 next if class($ns[$i]) eq "SPECIAL";
0f2fe21d
RH
1590 if (class($ns[$i]) eq "PV") {
1591 # Probably that pesky lexical @_
1592 next;
1593 }
8510e997 1594 my $name = $ns[$i]->PVX;
7dafbf52
DM
1595 my ($seq_st, $seq_en) =
1596 ($ns[$i]->FLAGS & SVf_FAKE)
1597 ? (0, 999999)
809abb02 1598 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
8510e997 1599
415d4c68
FC
1600 push @{$self->{'curcvlex'}{
1601 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
56cd2ef8 1602 }}, [$seq_st, $seq_en, $ns[$i]];
8510e997
RH
1603 }
1604 }
1605}
1606
ce4e655d
RH
1607sub find_scope_st { ((find_scope(@_))[0]); }
1608sub find_scope_en { ((find_scope(@_))[1]); }
1609
1610# Recurses down the tree, looking for pad variable introductions and COPs
1611sub find_scope {
1612 my ($self, $op, $scope_st, $scope_en) = @_;
ff97752d 1613 carp("Undefined op in find_scope") if !defined $op;
ce4e655d
RH
1614 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1615
b6b46d6f
AB
1616 my @queue = ($op);
1617 while(my $op = shift @queue ) {
1618 for (my $o=$op->first; $$o; $o=$o->sibling) {
1619 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1620 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1621 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1622 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1623 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1624 return ($scope_st, $scope_en);
1625 }
1626 elsif (is_state($o)) {
1627 my $c = $o->cop_seq;
1628 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1629 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1630 return ($scope_st, $scope_en);
1631 }
1632 elsif ($o->flags & OPf_KIDS) {
1633 unshift (@queue, $o);
1634 }
34a48b4b
RH
1635 }
1636 }
ce4e655d
RH
1637
1638 return ($scope_st, $scope_en);
34a48b4b
RH
1639}
1640
1641# Returns a list of subs which should be inserted before the COP
1642sub cop_subs {
1643 my ($self, $op, $out_seq) = @_;
1644 my $seq = $op->cop_seq;
8635e3c2
FC
1645 if ($] < 5.021006) {
1646 # If we have nephews, then our sequence number indicates
1647 # the cop_seq of the end of some sort of scope.
1648 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
ce4e655d
RH
1649 and my $nseq = $self->find_scope_st($op->sibling) ) {
1650 $seq = $nseq;
8635e3c2 1651 }
34a48b4b
RH
1652 }
1653 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1654 return $self->seq_subs($seq);
1655}
1656
1657sub seq_subs {
1658 my ($self, $seq) = @_;
1659 my @text;
1660#push @text, "# ($seq)\n";
1661
ce4e655d 1662 return "" if !defined $seq;
d88d1fe0 1663 my @pending;
34a48b4b
RH
1664 while (scalar(@{$self->{'subs_todo'}})
1665 and $seq > $self->{'subs_todo'}[0][0]) {
d88d1fe0
FC
1666 my $cv = $self->{'subs_todo'}[0][1];
1667 my $outside = $cv && $cv->OUTSIDE;
1668 if ($cv and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}}) {
1669 push @pending, shift @{$self->{'subs_todo'}};
1670 next;
1671 }
34a48b4b
RH
1672 push @text, $self->next_todo;
1673 }
d88d1fe0 1674 unshift @{$self->{'subs_todo'}}, @pending;
34a48b4b
RH
1675 return @text;
1676}
1677
95c04cde
NC
1678sub _features_from_bundle {
1679 my ($hints, $hh) = @_;
1873980a 1680 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
95c04cde
NC
1681 $hh->{$feature::feature{$_}} = 1;
1682 }
1683 return $hh;
1684}
1685
08c6f5ec 1686# Notice how subs and formats are inserted between statements here;
bc6b2ef6 1687# also $[ assignments and pragmas.
6e90668e
SM
1688sub pp_nextstate {
1689 my $self = shift;
9d2c6865 1690 my($op, $cx) = @_;
34a48b4b 1691 $self->{'curcop'} = $op;
6e90668e 1692 my @text;
34a48b4b 1693 push @text, $self->cop_subs($op);
4b1385ee
FC
1694 if (@text) {
1695 # Special marker to swallow up the semicolon
1696 push @text, "\0";
1697 }
11faa288 1698 my $stash = $op->stashpv;
6e90668e 1699 if ($stash ne $self->{'curstash'}) {
7741ceed 1700 push @text, $self->keyword("package") . " $stash;\n";
6e90668e
SM
1701 $self->{'curstash'} = $stash;
1702 }
08c6f5ec 1703
bc6b2ef6
Z
1704 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1705 push @text, '$[ = '. $op->arybase .";\n";
1706 $self->{'arybase'} = $op->arybase;
1707 }
1708
7a9b44b9
RH
1709 my $warnings = $op->warnings;
1710 my $warning_bits;
1711 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
810aef70 1712 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
7a9b44b9 1713 }
e31885a0 1714 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
810aef70 1715 $warning_bits = $warnings::NONE;
7a9b44b9 1716 }
e31885a0
RH
1717 elsif ($warnings->isa("B::SPECIAL")) {
1718 $warning_bits = undef;
1719 }
7a9b44b9 1720 else {
34a48b4b 1721 $warning_bits = $warnings->PV & WARN_MASK;
7a9b44b9
RH
1722 }
1723
e31885a0
RH
1724 if (defined ($warning_bits) and
1725 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
7741ceed
FC
1726 push @text,
1727 $self->declare_warnings($self->{'warnings'}, $warning_bits);
7a9b44b9
RH
1728 $self->{'warnings'} = $warning_bits;
1729 }
1730
2be95ceb 1731 my $hints = $] < 5.008009 ? $op->private : $op->hints;
0bb01b05 1732 my $old_hints = $self->{'hints'};
2be95ceb 1733 if ($self->{'hints'} != $hints) {
7741ceed 1734 push @text, $self->declare_hints($self->{'hints'}, $hints);
2be95ceb 1735 $self->{'hints'} = $hints;
a0405c92
RH
1736 }
1737
0bb01b05
FC
1738 my $newhh;
1739 if ($] > 5.009) {
1740 $newhh = $op->hints_hash->HASH;
1741 }
1742
1743 if ($] >= 5.015006) {
1744 # feature bundle hints
149758b3
NC
1745 my $from = $old_hints & $feature::hint_mask;
1746 my $to = $ hints & $feature::hint_mask;
0bb01b05 1747 if ($from != $to) {
149758b3 1748 if ($to == $feature::hint_mask) {
0bb01b05
FC
1749 if ($self->{'hinthash'}) {
1750 delete $self->{'hinthash'}{$_}
1751 for grep /^feature_/, keys %{$self->{'hinthash'}};
1752 }
1753 else { $self->{'hinthash'} = {} }
95c04cde
NC
1754 $self->{'hinthash'}
1755 = _features_from_bundle($from, $self->{'hinthash'});
0bb01b05
FC
1756 }
1757 else {
1758 my $bundle =
1759 $feature::hint_bundles[$to >> $feature::hint_shift];
1760 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
7741ceed
FC
1761 push @text,
1762 $self->keyword("no") . " feature;\n",
1763 $self->keyword("use") . " feature ':$bundle';\n";
0bb01b05
FC
1764 }
1765 }
1766 }
1767
1768 if ($] > 5.009) {
7741ceed 1769 push @text, $self->declare_hinthash(
0bb01b05
FC
1770 $self->{'hinthash'}, $newhh,
1771 $self->{indent_size}, $self->{hints},
1772 );
1773 $self->{'hinthash'} = $newhh;
0ced6c29
RGS
1774 }
1775
d989cdac
SM
1776 # This should go after of any branches that add statements, to
1777 # increase the chances that it refers to the same line it did in
1778 # the original program.
1779 if ($self->{'linenums'}) {
1780 push @text, "\f#line " . $op->line .
1781 ' "' . $op->file, qq'"\n';
1782 }
1783
98a1a137
Z
1784 push @text, $op->label . ": " if $op->label;
1785
6e90668e
SM
1786 return join("", @text);
1787}
1788
08c6f5ec 1789sub declare_warnings {
7741ceed 1790 my ($self, $from, $to) = @_;
e6f1f756 1791 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
7741ceed 1792 return $self->keyword("use") . " warnings;\n";
a0405c92 1793 }
e6f1f756 1794 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
7741ceed 1795 return $self->keyword("no") . " warnings;\n";
a0405c92 1796 }
4b1385ee 1797 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n\0";
a0405c92
RH
1798}
1799
1800sub declare_hints {
7741ceed 1801 my ($self, $from, $to) = @_;
a0035eb8
RH
1802 my $use = $to & ~$from;
1803 my $no = $from & ~$to;
1804 my $decls = "";
1805 for my $pragma (hint_pragmas($use)) {
7741ceed 1806 $decls .= $self->keyword("use") . " $pragma;\n";
a0035eb8
RH
1807 }
1808 for my $pragma (hint_pragmas($no)) {
7741ceed 1809 $decls .= $self->keyword("no") . " $pragma;\n";
a0035eb8
RH
1810 }
1811 return $decls;
1812}
1813
493c23c6
NC
1814# Internal implementation hints that the core sets automatically, so don't need
1815# (or want) to be passed back to the user
1816my %ignored_hints = (
1817 'open<' => 1,
1818 'open>' => 1,
dca6062a 1819 ':' => 1,
1c74777c
FC
1820 'strict/refs' => 1,
1821 'strict/subs' => 1,
1822 'strict/vars' => 1,
2e8342de 1823);
493c23c6 1824
a8095af7
FC
1825my %rev_feature;
1826
0ced6c29 1827sub declare_hinthash {
7741ceed 1828 my ($self, $from, $to, $indent, $hints) = @_;
a8095af7 1829 my $doing_features =
149758b3 1830 ($hints & $feature::hint_mask) == $feature::hint_mask;
0ced6c29 1831 my @decls;
a8095af7
FC
1832 my @features;
1833 my @unfeatures; # bugs?
0bb01b05 1834 for my $key (sort keys %$to) {
493c23c6 1835 next if $ignored_hints{$key};
a8095af7
FC
1836 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1837 next if $is_feature and not $doing_features;
04be0204 1838 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
a8095af7 1839 push(@features, $key), next if $is_feature;
035146a3 1840 push @decls,
7741ceed 1841 qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
035146a3
FC
1842 . (
1843 defined $to->{$key}
7741ceed 1844 ? single_delim("q", "'", $to->{$key}, $self)
035146a3
FC
1845 : 'undef'
1846 )
04be0204 1847 . qq(;);
0ced6c29
RGS
1848 }
1849 }
0bb01b05 1850 for my $key (sort keys %$from) {
493c23c6 1851 next if $ignored_hints{$key};
a8095af7
FC
1852 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1853 next if $is_feature and not $doing_features;
0ced6c29 1854 if (!exists $to->{$key}) {
a8095af7 1855 push(@unfeatures, $key), next if $is_feature;
0ced6c29
RGS
1856 push @decls, qq(delete \$^H{'$key'};);
1857 }
1858 }
a8095af7
FC
1859 my @ret;
1860 if (@features || @unfeatures) {
a8095af7
FC
1861 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1862 }
1863 if (@features) {
7741ceed 1864 push @ret, $self->keyword("use") . " feature "
a8095af7
FC
1865 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1866 }
1867 if (@unfeatures) {
7741ceed 1868 push @ret, $self->keyword("no") . " feature "
a8095af7
FC
1869 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1870 . ";\n";
1871 }
1872 @decls and
1873 push @ret,
4b1385ee 1874 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\0";
a8095af7 1875 return @ret;
0ced6c29
RGS
1876}
1877
a0035eb8
RH
1878sub hint_pragmas {
1879 my ($bits) = @_;
415d4c68 1880 my (@pragmas, @strict);
a0035eb8 1881 push @pragmas, "integer" if $bits & 0x1;
415d4c68
FC
1882 for (sort keys %strict_bits) {
1883 push @strict, "'$_'" if $bits & $strict_bits{$_};
1884 }
1885 if (@strict == keys %strict_bits) {
1886 push @pragmas, "strict";
1887 }
1888 elsif (@strict) {
1889 push @pragmas, "strict " . join ', ', @strict;
1890 }
a0035eb8
RH
1891 push @pragmas, "bytes" if $bits & 0x8;
1892 return @pragmas;
08c6f5ec
RH
1893}
1894
6e90668e 1895sub pp_dbstate { pp_nextstate(@_) }
3f872cb9 1896sub pp_setstate { pp_nextstate(@_) }
6e90668e
SM
1897
1898sub pp_unstack { return "" } # see also leaveloop
1899
80e3f4ad
FC
1900my %feature_keywords = (
1901 # keyword => 'feature',
1902 state => 'state',
1903 say => 'say',
1904 given => 'switch',
1905 when => 'switch',
1906 default => 'switch',
e36901c8 1907 break => 'switch',
7d789282 1908 evalbytes=>'evalbytes',
84ed0108 1909 __SUB__ => '__SUB__',
838f2281 1910 fc => 'fc',
80e3f4ad
FC
1911);
1912
3ac5308a
DM
1913# keywords that are strong and also have a prototype
1914#
1915my %strong_proto_keywords = map { $_ => 1 } qw(
3ac5308a
DM
1916 pos
1917 prototype
1918 scalar
1919 study
1920 undef
1921);
1922
a958cfbb
FC
1923sub feature_enabled {
1924 my($self,$name) = @_;
223b1722 1925 my $hh;
149758b3
NC
1926 my $hints = $self->{hints} & $feature::hint_mask;
1927 if ($hints && $hints != $feature::hint_mask) {
1873980a 1928 $hh = _features_from_bundle($hints);
223b1722
FC
1929 }
1930 elsif ($hints) { $hh = $self->{'hinthash'} }
a958cfbb
FC
1931 return $hh && $hh->{"feature_$feature_keywords{$name}"}
1932}
1933
1934sub keyword {
1935 my $self = shift;
1936 my $name = shift;
1937 return $name if $name =~ /^CORE::/; # just in case
1938 if (exists $feature_keywords{$name}) {
1939 return "CORE::$name" if not $self->feature_enabled($name);
80e3f4ad 1940 }
7741ceed
FC
1941 # This sub may be called for a program that has no nextstate ops. In
1942 # that case we may have a lexical sub named no/use/sub in scope but
1943 # but $self->lex_in_scope will return false because it depends on the
1944 # current nextstate op. So we need this alternate method if there is
1945 # no current cop.
1946 if (!$self->{'curcop'}) {
1947 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1948 return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
1949 || exists $self->{'curcvlex'}{"o&$name"};
1950 } elsif ($self->lex_in_scope("&$name")
1951 || $self->lex_in_scope("&$name", 1)) {
3188a821
FC
1952 return "CORE::$name";
1953 }
3ac5308a
DM
1954 if ($strong_proto_keywords{$name}
1955 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1956 && !defined eval{prototype "CORE::$name"})
4a1ac32e
FC
1957 ) { return $name }
1958 if (
1959 exists $self->{subs_declared}{$name}
1960 or
1961 exists &{"$self->{curstash}::$name"}
1962 ) {
1963 return "CORE::$name"
1964 }
1965 return $name;
1966}
1967
6e90668e
SM
1968sub baseop {
1969 my $self = shift;
9d2c6865 1970 my($op, $cx, $name) = @_;
4a1ac32e 1971 return $self->keyword($name);
6e90668e
SM
1972}
1973
e99ebc55
RH
1974sub pp_stub {
1975 my $self = shift;
1976 my($op, $cx, $name) = @_;
d989cdac 1977 if ($cx >= 1) {
e99ebc55
RH
1978 return "()";
1979 }
1980 else {
1981 return "();";
1982 }
1983}
6e90668e
SM
1984sub pp_wantarray { baseop(@_, "wantarray") }
1985sub pp_fork { baseop(@_, "fork") }
3ed82cfc
GS
1986sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1987sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1988sub pp_time { maybe_targmy(@_, \&baseop, "time") }
6e90668e
SM
1989sub pp_tms { baseop(@_, "times") }
1990sub pp_ghostent { baseop(@_, "gethostent") }
1991sub pp_gnetent { baseop(@_, "getnetent") }
1992sub pp_gprotoent { baseop(@_, "getprotoent") }
1993sub pp_gservent { baseop(@_, "getservent") }
1994sub pp_ehostent { baseop(@_, "endhostent") }
1995sub pp_enetent { baseop(@_, "endnetent") }
1996sub pp_eprotoent { baseop(@_, "endprotoent") }
1997sub pp_eservent { baseop(@_, "endservent") }
1998sub pp_gpwent { baseop(@_, "getpwent") }
1999sub pp_spwent { baseop(@_, "setpwent") }
2000sub pp_epwent { baseop(@_, "endpwent") }
2001sub pp_ggrent { baseop(@_, "getgrent") }
2002sub pp_sgrent { baseop(@_, "setgrent") }
2003sub pp_egrent { baseop(@_, "endgrent") }
2004sub pp_getlogin { baseop(@_, "getlogin") }
2005
2006sub POSTFIX () { 1 }
2007
9d2c6865
SM
2008# I couldn't think of a good short name, but this is the category of
2009# symbolic unary operators with interesting precedence
2010
2011sub pfixop {
2012 my $self = shift;
2013 my($op, $cx, $name, $prec, $flags) = (@_, 0);
2014 my $kid = $op->first;
2015 $kid = $self->deparse($kid, $prec);
843b15cc
FC
2016 return $self->maybe_parens(($flags & POSTFIX)
2017 ? "$kid$name"
2018 # avoid confusion with filetests
2019 : $name eq '-'
2020 && $kid =~ /^[a-zA-Z](?!\w)/
2021 ? "$name($kid)"
2022 : "$name$kid",
9d2c6865
SM
2023 $cx, $prec);
2024}
2025
2026sub pp_preinc { pfixop(@_, "++", 23) }
2027sub pp_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2028sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2029sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
9d2c6865
SM
2030sub pp_i_preinc { pfixop(@_, "++", 23) }
2031sub pp_i_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2032sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2033sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
68cc8748 2034sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
9d2c6865 2035
3ed82cfc
GS
2036sub pp_negate { maybe_targmy(@_, \&real_negate) }
2037sub real_negate {
9d2c6865
SM
2038 my $self = shift;
2039 my($op, $cx) = @_;
3f872cb9 2040 if ($op->first->name =~ /^(i_)?negate$/) {
9d2c6865
SM
2041 # avoid --$x
2042 $self->pfixop($op, $cx, "-", 21.5);
2043 } else {
2044 $self->pfixop($op, $cx, "-", 21);
2045 }
2046}
2047sub pp_i_negate { pp_negate(@_) }
2048
2049sub pp_not {
2050 my $self = shift;
2051 my($op, $cx) = @_;
2052 if ($cx <= 4) {
1cabb3b3 2053 $self->listop($op, $cx, "not", $op->first);
9d2c6865
SM
2054 } else {
2055 $self->pfixop($op, $cx, "!", 21);
2056 }
2057}
2058
6e90668e
SM
2059sub unop {
2060 my $self = shift;
9c56d9ea 2061 my($op, $cx, $name, $nollafr) = @_;
6e90668e 2062 my $kid;
9d2c6865 2063 if ($op->flags & OPf_KIDS) {
aaf643ce 2064 $kid = $op->first;
1c85afce
YO
2065 if (not $name) {
2066 # this deals with 'boolkeys' right now
2067 return $self->deparse($kid,$cx);
2068 }
deb20ba3
RGS
2069 my $builtinname = $name;
2070 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2071 if (defined prototype($builtinname)
2072 && prototype($builtinname) =~ /^;?\*/
e31885a0
RH
2073 && $kid->name eq "rv2gv") {
2074 $kid = $kid->first;
2075 }
2076
9c56d9ea
FC
2077 if ($nollafr) {
2078 ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
2079 return $self->maybe_parens(
2080 $self->keyword($name) . " $kid", $cx, 16
2081 );
2082 }
9d2c6865 2083 return $self->maybe_parens_unop($name, $kid, $cx);
6e90668e 2084 } else {
4d8ac5c7
FC
2085 return $self->maybe_parens(
2086 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
2087 $cx, 16,
2088 );
6e90668e 2089 }
6e90668e
SM
2090}
2091
3ed82cfc
GS
2092sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
2093sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
2094sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
2095sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
6e90668e
SM
2096sub pp_defined { unop(@_, "defined") }
2097sub pp_undef { unop(@_, "undef") }
2098sub pp_study { unop(@_, "study") }
6e90668e
SM
2099sub pp_ref { unop(@_, "ref") }
2100sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
2101
3ed82cfc
GS
2102sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
2103sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
2104sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
6e90668e 2105sub pp_srand { unop(@_, "srand") }
3ed82cfc
GS
2106sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
2107sub pp_log { maybe_targmy(@_, \&unop, "log") }
2108sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
2109sub pp_int { maybe_targmy(@_, \&unop, "int") }
2110sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
2111sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
2112sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
2113
2114sub pp_length { maybe_targmy(@_, \&unop, "length") }
2115sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2116sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
6e90668e
SM
2117
2118sub pp_each { unop(@_, "each") }
2119sub pp_values { unop(@_, "values") }
2120sub pp_keys { unop(@_, "keys") }
09dcfa7d 2121{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1c85afce
YO
2122sub pp_boolkeys {
2123 # no name because its an optimisation op that has no keyword
2124 unop(@_,"");
2125}
644741fd
NC
2126sub pp_aeach { unop(@_, "each") }
2127sub pp_avalues { unop(@_, "values") }
2128sub pp_akeys { unop(@_, "keys") }
6e90668e
SM
2129sub pp_pop { unop(@_, "pop") }
2130sub pp_shift { unop(@_, "shift") }
2131
2132sub pp_caller { unop(@_, "caller") }
2133sub pp_reset { unop(@_, "reset") }
2134sub pp_exit { unop(@_, "exit") }
2135sub pp_prototype { unop(@_, "prototype") }
2136
2137sub pp_close { unop(@_, "close") }
2138sub pp_fileno { unop(@_, "fileno") }
2139sub pp_umask { unop(@_, "umask") }
6e90668e
SM
2140sub pp_untie { unop(@_, "untie") }
2141sub pp_tied { unop(@_, "tied") }
2142sub pp_dbmclose { unop(@_, "dbmclose") }
2143sub pp_getc { unop(@_, "getc") }
2144sub pp_eof { unop(@_, "eof") }
2145sub pp_tell { unop(@_, "tell") }
2146sub pp_getsockname { unop(@_, "getsockname") }
2147sub pp_getpeername { unop(@_, "getpeername") }
2148
3ed82cfc
GS
2149sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
2150sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
6e90668e 2151sub pp_readlink { unop(@_, "readlink") }
3ed82cfc 2152sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
6e90668e
SM
2153sub pp_readdir { unop(@_, "readdir") }
2154sub pp_telldir { unop(@_, "telldir") }
2155sub pp_rewinddir { unop(@_, "rewinddir") }
2156sub pp_closedir { unop(@_, "closedir") }
3ed82cfc 2157sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
6e90668e
SM
2158sub pp_localtime { unop(@_, "localtime") }
2159sub pp_gmtime { unop(@_, "gmtime") }
2160sub pp_alarm { unop(@_, "alarm") }
3ed82cfc 2161sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
6e90668e 2162
94bb57f9 2163sub pp_dofile {
9c56d9ea 2164 my $code = unop(@_, "do", 1); # llafr does not apply
8b46c09b 2165 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
94bb57f9
FC
2166 $code;
2167}
7d789282
FC
2168sub pp_entereval {
2169 unop(
2170 @_,
2171 $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
2172 )
2173}
6e90668e
SM
2174
2175sub pp_ghbyname { unop(@_, "gethostbyname") }
2176sub pp_gnbyname { unop(@_, "getnetbyname") }
2177sub pp_gpbyname { unop(@_, "getprotobyname") }
2178sub pp_shostent { unop(@_, "sethostent") }
2179sub pp_snetent { unop(@_, "setnetent") }
2180sub pp_sprotoent { unop(@_, "setprotoent") }
2181sub pp_sservent { unop(@_, "setservent") }
2182sub pp_gpwnam { unop(@_, "getpwnam") }
2183sub pp_gpwuid { unop(@_, "getpwuid") }
2184sub pp_ggrnam { unop(@_, "getgrnam") }
2185sub pp_ggrgid { unop(@_, "getgrgid") }
2186
2187sub pp_lock { unop(@_, "lock") }
2188
0d863452 2189sub pp_continue { unop(@_, "continue"); }
c08f093b 2190sub pp_break { unop(@_, "break"); }
0d863452
RH
2191
2192sub givwhen {
2193 my $self = shift;
2194 my($op, $cx, $givwhen) = @_;
2195
2196 my $enterop = $op->first;
2197 my ($head, $block);
2198 if ($enterop->flags & OPf_SPECIAL) {
80e3f4ad 2199 $head = $self->keyword("default");
0d863452
RH
2200 $block = $self->deparse($enterop->first, 0);
2201 }
2202 else {
2203 my $cond = $enterop->first;
2204 my $cond_str = $self->deparse($cond, 1);
2205 $head = "$givwhen ($cond_str)";
2206 $block = $self->deparse($cond->sibling, 0);
2207 }
2208
2209 return "$head {\n".
2210 "\t$block\n".
2211 "\b}\cK";
2212}
2213
80e3f4ad
FC
2214sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2215sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
0d863452 2216
6e90668e
SM
2217sub pp_exists {
2218 my $self = shift;
9d2c6865 2219 my($op, $cx) = @_;
34a48b4b 2220 my $arg;
3188a821 2221 my $name = $self->keyword("exists");
34a48b4b
RH
2222 if ($op->private & OPpEXISTS_SUB) {
2223 # Checking for the existence of a subroutine
3188a821 2224 return $self->maybe_parens_func($name,
34a48b4b
RH
2225 $self->pp_rv2cv($op->first, 16), $cx, 16);
2226 }
2227 if ($op->flags & OPf_SPECIAL) {
2228 # Array element, not hash element
3188a821 2229 return $self->maybe_parens_func($name,
34a48b4b
RH
2230 $self->pp_aelem($op->first, 16), $cx, 16);
2231 }
3188a821 2232 return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
9d2c6865 2233 $cx, 16);
6e90668e
SM
2234}
2235
6e90668e
SM
2236sub pp_delete {
2237 my $self = shift;
9d2c6865 2238 my($op, $cx) = @_;
6e90668e 2239 my $arg;
3188a821 2240 my $name = $self->keyword("delete");
6e90668e 2241 if ($op->private & OPpSLICE) {
34a48b4b
RH
2242 if ($op->flags & OPf_SPECIAL) {
2243 # Deleting from an array, not a hash
3188a821 2244 return $self->maybe_parens_func($name,
34a48b4b
RH
2245 $self->pp_aslice($op->first, 16),
2246 $cx, 16);
2247 }
3188a821 2248 return $self->maybe_parens_func($name,
9d2c6865
SM
2249 $self->pp_hslice($op->first, 16),
2250 $cx, 16);
6e90668e 2251 } else {
34a48b4b
RH
2252 if ($op->flags & OPf_SPECIAL) {
2253 # Deleting from an array, not a hash
3188a821 2254 return $self->maybe_parens_func($name,
34a48b4b
RH
2255 $self->pp_aelem($op->first, 16),
2256 $cx, 16);
2257 }
3188a821 2258 return $self->maybe_parens_func($name,
9d2c6865
SM
2259 $self->pp_helem($op->first, 16),
2260 $cx, 16);
6e90668e 2261 }
6e90668e
SM
2262}
2263
6e90668e
SM
2264sub pp_require {
2265 my $self = shift;
9d2c6865 2266 my($op, $cx) = @_;
d5889722 2267 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
3f872cb9 2268 if (class($op) eq "UNOP" and $op->first->name eq "const"
4c1f658f 2269 and $op->first->private & OPpCONST_BARE)
6e90668e 2270 {
18228111 2271 my $name = $self->const_sv($op->first)->PV;
6e90668e
SM
2272 $name =~ s[/][::]g;
2273 $name =~ s/\.pm//g;
41df74e3 2274 return $self->maybe_parens("$opname $name", $cx, 16);
6e90668e 2275 } else {
41df74e3
FC
2276 $self->unop(
2277 $op, $cx,
c75b4828
FC
2278 $op->first->name eq 'const'
2279 && $op->first->private & OPpCONST_NOVER
2280 ? "no"
2281 : $opname,
41df74e3
FC
2282 1, # llafr does not apply
2283 );
6e90668e
SM
2284 }
2285}
2286
d989cdac 2287sub pp_scalar {
9d2c6865 2288 my $self = shift;
d9002312 2289 my($op, $cx) = @_;
9d2c6865
SM
2290 my $kid = $op->first;
2291 if (not null $kid->sibling) {
2292 # XXX Was a here-doc
2293 return $self->dquote($op);
2294 }
2295 $self->unop(@_, "scalar");
2296}
2297
2298
6e90668e
SM
2299sub padval {
2300 my $self = shift;
2301 my $targ = shift;
d989cdac 2302 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
6e90668e
SM
2303}
2304
78c72037
NC
2305sub anon_hash_or_list {
2306 my $self = shift;
d9002312 2307 my($op, $cx) = @_;
78c72037
NC
2308
2309 my($pre, $post) = @{{"anonlist" => ["[","]"],
2310 "anonhash" => ["{","}"]}->{$op->name}};
2311 my($expr, @exprs);
2312 $op = $op->first->sibling; # skip pushmark
2313 for (; !null($op); $op = $op->sibling) {
2314 $expr = $self->deparse($op, 6);
2315 push @exprs, $expr;
2316 }
d9002312
SM
2317 if ($pre eq "{" and $cx < 1) {
2318 # Disambiguate that it's not a block
2319 $pre = "+{";
2320 }
78c72037
NC
2321 return $pre . join(", ", @exprs) . $post;
2322}
2323
2324sub pp_anonlist {
d9002312
SM
2325 my $self = shift;
2326 my ($op, $cx) = @_;
78c72037 2327 if ($op->flags & OPf_SPECIAL) {
d9002312 2328 return $self->anon_hash_or_list($op, $cx);
78c72037
NC
2329 }
2330 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2331 return 'XXX';
2332}
2333
2334*pp_anonhash = \&pp_anonlist;
2335
6e90668e
SM
2336sub pp_refgen {
2337 my $self = shift;
9d2c6865 2338 my($op, $cx) = @_;
6e90668e 2339 my $kid = $op->first;
3f872cb9 2340 if ($kid->name eq "null") {
01762542
FC
2341 my $anoncode = $kid = $kid->first;
2342 if ($anoncode->name eq "anoncode"
2343 or !null($anoncode = $kid->sibling) and
2344 $anoncode->name eq "anoncode") {
2345 return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
3f872cb9
GS
2346 } elsif ($kid->name eq "pushmark") {
2347 my $sib_name = $kid->sibling->name;
c8ec376c 2348 if ($sib_name eq 'entersub') {
c8c62db7
AD
2349 my $text = $self->deparse($kid->sibling, 1);
2350 # Always show parens for \(&func()), but only with -p otherwise
2351 $text = "($text)" if $self->{'parens'}
2352 or $kid->sibling->private & OPpENTERSUB_AMPER;
2353 return "\\$text";
2354 }
2355 }
6e90668e 2356 }
c8ec376c 2357 local $self->{'in_refgen'} = 1;
9d2c6865 2358 $self->pfixop($op, $cx, "\\", 20);
6e90668e
SM
2359}
2360
09d856fb
CK
2361sub e_anoncode {
2362 my ($self, $info) = @_;
2363 my $text = $self->deparse_sub($info->{code});
7741ceed 2364 return $self->keyword("sub") . " $text";
09d856fb
CK
2365}
2366
6e90668e
SM
2367sub pp_srefgen { pp_refgen(@_) }
2368
2369sub pp_readline {
2370 my $self = shift;
9d2c6865 2371 my($op, $cx) = @_;
6e90668e 2372 my $kid = $op->first;
3f872cb9 2373 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
e31885a0
RH
2374 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2375 return $self->unop($op, $cx, "readline");
6e90668e
SM
2376}
2377
ad8caead
RGS
2378sub pp_rcatline {
2379 my $self = shift;
2380 my($op) = @_;
d989cdac 2381 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
ad8caead
RGS
2382}
2383
bd0865ec
GS
2384# Unary operators that can occur as pseudo-listops inside double quotes
2385sub dq_unop {
2386 my $self = shift;
2387 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2388 my $kid;
2389 if ($op->flags & OPf_KIDS) {
2390 $kid = $op->first;
2391 # If there's more than one kid, the first is an ex-pushmark.
2392 $kid = $kid->sibling if not null $kid->sibling;
2393 return $self->maybe_parens_unop($name, $kid, $cx);
2394 } else {
d989cdac 2395 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
bd0865ec
GS
2396 }
2397}
2398
2399sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2400sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2401sub pp_uc { dq_unop(@_, "uc") }
2402sub pp_lc { dq_unop(@_, "lc") }
3ed82cfc 2403sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
838f2281 2404sub pp_fc { dq_unop(@_, "fc") }
bd0865ec 2405
6e90668e
SM
2406sub loopex {
2407 my $self = shift;
9d2c6865 2408 my ($op, $cx, $name) = @_;
6e90668e 2409 if (class($op) eq "PVOP") {
41df74e3 2410 $name .= " " . $op->pv;
9d2c6865 2411 } elsif (class($op) eq "OP") {
41df74e3 2412 # no-op
6e90668e 2413 } elsif (class($op) eq "UNOP") {
1eb0b7be 2414 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
41df74e3 2415 $name .= " $kid";
6e90668e 2416 }
1eb0b7be 2417 return $self->maybe_parens($name, $cx, 7);
6e90668e
SM
2418}
2419
2420sub pp_last { loopex(@_, "last") }
2421sub pp_next { loopex(@_, "next") }
2422sub pp_redo { loopex(@_, "redo") }
2423sub pp_goto { loopex(@_, "goto") }
266da325 2424sub pp_dump { loopex(@_, "CORE::dump") }
6e90668e
SM
2425
2426sub ftst {
2427 my $self = shift;
9d2c6865 2428 my($op, $cx, $name) = @_;
6e90668e 2429 if (class($op) eq "UNOP") {
e38ccfd9 2430 # Genuine '-X' filetests are exempt from the LLAFR, but not
5830412d
FC
2431 # l?stat()
2432 if ($name =~ /^-/) {
2433 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2434 return $self->maybe_parens("$name $kid", $cx, 16);
2435 }
9d2c6865 2436 return $self->maybe_parens_unop($name, $op->first, $cx);
d989cdac 2437 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
9d2c6865 2438 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
6e90668e 2439 } else { # I don't think baseop filetests ever survive ck_ftst, but...
9d2c6865 2440 return $name;
6e90668e 2441 }
6e90668e
SM
2442}
2443
d989cdac
SM
2444sub pp_lstat { ftst(@_, "lstat") }
2445sub pp_stat { ftst(@_, "stat") }
2446sub pp_ftrread { ftst(@_, "-R") }
6e90668e 2447sub pp_ftrwrite { ftst(@_, "-W") }
d989cdac
SM
2448sub pp_ftrexec { ftst(@_, "-X") }
2449sub pp_fteread { ftst(@_, "-r") }
e31885a0 2450sub pp_ftewrite { ftst(@_, "-w") }
d989cdac
SM
2451sub pp_fteexec { ftst(@_, "-x") }
2452sub pp_ftis { ftst(@_, "-e") }
6e90668e
SM
2453sub pp_fteowned { ftst(@_, "-O") }
2454sub pp_ftrowned { ftst(@_, "-o") }
d989cdac
SM
2455sub pp_ftzero { ftst(@_, "-z") }
2456sub pp_ftsize { ftst(@_, "-s") }
2457sub pp_ftmtime { ftst(@_, "-M") }
2458sub pp_ftatime { ftst(@_, "-A") }
2459sub pp_ftctime { ftst(@_, "-C") }
2460sub pp_ftsock { ftst(@_, "-S") }
2461sub pp_ftchr { ftst(@_, "-c") }
2462sub pp_ftblk { ftst(@_, "-b") }
2463sub pp_ftfile { ftst(@_, "-f") }
2464sub pp_ftdir { ftst(@_, "-d") }
2465sub pp_ftpipe { ftst(@_, "-p") }
2466sub pp_ftlink { ftst(@_, "-l") }
2467sub pp_ftsuid { ftst(@_, "-u") }
2468sub pp_ftsgid { ftst(@_, "-g") }
2469sub pp_ftsvtx { ftst(@_, "-k") }
2470sub pp_fttty { ftst(@_, "-t") }
2471sub pp_fttext { ftst(@_, "-T") }
6e90668e
SM
2472sub pp_ftbinary { ftst(@_, "-B") }
2473
a798dbf2 2474sub SWAP_CHILDREN () { 1 }
6e90668e 2475sub ASSIGN () { 2 } # has OP= variant
7013e6ae 2476sub LIST_CONTEXT () { 4 } # Assignment is in list context
6e90668e 2477
9d2c6865
SM
2478my(%left, %right);
2479
2480sub assoc_class {
2481 my $op = shift;
3f872cb9
GS
2482 my $name = $op->name;
2483 if ($name eq "concat" and $op->first->name eq "concat") {
e38ccfd9 2484 # avoid spurious '=' -- see comment in pp_concat
3f872cb9 2485 return "concat";
9d2c6865 2486 }
3f872cb9
GS
2487 if ($name eq "null" and class($op) eq "UNOP"
2488 and $op->first->name =~ /^(and|x?or)$/
9d2c6865
SM
2489 and null $op->first->sibling)
2490 {
2491 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2492 # with a null that's used as the common end point of the two
2493 # flows of control. For precedence purposes, ignore it.
2494 # (COND_EXPRs have these too, but we don't bother with
2495 # their associativity).
2496 return assoc_class($op->first);
2497 }
2498 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2499}
2500
e38ccfd9 2501# Left associative operators, like '+', for which
9d2c6865
SM
2502# $a + $b + $c is equivalent to ($a + $b) + $c
2503
2504BEGIN {
3f872cb9
GS
2505 %left = ('multiply' => 19, 'i_multiply' => 19,
2506 'divide' => 19, 'i_divide' => 19,
2507 'modulo' => 19, 'i_modulo' => 19,
2508 'repeat' => 19,
2509 'add' => 18, 'i_add' => 18,
2510 'subtract' => 18, 'i_subtract' => 18,
2511 'concat' => 18,
2512 'left_shift' => 17, 'right_shift' => 17,
2513 'bit_and' => 13,
2514 'bit_or' => 12, 'bit_xor' => 12,
2515 'and' => 3,
2516 'or' => 2, 'xor' => 2,
9d2c6865
SM
2517 );
2518}
2519
2520sub deparse_binop_left {
2521 my $self = shift;
2522 my($op, $left, $prec) = @_;
58231d39 2523 if ($left{assoc_class($op)} && $left{assoc_class($left)}
9d2c6865
SM
2524 and $left{assoc_class($op)} == $left{assoc_class($left)})
2525 {
2526 return $self->deparse($left, $prec - .00001);
2527 } else {
2528 return $self->deparse($left, $prec);
2529 }
2530}
2531
e38ccfd9 2532# Right associative operators, like '=', for which
9d2c6865
SM
2533# $a = $b = $c is equivalent to $a = ($b = $c)
2534
2535BEGIN {
3f872cb9
GS
2536 %right = ('pow' => 22,
2537 'sassign=' => 7, 'aassign=' => 7,
2538 'multiply=' => 7, 'i_multiply=' => 7,
2539 'divide=' => 7, 'i_divide=' => 7,
2540 'modulo=' => 7, 'i_modulo=' => 7,
9187b6e4 2541 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
3f872cb9
GS
2542 'add=' => 7, 'i_add=' => 7,
2543 'subtract=' => 7, 'i_subtract=' => 7,
2544 'concat=' => 7,
2545 'left_shift=' => 7, 'right_shift=' => 7,
2546 'bit_and=' => 7,
2547 'bit_or=' => 7, 'bit_xor=' => 7,
2548 'andassign' => 7,
2549 'orassign' => 7,
9d2c6865
SM
2550 );
2551}
2552
2553sub deparse_binop_right {
2554 my $self = shift;
2555 my($op, $right, $prec) = @_;
58231d39 2556 if ($right{assoc_class($op)} && $right{assoc_class($right)}
9d2c6865
SM
2557 and $right{assoc_class($op)} == $right{assoc_class($right)})
2558 {
2559 return $self->deparse($right, $prec - .00001);
2560 } else {
2561 return $self->deparse($right, $prec);
2562 }
2563}
2564
a798dbf2 2565sub binop {
6e90668e 2566 my $self = shift;
9d2c6865 2567 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
a798dbf2
MB
2568 my $left = $op->first;
2569 my $right = $op->last;
9d2c6865
SM
2570 my $eq = "";
2571 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2572 $eq = "=";
2573 $prec = 7;
2574 }
a798dbf2
MB
2575 if ($flags & SWAP_CHILDREN) {
2576 ($left, $right) = ($right, $left);
2577 }
6a861075 2578 my $leftop = $left;
9d2c6865 2579 $left = $self->deparse_binop_left($op, $left, $prec);
90c0eb26 2580 $left = "($left)" if $flags & LIST_CONTEXT
6a861075
FC
2581 and $left !~ /^(my|our|local|)[\@\(]/
2582 || do {
2583 # Parenthesize if the left argument is a
2584 # lone repeat op.
2585 my $left = $leftop->first->sibling;
2586 $left->name eq 'repeat'
2587 && null($left->sibling);
2588 };
9d2c6865
SM
2589 $right = $self->deparse_binop_right($op, $right, $prec);
2590 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2591}
2592
3ed82cfc
GS
2593sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2594sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2595sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2596sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2597sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2598sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2599sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2600sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2601sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2602sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2603sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2604
2605sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2606sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2607sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2608sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2609sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
9d2c6865
SM
2610
2611sub pp_eq { binop(@_, "==", 14) }
2612sub pp_ne { binop(@_, "!=", 14) }
2613sub pp_lt { binop(@_, "<", 15) }
2614sub pp_gt { binop(@_, ">", 15) }
2615sub pp_ge { binop(@_, ">=", 15) }
2616sub pp_le { binop(@_, "<=", 15) }
2617sub pp_ncmp { binop(@_, "<=>", 14) }
2618sub pp_i_eq { binop(@_, "==", 14) }
2619sub pp_i_ne { binop(@_, "!=", 14) }
2620sub pp_i_lt { binop(@_, "<", 15) }
2621sub pp_i_gt { binop(@_, ">", 15) }
2622sub pp_i_ge { binop(@_, ">=", 15) }
2623sub pp_i_le { binop(@_, "<=", 15) }
2624sub pp_i_ncmp { binop(@_, "<=>", 14) }
2625
2626sub pp_seq { binop(@_, "eq", 14) }
2627sub pp_sne { binop(@_, "ne", 14) }
2628sub pp_slt { binop(@_, "lt", 15) }
2629sub pp_sgt { binop(@_, "gt", 15) }
2630sub pp_sge { binop(@_, "ge", 15) }
2631sub pp_sle { binop(@_, "le", 15) }
2632sub pp_scmp { binop(@_, "cmp", 14) }
2633
2634sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
7013e6ae 2635sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
6e90668e 2636
0d863452
RH
2637sub pp_smartmatch {
2638 my ($self, $op, $cx) = @_;
2639 if ($op->flags & OPf_SPECIAL) {
9210de83 2640 return $self->deparse($op->last, $cx);
0d863452
RH
2641 }
2642 else {
2643 binop(@_, "~~", 14);
2644 }
2645}
2646
e38ccfd9 2647# '.' is special because concats-of-concats are optimized to save copying
6e90668e 2648# by making all but the first concat stacked. The effect is as if the
e38ccfd9 2649# programmer had written '($a . $b) .= $c', except legal.
3ed82cfc
GS
2650sub pp_concat { maybe_targmy(@_, \&real_concat) }
2651sub real_concat {
6e90668e 2652 my $self = shift;
9d2c6865 2653 my($op, $cx) = @_;
6e90668e
SM
2654 my $left = $op->first;
2655 my $right = $op->last;
2656 my $eq = "";
9d2c6865 2657 my $prec = 18;
3f872cb9 2658 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
6e90668e 2659 $eq = "=";
9d2c6865 2660 $prec = 7;
6e90668e 2661 }
9d2c6865
SM
2662 $left = $self->deparse_binop_left($op, $left, $prec);
2663 $right = $self->deparse_binop_right($op, $right, $prec);
2664 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
6e90668e
SM
2665}
2666
6402d4ee
FC
2667sub pp_repeat { maybe_targmy(@_, \&repeat) }
2668
e38ccfd9 2669# 'x' is weird when the left arg is a list
6402d4ee 2670sub repeat {
6e90668e 2671 my $self = shift;
9d2c6865 2672 my($op, $cx) = @_;
6e90668e
SM
2673 my $left = $op->first;
2674 my $right = $op->last;
9d2c6865
SM
2675 my $eq = "";
2676 my $prec = 19;
2677 if ($op->flags & OPf_STACKED) {
2678 $eq = "=";
2679 $prec = 7;
2680 }
6e90668e 2681 if (null($right)) { # list repeat; count is inside left-side ex-list
5e462669 2682 # in 5.21.5 and earlier
6e90668e
SM
2683 my $kid = $left->first->sibling; # skip pushmark
2684 my @exprs;
2685 for (; !null($kid->sibling); $kid = $kid->sibling) {
9d2c6865 2686 push @exprs, $self->deparse($kid, 6);
6e90668e
SM
2687 }
2688 $right = $kid;
2689 $left = "(" . join(", ", @exprs). ")";
2690 } else {
5e462669
FC
2691 my $dolist = $op->private & OPpREPEAT_DOLIST;
2692 $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
2693 if ($dolist) {
2694 $left = "($left)";
2695 }
6e90668e 2696 }
9d2c6865
SM
2697 $right = $self->deparse_binop_right($op, $right, $prec);
2698 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
6e90668e
SM
2699}
2700
2701sub range {
2702 my $self = shift;
9d2c6865 2703 my ($op, $cx, $type) = @_;
6e90668e
SM
2704 my $left = $op->first;
2705 my $right = $left->sibling;
9d2c6865
SM
2706 $left = $self->deparse($left, 9);
2707 $right = $self->deparse($right, 9);
2708 return $self->maybe_parens("$left $type $right", $cx, 9);
6e90668e
SM
2709}
2710
2711sub pp_flop {
2712 my $self = shift;
9d2c6865 2713 my($op, $cx) = @_;
6e90668e
SM
2714 my $flip = $op->first;
2715 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
9d2c6865 2716 return $self->range($flip->first, $cx, $type);
6e90668e
SM
2717}
2718
2719# one-line while/until is handled in pp_leave
2720
2721sub logop {
2722 my $self = shift;
9d2c6865 2723 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
6e90668e
SM
2724 my $left = $op->first;
2725 my $right = $op->first->sibling;
7741ceed 2726 $blockname &&= $self->keyword($blockname);
d989cdac 2727 if ($cx < 1 and is_scope($right) and $blockname
58cccf98
SM
2728 and $self->{'expand'} < 7)
2729 { # if ($a) {$b}
9d2c6865
SM
2730 $left = $self->deparse($left, 1);
2731 $right = $self->deparse($right, 0);
2732 return "$blockname ($left) {\n\t$right\n\b}\cK";
d989cdac 2733 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
58cccf98 2734 and $self->{'expand'} < 7) { # $b if $a
9d2c6865
SM
2735 $right = $self->deparse($right, 1);
2736 $left = $self->deparse($left, 1);
2737 return "$right $blockname $left";
2738 } elsif ($cx > $lowprec and $highop) { # $a && $b
2739 $left = $self->deparse_binop_left($op, $left, $highprec);
2740 $right = $self->deparse_binop_right($op, $right, $highprec);
2741 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2742 } else { # $a and $b
2743 $left = $self->deparse_binop_left($op, $left, $lowprec);
2744 $right = $self->deparse_binop_right($op, $right, $lowprec);
d989cdac 2745 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
9d2c6865
SM
2746 }
2747}
2748
2749sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
f4a44678 2750sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
5b99f273 2751sub pp_dor { logop(@_, "//", 10) }
3ed82cfc
GS
2752
2753# xor is syntactically a logop, but it's really a binop (contrary to
2754# old versions of opcode.pl). Syntax is what matters here.
9d2c6865 2755sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
6e90668e
SM
2756
2757sub logassignop {
2758 my $self = shift;
9d2c6865 2759 my ($op, $cx, $opname) = @_;
6e90668e
SM
2760 my $left = $op->first;
2761 my $right = $op->first->sibling->first; # skip sassign
9d2c6865
SM
2762 $left = $self->deparse($left, 7);
2763 $right = $self->deparse($right, 7);
2764 return $self->maybe_parens("$left $opname $right", $cx, 7);
a798dbf2
MB
2765}
2766
6e90668e 2767sub pp_andassign { logassignop(@_, "&&=") }
c963b151
BD
2768sub pp_orassign { logassignop(@_, "||=") }
2769sub pp_dorassign { logassignop(@_, "//=") }
6e90668e 2770
b89b7257
FC
2771sub rv2gv_or_string {
2772 my($self,$op) = @_;
2773 if ($op->name eq "gv") { # could be open("open") or open("###")
be6cf5cf 2774 my($name,$quoted) =
1db94eeb 2775 $self->stash_variable_name("", $self->gv_or_padgv($op));
be6cf5cf 2776 $quoted ? $name : "*$name";
b89b7257
FC
2777 }
2778 else {
2779 $self->deparse($op, 6);
2780 }
2781}
2782
6e90668e
SM
2783sub listop {
2784 my $self = shift;
9c56d9ea 2785 my($op, $cx, $name, $kid, $nollafr) = @_;
9d2c6865
SM
2786 my(@exprs);
2787 my $parens = ($cx >= 5) || $self->{'parens'};
24fcb59f 2788 $kid ||= $op->first->sibling;
4d8ac5c7
FC
2789 # If there are no arguments, add final parentheses (or parenthesize the
2790 # whole thing if the llafr does not apply) to account for cases like
2791 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
2792 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2793 if (null $kid) {
2794 return $nollafr
2795 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2796 : $self->keyword($name) . '()' x (7 < $cx);
2797 }
e31885a0 2798 my $first;
4a1ac32e 2799 my $fullname = $self->keyword($name);
b72c97e8 2800 my $proto = prototype("CORE::$name");
bc1cc2c3
DM
2801 if (
2802 ( (defined $proto && $proto =~ /^;?\*/)
2803 || $name eq 'select' # select(F) doesn't have a proto
2804 )
2805 && $kid->name eq "rv2gv"
2806 && !($kid->private & OPpLVAL_INTRO)
2807 ) {
b89b7257 2808 $first = $self->rv2gv_or_string($kid->first);
e31885a0
RH
2809 }
2810 else {
2811 $first = $self->deparse($kid, 6);
2812 }
e99ebc55 2813 if ($name eq "chmod" && $first =~ /^\d+$/) {
a0035eb8 2814 $first = sprintf("%#o", $first);
e99ebc55 2815 }
9c56d9ea
FC
2816 $first = "+$first"
2817 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
9d2c6865
SM
2818 push @exprs, $first;
2819 $kid = $kid->sibling;
564cd6cb
FC
2820 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2821 && !($kid->private & OPpLVAL_INTRO)) {
b89b7257 2822 push @exprs, $first = $self->rv2gv_or_string($kid->first);
b72c97e8
RGS
2823 $kid = $kid->sibling;
2824 }
9d2c6865
SM
2825 for (; !null($kid); $kid = $kid->sibling) {
2826 push @exprs, $self->deparse($kid, 6);
2827 }
689e417f 2828 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
4a1ac32e
FC
2829 return "$exprs[0] = $fullname"
2830 . ($parens ? "($exprs[0])" : " $exprs[0]");
689e417f 2831 }
327088eb
DM
2832 if ($name =~ /^(system|exec)$/
2833 && ($op->flags & OPf_STACKED)
2834 && @exprs > 1)
2835 {
2836 # handle the "system prog a1,a2,.." form
2837 my $prog = shift @exprs;
2838 $exprs[0] = "$prog $exprs[0]";
2839 }
2840
9c56d9ea
FC
2841 if ($parens && $nollafr) {
2842 return "($fullname " . join(", ", @exprs) . ")";
2843 } elsif ($parens) {
4a1ac32e 2844 return "$fullname(" . join(", ", @exprs) . ")";
9d2c6865 2845 } else {
4a1ac32e 2846 return "$fullname " . join(", ", @exprs);
6e90668e 2847 }
6e90668e 2848}
a798dbf2 2849
6e90668e 2850sub pp_bless { listop(@_, "bless") }
3ed82cfc 2851sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
24fcb59f
FC
2852sub pp_substr {
2853 my ($self,$op,$cx) = @_;
2854 if ($op->private & OPpSUBSTR_REPL_FIRST) {
2855 return
2856 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2857 . " = "
2858 . $self->deparse($op->first->sibling, 7);
2859 }
2860 maybe_local(@_, listop(@_, "substr"))
2861}
6402d4ee 2862sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
3ed82cfc
GS
2863sub pp_index { maybe_targmy(@_, \&listop, "index") }
2864sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2865sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
6e90668e 2866sub pp_formline { listop(@_, "formline") } # see also deparse_format
3ed82cfc 2867sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
6e90668e
SM
2868sub pp_unpack { listop(@_, "unpack") }
2869sub pp_pack { listop(@_, "pack") }
3ed82cfc 2870sub pp_join { maybe_targmy(@_, \&listop, "join") }
6e90668e 2871sub pp_splice { listop(@_, "splice") }
3ed82cfc
GS
2872sub pp_push { maybe_targmy(@_, \&listop, "push") }
2873sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
6e90668e
SM
2874sub pp_reverse { listop(@_, "reverse") }
2875sub pp_warn { listop(@_, "warn") }
2876sub pp_die { listop(@_, "die") }
9c56d9ea 2877sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
6e90668e
SM
2878sub pp_open { listop(@_, "open") }
2879sub pp_pipe_op { listop(@_, "pipe") }
2880sub pp_tie { listop(@_, "tie") }
82bafd27 2881sub pp_binmode { listop(@_, "binmode") }
6e90668e
SM
2882sub pp_dbmopen { listop(@_, "dbmopen") }
2883sub pp_sselect { listop(@_, "select") }
2884sub pp_select { listop(@_, "select") }
2885sub pp_read { listop(@_, "read") }
2886sub pp_sysopen { listop(@_, "sysopen") }
2887sub pp_sysseek { listop(@_, "sysseek") }
2888sub pp_sysread { listop(@_, "sysread") }
2889sub pp_syswrite { listop(@_, "syswrite") }
2890sub pp_send { listop(@_, "send") }
2891sub pp_recv { listop(@_, "recv") }
2892sub pp_seek { listop(@_, "seek") }
6e90668e
SM
2893sub pp_fcntl { listop(@_, "fcntl") }
2894sub pp_ioctl { listop(@_, "ioctl") }
3ed82cfc 2895sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
6e90668e 2896sub pp_socket { listop(@_, "socket") }
5deb1341 2897sub pp_sockpair { listop(@_, "socketpair") }
6e90668e
SM
2898sub pp_bind { listop(@_, "bind") }
2899sub pp_connect { listop(@_, "connect") }
2900sub pp_listen { listop(@_, "listen") }
2901sub pp_accept { listop(@_, "accept") }
2902sub pp_shutdown { listop(@_, "shutdown") }
2903sub pp_gsockopt { listop(@_, "getsockopt") }
2904sub pp_ssockopt { listop(@_, "setsockopt") }
3ed82cfc
GS
2905sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2906sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2907sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2908sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2909sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2910sub pp_link { maybe_targmy(@_, \&listop, "link") }
2911sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2912sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
6e90668e
SM
2913sub pp_open_dir { listop(@_, "opendir") }
2914sub pp_seekdir { listop(@_, "seekdir") }
3ed82cfc
GS
2915sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2916sub pp_system { maybe_targmy(@_, \&listop, "system") }
2917sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2918sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2919sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2920sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2921sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
6e90668e
SM
2922sub pp_shmget { listop(@_, "shmget") }
2923sub pp_shmctl { listop(@_, "shmctl") }
2924sub pp_shmread { listop(@_, "shmread") }
2925sub pp_shmwrite { listop(@_, "shmwrite") }
2926sub pp_msgget { listop(@_, "msgget") }
2927sub pp_msgctl { listop(@_, "msgctl") }
2928sub pp_msgsnd { listop(@_, "msgsnd") }
2929sub pp_msgrcv { listop(@_, "msgrcv") }
2930sub pp_semget { listop(@_, "semget") }
2931sub pp_semctl { listop(@_, "semctl") }
2932sub pp_semop { listop(@_, "semop") }
2933sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2934sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2935sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2936sub pp_gsbyname { listop(@_, "getservbyname") }
2937sub pp_gsbyport { listop(@_, "getservbyport") }
2938sub pp_syscall { listop(@_, "syscall") }
2939
2940sub pp_glob {
2941 my $self = shift;
9d2c6865 2942 my($op, $cx) = @_;
93860275 2943 my $kid = $op->first->sibling; # skip pushmark
a32fbbd8
FC
2944 my $keyword =
2945 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
93860275
FC
2946 my $text;
2947 if ($keyword =~ /^CORE::/
2948 or $kid->name ne 'const'
2949 or ($text = $self->dq($kid))
2950 =~ /^\$?(\w|::|\`)+$/ # could look like a readline
a32fbbd8 2951 or $text =~ /[<>]/) {
93860275
FC
2952 $text = $self->deparse($kid);
2953 return $cx >= 5 || $self->{'parens'}
2954 ? "$keyword($text)"
2955 : "$keyword $text";
6e90668e
SM
2956 } else {
2957 return '<' . $text . '>';
2958 }
2959}
2960
f5aa8f4e
SM
2961# Truncate is special because OPf_SPECIAL makes a bareword first arg
2962# be a filehandle. This could probably be better fixed in the core
2963# by moving the GV lookup into ck_truc.
2964
2965sub pp_truncate {
2966 my $self = shift;
2967 my($op, $cx) = @_;
2968 my(@exprs);
2969 my $parens = ($cx >= 5) || $self->{'parens'};
2970 my $kid = $op->first->sibling;
acba1d67 2971 my $fh;
f5aa8f4e
SM
2972 if ($op->flags & OPf_SPECIAL) {
2973 # $kid is an OP_CONST
18228111 2974 $fh = $self->const_sv($kid)->PV;
f5aa8f4e
SM
2975 } else {
2976 $fh = $self->deparse($kid, 6);
2977 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2978 }
2979 my $len = $self->deparse($kid->sibling, 6);
4a1ac32e 2980 my $name = $self->keyword('truncate');
f5aa8f4e 2981 if ($parens) {
4a1ac32e 2982 return "$name($fh, $len)";
f5aa8f4e 2983 } else {
4a1ac32e 2984 return "$name $fh, $len";
f5aa8f4e 2985 }
f5aa8f4e
SM
2986}
2987
6e90668e
SM
2988sub indirop {
2989 my $self = shift;
9d2c6865 2990 my($op, $cx, $name) = @_;
6e90668e 2991 my($expr, @exprs);
521795fe 2992 my $firstkid = my $kid = $op->first->sibling;
6e90668e
SM
2993 my $indir = "";
2994 if ($op->flags & OPf_STACKED) {
2995 $indir = $kid;
2996 $indir = $indir->first; # skip rv2gv
2997 if (is_scope($indir)) {
9d2c6865 2998 $indir = "{" . $self->deparse($indir, 0) . "}";
d989cdac 2999 $indir = "{;}" if $indir eq "{}";
c73811ab
RH
3000 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
3001 $indir = $self->const_sv($indir)->PV;
6e90668e 3002 } else {
9d2c6865 3003 $indir = $self->deparse($indir, 24);
6e90668e
SM
3004 }
3005 $indir = $indir . " ";
3006 $kid = $kid->sibling;
3007 }
7e80da18 3008 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3ac6e0f9 3009 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
7e80da18
RH
3010 : '{$a <=> $b} ';
3011 }
3ac6e0f9 3012 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
7e80da18
RH
3013 $indir = '{$b cmp $a} ';
3014 }
6e90668e 3015 for (; !null($kid); $kid = $kid->sibling) {
521795fe 3016 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
6e90668e
SM
3017 push @exprs, $expr;
3018 }
4a1ac32e 3019 my $name2;
3ac6e0f9 3020 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
4a1ac32e 3021 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3ac6e0f9 3022 }
4a1ac32e 3023 else { $name2 = $self->keyword($name) }
2b6e98cb 3024 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3ac6e0f9 3025 return "$exprs[0] = $name2 $indir $exprs[0]";
2b6e98cb
DM
3026 }
3027
d989cdac 3028 my $args = $indir . join(", ", @exprs);
521795fe 3029 if ($indir ne "" && $name eq "sort") {
d989cdac
SM
3030 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
3031 # give bareword warnings in that case. Therefore if context
3032 # requires, we'll put parens around the outside "(sort f 1, 2,
3033 # 3)". Unfortunately, we'll currently think the parens are
3c4b39be 3034 # necessary more often that they really are, because we don't
d989cdac
SM
3035 # distinguish which side of an assignment we're on.
3036 if ($cx >= 5) {
3ac6e0f9 3037 return "($name2 $args)";
d989cdac 3038 } else {
3ac6e0f9 3039 return "$name2 $args";
d989cdac 3040 }
521795fe
FC
3041 } elsif (
3042 !$indir && $name eq "sort"
ca331985 3043 && !null($op->first->sibling)
521795fe
FC
3044 && $op->first->sibling->name eq 'entersub'
3045 ) {
3046 # We cannot say sort foo(bar), as foo will be interpreted as a
3047 # comparison routine. We have to say sort(...) in that case.
3048 return "$name2($args)";
d989cdac 3049 } else {
3ac6e0f9 3050 return $self->maybe_parens_func($name2, $args, $cx, 5);
d989cdac
SM
3051 }
3052
6e90668e
SM
3053}
3054
3055sub pp_prtf { indirop(@_, "printf") }
3056sub pp_print { indirop(@_, "print") }
9b08e3d3 3057sub pp_say { indirop(@_, "say") }
6e90668e
SM
3058sub pp_sort { indirop(@_, "sort") }
3059
3060sub mapop {
3061 my $self = shift;
9d2c6865 3062 my($op, $cx, $name) = @_;
6e90668e
SM
3063 my($expr, @exprs);
3064 my $kid = $op->first; # this is the (map|grep)start
3065 $kid = $kid->first->sibling; # skip a pushmark
3066 my $code = $kid->first; # skip a null
3067 if (is_scope $code) {
f4a44678 3068 $code = "{" . $self->deparse($code, 0) . "} ";
6e90668e 3069 } else {
6d08f7b3
DM
3070 $code = $self->deparse($code, 24);
3071 $code .= ", " if !null($kid->sibling);
6e90668e
SM
3072 }
3073 $kid = $kid->sibling;
3074 for (; !null($kid); $kid = $kid->sibling) {
9d2c6865 3075 $expr = $self->deparse($kid, 6);
9a58b761 3076 push @exprs, $expr if defined $expr;
6e90668e 3077 }
3188a821
FC
3078 return $self->maybe_parens_func($self->keyword($name),
3079 $code . join(", ", @exprs), $cx, 5);
6e90668e
SM
3080}
3081
d989cdac
SM
3082sub pp_mapwhile { mapop(@_, "map") }
3083sub pp_grepwhile { mapop(@_, "grep") }
11e09183
SP
3084sub pp_mapstart { baseop(@_, "map") }
3085sub pp_grepstart { baseop(@_, "grep") }
6e90668e 3086
12cea2fa
FC
3087my %uses_intro;
3088BEGIN {
3089 @uses_intro{
3090 eval { require B::Op_private }
e58dedd3 3091 ? @{$B::Op_private::ops_using{OPpLVAL_INTRO}}
12cea2fa
FC
3092 : qw(gvsv rv2sv rv2hv rv2gv rv2av aelem helem aslice
3093 hslice delete padsv padav padhv enteriter entersub padrange
3094 pushmark cond_expr refassign list)
3095 } = ();
3096 delete @uses_intro{qw( lvref lvrefslice lvavref )};
3097}
3098
6e90668e
SM
3099sub pp_list {
3100 my $self = shift;
9d2c6865 3101 my($op, $cx) = @_;
6e90668e
SM
3102 my($expr, @exprs);
3103 my $kid = $op->first->sibling; # skip pushmark
958ed56b 3104 return '' if class($kid) eq 'NULL';
6e90668e 3105 my $lop;
3462b4ac 3106 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
56cd2ef8 3107 my $type;
6e90668e 3108 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3b4e80b8 3109 my $lopname = $lop->name;
5f4d8496 3110 my $loppriv = $lop->private;
56cd2ef8 3111 my $newtype;
12cea2fa 3112 if ($lopname =~ /^pad[ash]v$/ && $loppriv & OPpLVAL_INTRO) {
5f4d8496
FC
3113 if ($loppriv & OPpPAD_STATE) { # state()
3114 ($local = "", last) if $local !~ /^(?:either|state)$/;
3462b4ac
RGS
3115 $local = "state";
3116 } else { # my()
5f4d8496 3117 ($local = "", last) if $local !~ /^(?:either|my)$/;
3462b4ac
RGS
3118 $local = "my";
3119 }
56cd2ef8
FC
3120 my $padname = $self->padname_sv($lop->targ);
3121 if ($padname->FLAGS & SVpad_TYPED) {
3122 $newtype = $padname->SvSTASH->NAME;
3123 }
3b4e80b8 3124 } elsif ($lopname =~ /^(?:gv|rv2)([ash])v$/
5f4d8496 3125 && $loppriv & OPpOUR_INTRO
3b4e80b8 3126 or $lopname eq "null" && $lop->first->name eq "gvsv"
b8e103fc 3127 && $lop->first->private & OPpOUR_INTRO) { # our()
5f4d8496
FC
3128 my $newlocal = "local " x !!($loppriv & OPpLVAL_INTRO) . "our";
3129 ($local = "", last)
3130 if $local ne 'either' && $local ne $newlocal;
3131 $local = $newlocal;
56cd2ef8
FC
3132 my $funny = !$1 || $1 eq 's' ? '$' : $1 eq 'a' ? '@' : '%';
3133 if (my $t = $self->find_our_type(
3134 $funny . $self->gv_or_padgv($lop->first)->NAME
3135 )) {
3136 $newtype = $t;
3137 }
12cea2fa
FC
3138 } elsif ($lopname ne 'undef'
3139 and !($loppriv & OPpLVAL_INTRO)
3140 || !exists $uses_intro{$lopname eq 'null'
3141 ? substr B::ppname($lop->targ), 3
3142 : $lopname})
3143 {
3144 $local = ""; # or not
3145 last;
3146 } elsif ($lopname ne "undef")
3ac6e0f9
RGS
3147 {
3148 # local()
5f4d8496 3149 ($local = "", last) if $local !~ /^(?:either|local)$/;
6e90668e
SM
3150 $local = "local";
3151 }
56cd2ef8
FC
3152 if (defined $type && defined $newtype && $newtype ne $type) {
3153 $local = '';
3154 last;
3155 }
3156 $type = $newtype;
6e90668e
SM
3157 }
3158 $local = "" if $local eq "either"; # no point if it's all undefs
5f4d8496 3159 $local &&= join ' ', map $self->keyword($_), split / /, $local;
56cd2ef8 3160 $local .= " $type " if $local && length $type;
f5aa8f4e 3161 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
6e90668e
SM
3162 for (; !null($kid); $kid = $kid->sibling) {
3163 if ($local) {
3f872cb9 3164 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
6e90668e
SM
3165 $lop = $kid->first;
3166 } else {
3167 $lop = $kid;
3168 }
3169 $self->{'avoid_local'}{$$lop}++;
9d2c6865 3170 $expr = $self->deparse($kid, 6);
6e90668e
SM
3171 delete $self->{'avoid_local'}{$$lop};
3172 } else {
9d2c6865 3173 $expr = $self->deparse($kid, 6);
6e90668e
SM
3174 }
3175 push @exprs, $expr;
3176 }
9d2c6865
SM
3177 if ($local) {
3178 return "$local(" . join(", ", @exprs) . ")";
3179 } else {
3180 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
3181 }
6e90668e
SM
3182}
3183
6f611a1a
GS
3184sub is_ifelse_cont {
3185 my $op = shift;
3186 return ($op->name eq "null" and class($op) eq "UNOP"
3187 and $op->first->name =~ /^(and|cond_expr)$/
3188 and is_scope($op->first->first->sibling));
3189}
3190
6e90668e
SM
3191sub pp_cond_expr {
3192 my $self = shift;
9d2c6865 3193 my($op, $cx) = @_;
6e90668e
SM
3194 my $cond = $op->first;
3195 my $true = $cond->sibling;
3196 my $false = $true->sibling;
9d2c6865 3197 my $cuddle = $self->{'cuddle'};
d989cdac 3198 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
58cccf98
SM
3199 (is_scope($false) || is_ifelse_cont($false))
3200 and $self->{'expand'} < 7) {
f5aa8f4e 3201 $cond = $self->deparse($cond, 8);
cfaba469 3202 $true = $self->deparse($true, 6);
9d2c6865
SM
3203 $false = $self->deparse($false, 8);
3204 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
6f611a1a
GS
3205 }
3206
f5aa8f4e 3207 $cond = $self->deparse($cond, 1);
d989cdac 3208 $true = $self->deparse($true, 0);
7741ceed 3209 my $head = $self->keyword("if") . " ($cond) {\n\t$true\n\b}";
6f611a1a 3210 my @elsifs;
7741ceed 3211 my $elsif;
6f611a1a
GS
3212 while (!null($false) and is_ifelse_cont($false)) {
3213 my $newop = $false->first;
3214 my $newcond = $newop->first;
3215 my $newtrue = $newcond->sibling;
3216 $false = $newtrue->sibling; # last in chain is OP_AND => no else
7ecdd211
PJ
3217 if ($newcond->name eq "lineseq")
3218 {
3219 # lineseq to ensure correct line numbers in elsif()
3220 # Bug #37302 fixed by change #33710.
3221 $newcond = $newcond->first->sibling;
3222 }
6f611a1a
GS
3223 $newcond = $self->deparse($newcond, 1);
3224 $newtrue = $self->deparse($newtrue, 0);
7741ceed
FC
3225 $elsif ||= $self->keyword("elsif");
3226 push @elsifs, "$elsif ($newcond) {\n\t$newtrue\n\b}";
6f611a1a 3227 }
d989cdac 3228 if (!null($false)) {
7741ceed 3229 $false = $cuddle . $self->keyword("else") . " {\n\t" .
6f611a1a
GS
3230 $self->deparse($false, 0) . "\n\b}\cK";
3231 } else {
3232 $false = "\cK";
6e90668e 3233 }
d989cdac 3234 return $head . join($cuddle, "", @elsifs) . $false;
6e90668e
SM
3235}
3236
95562366
NC
3237sub pp_once {
3238 my ($self, $op, $cx) = @_;
3239 my $cond = $op->first;
3240 my $true = $cond->sibling;
3241
a1b22abd
FC
3242 my $ret = $self->deparse($true, $cx);
3243 $ret =~ s/^(\(?)\$/$1 . $self->keyword("state") . ' $'/e;
3244 $ret;
95562366
NC
3245}
3246
58cccf98 3247sub loop_common {
6e90668e 3248 my $self = shift;
58cccf98 3249 my($op, $cx, $init) = @_;
6e90668e
SM
3250 my $enter = $op->first;
3251 my $kid = $enter->sibling;
0ced6c29
RGS
3252 local(@$self{qw'curstash warnings hints hinthash'})
3253 = @$self{qw'curstash warnings hints hinthash'};
6e90668e 3254 my $head = "";
9d2c6865 3255 my $bare = 0;
58cccf98
SM
3256 my $body;
3257 my $cond = undef;
22584011 3258 my $name;
d989cdac 3259 if ($kid->name eq "lineseq") { # bare or infinite loop
241416b8 3260 if ($kid->last->name eq "unstack") { # infinite
e99ebc55 3261 $head = "while (1) "; # Can't use for(;;) if there's a continue
58cccf98 3262 $cond = "";
9d2c6865
SM
3263 } else {
3264 $bare = 1;
6e90668e 3265 }
58cccf98 3266 $body = $kid;
3f872cb9 3267 } elsif ($enter->name eq "enteriter") { # foreach
6e90668e
SM
3268 my $ary = $enter->first->sibling; # first was pushmark
3269 my $var = $ary->sibling;
36d57d93
RGS
3270 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
3271 # "reverse" was optimised away
aae53c41 3272 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
36d57d93 3273 } elsif ($enter->flags & OPf_STACKED
f5aa8f4e
SM
3274 and not null $ary->first->sibling->sibling)
3275 {
d7f5b6da
SM
3276 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
3277 $self->deparse($ary->first->sibling->sibling, 9);
d8d95777
GA
3278 } else {
3279 $ary = $self->deparse($ary, 1);
3280 }
6e90668e 3281 if (null $var) {
dacd2ca7 3282 $var = $self->pp_padsv($enter, 1, 1);
3f872cb9 3283 } elsif ($var->name eq "rv2gv") {
9d2c6865 3284 $var = $self->pp_rv2sv($var, 1);
241416b8
DM
3285 if ($enter->private & OPpOUR_INTRO) {
3286 # our declarations don't have package names
3287 $var =~ s/^(.).*::/$1/;
3288 $var = "our $var";
3289 }
3f872cb9 3290 } elsif ($var->name eq "gv") {
9d2c6865 3291 $var = "\$" . $self->deparse($var, 1);
9187b6e4
FC
3292 } else {
3293 $var = $self->deparse($var, 1);
6e90668e 3294 }
58cccf98 3295 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
afb60448 3296 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
cf24a840
SM
3297 confess unless $var eq '$_';
3298 $body = $body->first;
7741ceed
FC
3299 return $self->deparse($body, 2) . " "
3300 . $self->keyword("foreach") . " ($ary)";
cf24a840
SM
3301 }
3302 $head = "foreach $var ($ary) ";
3f872cb9 3303 } elsif ($kid->name eq "null") { # while/until
6e90668e 3304 $kid = $kid->first;
22584011
FC
3305 $name = {"and" => "while", "or" => "until"}->{$kid->name};
3306 $cond = $kid->first;
58cccf98 3307 $body = $kid->first->sibling;
3f872cb9 3308 } elsif ($kid->name eq "stub") { # bare and empty
9d2c6865 3309 return "{;}"; # {} could be a hashref
6e90668e 3310 }
58cccf98 3311 # If there isn't a continue block, then the next pointer for the loop
241416b8 3312 # will point to the unstack, which is kid's last child, except
58cccf98 3313 # in a bare loop, when it will point to the leaveloop. When neither of
241416b8 3314 # these conditions hold, then the second-to-last child is the continue
58cccf98
SM
3315 # block (or the last in a bare loop).
3316 my $cont_start = $enter->nextop;
3317 my $cont;
22584011
FC
3318 my $precond;
3319 my $postcond;
241416b8 3320 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
58cccf98
SM
3321 if ($bare) {
3322 $cont = $body->last;
3323 } else {
3324 $cont = $body->first;
241416b8 3325 while (!null($cont->sibling->sibling)) {
58cccf98
SM
3326 $cont = $cont->sibling;
3327 }
3328 }
3329 my $state = $body->first;
3330 my $cuddle = $self->{'cuddle'};
3331 my @states;
3332 for (; $$state != $$cont; $state = $state->sibling) {
3333 push @states, $state;
3334 }
93a8ff62 3335 $body = $self->lineseq(undef, 0, @states);
58cccf98 3336 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
22584011
FC
3337 $precond = "for ($init; ";
3338 $postcond = "; " . $self->deparse($cont, 1) .") ";
58cccf98
SM
3339 $cont = "\cK";
3340 } else {
3341 $cont = $cuddle . "continue {\n\t" .
3342 $self->deparse($cont, 0) . "\n\b}\cK";
6e90668e 3343 }
6e90668e 3344 } else {
7a9b44b9 3345 return "" if !defined $body;
c73811ab 3346 if (length $init) {
22584011
FC
3347 $precond = "for ($init; ";
3348 $postcond = ";) ";
c73811ab 3349 }
9d2c6865 3350 $cont = "\cK";
58cccf98 3351 $body = $self->deparse($body, 0);
6e90668e 3352 }
22584011 3353 if ($precond) { # for(;;)
88a758b5
FC
3354 $cond &&= $name eq 'until'
3355 ? listop($self, undef, 1, "not", $cond->first)
3356 : $self->deparse($cond, 1);
22584011
FC
3357 $head = "$precond$cond$postcond";
3358 }
3359 if ($name && !$head) {
3360 ref $cond and $cond = $self->deparse($cond, 1);
3361 $head = "$name ($cond) ";
3362 }
7741ceed 3363 $head =~ s/^(for(?:each)?|while|until)/$self->keyword($1)/e;
ce4e655d 3364 $body =~ s/;?$/;\n/;
34a48b4b
RH
3365
3366 return $head . "{\n\t" . $body . "\b}" . $cont;
58cccf98
SM
3367}
3368
09d856fb 3369sub pp_leaveloop { shift->loop_common(@_, "") }
58cccf98
SM
3370
3371sub for_loop {
3372 my $self = shift;
3373 my($op, $cx) = @_;
3374 my $init = $self->deparse($op, 1);
eae48c89
Z
3375 my $s = $op->sibling;
3376 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3377 return $self->loop_common($ll, $cx, $init);
6e90668e
SM
3378}
3379
3380sub pp_leavetry {
3381 my $self = shift;
9d2c6865 3382 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
bd0865ec 3383}
6e90668e 3384
7d3c8a68
SM
3385sub _op_is_or_was {
3386 my ($op, $expect_type) = @_;
3387 my $type = $op->type;
3388 return($type == $expect_type
3389 || ($type == OP_NULL && $op->targ == $expect_type));
3390}
3391
a798dbf2 3392sub pp_null {
34b54951 3393 my($self, $op, $cx) = @_;
6e90668e 3394 if (class($op) eq "OP") {
f4a44678
SM
3395 # old value is lost
3396 return $self->{'ex_const'} if $op->targ == OP_CONST;
619dadb5 3397 } elsif (class ($op) eq "COP") {
34b54951 3398 return &pp_nextstate;
7d3c8a68
SM
3399 } elsif ($op->first->name eq 'pushmark'
3400 or $op->first->name eq 'null'
3401 && $op->first->targ == OP_PUSHMARK
3402 && _op_is_or_was($op, OP_LIST)) {
9d2c6865 3403 return $self->pp_list($op, $cx);
3f872cb9 3404 } elsif ($op->first->name eq "enter") {
9d2c6865 3405 return $self->pp_leave($op, $cx);
31c6271a
RD
3406 } elsif ($op->first->name eq "leave") {
3407 return $self->pp_leave($op->first, $cx);