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