This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[MERGE] t/TEST -deparse fixups
[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) = @_;
66cc68c1
DM
2148 $from //= '';
2149 my $all = (warnings::bits("all") & WARN_MASK);
2150 unless ((($from & WARN_MASK) & ~$all) =~ /[^\0]/) {
2151 # no FATAL bits need turning off
2152 if ( ($to & WARN_MASK) eq $all) {
2153 return $self->keyword("use") . " warnings;\n";
2154 }
2155 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
2156 return $self->keyword("no") . " warnings;\n";
2157 }
a0405c92 2158 }
66cc68c1 2159
74b899ae
KW
2160 return "BEGIN {\${^WARNING_BITS} = \""
2161 . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
2162 . "\"}\n\cK";
a0405c92
RH
2163}
2164
2165sub declare_hints {
7741ceed 2166 my ($self, $from, $to) = @_;
a0035eb8
RH
2167 my $use = $to & ~$from;
2168 my $no = $from & ~$to;
2169 my $decls = "";
2170 for my $pragma (hint_pragmas($use)) {
7741ceed 2171 $decls .= $self->keyword("use") . " $pragma;\n";
a0035eb8
RH
2172 }
2173 for my $pragma (hint_pragmas($no)) {
7741ceed 2174 $decls .= $self->keyword("no") . " $pragma;\n";
a0035eb8
RH
2175 }
2176 return $decls;
2177}
2178
493c23c6
NC
2179# Internal implementation hints that the core sets automatically, so don't need
2180# (or want) to be passed back to the user
2181my %ignored_hints = (
2182 'open<' => 1,
2183 'open>' => 1,
dca6062a 2184 ':' => 1,
1c74777c
FC
2185 'strict/refs' => 1,
2186 'strict/subs' => 1,
2187 'strict/vars' => 1,
2e8342de 2188);
493c23c6 2189
a8095af7
FC
2190my %rev_feature;
2191
0ced6c29 2192sub declare_hinthash {
7741ceed 2193 my ($self, $from, $to, $indent, $hints) = @_;
a8095af7 2194 my $doing_features =
149758b3 2195 ($hints & $feature::hint_mask) == $feature::hint_mask;
0ced6c29 2196 my @decls;
a8095af7
FC
2197 my @features;
2198 my @unfeatures; # bugs?
0bb01b05 2199 for my $key (sort keys %$to) {
493c23c6 2200 next if $ignored_hints{$key};
843835bc 2201 my $is_feature = $key =~ /^feature_/;
a8095af7 2202 next if $is_feature and not $doing_features;
04be0204 2203 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
a8095af7 2204 push(@features, $key), next if $is_feature;
035146a3 2205 push @decls,
7741ceed 2206 qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
035146a3
FC
2207 . (
2208 defined $to->{$key}
7741ceed 2209 ? single_delim("q", "'", $to->{$key}, $self)
035146a3
FC
2210 : 'undef'
2211 )
04be0204 2212 . qq(;);
0ced6c29
RGS
2213 }
2214 }
0bb01b05 2215 for my $key (sort keys %$from) {
493c23c6 2216 next if $ignored_hints{$key};
843835bc 2217 my $is_feature = $key =~ /^feature_/;
a8095af7 2218 next if $is_feature and not $doing_features;
0ced6c29 2219 if (!exists $to->{$key}) {
a8095af7 2220 push(@unfeatures, $key), next if $is_feature;
0ced6c29
RGS
2221 push @decls, qq(delete \$^H{'$key'};);
2222 }
2223 }
a8095af7
FC
2224 my @ret;
2225 if (@features || @unfeatures) {
a8095af7
FC
2226 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
2227 }
2228 if (@features) {
7741ceed 2229 push @ret, $self->keyword("use") . " feature "
a8095af7
FC
2230 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
2231 }
2232 if (@unfeatures) {
7741ceed 2233 push @ret, $self->keyword("no") . " feature "
a8095af7
FC
2234 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
2235 . ";\n";
2236 }
2237 @decls and
2238 push @ret,
5e617af5 2239 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
a8095af7 2240 return @ret;
0ced6c29
RGS
2241}
2242
a0035eb8
RH
2243sub hint_pragmas {
2244 my ($bits) = @_;
415d4c68 2245 my (@pragmas, @strict);
a0035eb8 2246 push @pragmas, "integer" if $bits & 0x1;
415d4c68
FC
2247 for (sort keys %strict_bits) {
2248 push @strict, "'$_'" if $bits & $strict_bits{$_};
2249 }
2250 if (@strict == keys %strict_bits) {
2251 push @pragmas, "strict";
2252 }
2253 elsif (@strict) {
2254 push @pragmas, "strict " . join ', ', @strict;
2255 }
a0035eb8
RH
2256 push @pragmas, "bytes" if $bits & 0x8;
2257 return @pragmas;
08c6f5ec
RH
2258}
2259
6e90668e 2260sub pp_dbstate { pp_nextstate(@_) }
3f872cb9 2261sub pp_setstate { pp_nextstate(@_) }
6e90668e
SM
2262
2263sub pp_unstack { return "" } # see also leaveloop
2264
80e3f4ad
FC
2265my %feature_keywords = (
2266 # keyword => 'feature',
2267 state => 'state',
2268 say => 'say',
2269 given => 'switch',
2270 when => 'switch',
2271 default => 'switch',
e36901c8 2272 break => 'switch',
7d789282 2273 evalbytes=>'evalbytes',
84ed0108 2274 __SUB__ => '__SUB__',
838f2281 2275 fc => 'fc',
80e3f4ad
FC
2276);
2277
3ac5308a
DM
2278# keywords that are strong and also have a prototype
2279#
2280my %strong_proto_keywords = map { $_ => 1 } qw(
3ac5308a
DM
2281 pos
2282 prototype
2283 scalar
2284 study
2285 undef
2286);
2287
a958cfbb
FC
2288sub feature_enabled {
2289 my($self,$name) = @_;
223b1722 2290 my $hh;
149758b3
NC
2291 my $hints = $self->{hints} & $feature::hint_mask;
2292 if ($hints && $hints != $feature::hint_mask) {
1873980a 2293 $hh = _features_from_bundle($hints);
223b1722
FC
2294 }
2295 elsif ($hints) { $hh = $self->{'hinthash'} }
a958cfbb
FC
2296 return $hh && $hh->{"feature_$feature_keywords{$name}"}
2297}
2298
2299sub keyword {
2300 my $self = shift;
2301 my $name = shift;
2302 return $name if $name =~ /^CORE::/; # just in case
2303 if (exists $feature_keywords{$name}) {
2304 return "CORE::$name" if not $self->feature_enabled($name);
80e3f4ad 2305 }
7741ceed
FC
2306 # This sub may be called for a program that has no nextstate ops. In
2307 # that case we may have a lexical sub named no/use/sub in scope but
2308 # but $self->lex_in_scope will return false because it depends on the
2309 # current nextstate op. So we need this alternate method if there is
2310 # no current cop.
2311 if (!$self->{'curcop'}) {
2312 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
2313 return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
2314 || exists $self->{'curcvlex'}{"o&$name"};
2315 } elsif ($self->lex_in_scope("&$name")
2316 || $self->lex_in_scope("&$name", 1)) {
3188a821
FC
2317 return "CORE::$name";
2318 }
3ac5308a
DM
2319 if ($strong_proto_keywords{$name}
2320 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
2321 && !defined eval{prototype "CORE::$name"})
4a1ac32e
FC
2322 ) { return $name }
2323 if (
2324 exists $self->{subs_declared}{$name}
2325 or
2326 exists &{"$self->{curstash}::$name"}
2327 ) {
2328 return "CORE::$name"
2329 }
2330 return $name;
2331}
2332
6e90668e
SM
2333sub baseop {
2334 my $self = shift;
9d2c6865 2335 my($op, $cx, $name) = @_;
4a1ac32e 2336 return $self->keyword($name);
6e90668e
SM
2337}
2338
ddb55548 2339sub pp_stub { "()" }
6e90668e
SM
2340sub pp_wantarray { baseop(@_, "wantarray") }
2341sub pp_fork { baseop(@_, "fork") }
3ed82cfc
GS
2342sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
2343sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
2344sub pp_time { maybe_targmy(@_, \&baseop, "time") }
6e90668e
SM
2345sub pp_tms { baseop(@_, "times") }
2346sub pp_ghostent { baseop(@_, "gethostent") }
2347sub pp_gnetent { baseop(@_, "getnetent") }
2348sub pp_gprotoent { baseop(@_, "getprotoent") }
2349sub pp_gservent { baseop(@_, "getservent") }
2350sub pp_ehostent { baseop(@_, "endhostent") }
2351sub pp_enetent { baseop(@_, "endnetent") }
2352sub pp_eprotoent { baseop(@_, "endprotoent") }
2353sub pp_eservent { baseop(@_, "endservent") }
2354sub pp_gpwent { baseop(@_, "getpwent") }
2355sub pp_spwent { baseop(@_, "setpwent") }
2356sub pp_epwent { baseop(@_, "endpwent") }
2357sub pp_ggrent { baseop(@_, "getgrent") }
2358sub pp_sgrent { baseop(@_, "setgrent") }
2359sub pp_egrent { baseop(@_, "endgrent") }
2360sub pp_getlogin { baseop(@_, "getlogin") }
2361
2362sub POSTFIX () { 1 }
2363
9d2c6865
SM
2364# I couldn't think of a good short name, but this is the category of
2365# symbolic unary operators with interesting precedence
2366
2367sub pfixop {
2368 my $self = shift;
2369 my($op, $cx, $name, $prec, $flags) = (@_, 0);
2370 my $kid = $op->first;
2371 $kid = $self->deparse($kid, $prec);
843b15cc
FC
2372 return $self->maybe_parens(($flags & POSTFIX)
2373 ? "$kid$name"
2374 # avoid confusion with filetests
2375 : $name eq '-'
2376 && $kid =~ /^[a-zA-Z](?!\w)/
2377 ? "$name($kid)"
2378 : "$name$kid",
9d2c6865
SM
2379 $cx, $prec);
2380}
2381
2382sub pp_preinc { pfixop(@_, "++", 23) }
2383sub pp_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2384sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2385sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
9d2c6865
SM
2386sub pp_i_preinc { pfixop(@_, "++", 23) }
2387sub pp_i_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2388sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2389sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
68cc8748 2390sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
27f31adf
FC
2391*pp_ncomplement = *pp_complement;
2392sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) }
9d2c6865 2393
3ed82cfc
GS
2394sub pp_negate { maybe_targmy(@_, \&real_negate) }
2395sub real_negate {
9d2c6865
SM
2396 my $self = shift;
2397 my($op, $cx) = @_;
3f872cb9 2398 if ($op->first->name =~ /^(i_)?negate$/) {
9d2c6865
SM
2399 # avoid --$x
2400 $self->pfixop($op, $cx, "-", 21.5);
2401 } else {
2402 $self->pfixop($op, $cx, "-", 21);
2403 }
2404}
2405sub pp_i_negate { pp_negate(@_) }
2406
2407sub pp_not {
2408 my $self = shift;
2409 my($op, $cx) = @_;
2410 if ($cx <= 4) {
1cabb3b3 2411 $self->listop($op, $cx, "not", $op->first);
9d2c6865
SM
2412 } else {
2413 $self->pfixop($op, $cx, "!", 21);
2414 }
2415}
2416
6e90668e
SM
2417sub unop {
2418 my $self = shift;
9c56d9ea 2419 my($op, $cx, $name, $nollafr) = @_;
6e90668e 2420 my $kid;
9d2c6865 2421 if ($op->flags & OPf_KIDS) {
aaf643ce 2422 $kid = $op->first;
1c85afce
YO
2423 if (not $name) {
2424 # this deals with 'boolkeys' right now
2425 return $self->deparse($kid,$cx);
2426 }
deb20ba3
RGS
2427 my $builtinname = $name;
2428 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2429 if (defined prototype($builtinname)
9cef6114 2430 && $builtinname ne 'CORE::readline'
deb20ba3 2431 && prototype($builtinname) =~ /^;?\*/
e31885a0
RH
2432 && $kid->name eq "rv2gv") {
2433 $kid = $kid->first;
2434 }
2435
9c56d9ea 2436 if ($nollafr) {
917a8f4f
FC
2437 if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) {
2438 # require foo() is a syntax error.
2439 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2440 }
9c56d9ea
FC
2441 return $self->maybe_parens(
2442 $self->keyword($name) . " $kid", $cx, 16
2443 );
2444 }
9d2c6865 2445 return $self->maybe_parens_unop($name, $kid, $cx);
6e90668e 2446 } else {
4d8ac5c7
FC
2447 return $self->maybe_parens(
2448 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
2449 $cx, 16,
2450 );
6e90668e 2451 }
6e90668e
SM
2452}
2453
3ed82cfc
GS
2454sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
2455sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
2456sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
2457sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
6e90668e
SM
2458sub pp_defined { unop(@_, "defined") }
2459sub pp_undef { unop(@_, "undef") }
2460sub pp_study { unop(@_, "study") }
6e90668e
SM
2461sub pp_ref { unop(@_, "ref") }
2462sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
2463
3ed82cfc
GS
2464sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
2465sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
2466sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
6e90668e 2467sub pp_srand { unop(@_, "srand") }
3ed82cfc
GS
2468sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
2469sub pp_log { maybe_targmy(@_, \&unop, "log") }
2470sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
2471sub pp_int { maybe_targmy(@_, \&unop, "int") }
2472sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
2473sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
2474sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
2475
2476sub pp_length { maybe_targmy(@_, \&unop, "length") }
2477sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2478sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
6e90668e
SM
2479
2480sub pp_each { unop(@_, "each") }
2481sub pp_values { unop(@_, "values") }
2482sub pp_keys { unop(@_, "keys") }
09dcfa7d 2483{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1c85afce
YO
2484sub pp_boolkeys {
2485 # no name because its an optimisation op that has no keyword
2486 unop(@_,"");
2487}
644741fd
NC
2488sub pp_aeach { unop(@_, "each") }
2489sub pp_avalues { unop(@_, "values") }
2490sub pp_akeys { unop(@_, "keys") }
6e90668e
SM
2491sub pp_pop { unop(@_, "pop") }
2492sub pp_shift { unop(@_, "shift") }
2493
2494sub pp_caller { unop(@_, "caller") }
2495sub pp_reset { unop(@_, "reset") }
2496sub pp_exit { unop(@_, "exit") }
2497sub pp_prototype { unop(@_, "prototype") }
2498
2499sub pp_close { unop(@_, "close") }
2500sub pp_fileno { unop(@_, "fileno") }
2501sub pp_umask { unop(@_, "umask") }
6e90668e
SM
2502sub pp_untie { unop(@_, "untie") }
2503sub pp_tied { unop(@_, "tied") }
2504sub pp_dbmclose { unop(@_, "dbmclose") }
2505sub pp_getc { unop(@_, "getc") }
2506sub pp_eof { unop(@_, "eof") }
2507sub pp_tell { unop(@_, "tell") }
2508sub pp_getsockname { unop(@_, "getsockname") }
2509sub pp_getpeername { unop(@_, "getpeername") }
2510
0175f038
FC
2511sub pp_chdir {
2512 my ($self, $op, $cx) = @_;
3c4a43a5 2513 if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) {
0175f038
FC
2514 my $kw = $self->keyword("chdir");
2515 my $kid = $self->const_sv($op->first)->PV;
2516 my $code = $kw
2517 . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid");
2518 maybe_targmy(@_, sub { $_[3] }, $code);
2519 } else {
2520 maybe_targmy(@_, \&unop, "chdir")
2521 }
2522}
2523
3ed82cfc 2524sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
6e90668e 2525sub pp_readlink { unop(@_, "readlink") }
3ed82cfc 2526sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
6e90668e
SM
2527sub pp_readdir { unop(@_, "readdir") }
2528sub pp_telldir { unop(@_, "telldir") }
2529sub pp_rewinddir { unop(@_, "rewinddir") }
2530sub pp_closedir { unop(@_, "closedir") }
3ed82cfc 2531sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
6e90668e
SM
2532sub pp_localtime { unop(@_, "localtime") }
2533sub pp_gmtime { unop(@_, "gmtime") }
2534sub pp_alarm { unop(@_, "alarm") }
3ed82cfc 2535sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
6e90668e 2536
94bb57f9 2537sub pp_dofile {
9c56d9ea 2538 my $code = unop(@_, "do", 1); # llafr does not apply
8b46c09b 2539 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
94bb57f9
FC
2540 $code;
2541}
7d789282
FC
2542sub pp_entereval {
2543 unop(
2544 @_,
c7c39989 2545 $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval"
7d789282
FC
2546 )
2547}
6e90668e
SM
2548
2549sub pp_ghbyname { unop(@_, "gethostbyname") }
2550sub pp_gnbyname { unop(@_, "getnetbyname") }
2551sub pp_gpbyname { unop(@_, "getprotobyname") }
2552sub pp_shostent { unop(@_, "sethostent") }
2553sub pp_snetent { unop(@_, "setnetent") }
2554sub pp_sprotoent { unop(@_, "setprotoent") }
2555sub pp_sservent { unop(@_, "setservent") }
2556sub pp_gpwnam { unop(@_, "getpwnam") }
2557sub pp_gpwuid { unop(@_, "getpwuid") }
2558sub pp_ggrnam { unop(@_, "getgrnam") }
2559sub pp_ggrgid { unop(@_, "getgrgid") }
2560
2561sub pp_lock { unop(@_, "lock") }
2562
0d863452 2563sub pp_continue { unop(@_, "continue"); }
c08f093b 2564sub pp_break { unop(@_, "break"); }
0d863452
RH
2565
2566sub givwhen {
2567 my $self = shift;
2568 my($op, $cx, $givwhen) = @_;
2569
2570 my $enterop = $op->first;
2571 my ($head, $block);
2572 if ($enterop->flags & OPf_SPECIAL) {
80e3f4ad 2573 $head = $self->keyword("default");
0d863452
RH
2574 $block = $self->deparse($enterop->first, 0);
2575 }
2576 else {
2577 my $cond = $enterop->first;
2578 my $cond_str = $self->deparse($cond, 1);
2579 $head = "$givwhen ($cond_str)";
2580 $block = $self->deparse($cond->sibling, 0);
2581 }
2582
2583 return "$head {\n".
2584 "\t$block\n".
2585 "\b}\cK";
2586}
2587
80e3f4ad
FC
2588sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2589sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
0d863452 2590
6e90668e
SM
2591sub pp_exists {
2592 my $self = shift;
9d2c6865 2593 my($op, $cx) = @_;
34a48b4b 2594 my $arg;
3188a821 2595 my $name = $self->keyword("exists");
34a48b4b
RH
2596 if ($op->private & OPpEXISTS_SUB) {
2597 # Checking for the existence of a subroutine
3188a821 2598 return $self->maybe_parens_func($name,
34a48b4b
RH
2599 $self->pp_rv2cv($op->first, 16), $cx, 16);
2600 }
2601 if ($op->flags & OPf_SPECIAL) {
2602 # Array element, not hash element
3188a821 2603 return $self->maybe_parens_func($name,
34a48b4b
RH
2604 $self->pp_aelem($op->first, 16), $cx, 16);
2605 }
3188a821 2606 return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
9d2c6865 2607 $cx, 16);
6e90668e
SM
2608}
2609
6e90668e
SM
2610sub pp_delete {
2611 my $self = shift;
9d2c6865 2612 my($op, $cx) = @_;
6e90668e 2613 my $arg;
3188a821 2614 my $name = $self->keyword("delete");
ac1e5644 2615 if ($op->private & (OPpSLICE|OPpKVSLICE)) {
34a48b4b
RH
2616 if ($op->flags & OPf_SPECIAL) {
2617 # Deleting from an array, not a hash
3188a821 2618 return $self->maybe_parens_func($name,
34a48b4b
RH
2619 $self->pp_aslice($op->first, 16),
2620 $cx, 16);
2621 }
3188a821 2622 return $self->maybe_parens_func($name,
9d2c6865
SM
2623 $self->pp_hslice($op->first, 16),
2624 $cx, 16);
6e90668e 2625 } else {
34a48b4b
RH
2626 if ($op->flags & OPf_SPECIAL) {
2627 # Deleting from an array, not a hash
3188a821 2628 return $self->maybe_parens_func($name,
34a48b4b
RH
2629 $self->pp_aelem($op->first, 16),
2630 $cx, 16);
2631 }
3188a821 2632 return $self->maybe_parens_func($name,
9d2c6865
SM
2633 $self->pp_helem($op->first, 16),
2634 $cx, 16);
6e90668e 2635 }
6e90668e
SM
2636}
2637
6e90668e
SM
2638sub pp_require {
2639 my $self = shift;
9d2c6865 2640 my($op, $cx) = @_;
d5889722 2641 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
5e7acd25
FC
2642 my $kid = $op->first;
2643 if ($kid->name eq 'const') {
2644 my $priv = $kid->private;
2645 my $sv = $self->const_sv($kid);
2646 my $arg;
2647 if ($priv & OPpCONST_BARE) {
2648 $arg = $sv->PV;
2649 $arg =~ s[/][::]g;
2650 $arg =~ s/\.pm//g;
2651 } elsif ($priv & OPpCONST_NOVER) {
2652 $opname = $self->keyword('no');
2653 $arg = $self->const($sv, 16);
2654 } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) {
2655 $arg = $tmp;
2656 }
2657 if ($arg) {
2658 return $self->maybe_parens("$opname $arg", $cx, 16);
2659 }
2660 }
2661 $self->unop(
41df74e3 2662 $op, $cx,
5e7acd25 2663 $opname,
41df74e3 2664 1, # llafr does not apply
5e7acd25 2665 );
6e90668e
SM
2666}
2667
d989cdac 2668sub pp_scalar {
9d2c6865 2669 my $self = shift;
d9002312 2670 my($op, $cx) = @_;
9d2c6865
SM
2671 my $kid = $op->first;
2672 if (not null $kid->sibling) {
2673 # XXX Was a here-doc
2674 return $self->dquote($op);
2675 }
2676 $self->unop(@_, "scalar");
2677}
2678
2679
6e90668e
SM
2680sub padval {
2681 my $self = shift;
2682 my $targ = shift;
d989cdac 2683 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
6e90668e
SM
2684}
2685
78c72037
NC
2686sub anon_hash_or_list {
2687 my $self = shift;
d9002312 2688 my($op, $cx) = @_;
78c72037
NC
2689
2690 my($pre, $post) = @{{"anonlist" => ["[","]"],
2691 "anonhash" => ["{","}"]}->{$op->name}};
2692 my($expr, @exprs);
2693 $op = $op->first->sibling; # skip pushmark
2694 for (; !null($op); $op = $op->sibling) {
2695 $expr = $self->deparse($op, 6);
2696 push @exprs, $expr;
2697 }
d9002312
SM
2698 if ($pre eq "{" and $cx < 1) {
2699 # Disambiguate that it's not a block
2700 $pre = "+{";
2701 }
78c72037
NC
2702 return $pre . join(", ", @exprs) . $post;
2703}
2704
2705sub pp_anonlist {
d9002312
SM
2706 my $self = shift;
2707 my ($op, $cx) = @_;
78c72037 2708 if ($op->flags & OPf_SPECIAL) {
d9002312 2709 return $self->anon_hash_or_list($op, $cx);
78c72037
NC
2710 }
2711 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2712 return 'XXX';
2713}
2714
2715*pp_anonhash = \&pp_anonlist;
2716
6e90668e
SM
2717sub pp_refgen {
2718 my $self = shift;
9d2c6865 2719 my($op, $cx) = @_;
6e90668e 2720 my $kid = $op->first;
3f872cb9 2721 if ($kid->name eq "null") {
01762542 2722 my $anoncode = $kid = $kid->first;
b77472f9
FC
2723 if ($anoncode->name eq "anonconst") {
2724 $anoncode = $anoncode->first->first->sibling;
2725 }
01762542
FC
2726 if ($anoncode->name eq "anoncode"
2727 or !null($anoncode = $kid->sibling) and
2728 $anoncode->name eq "anoncode") {
2729 return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
3f872cb9
GS
2730 } elsif ($kid->name eq "pushmark") {
2731 my $sib_name = $kid->sibling->name;
c8ec376c 2732 if ($sib_name eq 'entersub') {
c8c62db7
AD
2733 my $text = $self->deparse($kid->sibling, 1);
2734 # Always show parens for \(&func()), but only with -p otherwise
2735 $text = "($text)" if $self->{'parens'}
2736 or $kid->sibling->private & OPpENTERSUB_AMPER;
2737 return "\\$text";
2738 }
2739 }
6e90668e 2740 }
c8ec376c 2741 local $self->{'in_refgen'} = 1;
9d2c6865 2742 $self->pfixop($op, $cx, "\\", 20);
6e90668e
SM
2743}
2744
09d856fb
CK
2745sub e_anoncode {
2746 my ($self, $info) = @_;
2747 my $text = $self->deparse_sub($info->{code});
7741ceed 2748 return $self->keyword("sub") . " $text";
09d856fb
CK
2749}
2750
6e90668e
SM
2751sub pp_srefgen { pp_refgen(@_) }
2752
2753sub pp_readline {
2754 my $self = shift;
9d2c6865 2755 my($op, $cx) = @_;
6e90668e 2756 my $kid = $op->first;
18371617
LM
2757 if (is_scalar($kid)
2758 and $op->flags & OPf_SPECIAL
2759 and $self->deparse($kid, 1) eq 'ARGV')
2760 {
2761 return '<<>>';
65ef2c3e 2762 }
e31885a0 2763 return $self->unop($op, $cx, "readline");
6e90668e
SM
2764}
2765
ad8caead
RGS
2766sub pp_rcatline {
2767 my $self = shift;
2768 my($op) = @_;
d989cdac 2769 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
ad8caead
RGS
2770}
2771
bd0865ec
GS
2772# Unary operators that can occur as pseudo-listops inside double quotes
2773sub dq_unop {
2774 my $self = shift;
2775 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2776 my $kid;
2777 if ($op->flags & OPf_KIDS) {
2778 $kid = $op->first;
2779 # If there's more than one kid, the first is an ex-pushmark.
2780 $kid = $kid->sibling if not null $kid->sibling;
2781 return $self->maybe_parens_unop($name, $kid, $cx);
2782 } else {
d989cdac 2783 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
bd0865ec
GS
2784 }
2785}
2786
2787sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2788sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2789sub pp_uc { dq_unop(@_, "uc") }
2790sub pp_lc { dq_unop(@_, "lc") }
3ed82cfc 2791sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
838f2281 2792sub pp_fc { dq_unop(@_, "fc") }
bd0865ec 2793
6e90668e
SM
2794sub loopex {
2795 my $self = shift;
9d2c6865 2796 my ($op, $cx, $name) = @_;
6e90668e 2797 if (class($op) eq "PVOP") {
41df74e3 2798 $name .= " " . $op->pv;
9d2c6865 2799 } elsif (class($op) eq "OP") {
41df74e3 2800 # no-op
6e90668e 2801 } elsif (class($op) eq "UNOP") {
1eb0b7be 2802 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
df465735
FC
2803 # last foo() is a syntax error.
2804 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
41df74e3 2805 $name .= " $kid";
6e90668e 2806 }
1eb0b7be 2807 return $self->maybe_parens($name, $cx, 7);
6e90668e
SM
2808}
2809
2810sub pp_last { loopex(@_, "last") }
2811sub pp_next { loopex(@_, "next") }
2812sub pp_redo { loopex(@_, "redo") }
2813sub pp_goto { loopex(@_, "goto") }
266da325 2814sub pp_dump { loopex(@_, "CORE::dump") }
6e90668e
SM
2815
2816sub ftst {
2817 my $self = shift;
9d2c6865 2818 my($op, $cx, $name) = @_;
6e90668e 2819 if (class($op) eq "UNOP") {
e38ccfd9 2820 # Genuine '-X' filetests are exempt from the LLAFR, but not
5830412d
FC
2821 # l?stat()
2822 if ($name =~ /^-/) {
2823 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2824 return $self->maybe_parens("$name $kid", $cx, 16);
2825 }
9d2c6865 2826 return $self->maybe_parens_unop($name, $op->first, $cx);
d989cdac 2827 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
9d2c6865 2828 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
6e90668e 2829 } else { # I don't think baseop filetests ever survive ck_ftst, but...
9d2c6865 2830 return $name;
6e90668e 2831 }
6e90668e
SM
2832}
2833
d989cdac
SM
2834sub pp_lstat { ftst(@_, "lstat") }
2835sub pp_stat { ftst(@_, "stat") }
2836sub pp_ftrread { ftst(@_, "-R") }
6e90668e 2837sub pp_ftrwrite { ftst(@_, "-W") }
d989cdac
SM
2838sub pp_ftrexec { ftst(@_, "-X") }
2839sub pp_fteread { ftst(@_, "-r") }
e31885a0 2840sub pp_ftewrite { ftst(@_, "-w") }
d989cdac
SM
2841sub pp_fteexec { ftst(@_, "-x") }
2842sub pp_ftis { ftst(@_, "-e") }
6e90668e
SM
2843sub pp_fteowned { ftst(@_, "-O") }
2844sub pp_ftrowned { ftst(@_, "-o") }
d989cdac
SM
2845sub pp_ftzero { ftst(@_, "-z") }
2846sub pp_ftsize { ftst(@_, "-s") }
2847sub pp_ftmtime { ftst(@_, "-M") }
2848sub pp_ftatime { ftst(@_, "-A") }
2849sub pp_ftctime { ftst(@_, "-C") }
2850sub pp_ftsock { ftst(@_, "-S") }
2851sub pp_ftchr { ftst(@_, "-c") }
2852sub pp_ftblk { ftst(@_, "-b") }
2853sub pp_ftfile { ftst(@_, "-f") }
2854sub pp_ftdir { ftst(@_, "-d") }
2855sub pp_ftpipe { ftst(@_, "-p") }
2856sub pp_ftlink { ftst(@_, "-l") }
2857sub pp_ftsuid { ftst(@_, "-u") }
2858sub pp_ftsgid { ftst(@_, "-g") }
2859sub pp_ftsvtx { ftst(@_, "-k") }
2860sub pp_fttty { ftst(@_, "-t") }
2861sub pp_fttext { ftst(@_, "-T") }
6e90668e
SM
2862sub pp_ftbinary { ftst(@_, "-B") }
2863
a798dbf2 2864sub SWAP_CHILDREN () { 1 }
6e90668e 2865sub ASSIGN () { 2 } # has OP= variant
7013e6ae 2866sub LIST_CONTEXT () { 4 } # Assignment is in list context
6e90668e 2867
9d2c6865
SM
2868my(%left, %right);
2869
2870sub assoc_class {
2871 my $op = shift;
3f872cb9
GS
2872 my $name = $op->name;
2873 if ($name eq "concat" and $op->first->name eq "concat") {
e38ccfd9 2874 # avoid spurious '=' -- see comment in pp_concat
3f872cb9 2875 return "concat";
9d2c6865 2876 }
3f872cb9
GS
2877 if ($name eq "null" and class($op) eq "UNOP"
2878 and $op->first->name =~ /^(and|x?or)$/
9d2c6865
SM
2879 and null $op->first->sibling)
2880 {
2881 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2882 # with a null that's used as the common end point of the two
2883 # flows of control. For precedence purposes, ignore it.
2884 # (COND_EXPRs have these too, but we don't bother with
2885 # their associativity).
2886 return assoc_class($op->first);
2887 }
2888 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2889}
2890
e38ccfd9 2891# Left associative operators, like '+', for which
9d2c6865
SM
2892# $a + $b + $c is equivalent to ($a + $b) + $c
2893
2894BEGIN {
3f872cb9
GS
2895 %left = ('multiply' => 19, 'i_multiply' => 19,
2896 'divide' => 19, 'i_divide' => 19,
2897 'modulo' => 19, 'i_modulo' => 19,
2898 'repeat' => 19,
2899 'add' => 18, 'i_add' => 18,
2900 'subtract' => 18, 'i_subtract' => 18,
2901 'concat' => 18,
2902 'left_shift' => 17, 'right_shift' => 17,
27f31adf 2903 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13,
3f872cb9 2904 'bit_or' => 12, 'bit_xor' => 12,
27f31adf
FC
2905 'sbit_or' => 12, 'sbit_xor' => 12,
2906 'nbit_or' => 12, 'nbit_xor' => 12,
3f872cb9
GS
2907 'and' => 3,
2908 'or' => 2, 'xor' => 2,
9d2c6865
SM
2909 );
2910}
2911
2912sub deparse_binop_left {
2913 my $self = shift;
2914 my($op, $left, $prec) = @_;
58231d39 2915 if ($left{assoc_class($op)} && $left{assoc_class($left)}
9d2c6865
SM
2916 and $left{assoc_class($op)} == $left{assoc_class($left)})
2917 {
2918 return $self->deparse($left, $prec - .00001);
2919 } else {
2920 return $self->deparse($left, $prec);
2921 }
2922}
2923
e38ccfd9 2924# Right associative operators, like '=', for which
9d2c6865
SM
2925# $a = $b = $c is equivalent to $a = ($b = $c)
2926
2927BEGIN {
3f872cb9
GS
2928 %right = ('pow' => 22,
2929 'sassign=' => 7, 'aassign=' => 7,
2930 'multiply=' => 7, 'i_multiply=' => 7,
2931 'divide=' => 7, 'i_divide=' => 7,
2932 'modulo=' => 7, 'i_modulo=' => 7,
9187b6e4 2933 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
3f872cb9
GS
2934 'add=' => 7, 'i_add=' => 7,
2935 'subtract=' => 7, 'i_subtract=' => 7,
2936 'concat=' => 7,
2937 'left_shift=' => 7, 'right_shift=' => 7,
27f31adf
FC
2938 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7,
2939 'nbit_or=' => 7, 'nbit_xor=' => 7,
2940 'sbit_or=' => 7, 'sbit_xor=' => 7,
3f872cb9
GS
2941 'andassign' => 7,
2942 'orassign' => 7,
9d2c6865
SM
2943 );
2944}
2945
2946sub deparse_binop_right {
2947 my $self = shift;
2948 my($op, $right, $prec) = @_;
58231d39 2949 if ($right{assoc_class($op)} && $right{assoc_class($right)}
9d2c6865
SM
2950 and $right{assoc_class($op)} == $right{assoc_class($right)})
2951 {
2952 return $self->deparse($right, $prec - .00001);
2953 } else {
2954 return $self->deparse($right, $prec);
2955 }
2956}
2957
a798dbf2 2958sub binop {
6e90668e 2959 my $self = shift;
9d2c6865 2960 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
a798dbf2
MB
2961 my $left = $op->first;
2962 my $right = $op->last;
9d2c6865
SM
2963 my $eq = "";
2964 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2965 $eq = "=";
2966 $prec = 7;
2967 }
a798dbf2
MB
2968 if ($flags & SWAP_CHILDREN) {
2969 ($left, $right) = ($right, $left);
2970 }
6a861075 2971 my $leftop = $left;
9d2c6865 2972 $left = $self->deparse_binop_left($op, $left, $prec);
90c0eb26 2973 $left = "($left)" if $flags & LIST_CONTEXT
c4874d8a 2974 and $left !~ /^(my|our|local|state|)\s*[\@%\(]/
6a861075
FC
2975 || do {
2976 # Parenthesize if the left argument is a
2977 # lone repeat op.
2978 my $left = $leftop->first->sibling;
2979 $left->name eq 'repeat'
2980 && null($left->sibling);
2981 };
9d2c6865
SM
2982 $right = $self->deparse_binop_right($op, $right, $prec);
2983 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2984}
2985
3ed82cfc
GS
2986sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2987sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2988sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2989sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2990sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2991sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2992sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2993sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2994sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2995sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2996sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2997
2998sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2999sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
3000sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
3001sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
3002sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
27f31adf
FC
3003*pp_nbit_and = *pp_bit_and;
3004*pp_nbit_or = *pp_bit_or;
3005*pp_nbit_xor = *pp_bit_xor;
3006sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) }
3007sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) }
3008sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) }
9d2c6865
SM
3009
3010sub pp_eq { binop(@_, "==", 14) }
3011sub pp_ne { binop(@_, "!=", 14) }
3012sub pp_lt { binop(@_, "<", 15) }
3013sub pp_gt { binop(@_, ">", 15) }
3014sub pp_ge { binop(@_, ">=", 15) }
3015sub pp_le { binop(@_, "<=", 15) }
3016sub pp_ncmp { binop(@_, "<=>", 14) }
3017sub pp_i_eq { binop(@_, "==", 14) }
3018sub pp_i_ne { binop(@_, "!=", 14) }
3019sub pp_i_lt { binop(@_, "<", 15) }
3020sub pp_i_gt { binop(@_, ">", 15) }
3021sub pp_i_ge { binop(@_, ">=", 15) }
3022sub pp_i_le { binop(@_, "<=", 15) }
d1455c67 3023sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) }
9d2c6865
SM
3024
3025sub pp_seq { binop(@_, "eq", 14) }
3026sub pp_sne { binop(@_, "ne", 14) }
3027sub pp_slt { binop(@_, "lt", 15) }
3028sub pp_sgt { binop(@_, "gt", 15) }
3029sub pp_sge { binop(@_, "ge", 15) }
3030sub pp_sle { binop(@_, "le", 15) }
d1455c67 3031sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) }
9d2c6865
SM
3032
3033sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
7013e6ae 3034sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
6e90668e 3035
0d863452
RH
3036sub pp_smartmatch {
3037 my ($self, $op, $cx) = @_;
b54ed1c7 3038 if (($op->flags & OPf_SPECIAL) && $self->{expand} < 2) {
9210de83 3039 return $self->deparse($op->last, $cx);
0d863452
RH
3040 }
3041 else {
3042 binop(@_, "~~", 14);
3043 }
3044}
3045
e38ccfd9 3046# '.' is special because concats-of-concats are optimized to save copying
6e90668e 3047# by making all but the first concat stacked. The effect is as if the
e38ccfd9 3048# programmer had written '($a . $b) .= $c', except legal.
3ed82cfc
GS
3049sub pp_concat { maybe_targmy(@_, \&real_concat) }
3050sub real_concat {
6e90668e 3051 my $self = shift;
9d2c6865 3052 my($op, $cx) = @_;
6e90668e
SM
3053 my $left = $op->first;
3054 my $right = $op->last;
3055 my $eq = "";
9d2c6865 3056 my $prec = 18;
4b75096e
DM
3057 if (($op->flags & OPf_STACKED) and !($op->private & OPpCONCAT_NESTED)) {
3058 # '.=' rather than optimised '.'
6e90668e 3059 $eq = "=";
9d2c6865 3060 $prec = 7;
6e90668e 3061 }
9d2c6865
SM
3062 $left = $self->deparse_binop_left($op, $left, $prec);
3063 $right = $self->deparse_binop_right($op, $right, $prec);
3064 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
6e90668e
SM
3065}
3066
6402d4ee
FC
3067sub pp_repeat { maybe_targmy(@_, \&repeat) }
3068
e38ccfd9 3069# 'x' is weird when the left arg is a list
6402d4ee 3070sub repeat {
6e90668e 3071 my $self = shift;
9d2c6865 3072 my($op, $cx) = @_;
6e90668e
SM
3073 my $left = $op->first;
3074 my $right = $op->last;
9d2c6865
SM
3075 my $eq = "";
3076 my $prec = 19;
3077 if ($op->flags & OPf_STACKED) {
3078 $eq = "=";
3079 $prec = 7;
3080 }
6e90668e 3081 if (null($right)) { # list repeat; count is inside left-side ex-list
5e462669 3082 # in 5.21.5 and earlier
6e90668e
SM
3083 my $kid = $left->first->sibling; # skip pushmark
3084 my @exprs;
3085 for (; !null($kid->sibling); $kid = $kid->sibling) {
9d2c6865 3086 push @exprs, $self->deparse($kid, 6);
6e90668e
SM
3087 }
3088 $right = $kid;
3089 $left = "(" . join(", ", @exprs). ")";
3090 } else {
5e462669
FC
3091 my $dolist = $op->private & OPpREPEAT_DOLIST;
3092 $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
3093 if ($dolist) {
3094 $left = "($left)";
3095 }
6e90668e 3096 }
9d2c6865
SM
3097 $right = $self->deparse_binop_right($op, $right, $prec);
3098 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
6e90668e
SM
3099}
3100
3101sub range {
3102 my $self = shift;
9d2c6865 3103 my ($op, $cx, $type) = @_;
6e90668e
SM
3104 my $left = $op->first;
3105 my $right = $left->sibling;
9d2c6865
SM
3106 $left = $self->deparse($left, 9);
3107 $right = $self->deparse($right, 9);
3108 return $self->maybe_parens("$left $type $right", $cx, 9);
6e90668e
SM
3109}
3110
3111sub pp_flop {
3112 my $self = shift;
9d2c6865 3113 my($op, $cx) = @_;
6e90668e
SM
3114 my $flip = $op->first;
3115 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
9d2c6865 3116 return $self->range($flip->first, $cx, $type);
6e90668e
SM
3117}
3118
3119# one-line while/until is handled in pp_leave
3120
3121sub logop {
3122 my $self = shift;
9d2c6865 3123 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
6e90668e
SM
3124 my $left = $op->first;
3125 my $right = $op->first->sibling;
7741ceed 3126 $blockname &&= $self->keyword($blockname);
d989cdac 3127 if ($cx < 1 and is_scope($right) and $blockname
58cccf98
SM
3128 and $self->{'expand'} < 7)
3129 { # if ($a) {$b}
9d2c6865
SM
3130 $left = $self->deparse($left, 1);
3131 $right = $self->deparse($right, 0);
3132 return "$blockname ($left) {\n\t$right\n\b}\cK";
d989cdac 3133 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
58cccf98 3134 and $self->{'expand'} < 7) { # $b if $a
9d2c6865
SM
3135 $right = $self->deparse($right, 1);
3136 $left = $self->deparse($left, 1);
3137 return "$right $blockname $left";
3138 } elsif ($cx > $lowprec and $highop) { # $a && $b
3139 $left = $self->deparse_binop_left($op, $left, $highprec);
3140 $right = $self->deparse_binop_right($op, $right, $highprec);
3141 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
3142 } else { # $a and $b
3143 $left = $self->deparse_binop_left($op, $left, $lowprec);
3144 $right = $self->deparse_binop_right($op, $right, $lowprec);
d989cdac 3145 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
9d2c6865
SM
3146 }
3147}
3148
3149sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
f4a44678 3150sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
5b99f273 3151sub pp_dor { logop(@_, "//", 10) }
3ed82cfc
GS
3152
3153# xor is syntactically a logop, but it's really a binop (contrary to
3154# old versions of opcode.pl). Syntax is what matters here.
9d2c6865 3155sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
6e90668e
SM
3156
3157sub logassignop {
3158 my $self = shift;
9d2c6865 3159 my ($op, $cx, $opname) = @_;
6e90668e
SM
3160 my $left = $op->first;
3161 my $right = $op->first->sibling->first; # skip sassign
9d2c6865
SM
3162 $left = $self->deparse($left, 7);
3163 $right = $self->deparse($right, 7);
3164 return $self->maybe_parens("$left $opname $right", $cx, 7);
a798dbf2
MB
3165}
3166
6e90668e 3167sub pp_andassign { logassignop(@_, "&&=") }
c963b151
BD
3168sub pp_orassign { logassignop(@_, "||=") }
3169sub pp_dorassign { logassignop(@_, "//=") }
6e90668e 3170
b89b7257
FC
3171sub rv2gv_or_string {
3172 my($self,$op) = @_;
3173 if ($op->name eq "gv") { # could be open("open") or open("###")
be6cf5cf 3174 my($name,$quoted) =
1db94eeb 3175 $self->stash_variable_name("", $self->gv_or_padgv($op));
be6cf5cf 3176 $quoted ? $name : "*$name";
b89b7257
FC
3177 }
3178 else {
3179 $self->deparse($op, 6);
3180 }
3181}
3182
6e90668e
SM
3183sub listop {
3184 my $self = shift;
9c56d9ea 3185 my($op, $cx, $name, $kid, $nollafr) = @_;
9d2c6865
SM
3186 my(@exprs);
3187 my $parens = ($cx >= 5) || $self->{'parens'};
24fcb59f 3188 $kid ||= $op->first->sibling;
4d8ac5c7
FC
3189 # If there are no arguments, add final parentheses (or parenthesize the
3190 # whole thing if the llafr does not apply) to account for cases like
3191 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
3192 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
3193 if (null $kid) {
3194 return $nollafr
3195 ? $self->maybe_parens($self->keyword($name), $cx, 7)
3196 : $self->keyword($name) . '()' x (7 < $cx);
3197 }
e31885a0 3198 my $first;
4a1ac32e 3199 my $fullname = $self->keyword($name);
b72c97e8 3200 my $proto = prototype("CORE::$name");
bc1cc2c3
DM
3201 if (
3202 ( (defined $proto && $proto =~ /^;?\*/)
3203 || $name eq 'select' # select(F) doesn't have a proto
3204 )
3205 && $kid->name eq "rv2gv"
3206 && !($kid->private & OPpLVAL_INTRO)
3207 ) {
b89b7257 3208 $first = $self->rv2gv_or_string($kid->first);
e31885a0
RH
3209 }
3210 else {
3211 $first = $self->deparse($kid, 6);
3212 }
e99ebc55 3213 if ($name eq "chmod" && $first =~ /^\d+$/) {
a0035eb8 3214 $first = sprintf("%#o", $first);
e99ebc55 3215 }
9c56d9ea
FC
3216 $first = "+$first"
3217 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
9d2c6865
SM
3218 push @exprs, $first;
3219 $kid = $kid->sibling;
564cd6cb
FC
3220 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
3221 && !($kid->private & OPpLVAL_INTRO)) {
b89b7257 3222 push @exprs, $first = $self->rv2gv_or_string($kid->first);
b72c97e8
RGS
3223 $kid = $kid->sibling;
3224 }
9d2c6865
SM
3225 for (; !null($kid); $kid = $kid->sibling) {
3226 push @exprs, $self->deparse($kid, 6);
3227 }
689e417f 3228 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
4a1ac32e
FC
3229 return "$exprs[0] = $fullname"
3230 . ($parens ? "($exprs[0])" : " $exprs[0]");
689e417f 3231 }
327088eb 3232
9c56d9ea
FC
3233 if ($parens && $nollafr) {
3234 return "($fullname " . join(", ", @exprs) . ")";
3235 } elsif ($parens) {
4a1ac32e 3236 return "$fullname(" . join(", ", @exprs) . ")";
9d2c6865 3237 } else {
4a1ac32e 3238 return "$fullname " . join(", ", @exprs);
6e90668e 3239 }
6e90668e 3240}
a798dbf2 3241
6e90668e 3242sub pp_bless { listop(@_, "bless") }
3ed82cfc 3243sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
24fcb59f
FC
3244sub pp_substr {
3245 my ($self,$op,$cx) = @_;
3246 if ($op->private & OPpSUBSTR_REPL_FIRST) {
3247 return
3248 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
3249 . " = "
3250 . $self->deparse($op->first->sibling, 7);
3251 }
3252 maybe_local(@_, listop(@_, "substr"))
3253}
7e8d786b
DM
3254
3255sub pp_index {
3256 # Also handles pp_rindex.
3257 #
3258 # The body of this function includes an unrolled maybe_targmy(),
3259 # since the two parts of that sub's actions need to have have the
3260 # '== -1' bit in between
3261
3262 my($self, $op, $cx) = @_;
3263
3264 my $lex = ($op->private & OPpTARGET_MY);
3265 my $bool = ($op->private & OPpTRUEBOOL);
3266
3267 my $val = $self->listop($op, ($bool ? 14 : $lex ? 7 : $cx), $op->name);
3268
3269 # (index() == -1) has op_eq and op_const optimised away
3270 if ($bool) {
3271 $val .= ($op->private & OPpINDEX_BOOLNEG) ? " == -1" : " != -1";
3272 $val = "($val)" if ($op->flags & OPf_PARENS);
3273 }
3274 if ($lex) {
3275 my $var = $self->padname($op->targ);
3276 $val = $self->maybe_parens("$var = $val", $cx, 7);
3277 }
3278 $val;
3279}
3280
3281sub pp_rindex { pp_index(@_); }
6402d4ee 3282sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
3ed82cfc 3283sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
6e90668e 3284sub pp_formline { listop(@_, "formline") } # see also deparse_format
3ed82cfc 3285sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
6e90668e
SM
3286sub pp_unpack { listop(@_, "unpack") }
3287sub pp_pack { listop(@_, "pack") }
3ed82cfc 3288sub pp_join { maybe_targmy(@_, \&listop, "join") }
6e90668e 3289sub pp_splice { listop(@_, "splice") }
3ed82cfc
GS
3290sub pp_push { maybe_targmy(@_, \&listop, "push") }
3291sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
6e90668e
SM
3292sub pp_reverse { listop(@_, "reverse") }
3293sub pp_warn { listop(@_, "warn") }
3294sub pp_die { listop(@_, "die") }
9c56d9ea 3295sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
6e90668e
SM
3296sub pp_open { listop(@_, "open") }
3297sub pp_pipe_op { listop(@_, "pipe") }
3298sub pp_tie { listop(@_, "tie") }
82bafd27 3299sub pp_binmode { listop(@_, "binmode") }
6e90668e
SM
3300sub pp_dbmopen { listop(@_, "dbmopen") }
3301sub pp_sselect { listop(@_, "select") }
3302sub pp_select { listop(@_, "select") }
3303sub pp_read { listop(@_, "read") }
3304sub pp_sysopen { listop(@_, "sysopen") }
3305sub pp_sysseek { listop(@_, "sysseek") }
3306sub pp_sysread { listop(@_, "sysread") }
3307sub pp_syswrite { listop(@_, "syswrite") }
3308sub pp_send { listop(@_, "send") }
3309sub pp_recv { listop(@_, "recv") }
3310sub pp_seek { listop(@_, "seek") }
6e90668e
SM
3311sub pp_fcntl { listop(@_, "fcntl") }
3312sub pp_ioctl { listop(@_, "ioctl") }
3ed82cfc 3313sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
6e90668e 3314sub pp_socket { listop(@_, "socket") }
5deb1341 3315sub pp_sockpair { listop(@_, "socketpair") }
6e90668e
SM
3316sub pp_bind { listop(@_, "bind") }
3317sub pp_connect { listop(@_, "connect") }
3318sub pp_listen { listop(@_, "listen") }
3319sub pp_accept { listop(@_, "accept") }
3320sub pp_shutdown { listop(@_, "shutdown") }
3321sub pp_gsockopt { listop(@_, "getsockopt") }
3322sub pp_ssockopt { listop(@_, "setsockopt") }
3ed82cfc
GS
3323sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
3324sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
3325sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
3326sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
3327sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
3328sub pp_link { maybe_targmy(@_, \&listop, "link") }
3329sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
3330sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
6e90668e
SM
3331sub pp_open_dir { listop(@_, "opendir") }
3332sub pp_seekdir { listop(@_, "seekdir") }
3ed82cfc 3333sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
9d52f6f3
FC
3334sub pp_system { maybe_targmy(@_, \&indirop, "system") }
3335sub pp_exec { maybe_targmy(@_, \&indirop, "exec") }
3ed82cfc
GS
3336sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
3337sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
3338sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
3339sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
6e90668e
SM
3340sub pp_shmget { listop(@_, "shmget") }
3341sub pp_shmctl { listop(@_, "shmctl") }
3342sub pp_shmread { listop(@_, "shmread") }
3343sub pp_shmwrite { listop(@_, "shmwrite") }
3344sub pp_msgget { listop(@_, "msgget") }
3345sub pp_msgctl { listop(@_, "msgctl") }
3346sub pp_msgsnd { listop(@_, "msgsnd") }
3347sub pp_msgrcv { listop(@_, "msgrcv") }
3348sub pp_semget { listop(@_, "semget") }
3349sub pp_semctl { listop(@_, "semctl") }
3350sub pp_semop { listop(@_, "semop") }
3351sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
3352sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
3353sub pp_gpbynumber { listop(@_, "getprotobynumber") }
3354sub pp_gsbyname { listop(@_, "getservbyname") }
3355sub pp_gsbyport { listop(@_, "getservbyport") }
3356sub pp_syscall { listop(@_, "syscall") }
3357
3358sub pp_glob {
3359 my $self = shift;
9d2c6865 3360 my($op, $cx) = @_;
93860275 3361 my $kid = $op->first->sibling; # skip pushmark
a32fbbd8
FC
3362 my $keyword =
3363 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
18371617
LM
3364 my $text = $self->deparse($kid);
3365 return $cx >= 5 || $self->{'parens'}
3366 ? "$keyword($text)"
3367 : "$keyword $text";
6e90668e
SM
3368}
3369
f5aa8f4e
SM
3370# Truncate is special because OPf_SPECIAL makes a bareword first arg
3371# be a filehandle. This could probably be better fixed in the core
3372# by moving the GV lookup into ck_truc.
3373
3374sub pp_truncate {
3375 my $self = shift;
3376 my($op, $cx) = @_;
3377 my(@exprs);
3378 my $parens = ($cx >= 5) || $self->{'parens'};
3379 my $kid = $op->first->sibling;
acba1d67 3380 my $fh;
f5aa8f4e
SM
3381 if ($op->flags & OPf_SPECIAL) {
3382 # $kid is an OP_CONST
18228111 3383 $fh = $self->const_sv($kid)->PV;
f5aa8f4e
SM
3384 } else {
3385 $fh = $self->deparse($kid, 6);
3386 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
3387 }
3388 my $len = $self->deparse($kid->sibling, 6);
4a1ac32e 3389 my $name = $self->keyword('truncate');
f5aa8f4e 3390 if ($parens) {
4a1ac32e 3391 return "$name($fh, $len)";
f5aa8f4e 3392 } else {
4a1ac32e 3393 return "$name $fh, $len";
f5aa8f4e 3394 }
f5aa8f4e
SM
3395}
3396
6e90668e
SM
3397sub indirop {
3398 my $self = shift;
9d2c6865 3399 my($op, $cx, $name) = @_;
6e90668e 3400 my($expr, @exprs);
521795fe 3401 my $firstkid = my $kid = $op->first->sibling;
6e90668e
SM
3402 my $indir = "";
3403 if ($op->flags & OPf_STACKED) {
3404 $indir = $kid;
3405 $indir = $indir->first; # skip rv2gv
3406 if (is_scope($indir)) {
9d2c6865 3407 $indir = "{" . $self->deparse($indir, 0) . "}";
d989cdac 3408 $indir = "{;}" if $indir eq "{}";
c73811ab
RH
3409 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
3410 $indir = $self->const_sv($indir)->PV;
6e90668e 3411 } else {
9d2c6865 3412 $indir = $self->deparse($indir, 24);
6e90668e
SM
3413 }
3414 $indir = $indir . " ";
3415 $kid = $kid->sibling;
3416 }
7e80da18 3417 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3ac6e0f9 3418 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
7e80da18
RH
3419 : '{$a <=> $b} ';
3420 }
3ac6e0f9 3421 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
7e80da18
RH
3422 $indir = '{$b cmp $a} ';
3423 }
6e90668e 3424 for (; !null($kid); $kid = $kid->sibling) {
521795fe 3425 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
6e90668e
SM
3426 push @exprs, $expr;
3427 }
4a1ac32e 3428 my $name2;
3ac6e0f9 3429 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
4a1ac32e 3430 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3ac6e0f9 3431 }
4a1ac32e 3432 else { $name2 = $self->keyword($name) }
2b6e98cb 3433 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3ac6e0f9 3434 return "$exprs[0] = $name2 $indir $exprs[0]";
2b6e98cb
DM
3435 }
3436
d989cdac 3437 my $args = $indir . join(", ", @exprs);
521795fe 3438 if ($indir ne "" && $name eq "sort") {
d989cdac
SM
3439 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
3440 # give bareword warnings in that case. Therefore if context
3441 # requires, we'll put parens around the outside "(sort f 1, 2,
3442 # 3)". Unfortunately, we'll currently think the parens are
3c4b39be 3443 # necessary more often that they really are, because we don't
d989cdac
SM
3444 # distinguish which side of an assignment we're on.
3445 if ($cx >= 5) {
3ac6e0f9 3446 return "($name2 $args)";
d989cdac 3447 } else {
3ac6e0f9 3448 return "$name2 $args";
d989cdac 3449 }
521795fe
FC
3450 } elsif (
3451 !$indir && $name eq "sort"
ca331985 3452 && !null($op->first->sibling)
521795fe
FC
3453 && $op->first->sibling->name eq 'entersub'
3454 ) {
3455 # We cannot say sort foo(bar), as foo will be interpreted as a
3456 # comparison routine. We have to say sort(...) in that case.
3457 return "$name2($args)";
d989cdac 3458 } else {
9d52f6f3
FC
3459 return length $args
3460 ? $self->maybe_parens_func($name2, $args, $cx, 5)
3461 : $name2 . '()' x (7 < $cx);
d989cdac
SM
3462 }
3463
6e90668e
SM
3464}
3465
3466sub pp_prtf { indirop(@_, "printf") }
3467sub pp_print { indirop(@_, "print") }
9b08e3d3 3468sub pp_say { indirop(@_, "say") }
6e90668e
SM
3469sub pp_sort { indirop(@_, "sort") }
3470
3471sub mapop {
3472 my $self = shift;
9d2c6865 3473 my($op, $cx, $name) = @_;
6e90668e
SM
3474 my($expr, @exprs);
3475 my $kid = $op->first; # this is the (map|grep)start
3476 $kid = $kid->first->sibling; # skip a pushmark
3477 my $code = $kid->first; # skip a null
3478 if (is_scope $code) {
f4a44678 3479 $code = "{" . $self->deparse($code, 0) . "} ";
6e90668e 3480 } else {
6d08f7b3
DM
3481 $code = $self->deparse($code, 24);