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