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