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