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