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