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