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