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