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