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