This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
move sub attributes before the signature
[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
894f226e 1187# or altered. In this case we return "()" and fall back to general
60f638af
DM
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 { ...; }
894f226e 1278# or : prototype($$) lvalue ($a, $b) { ...; };
60f638af 1279
6e90668e
SM
1280sub deparse_sub {
1281 my $self = shift;
1282 my $cv = shift;
9fe5784b 1283 my @attrs;
894f226e
DM
1284 my $proto;
1285 my $sig;
9fe5784b 1286
ce4e655d 1287Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
34a48b4b
RH
1288Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1289 local $self->{'curcop'} = $self->{'curcop'};
9fe5784b
DM
1290
1291 my $has_sig = $self->{hinthash}{feature_signatures};
6e90668e 1292 if ($cv->FLAGS & SVf_POK) {
894f226e 1293 my $myproto = $cv->PV;
9fe5784b 1294 if ($has_sig) {
894f226e 1295 push @attrs, "prototype($myproto)";
9fe5784b
DM
1296 }
1297 else {
894f226e 1298 $proto = $myproto;
9fe5784b 1299 }
6e90668e 1300 }
b77472f9 1301 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE|CVf_ANONCONST)) {
9fe5784b 1302 push @attrs, "lvalue" if $cv->CvFLAGS & CVf_LVALUE;
9fe5784b
DM
1303 push @attrs, "method" if $cv->CvFLAGS & CVf_METHOD;
1304 push @attrs, "const" if $cv->CvFLAGS & CVf_ANONCONST;
6aaf4108
SC
1305 }
1306
6e90668e 1307 local($self->{'curcv'}) = $cv;
8510e997 1308 local($self->{'curcvlex'});
0ced6c29
RGS
1309 local(@$self{qw'curstash warnings hints hinthash'})
1310 = @$self{qw'curstash warnings hints hinthash'};
ce4e655d 1311 my $body;
a7fd8ef6
DM
1312 my $root = $cv->ROOT;
1313 local $B::overlay = {};
1314 if (not null $root) {
d4f1bfe7 1315 $self->pad_subs($cv);
a7fd8ef6
DM
1316 $self->pessimise($root, $cv->START);
1317 my $lineseq = $root->first;
ce4e655d 1318 if ($lineseq->name eq "lineseq") {
60f638af
DM
1319 my $firstop = $lineseq->first;
1320
1321 if ($has_sig) {
1322 my $o2;
1323 # try to deparse first few ops as a signature if possible
1324 if ( $$firstop
1325 and $firstop->name =~ /^(next|db)state$/
1326 and (($o2 = $firstop->sibling))
1327 and $$o2)
1328 {
1329 if ($o2->name eq 'argcheck') {
894f226e 1330 my ($nexto, $mysig) = $self->deparse_argops($firstop, $cv);
60f638af
DM
1331 if (defined $nexto) {
1332 $firstop = $nexto;
894f226e 1333 $sig = $mysig;
60f638af
DM
1334 }
1335 }
1336 }
1337 }
1338
1339 my @ops;
1340 for (my $o = $firstop; $$o; $o=$o->sibling) {
ce4e655d
RH
1341 push @ops, $o;
1342 }
93a8ff62 1343 $body = $self->lineseq(undef, 0, @ops).";";
60f638af 1344 if (!$has_sig and $ops[-1]->name =~ /^(next|db)state$/) {
4fa06845
DM
1345 # this handles void context in
1346 # use feature signatures; sub ($=1) {}
1347 $body .= "\n()";
1348 }
ce4e655d
RH
1349 my $scope_en = $self->find_scope_en($lineseq);
1350 if (defined $scope_en) {
1351 my $subs = join"", $self->seq_subs($scope_en);
1352 $body .= ";\n$subs" if length($subs);
1353 }
1354 }
1355 else {
a7fd8ef6 1356 $body = $self->deparse($root->first, 0);
ce4e655d 1357 }
9fe5784b 1358 $body = "{\n\t$body\n\b}";
de3f1649 1359 }
ce4e655d
RH
1360 else {
1361 my $sv = $cv->const_sv;
1362 if ($$sv) {
1363 # uh-oh. inlinable sub... format it differently
9fe5784b 1364 $body = "{ " . $self->const($sv, 0) . " }\n";
ce4e655d 1365 } else { # XSUB? (or just a declaration)
9fe5784b 1366 $body = ';'
ce4e655d 1367 }
6e90668e 1368 }
894f226e
DM
1369 $proto = defined $proto ? "($proto) " : "";
1370 $sig = defined $sig ? "($sig) " : "";
9fe5784b
DM
1371 my $attrs = '';
1372 $attrs = ': ' . join('', map "$_ ", @attrs) if @attrs;
894f226e 1373 return "$proto$attrs$sig$body\n";
6e90668e
SM
1374}
1375
1376sub deparse_format {
1377 my $self = shift;
1378 my $form = shift;
1379 my @text;
1380 local($self->{'curcv'}) = $form;
8510e997 1381 local($self->{'curcvlex'});
67fc2416 1382 local($self->{'in_format'}) = 1;
0ced6c29
RGS
1383 local(@$self{qw'curstash warnings hints hinthash'})
1384 = @$self{qw'curstash warnings hints hinthash'};
6e90668e 1385 my $op = $form->ROOT;
a7fd8ef6
DM
1386 local $B::overlay = {};
1387 $self->pessimise($op, $form->START);
6e90668e 1388 my $kid;
fb725297
RGS
1389 return "\f." if $op->first->name eq 'stub'
1390 || $op->first->name eq 'nextstate';
6e90668e
SM
1391 $op = $op->first->first; # skip leavewrite, lineseq
1392 while (not null $op) {
1393 $op = $op->sibling; # skip nextstate
1394 my @exprs;
1395 $kid = $op->first->sibling; # skip pushmark
a5b0cd91 1396 push @text, "\f".$self->const_sv($kid)->PV;
6e90668e
SM
1397 $kid = $kid->sibling;
1398 for (; not null $kid; $kid = $kid->sibling) {
93a8ff62 1399 push @exprs, $self->deparse($kid, -1);
31c26a0a 1400 $exprs[-1] =~ s/;\z//;
6e90668e 1401 }
a5b0cd91 1402 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
6e90668e
SM
1403 $op = $op->sibling;
1404 }
a5b0cd91 1405 return join("", @text) . "\f.";
6e90668e
SM
1406}
1407
6e90668e 1408sub is_scope {
a798dbf2 1409 my $op = shift;
3f872cb9
GS
1410 return $op->name eq "leave" || $op->name eq "scope"
1411 || $op->name eq "lineseq"
d989cdac 1412 || ($op->name eq "null" && class($op) eq "UNOP"
3f872cb9 1413 && (is_scope($op->first) || $op->first->name eq "enter"));
6e90668e
SM
1414}
1415
1416sub is_state {
3f872cb9
GS
1417 my $name = $_[0]->name;
1418 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
6e90668e
SM
1419}
1420
e38ccfd9 1421sub is_miniwhile { # check for one-line loop ('foo() while $y--')
6e90668e 1422 my $op = shift;
d989cdac 1423 return (!null($op) and null($op->sibling)
3f872cb9
GS
1424 and $op->name eq "null" and class($op) eq "UNOP"
1425 and (($op->first->name =~ /^(and|or)$/
1426 and $op->first->first->sibling->name eq "lineseq")
1427 or ($op->first->name eq "lineseq"
6e90668e 1428 and not null $op->first->first->sibling
3f872cb9 1429 and $op->first->first->sibling->name eq "unstack")
6e90668e
SM
1430 ));
1431}
1432
d989cdac
SM
1433# Check if the op and its sibling are the initialization and the rest of a
1434# for (..;..;..) { ... } loop
1435sub is_for_loop {
1436 my $op = shift;
1437 # This OP might be almost anything, though it won't be a
1438 # nextstate. (It's the initialization, so in the canonical case it
eae48c89
Z
1439 # will be an sassign.) The sibling is (old style) a lineseq whose
1440 # first child is a nextstate and whose second is a leaveloop, or
1441 # (new style) an unstack whose sibling is a leaveloop.
d989cdac 1442 my $lseq = $op->sibling;
eae48c89
Z
1443 return 0 unless !is_state($op) and !null($lseq);
1444 if ($lseq->name eq "lineseq") {
d989cdac
SM
1445 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1446 && (my $sib = $lseq->first->sibling)) {
1447 return (!null($sib) && $sib->name eq "leaveloop");
1448 }
eae48c89
Z
1449 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1450 my $sib = $lseq->sibling;
1451 return $sib && !null($sib) && $sib->name eq "leaveloop";
d989cdac
SM
1452 }
1453 return 0;
1454}
1455
6e90668e
SM
1456sub is_scalar {
1457 my $op = shift;
3f872cb9
GS
1458 return ($op->name eq "rv2sv" or
1459 $op->name eq "padsv" or
1460 $op->name eq "gv" or # only in array/hash constructs
bd0865ec 1461 $op->flags & OPf_KIDS && !null($op->first)
3f872cb9 1462 && $op->first->name eq "gvsv");
6e90668e
SM
1463}
1464
9d2c6865
SM
1465sub maybe_parens {
1466 my $self = shift;
1467 my($text, $cx, $prec) = @_;
1468 if ($prec < $cx # unary ops nest just fine
1469 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1470 or $self->{'parens'})
1471 {
1472 $text = "($text)";
1473 # In a unop, let parent reuse our parens; see maybe_parens_unop
1474 $text = "\cS" . $text if $cx == 16;
1475 return $text;
1476 } else {
1477 return $text;
1478 }
1479}
1480
e38ccfd9 1481# same as above, but get around the 'if it looks like a function' rule
9d2c6865
SM
1482sub maybe_parens_unop {
1483 my $self = shift;
1484 my($name, $kid, $cx) = @_;
1485 if ($cx > 16 or $self->{'parens'}) {
a0035eb8
RH
1486 $kid = $self->deparse($kid, 1);
1487 if ($name eq "umask" && $kid =~ /^\d+$/) {
1488 $kid = sprintf("%#o", $kid);
1489 }
4a1ac32e 1490 return $self->keyword($name) . "($kid)";
9d2c6865
SM
1491 } else {
1492 $kid = $self->deparse($kid, 16);
a0035eb8
RH
1493 if ($name eq "umask" && $kid =~ /^\d+$/) {
1494 $kid = sprintf("%#o", $kid);
1495 }
4a1ac32e 1496 $name = $self->keyword($name);
9d2c6865
SM
1497 if (substr($kid, 0, 1) eq "\cS") {
1498 # use kid's parens
1499 return $name . substr($kid, 1);
1500 } elsif (substr($kid, 0, 1) eq "(") {
1501 # avoid looks-like-a-function trap with extra parens
e38ccfd9 1502 # ('+' can lead to ambiguities)
9d2c6865
SM
1503 return "$name(" . $kid . ")";
1504 } else {
1505 return "$name $kid";
1506 }
1507 }
1508}
1509
1510sub maybe_parens_func {
1511 my $self = shift;
1512 my($func, $text, $cx, $prec) = @_;
1513 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1514 return "$func($text)";
1515 } else {
1516 return "$func $text";
1517 }
1518}
1519
56cd2ef8
FC
1520sub find_our_type {
1521 my ($self, $name) = @_;
1522 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
5afbd733 1523 my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0;
56cd2ef8
FC
1524 for my $a (@{$self->{'curcvlex'}{"o$name"}}) {
1525 my ($st, undef, $padname) = @$a;
5afbd733 1526 if ($st >= $seq && $padname->FLAGS & SVpad_TYPED) {
56cd2ef8
FC
1527 return $padname->SvSTASH->NAME;
1528 }
1529 }
1530 return '';
1531}
1532
6e90668e
SM
1533sub maybe_local {
1534 my $self = shift;
9d2c6865 1535 my($op, $cx, $text) = @_;
c8ec376c 1536 my $name = $op->name;
9187b6e4
FC
1537 my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign
1538 |lv(?:av)?ref)$/x)
de183bbb
FC
1539 ? OPpOUR_INTRO
1540 : 0;
1541 my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO;
c8ec376c
FC
1542 # The @a in \(@a) isn't in ref context, but only when the
1543 # parens are there.
1544 my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/
1545 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
de183bbb 1546 if ((my $priv = $op->private) & ($lval_intro|$our_intro)) {
f3515641 1547 my @our_local;
de183bbb 1548 push @our_local, "local" if $priv & $lval_intro;
f3515641 1549 push @our_local, "our" if $priv & $our_intro;
3188a821 1550 my $our_local = join " ", map $self->keyword($_), @our_local;
f3515641 1551 if( $our_local[-1] eq 'our' ) {
640d5d41
FC
1552 if ( $text !~ /^\W(\w+::)*\w+\z/
1553 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1554 ) {
1555 die "Unexpected our($text)\n";
1556 }
d989cdac 1557 $text =~ s/(\w+::)+//;
56cd2ef8
FC
1558
1559 if (my $type = $self->find_our_type($text)) {
1560 $our_local .= ' ' . $type;
1561 }
8e3542b6 1562 }
c8ec376c
FC
1563 return $need_parens ? "($text)" : $text
1564 if $self->{'avoid_local'}{$$op};
1565 if ($need_parens) {
1566 return "$our_local($text)";
1567 } elsif (want_scalar($op)) {
ce4e655d 1568 return "$our_local $text";
e8d3f51b 1569 } else {
ce4e655d 1570 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
e8d3f51b 1571 }
6e90668e 1572 } else {
c8ec376c 1573 return $need_parens ? "($text)" : $text;
a798dbf2 1574 }
a798dbf2
MB
1575}
1576
3ed82cfc
GS
1577sub maybe_targmy {
1578 my $self = shift;
1579 my($op, $cx, $func, @args) = @_;
1580 if ($op->private & OPpTARGET_MY) {
1581 my $var = $self->padname($op->targ);
1582 my $val = $func->($self, $op, 7, @args);
1583 return $self->maybe_parens("$var = $val", $cx, 7);
1584 } else {
1585 return $func->($self, $op, $cx, @args);
1586 }
1587}
1588
6e90668e
SM
1589sub padname_sv {
1590 my $self = shift;
1591 my $targ = shift;
d989cdac 1592 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
6e90668e
SM
1593}
1594
1595sub maybe_my {
1596 my $self = shift;
8db6f480 1597 my($op, $cx, $text, $padname, $forbid_parens) = @_;
c8ec376c
FC
1598 # The @a in \(@a) isn't in ref context, but only when the
1599 # parens are there.
1600 my $need_parens = !$forbid_parens && $self->{'in_refgen'}
1601 && $op->name =~ /[ah]v\z/
1602 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
0ed5b3c8
FC
1603 # The @a in \my @a must not have parens.
1604 if (!$need_parens && $self->{'in_refgen'}) {
1605 $forbid_parens = 1;
1606 }
4c1f658f 1607 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
bcff4148
FC
1608 # Check $padname->FLAGS for statehood, rather than $op->private,
1609 # because enteriter ops do not carry the flag.
3188a821 1610 my $my =
bcff4148 1611 $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my");
56cd2ef8
FC
1612 if ($padname->FLAGS & SVpad_TYPED) {
1613 $my .= ' ' . $padname->SvSTASH->NAME;
1614 }
c8ec376c
FC
1615 if ($need_parens) {
1616 return "$my($text)";
1617 } elsif ($forbid_parens || want_scalar($op)) {
3462b4ac 1618 return "$my $text";
e8d3f51b 1619 } else {
3462b4ac 1620 return $self->maybe_parens_func($my, $text, $cx, 16);
e8d3f51b 1621 }
6e90668e 1622 } else {
c8ec376c 1623 return $need_parens ? "($text)" : $text;
6e90668e
SM
1624 }
1625}
1626
9d2c6865
SM
1627# The following OPs don't have functions:
1628
1629# pp_padany -- does not exist after parsing
9d2c6865 1630
2ae48fff
RGS
1631sub AUTOLOAD {
1632 if ($AUTOLOAD =~ s/^.*::pp_//) {
5e8c3db2
FC
1633 warn "unexpected OP_".
1634 ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD);
2ae48fff
RGS
1635 return "XXX";
1636 } else {
1637 die "Undefined subroutine $AUTOLOAD called";
1638 }
9d2c6865 1639}
6e90668e 1640
611c1e95
IZ
1641sub DESTROY {} # Do not AUTOLOAD
1642
ce4e655d
RH
1643# $root should be the op which represents the root of whatever
1644# we're sequencing here. If it's undefined, then we don't append
1645# any subroutine declarations to the deparsed ops, otherwise we
1646# append appropriate declarations.
58cccf98 1647sub lineseq {
93a8ff62 1648 my($self, $root, $cx, @ops) = @_;
58cccf98 1649 my($expr, @exprs);
ce4e655d
RH
1650
1651 my $out_cop = $self->{'curcop'};
1652 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1653 my $limit_seq;
1654 if (defined $root) {
1655 $limit_seq = $out_seq;
76df5e8f
DM
1656 my $nseq;
1657 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
ce4e655d
RH
1658 $limit_seq = $nseq if !defined($limit_seq)
1659 or defined($nseq) && $nseq < $limit_seq;
1660 }
1661 $limit_seq = $self->{'limit_seq'}
1662 if defined($self->{'limit_seq'})
1663 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1664 local $self->{'limit_seq'} = $limit_seq;
09d856fb
CK
1665
1666 $self->walk_lineseq($root, \@ops,
1667 sub { push @exprs, $_[0]} );
1668
93a8ff62
FC
1669 my $sep = $cx ? '; ' : ";\n";
1670 my $body = join($sep, grep {length} @exprs);
ce4e655d 1671 my $subs = "";
67fc2416 1672 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
ce4e655d
RH
1673 $subs = join "\n", $self->seq_subs($limit_seq);
1674 }
93a8ff62 1675 return join($sep, grep {length} $body, $subs);
6e90668e
SM
1676}
1677
58cccf98 1678sub scopeop {
d989cdac 1679 my($real_block, $self, $op, $cx) = @_;
58cccf98
SM
1680 my $kid;
1681 my @kids;
a0405c92 1682
0ced6c29
RGS
1683 local(@$self{qw'curstash warnings hints hinthash'})
1684 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
58cccf98
SM
1685 if ($real_block) {
1686 $kid = $op->first->sibling; # skip enter
1687 if (is_miniwhile($kid)) {
1688 my $top = $kid->first;
1689 my $name = $top->name;
1690 if ($name eq "and") {
7741ceed 1691 $name = $self->keyword("while");
58cccf98 1692 } elsif ($name eq "or") {
7741ceed 1693 $name = $self->keyword("until");
58cccf98 1694 } else { # no conditional -> while 1 or until 0
7741ceed
FC
1695 return $self->deparse($top->first, 1) . " "
1696 . $self->keyword("while") . " 1";
58cccf98
SM
1697 }
1698 my $cond = $top->first;
1699 my $body = $cond->sibling->first; # skip lineseq
1700 $cond = $self->deparse($cond, 1);
1701 $body = $self->deparse($body, 1);
1702 return "$body $name $cond";
6e90668e 1703 }
58cccf98
SM
1704 } else {
1705 $kid = $op->first;
1706 }
1707 for (; !null($kid); $kid = $kid->sibling) {
1708 push @kids, $kid;
6e90668e 1709 }
d989cdac 1710 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
73582821 1711 my $body = $self->lineseq($op, 0, @kids);
3188a821
FC
1712 return is_lexical_subs(@kids)
1713 ? $body
1714 : ($self->lex_in_scope("&do") ? "CORE::do" : "do")
1715 . " {\n\t$body\n\b}";
9d2c6865 1716 } else {
93a8ff62 1717 my $lineseq = $self->lineseq($op, $cx, @kids);
7a9b44b9 1718 return (length ($lineseq) ? "$lineseq;" : "");
6e90668e 1719 }
6e90668e
SM
1720}
1721
ce4e655d 1722sub pp_scope { scopeop(0, @_); }
58cccf98
SM
1723sub pp_lineseq { scopeop(0, @_); }
1724sub pp_leave { scopeop(1, @_); }
9d2c6865 1725
d989cdac
SM
1726# This is a special case of scopeop and lineseq, for the case of the
1727# main_root. The difference is that we print the output statements as
1728# soon as we get them, for the sake of impatient users.
1729sub deparse_root {
1730 my $self = shift;
1731 my($op) = @_;
0ced6c29
RGS
1732 local(@$self{qw'curstash warnings hints hinthash'})
1733 = @$self{qw'curstash warnings hints hinthash'};
d989cdac 1734 my @kids;
4ca8de37 1735 return if null $op->first; # Can happen, e.g., for Bytecode without -k
d989cdac
SM
1736 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1737 push @kids, $kid;
1738 }
09d856fb 1739 $self->walk_lineseq($op, \@kids,
4b1385ee 1740 sub { return unless length $_[0];
5e617af5 1741 print $self->indent($_[0].';');
4b1385ee 1742 print "\n"
5e617af5 1743 unless $_[1] == $#kids;
09d856fb
CK
1744 });
1745}
1746
1747sub walk_lineseq {
1748 my ($self, $op, $kids, $callback) = @_;
1749 my @kids = @$kids;
d989cdac
SM
1750 for (my $i = 0; $i < @kids; $i++) {
1751 my $expr = "";
1752 if (is_state $kids[$i]) {
09d856fb 1753 $expr = $self->deparse($kids[$i++], 0);
d989cdac 1754 if ($i > $#kids) {
09d856fb 1755 $callback->($expr, $i);
d989cdac
SM
1756 last;
1757 }
1758 }
1759 if (is_for_loop($kids[$i])) {
eae48c89
Z
1760 $callback->($expr . $self->for_loop($kids[$i], 0),
1761 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
d989cdac
SM
1762 next;
1763 }
6b6b21da 1764 my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2);
34b54951 1765 $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise
6b6b21da 1766 $expr .= $expr2;
09d856fb 1767 $callback->($expr, $i);
d989cdac
SM
1768 }
1769}
1770
6e90668e
SM
1771# The BEGIN {} is used here because otherwise this code isn't executed
1772# when you run B::Deparse on itself.
1773my %globalnames;
1774BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1775 "ENV", "ARGV", "ARGVOUT", "_"); }
1776
1777sub gv_name {
1778 my $self = shift;
1779 my $gv = shift;
b89b7257 1780 my $raw = shift;
32cc5cd1
FC
1781#Carp::confess() unless ref($gv) eq "B::GV";
1782 my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0;
1783 my $stash = ($cv || $gv)->STASH->NAME;
1784 my $name = $raw
1785 ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME
1786 : $cv
1787 ? B::safename($cv->NAME_HEK || $cv->GV->NAME)
1788 : $gv->SAFENAME;
8b2d6640
FC
1789 if ($stash eq 'main' && $name =~ /^::/) {
1790 $stash = '::';
1791 }
b861b87f
FC
1792 elsif (($stash eq 'main'
1793 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
8b2d6640
FC
1794 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1795 && ($stash eq 'main' || $name !~ /::/))
b861b87f 1796 )
9d2c6865 1797 {
6e90668e
SM
1798 $stash = "";
1799 } else {
1800 $stash = $stash . "::";
a798dbf2 1801 }
b89b7257 1802 if (!$raw and $name =~ /^(\^..|{)/) {
083bda02 1803 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
6e90668e
SM
1804 }
1805 return $stash . $name;
a798dbf2
MB
1806}
1807
8510e997 1808# Return the name to use for a stash variable.
415d4c68
FC
1809# If a lexical with the same name is in scope, or
1810# if strictures are enabled, it may need to be
8510e997
RH
1811# fully-qualified.
1812sub stash_variable {
bb8996b8 1813 my ($self, $prefix, $name, $cx) = @_;
8510e997 1814
dd666160 1815 return $prefix.$self->maybe_qualify($prefix, $name) if $name =~ /::/;
8510e997 1816
d49c3562 1817 unless ($prefix eq '$' || $prefix eq '@' || $prefix eq '&' || #'
8510e997
RH
1818 $prefix eq '%' || $prefix eq '$#') {
1819 return "$prefix$name";
1820 }
1821
b6bba886 1822 if ($name =~ /^[^[:alpha:]_+-]$/) {
61154ac0
FC
1823 if (defined $cx && $cx == 26) {
1824 if ($prefix eq '@') {
bb8996b8
HY
1825 return "$prefix\{$name}";
1826 }
61154ac0
FC
1827 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1828 }
1829 if ($prefix eq '$#') {
6ec73527 1830 return "\$#{$name}";
61154ac0 1831 }
6ec73527 1832 }
bb8996b8 1833
415d4c68 1834 return $prefix . $self->maybe_qualify($prefix, $name);
8510e997
RH
1835}
1836
93e453e2
KW
1837my %unctrl = # portable to EBCDIC
1838 (
dd405ed7
KW
1839 "\c@" => '@', # unused
1840 "\cA" => 'A',
1841 "\cB" => 'B',
1842 "\cC" => 'C',
1843 "\cD" => 'D',
1844 "\cE" => 'E',
1845 "\cF" => 'F',
1846 "\cG" => 'G',
1847 "\cH" => 'H',
1848 "\cI" => 'I',
1849 "\cJ" => 'J',
1850 "\cK" => 'K',
1851 "\cL" => 'L',
1852 "\cM" => 'M',
1853 "\cN" => 'N',
1854 "\cO" => 'O',
1855 "\cP" => 'P',
1856 "\cQ" => 'Q',
1857 "\cR" => 'R',
1858 "\cS" => 'S',
1859 "\cT" => 'T',
1860 "\cU" => 'U',
1861 "\cV" => 'V',
1862 "\cW" => 'W',
1863 "\cX" => 'X',
1864 "\cY" => 'Y',
1865 "\cZ" => 'Z',
1866 "\c[" => '[', # unused
1867 "\c\\" => '\\', # unused
1868 "\c]" => ']', # unused
1869 "\c_" => '_', # unused
93e453e2
KW
1870 );
1871
be6cf5cf
FC
1872# Return just the name, without the prefix. It may be returned as a quoted
1873# string. The second return value is a boolean indicating that.
1874sub stash_variable_name {
1875 my($self, $prefix, $gv) = @_;
1876 my $name = $self->gv_name($gv, 1);
415d4c68 1877 $name = $self->maybe_qualify($prefix,$name);
be6cf5cf 1878 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
dd405ed7 1879 $name =~ s/^([\ca-\cz])/'^' . $unctrl{$1}/e;
be6cf5cf
FC
1880 $name =~ /^(\^..|{)/ and $name = "{$name}";
1881 return $name, 0; # not quoted
1882 }
1883 else {
7741ceed 1884 single_delim("q", "'", $name, $self), 1;
be6cf5cf
FC
1885 }
1886}
1887
415d4c68
FC
1888sub maybe_qualify {
1889 my ($self,$prefix,$name) = @_;
1890 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
dd666160
Z
1891 if ($prefix eq "") {
1892 $name .= "::" if $name =~ /(?:\ACORE::[^:]*|::)\z/;
1893 return $name;
1894 }
1895 return $name if $name =~ /::/;
415d4c68
FC
1896 return $self->{'curstash'}.'::'. $name
1897 if
36727b53
FC
1898 $name =~ /^(?!\d)\w/ # alphabetic
1899 && $v !~ /^\$[ab]\z/ # not $a or $b
257296eb 1900 && $v =~ /\A[\$\@\%\&]/ # scalar, array, hash, or sub
415d4c68
FC
1901 && !$globalnames{$name} # not a global name
1902 && $self->{hints} & $strict_bits{vars} # strict vars
1903 && !$self->lex_in_scope($v,1) # no "our"
1904 or $self->lex_in_scope($v); # conflicts with "my" variable
1905 return $name;
1906}
1907
8510e997 1908sub lex_in_scope {
415d4c68
FC
1909 my ($self, $name, $our) = @_;
1910 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
8510e997
RH
1911 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1912
6ec152c3 1913 return 0 if !defined($self->{'curcop'});
8510e997
RH
1914 my $seq = $self->{'curcop'}->cop_seq;
1915 return 0 if !exists $self->{'curcvlex'}{$name};
1916 for my $a (@{$self->{'curcvlex'}{$name}}) {
1917 my ($st, $en) = @$a;
1918 return 1 if $seq > $st && $seq <= $en;
1919 }
1920 return 0;
1921}
1922
1923sub populate_curcvlex {
1924 my $self = shift;
ce4e655d 1925 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
7dafbf52
DM
1926 my $padlist = $cv->PADLIST;
1927 # an undef CV still in lexical chain
1928 next if class($padlist) eq "SPECIAL";
1929 my @padlist = $padlist->ARRAY;
8510e997
RH
1930 my @ns = $padlist[0]->ARRAY;
1931
1932 for (my $i=0; $i<@ns; ++$i) {
1933 next if class($ns[$i]) eq "SPECIAL";
0f2fe21d
RH
1934 if (class($ns[$i]) eq "PV") {
1935 # Probably that pesky lexical @_
1936 next;
1937 }
8510e997 1938 my $name = $ns[$i]->PVX;
679f2252 1939 next unless defined $name;
7dafbf52
DM
1940 my ($seq_st, $seq_en) =
1941 ($ns[$i]->FLAGS & SVf_FAKE)
1942 ? (0, 999999)
809abb02 1943 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
8510e997 1944
415d4c68
FC
1945 push @{$self->{'curcvlex'}{
1946 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
56cd2ef8 1947 }}, [$seq_st, $seq_en, $ns[$i]];
8510e997
RH
1948 }
1949 }
1950}
1951
ce4e655d
RH
1952sub find_scope_st { ((find_scope(@_))[0]); }
1953sub find_scope_en { ((find_scope(@_))[1]); }
1954
1955# Recurses down the tree, looking for pad variable introductions and COPs
1956sub find_scope {
1957 my ($self, $op, $scope_st, $scope_en) = @_;
ff97752d 1958 carp("Undefined op in find_scope") if !defined $op;
ce4e655d
RH
1959 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1960
b6b46d6f
AB
1961 my @queue = ($op);
1962 while(my $op = shift @queue ) {
1963 for (my $o=$op->first; $$o; $o=$o->sibling) {
1964 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1965 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1966 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1967 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1968 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1969 return ($scope_st, $scope_en);
1970 }
1971 elsif (is_state($o)) {
1972 my $c = $o->cop_seq;
1973 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1974 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1975 return ($scope_st, $scope_en);
1976 }
1977 elsif ($o->flags & OPf_KIDS) {
1978 unshift (@queue, $o);
1979 }
34a48b4b
RH
1980 }
1981 }
ce4e655d
RH
1982
1983 return ($scope_st, $scope_en);
34a48b4b
RH
1984}
1985
1986# Returns a list of subs which should be inserted before the COP
1987sub cop_subs {
1988 my ($self, $op, $out_seq) = @_;
1989 my $seq = $op->cop_seq;
34a48b4b
RH
1990 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1991 return $self->seq_subs($seq);
1992}
1993
1994sub seq_subs {
1995 my ($self, $seq) = @_;
1996 my @text;
1997#push @text, "# ($seq)\n";
1998
ce4e655d 1999 return "" if !defined $seq;
d88d1fe0 2000 my @pending;
34a48b4b
RH
2001 while (scalar(@{$self->{'subs_todo'}})
2002 and $seq > $self->{'subs_todo'}[0][0]) {
d88d1fe0 2003 my $cv = $self->{'subs_todo'}[0][1];
d4f1bfe7
FC
2004 # Skip the OUTSIDE check for lexical subs. We may be deparsing a
2005 # cloned anon sub with lexical subs declared in it, in which case
2006 # the OUTSIDE pointer points to the anon protosub.
c310a5ab 2007 my $lexical = ref $self->{'subs_todo'}[0][3];
d4f1bfe7
FC
2008 my $outside = !$lexical && $cv && $cv->OUTSIDE;
2009 if (!$lexical and $cv
2010 and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}})
2011 {
d88d1fe0
FC
2012 push @pending, shift @{$self->{'subs_todo'}};
2013 next;
2014 }
34a48b4b
RH
2015 push @text, $self->next_todo;
2016 }
d88d1fe0 2017 unshift @{$self->{'subs_todo'}}, @pending;
34a48b4b
RH
2018 return @text;
2019}
2020
95c04cde
NC
2021sub _features_from_bundle {
2022 my ($hints, $hh) = @_;
1873980a 2023 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
95c04cde
NC
2024 $hh->{$feature::feature{$_}} = 1;
2025 }
2026 return $hh;
2027}
2028
d5994d07
DM
2029# generate any pragmas, 'package foo' etc needed to synchronise
2030# with the given cop
2031
2032sub pragmata {
6e90668e 2033 my $self = shift;
d5994d07
DM
2034 my($op) = @_;
2035
6e90668e 2036 my @text;
bc304ab2 2037
11faa288 2038 my $stash = $op->stashpv;
6e90668e 2039 if ($stash ne $self->{'curstash'}) {
7741ceed 2040 push @text, $self->keyword("package") . " $stash;\n";
6e90668e
SM
2041 $self->{'curstash'} = $stash;
2042 }
08c6f5ec 2043
bc6b2ef6
Z
2044 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
2045 push @text, '$[ = '. $op->arybase .";\n";
2046 $self->{'arybase'} = $op->arybase;
2047 }
2048
7a9b44b9
RH
2049 my $warnings = $op->warnings;
2050 my $warning_bits;
2051 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
810aef70 2052 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
7a9b44b9 2053 }
e31885a0 2054 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
810aef70 2055 $warning_bits = $warnings::NONE;
7a9b44b9 2056 }
e31885a0
RH
2057 elsif ($warnings->isa("B::SPECIAL")) {
2058 $warning_bits = undef;
2059 }
7a9b44b9 2060 else {
34a48b4b 2061 $warning_bits = $warnings->PV & WARN_MASK;
7a9b44b9
RH
2062 }
2063
e31885a0
RH
2064 if (defined ($warning_bits) and
2065 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
7741ceed
FC
2066 push @text,
2067 $self->declare_warnings($self->{'warnings'}, $warning_bits);
7a9b44b9
RH
2068 $self->{'warnings'} = $warning_bits;
2069 }
2070
843835bc 2071 my $hints = $op->hints;
0bb01b05 2072 my $old_hints = $self->{'hints'};
2be95ceb 2073 if ($self->{'hints'} != $hints) {
7741ceed 2074 push @text, $self->declare_hints($self->{'hints'}, $hints);
2be95ceb 2075 $self->{'hints'} = $hints;
a0405c92
RH
2076 }
2077
0bb01b05 2078 my $newhh;
843835bc 2079 $newhh = $op->hints_hash->HASH;
0bb01b05 2080
843835bc 2081 {
0bb01b05 2082 # feature bundle hints
149758b3
NC
2083 my $from = $old_hints & $feature::hint_mask;
2084 my $to = $ hints & $feature::hint_mask;
0bb01b05 2085 if ($from != $to) {
149758b3 2086 if ($to == $feature::hint_mask) {
0bb01b05
FC
2087 if ($self->{'hinthash'}) {
2088 delete $self->{'hinthash'}{$_}
2089 for grep /^feature_/, keys %{$self->{'hinthash'}};
2090 }
2091 else { $self->{'hinthash'} = {} }
95c04cde
NC
2092 $self->{'hinthash'}
2093 = _features_from_bundle($from, $self->{'hinthash'});
0bb01b05
FC
2094 }
2095 else {
2096 my $bundle =
2097 $feature::hint_bundles[$to >> $feature::hint_shift];
2098 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
7741ceed 2099 push @text,
127ce1cd 2100 $self->keyword("no") . " feature ':all';\n",
7741ceed 2101 $self->keyword("use") . " feature ':$bundle';\n";
0bb01b05
FC
2102 }
2103 }
2104 }
2105
843835bc 2106 {
7741ceed 2107 push @text, $self->declare_hinthash(
0bb01b05
FC
2108 $self->{'hinthash'}, $newhh,
2109 $self->{indent_size}, $self->{hints},
2110 );
2111 $self->{'hinthash'} = $newhh;
0ced6c29
RGS
2112 }
2113
d5994d07
DM
2114 return join("", @text);
2115}
2116
2117
2118# Notice how subs and formats are inserted between statements here;
2119# also $[ assignments and pragmas.
2120sub pp_nextstate {
2121 my $self = shift;
2122 my($op, $cx) = @_;
2123 $self->{'curcop'} = $op;
2124
e276dec7 2125 my @text;
d5994d07 2126
bc304ab2
DM
2127 my @subs = $self->cop_subs($op);
2128 if (@subs) {
2129 # Special marker to swallow up the semicolon
2130 push @subs, "\cK";
2131 }
2132 push @text, @subs;
2133
e276dec7 2134 push @text, $self->pragmata($op);
d5994d07 2135
bc304ab2 2136
d989cdac
SM
2137 # This should go after of any branches that add statements, to
2138 # increase the chances that it refers to the same line it did in
2139 # the original program.
e56a605e 2140 if ($self->{'linenums'} && $cx != .5) { # $cx == .5 means in a format
d989cdac
SM
2141 push @text, "\f#line " . $op->line .
2142 ' "' . $op->file, qq'"\n';
2143 }
2144
98a1a137
Z
2145 push @text, $op->label . ": " if $op->label;
2146
6e90668e
SM
2147 return join("", @text);
2148}
2149
08c6f5ec 2150sub declare_warnings {
7741ceed 2151 my ($self, $from, $to) = @_;
66cc68c1
DM
2152 $from //= '';
2153 my $all = (warnings::bits("all") & WARN_MASK);
2154 unless ((($from & WARN_MASK) & ~$all) =~ /[^\0]/) {
2155 # no FATAL bits need turning off
2156 if ( ($to & WARN_MASK) eq $all) {
2157 return $self->keyword("use") . " warnings;\n";
2158 }
2159 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
2160 return $self->keyword("no") . " warnings;\n";
2161 }
a0405c92 2162 }
66cc68c1 2163
74b899ae
KW
2164 return "BEGIN {\${^WARNING_BITS} = \""
2165 . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
2166 . "\"}\n\cK";
a0405c92
RH
2167}
2168
2169sub declare_hints {
7741ceed 2170 my ($self, $from, $to) = @_;
a0035eb8
RH
2171 my $use = $to & ~$from;
2172 my $no = $from & ~$to;
2173 my $decls = "";
2174 for my $pragma (hint_pragmas($use)) {
7741ceed 2175 $decls .= $self->keyword("use") . " $pragma;\n";
a0035eb8
RH
2176 }
2177 for my $pragma (hint_pragmas($no)) {
7741ceed 2178 $decls .= $self->keyword("no") . " $pragma;\n";
a0035eb8
RH
2179 }
2180 return $decls;
2181}
2182
493c23c6
NC
2183# Internal implementation hints that the core sets automatically, so don't need
2184# (or want) to be passed back to the user
2185my %ignored_hints = (
2186 'open<' => 1,
2187 'open>' => 1,
dca6062a 2188 ':' => 1,
1c74777c
FC
2189 'strict/refs' => 1,
2190 'strict/subs' => 1,
2191 'strict/vars' => 1,
2e8342de 2192);
493c23c6 2193
a8095af7
FC
2194my %rev_feature;
2195
0ced6c29 2196sub declare_hinthash {
7741ceed 2197 my ($self, $from, $to, $indent, $hints) = @_;
a8095af7 2198 my $doing_features =
149758b3 2199 ($hints & $feature::hint_mask) == $feature::hint_mask;
0ced6c29 2200 my @decls;
a8095af7
FC
2201 my @features;
2202 my @unfeatures; # bugs?
0bb01b05 2203 for my $key (sort keys %$to) {
493c23c6 2204 next if $ignored_hints{$key};
843835bc 2205 my $is_feature = $key =~ /^feature_/;
a8095af7 2206 next if $is_feature and not $doing_features;
04be0204 2207 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
a8095af7 2208 push(@features, $key), next if $is_feature;
035146a3 2209 push @decls,
7741ceed 2210 qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
035146a3
FC
2211 . (
2212 defined $to->{$key}
7741ceed 2213 ? single_delim("q", "'", $to->{$key}, $self)
035146a3
FC
2214 : 'undef'
2215 )
04be0204 2216 . qq(;);
0ced6c29
RGS
2217 }
2218 }
0bb01b05 2219 for my $key (sort keys %$from) {
493c23c6 2220 next if $ignored_hints{$key};
843835bc 2221 my $is_feature = $key =~ /^feature_/;
a8095af7 2222 next if $is_feature and not $doing_features;
0ced6c29 2223 if (!exists $to->{$key}) {
a8095af7 2224 push(@unfeatures, $key), next if $is_feature;
0ced6c29
RGS
2225 push @decls, qq(delete \$^H{'$key'};);
2226 }
2227 }
a8095af7
FC
2228 my @ret;
2229 if (@features || @unfeatures) {
a8095af7
FC
2230 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
2231 }
2232 if (@features) {
7741ceed 2233 push @ret, $self->keyword("use") . " feature "
a8095af7
FC
2234 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
2235 }
2236 if (@unfeatures) {
7741ceed 2237 push @ret, $self->keyword("no") . " feature "
a8095af7
FC
2238 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
2239 . ";\n";
2240 }
2241 @decls and
2242 push @ret,
5e617af5 2243 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
a8095af7 2244 return @ret;
0ced6c29
RGS
2245}
2246
a0035eb8
RH
2247sub hint_pragmas {
2248 my ($bits) = @_;
415d4c68 2249 my (@pragmas, @strict);
a0035eb8 2250 push @pragmas, "integer" if $bits & 0x1;
415d4c68
FC
2251 for (sort keys %strict_bits) {
2252 push @strict, "'$_'" if $bits & $strict_bits{$_};
2253 }
2254 if (@strict == keys %strict_bits) {
2255 push @pragmas, "strict";
2256 }
2257 elsif (@strict) {
2258 push @pragmas, "strict " . join ', ', @strict;
2259 }
a0035eb8
RH
2260 push @pragmas, "bytes" if $bits & 0x8;
2261 return @pragmas;
08c6f5ec
RH
2262}
2263
6e90668e 2264sub pp_dbstate { pp_nextstate(@_) }
3f872cb9 2265sub pp_setstate { pp_nextstate(@_) }
6e90668e
SM
2266
2267sub pp_unstack { return "" } # see also leaveloop
2268
80e3f4ad
FC
2269my %feature_keywords = (
2270 # keyword => 'feature',
2271 state => 'state',
2272 say => 'say',
2273 given => 'switch',
7896dde7
Z
2274 when => 'switch',
2275 default => 'switch',
2276 break => 'switch',
7d789282 2277 evalbytes=>'evalbytes',
84ed0108 2278 __SUB__ => '__SUB__',
838f2281 2279 fc => 'fc',
80e3f4ad
FC
2280);
2281
3ac5308a
DM
2282# keywords that are strong and also have a prototype
2283#
2284my %strong_proto_keywords = map { $_ => 1 } qw(
3ac5308a
DM
2285 pos
2286 prototype
2287 scalar
2288 study
2289 undef
2290);
2291
a958cfbb
FC
2292sub feature_enabled {
2293 my($self,$name) = @_;
223b1722 2294 my $hh;
149758b3
NC
2295 my $hints = $self->{hints} & $feature::hint_mask;
2296 if ($hints && $hints != $feature::hint_mask) {
1873980a 2297 $hh = _features_from_bundle($hints);
223b1722
FC
2298 }
2299 elsif ($hints) { $hh = $self->{'hinthash'} }
a958cfbb
FC
2300 return $hh && $hh->{"feature_$feature_keywords{$name}"}
2301}
2302
2303sub keyword {
2304 my $self = shift;
2305 my $name = shift;
2306 return $name if $name =~ /^CORE::/; # just in case
2307 if (exists $feature_keywords{$name}) {
2308 return "CORE::$name" if not $self->feature_enabled($name);
80e3f4ad 2309 }
7741ceed
FC
2310 # This sub may be called for a program that has no nextstate ops. In
2311 # that case we may have a lexical sub named no/use/sub in scope but
2312 # but $self->lex_in_scope will return false because it depends on the
2313 # current nextstate op. So we need this alternate method if there is
2314 # no current cop.
2315 if (!$self->{'curcop'}) {
2316 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
2317 return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
2318 || exists $self->{'curcvlex'}{"o&$name"};
2319 } elsif ($self->lex_in_scope("&$name")
2320 || $self->lex_in_scope("&$name", 1)) {
3188a821
FC
2321 return "CORE::$name";
2322 }
3ac5308a
DM
2323 if ($strong_proto_keywords{$name}
2324 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
2325 && !defined eval{prototype "CORE::$name"})
4a1ac32e
FC
2326 ) { return $name }
2327 if (
2328 exists $self->{subs_declared}{$name}
2329 or
2330 exists &{"$self->{curstash}::$name"}
2331 ) {
2332 return "CORE::$name"
2333 }
2334 return $name;
2335}
2336
6e90668e
SM
2337sub baseop {
2338 my $self = shift;
9d2c6865 2339 my($op, $cx, $name) = @_;
4a1ac32e 2340 return $self->keyword($name);
6e90668e
SM
2341}
2342
ddb55548 2343sub pp_stub { "()" }
6e90668e
SM
2344sub pp_wantarray { baseop(@_, "wantarray") }
2345sub pp_fork { baseop(@_, "fork") }
3ed82cfc
GS
2346sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
2347sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
2348sub pp_time { maybe_targmy(@_, \&baseop, "time") }
6e90668e
SM
2349sub pp_tms { baseop(@_, "times") }
2350sub pp_ghostent { baseop(@_, "gethostent") }
2351sub pp_gnetent { baseop(@_, "getnetent") }
2352sub pp_gprotoent { baseop(@_, "getprotoent") }
2353sub pp_gservent { baseop(@_, "getservent") }
2354sub pp_ehostent { baseop(@_, "endhostent") }
2355sub pp_enetent { baseop(@_, "endnetent") }
2356sub pp_eprotoent { baseop(@_, "endprotoent") }
2357sub pp_eservent { baseop(@_, "endservent") }
2358sub pp_gpwent { baseop(@_, "getpwent") }
2359sub pp_spwent { baseop(@_, "setpwent") }
2360sub pp_epwent { baseop(@_, "endpwent") }
2361sub pp_ggrent { baseop(@_, "getgrent") }
2362sub pp_sgrent { baseop(@_, "setgrent") }
2363sub pp_egrent { baseop(@_, "endgrent") }
2364sub pp_getlogin { baseop(@_, "getlogin") }
2365
2366sub POSTFIX () { 1 }
2367
9d2c6865
SM
2368# I couldn't think of a good short name, but this is the category of
2369# symbolic unary operators with interesting precedence
2370
2371sub pfixop {
2372 my $self = shift;
2373 my($op, $cx, $name, $prec, $flags) = (@_, 0);
2374 my $kid = $op->first;
2375 $kid = $self->deparse($kid, $prec);
843b15cc
FC
2376 return $self->maybe_parens(($flags & POSTFIX)
2377 ? "$kid$name"
2378 # avoid confusion with filetests
2379 : $name eq '-'
2380 && $kid =~ /^[a-zA-Z](?!\w)/
2381 ? "$name($kid)"
2382 : "$name$kid",
9d2c6865
SM
2383 $cx, $prec);
2384}
2385
2386sub pp_preinc { pfixop(@_, "++", 23) }
2387sub pp_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2388sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2389sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
9d2c6865
SM
2390sub pp_i_preinc { pfixop(@_, "++", 23) }
2391sub pp_i_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2392sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2393sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
68cc8748 2394sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
27f31adf
FC
2395*pp_ncomplement = *pp_complement;
2396sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) }
9d2c6865 2397
3ed82cfc
GS
2398sub pp_negate { maybe_targmy(@_, \&real_negate) }
2399sub real_negate {
9d2c6865
SM
2400 my $self = shift;
2401 my($op, $cx) = @_;
3f872cb9 2402 if ($op->first->name =~ /^(i_)?negate$/) {
9d2c6865
SM
2403 # avoid --$x
2404 $self->pfixop($op, $cx, "-", 21.5);
2405 } else {
2406 $self->pfixop($op, $cx, "-", 21);
2407 }
2408}
2409sub pp_i_negate { pp_negate(@_) }
2410
2411sub pp_not {
2412 my $self = shift;
2413 my($op, $cx) = @_;
2414 if ($cx <= 4) {
1cabb3b3 2415 $self->listop($op, $cx, "not", $op->first);
9d2c6865
SM
2416 } else {
2417 $self->pfixop($op, $cx, "!", 21);
2418 }
2419}
2420
6e90668e
SM
2421sub unop {
2422 my $self = shift;
9c56d9ea 2423 my($op, $cx, $name, $nollafr) = @_;
6e90668e 2424 my $kid;
9d2c6865 2425 if ($op->flags & OPf_KIDS) {
aaf643ce 2426 $kid = $op->first;
1c85afce
YO
2427 if (not $name) {
2428 # this deals with 'boolkeys' right now
2429 return $self->deparse($kid,$cx);
2430 }
deb20ba3
RGS
2431 my $builtinname = $name;
2432 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2433 if (defined prototype($builtinname)
9cef6114 2434 && $builtinname ne 'CORE::readline'
deb20ba3 2435 && prototype($builtinname) =~ /^;?\*/
e31885a0
RH
2436 && $kid->name eq "rv2gv") {
2437 $kid = $kid->first;
2438 }
2439
9c56d9ea 2440 if ($nollafr) {
917a8f4f
FC
2441 if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) {
2442 # require foo() is a syntax error.
2443 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2444 }
9c56d9ea
FC
2445 return $self->maybe_parens(
2446 $self->keyword($name) . " $kid", $cx, 16
2447 );
2448 }
9d2c6865 2449 return $self->maybe_parens_unop($name, $kid, $cx);
6e90668e 2450 } else {
4d8ac5c7
FC
2451 return $self->maybe_parens(
2452 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
2453 $cx, 16,
2454 );
6e90668e 2455 }
6e90668e
SM
2456}
2457
3ed82cfc
GS
2458sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
2459sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
2460sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
2461sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
6e90668e
SM
2462sub pp_defined { unop(@_, "defined") }
2463sub pp_undef { unop(@_, "undef") }
2464sub pp_study { unop(@_, "study") }
6e90668e
SM
2465sub pp_ref { unop(@_, "ref") }
2466sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
2467
3ed82cfc
GS
2468sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
2469sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
2470sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
6e90668e 2471sub pp_srand { unop(@_, "srand") }
3ed82cfc
GS
2472sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
2473sub pp_log { maybe_targmy(@_, \&unop, "log") }
2474sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
2475sub pp_int { maybe_targmy(@_, \&unop, "int") }
2476sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
2477sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
2478sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
2479
2480sub pp_length { maybe_targmy(@_, \&unop, "length") }
2481sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2482sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
6e90668e
SM
2483
2484sub pp_each { unop(@_, "each") }
2485sub pp_values { unop(@_, "values") }
2486sub pp_keys { unop(@_, "keys") }
09dcfa7d 2487{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1c85afce
YO
2488sub pp_boolkeys {
2489 # no name because its an optimisation op that has no keyword
2490 unop(@_,"");
2491}
644741fd
NC
2492sub pp_aeach { unop(@_, "each") }
2493sub pp_avalues { unop(@_, "values") }
2494sub pp_akeys { unop(@_, "keys") }
6e90668e
SM
2495sub pp_pop { unop(@_, "pop") }
2496sub pp_shift { unop(@_, "shift") }
2497
2498sub pp_caller { unop(@_, "caller") }
2499sub pp_reset { unop(@_, "reset") }
2500sub pp_exit { unop(@_, "exit") }
2501sub pp_prototype { unop(@_, "prototype") }
2502
2503sub pp_close { unop(@_, "close") }
2504sub pp_fileno { unop(@_, "fileno") }
2505sub pp_umask { unop(@_, "umask") }
6e90668e
SM
2506sub pp_untie { unop(@_, "untie") }
2507sub pp_tied { unop(@_, "tied") }
2508sub pp_dbmclose { unop(@_, "dbmclose") }
2509sub pp_getc { unop(@_, "getc") }
2510sub pp_eof { unop(@_, "eof") }
2511sub pp_tell { unop(@_, "tell") }
2512sub pp_getsockname { unop(@_, "getsockname") }
2513sub pp_getpeername { unop(@_, "getpeername") }
2514
0175f038
FC
2515sub pp_chdir {
2516 my ($self, $op, $cx) = @_;
3c4a43a5 2517 if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) {
0175f038
FC
2518 my $kw = $self->keyword("chdir");
2519 my $kid = $self->const_sv($op->first)->PV;
2520 my $code = $kw
2521 . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid");
2522 maybe_targmy(@_, sub { $_[3] }, $code);
2523 } else {
2524 maybe_targmy(@_, \&unop, "chdir")
2525 }
2526}
2527
3ed82cfc 2528sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
6e90668e 2529sub pp_readlink { unop(@_, "readlink") }
3ed82cfc 2530sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
6e90668e
SM
2531sub pp_readdir { unop(@_, "readdir") }
2532sub pp_telldir { unop(@_, "telldir") }
2533sub pp_rewinddir { unop(@_, "rewinddir") }
2534sub pp_closedir { unop(@_, "closedir") }
3ed82cfc 2535sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
6e90668e
SM
2536sub pp_localtime { unop(@_, "localtime") }
2537sub pp_gmtime { unop(@_, "gmtime") }
2538sub pp_alarm { unop(@_, "alarm") }
3ed82cfc 2539sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
6e90668e 2540
94bb57f9 2541sub pp_dofile {
9c56d9ea 2542 my $code = unop(@_, "do", 1); # llafr does not apply
8b46c09b 2543 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
94bb57f9
FC
2544 $code;
2545}
7d789282
FC
2546sub pp_entereval {
2547 unop(
2548 @_,
c7c39989 2549 $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval"
7d789282
FC
2550 )
2551}
6e90668e
SM
2552
2553sub pp_ghbyname { unop(@_, "gethostbyname") }
2554sub pp_gnbyname { unop(@_, "getnetbyname") }
2555sub pp_gpbyname { unop(@_, "getprotobyname") }
2556sub pp_shostent { unop(@_, "sethostent") }
2557sub pp_snetent { unop(@_, "setnetent") }
2558sub pp_sprotoent { unop(@_, "setprotoent") }
2559sub pp_sservent { unop(@_, "setservent") }
2560sub pp_gpwnam { unop(@_, "getpwnam") }
2561sub pp_gpwuid { unop(@_, "getpwuid") }
2562sub pp_ggrnam { unop(@_, "getgrnam") }
2563sub pp_ggrgid { unop(@_, "getgrgid") }
2564
2565sub pp_lock { unop(@_, "lock") }
2566
0d863452 2567sub pp_continue { unop(@_, "continue"); }
7896dde7 2568sub pp_break { unop(@_, "break"); }
0d863452 2569
7896dde7
Z
2570sub givwhen {
2571 my $self = shift;
2572 my($op, $cx, $givwhen) = @_;
0d863452
RH
2573
2574 my $enterop = $op->first;
7896dde7
Z
2575 my ($head, $block);
2576 if ($enterop->flags & OPf_SPECIAL) {
2577 $head = $self->keyword("default");
2578 $block = $self->deparse($enterop->first, 0);
0d863452 2579 }
7896dde7
Z
2580 else {
2581 my $cond = $enterop->first;
2582 my $cond_str = $self->deparse($cond, 1);
2583 $head = "$givwhen ($cond_str)";
2584 $block = $self->deparse($cond->sibling, 0);
2585 }
2586
2587 return "$head {\n".
2588 "\t$block\n".
2589 "\b}\cK";
0d863452
RH
2590}
2591
7896dde7
Z
2592sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2593sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
2594
6e90668e
SM
2595sub pp_exists {
2596 my $self = shift;
9d2c6865 2597 my($op, $cx) = @_;
34a48b4b 2598 my $arg;
3188a821 2599 my $name = $self->keyword("exists");
34a48b4b
RH
2600 if ($op->private & OPpEXISTS_SUB) {
2601 # Checking for the existence of a subroutine
3188a821 2602 return $self->maybe_parens_func($name,
34a48b4b
RH
2603 $self->pp_rv2cv($op->first, 16), $cx, 16);
2604 }
2605 if ($op->flags & OPf_SPECIAL) {
2606 # Array element, not hash element
3188a821 2607 return $self->maybe_parens_func($name,
34a48b4b
RH
2608 $self->pp_aelem($op->first, 16), $cx, 16);
2609 }
3188a821 2610 return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
9d2c6865 2611 $cx, 16);
6e90668e
SM
2612}
2613
6e90668e
SM
2614sub pp_delete {
2615 my $self = shift;
9d2c6865 2616 my($op, $cx) = @_;
6e90668e 2617 my $arg;
3188a821 2618 my $name = $self->keyword("delete");
ac1e5644 2619 if ($op->private & (OPpSLICE|OPpKVSLICE)) {
34a48b4b
RH
2620 if ($op->flags & OPf_SPECIAL) {
2621 # Deleting from an array, not a hash
3188a821 2622 return $self->maybe_parens_func($name,
34a48b4b
RH
2623 $self->pp_aslice($op->first, 16),
2624 $cx, 16);
2625 }
3188a821 2626 return $self->maybe_parens_func($name,
9d2c6865
SM
2627 $self->pp_hslice($op->first, 16),
2628 $cx, 16);
6e90668e 2629 } else {
34a48b4b
RH
2630 if ($op->flags & OPf_SPECIAL) {
2631 # Deleting from an array, not a hash
3188a821 2632 return $self->maybe_parens_func($name,
34a48b4b
RH
2633 $self->pp_aelem($op->first, 16),
2634 $cx, 16);
2635 }
3188a821 2636 return $self->maybe_parens_func($name,
9d2c6865
SM
2637 $self->pp_helem($op->first, 16),
2638 $cx, 16);
6e90668e 2639 }
6e90668e
SM
2640}
2641
6e90668e
SM
2642sub pp_require {
2643 my $self = shift;
9d2c6865 2644 my($op, $cx) = @_;
d5889722 2645 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
5e7acd25
FC
2646 my $kid = $op->first;
2647 if ($kid->name eq 'const') {
2648 my $priv = $kid->private;
2649 my $sv = $self->const_sv($kid);
2650 my $arg;
2651 if ($priv & OPpCONST_BARE) {
2652 $arg = $sv->PV;
2653 $arg =~ s[/][::]g;
2654 $arg =~ s/\.pm//g;
2655 } elsif ($priv & OPpCONST_NOVER) {
2656 $opname = $self->keyword('no');
2657 $arg = $self->const($sv, 16);
2658 } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) {
2659 $arg = $tmp;
2660 }
2661 if ($arg) {
2662 return $self->maybe_parens("$opname $arg", $cx, 16);
2663 }
2664 }
2665 $self->unop(
41df74e3 2666 $op, $cx,
5e7acd25 2667 $opname,
41df74e3 2668 1, # llafr does not apply
5e7acd25 2669 );
6e90668e
SM
2670}
2671
d989cdac 2672sub pp_scalar {
9d2c6865 2673 my $self = shift;
d9002312 2674 my($op, $cx) = @_;
9d2c6865
SM
2675 my $kid = $op->first;
2676 if (not null $kid->sibling) {
2677 # XXX Was a here-doc
2678 return $self->dquote($op);
2679 }
2680 $self->unop(@_, "scalar");
2681}
2682
2683
6e90668e
SM
2684sub padval {
2685 my $self = shift;
2686 my $targ = shift;
d989cdac 2687 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
6e90668e
SM
2688}
2689
78c72037
NC
2690sub anon_hash_or_list {
2691 my $self = shift;
d9002312 2692 my($op, $cx) = @_;
78c72037
NC
2693
2694 my($pre, $post) = @{{"anonlist" => ["[","]"],
2695 "anonhash" => ["{","}"]}->{$op->name}};
2696 my($expr, @exprs);
2697 $op = $op->first->sibling; # skip pushmark
2698 for (; !null($op); $op = $op->sibling) {
2699 $expr = $self->deparse($op, 6);
2700 push @exprs, $expr;
2701 }
d9002312
SM
2702 if ($pre eq "{" and $cx < 1) {
2703 # Disambiguate that it's not a block
2704 $pre = "+{";
2705 }
78c72037
NC
2706 return $pre . join(", ", @exprs) . $post;
2707}
2708
2709sub pp_anonlist {
d9002312
SM
2710 my $self = shift;
2711 my ($op, $cx) = @_;
78c72037 2712 if ($op->flags & OPf_SPECIAL) {
d9002312 2713 return $self->anon_hash_or_list($op, $cx);
78c72037
NC
2714 }
2715 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2716 return 'XXX';
2717}
2718
2719*pp_anonhash = \&pp_anonlist;
2720
6e90668e
SM
2721sub pp_refgen {
2722 my $self = shift;
9d2c6865 2723 my($op, $cx) = @_;
6e90668e 2724 my $kid = $op->first;
3f872cb9 2725 if ($kid->name eq "null") {
01762542 2726 my $anoncode = $kid = $kid->first;
b77472f9
FC
2727 if ($anoncode->name eq "anonconst") {
2728 $anoncode = $anoncode->first->first->sibling;
2729 }
01762542
FC
2730 if ($anoncode->name eq "anoncode"
2731 or !null($anoncode = $kid->sibling) and
2732 $anoncode->name eq "anoncode") {
2733 return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
3f872cb9
GS
2734 } elsif ($kid->name eq "pushmark") {
2735 my $sib_name = $kid->sibling->name;
c8ec376c 2736 if ($sib_name eq 'entersub') {
c8c62db7
AD
2737 my $text = $self->deparse($kid->sibling, 1);
2738 # Always show parens for \(&func()), but only with -p otherwise
2739 $text = "($text)" if $self->{'parens'}
2740 or $kid->sibling->private & OPpENTERSUB_AMPER;
2741 return "\\$text";
2742 }
2743 }
6e90668e 2744 }
c8ec376c 2745 local $self->{'in_refgen'} = 1;
9d2c6865 2746 $self->pfixop($op, $cx, "\\", 20);
6e90668e
SM
2747}
2748
09d856fb
CK
2749sub e_anoncode {
2750 my ($self, $info) = @_;
2751 my $text = $self->deparse_sub($info->{code});
7741ceed 2752 return $self->keyword("sub") . " $text";
09d856fb
CK
2753}
2754
6e90668e
SM
2755sub pp_srefgen { pp_refgen(@_) }
2756
2757sub pp_readline {
2758 my $self = shift;
9d2c6865 2759 my($op, $cx) = @_;
6e90668e 2760 my $kid = $op->first;
18371617
LM
2761 if (is_scalar($kid)
2762 and $op->flags & OPf_SPECIAL
2763 and $self->deparse($kid, 1) eq 'ARGV')
2764 {
2765 return '<<>>';
65ef2c3e 2766 }
e31885a0 2767 return $self->unop($op, $cx, "readline");
6e90668e
SM
2768}
2769
ad8caead
RGS
2770sub pp_rcatline {
2771 my $self = shift;
2772 my($op) = @_;
d989cdac 2773 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
ad8caead
RGS
2774}
2775
bd0865ec
GS
2776# Unary operators that can occur as pseudo-listops inside double quotes
2777sub dq_unop {
2778 my $self = shift;
2779 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2780 my $kid;
2781 if ($op->flags & OPf_KIDS) {
2782 $kid = $op->first;
2783 # If there's more than one kid, the first is an ex-pushmark.
2784 $kid = $kid->sibling if not null $kid->sibling;
2785 return $self->maybe_parens_unop($name, $kid, $cx);
2786 } else {
d989cdac 2787 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
bd0865ec
GS
2788 }
2789}
2790
2791sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2792sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2793sub pp_uc { dq_unop(@_, "uc") }
2794sub pp_lc { dq_unop(@_, "lc") }
3ed82cfc 2795sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
838f2281 2796sub pp_fc { dq_unop(@_, "fc") }
bd0865ec 2797
6e90668e
SM
2798sub loopex {
2799 my $self = shift;
9d2c6865 2800 my ($op, $cx, $name) = @_;
6e90668e 2801 if (class($op) eq "PVOP") {
41df74e3 2802 $name .= " " . $op->pv;
9d2c6865 2803 } elsif (class($op) eq "OP") {
41df74e3 2804 # no-op
6e90668e 2805 } elsif (class($op) eq "UNOP") {
1eb0b7be 2806 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
df465735
FC
2807 # last foo() is a syntax error.
2808 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
41df74e3 2809 $name .= " $kid";
6e90668e 2810 }
1eb0b7be 2811 return $self->maybe_parens($name, $cx, 7);
6e90668e
SM
2812}
2813
2814sub pp_last { loopex(@_, "last") }
2815sub pp_next { loopex(@_, "next") }
2816sub pp_redo { loopex(@_, "redo") }
2817sub pp_goto { loopex(@_, "goto") }
266da325 2818sub pp_dump { loopex(@_, "CORE::dump") }
6e90668e
SM
2819
2820sub ftst {
2821 my $self = shift;
9d2c6865 2822 my($op, $cx, $name) = @_;
6e90668e 2823 if (class($op) eq "UNOP") {
e38ccfd9 2824 # Genuine '-X' filetests are exempt from the LLAFR, but not
5830412d
FC
2825 # l?stat()
2826 if ($name =~ /^-/) {
2827 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2828 return $self->maybe_parens("$name $kid", $cx, 16);
2829 }
9d2c6865 2830 return $self->maybe_parens_unop($name, $op->first, $cx);
d989cdac 2831 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
9d2c6865 2832 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
6e90668e 2833 } else { # I don't think baseop filetests ever survive ck_ftst, but...
9d2c6865 2834 return $name;
6e90668e 2835 }
6e90668e
SM
2836}
2837
d989cdac
SM
2838sub pp_lstat { ftst(@_, "lstat") }
2839sub pp_stat { ftst(@_, "stat") }
2840sub pp_ftrread { ftst(@_, "-R") }
6e90668e 2841sub pp_ftrwrite { ftst(@_, "-W") }
d989cdac
SM
2842sub pp_ftrexec { ftst(@_, "-X") }
2843sub pp_fteread { ftst(@_, "-r") }
e31885a0 2844sub pp_ftewrite { ftst(@_, "-w") }
d989cdac
SM
2845sub pp_fteexec { ftst(@_, "-x") }
2846sub pp_ftis { ftst(@_, "-e") }
6e90668e
SM
2847sub pp_fteowned { ftst(@_, "-O") }
2848sub pp_ftrowned { ftst(@_, "-o") }
d989cdac
SM
2849sub pp_ftzero { ftst(@_, "-z") }
2850sub pp_ftsize { ftst(@_, "-s") }
2851sub pp_ftmtime { ftst(@_, "-M") }
2852sub pp_ftatime { ftst(@_, "-A") }
2853sub pp_ftctime { ftst(@_, "-C") }
2854sub pp_ftsock { ftst(@_, "-S") }
2855sub pp_ftchr { ftst(@_, "-c") }
2856sub pp_ftblk { ftst(@_, "-b") }
2857sub pp_ftfile { ftst(@_, "-f") }
2858sub pp_ftdir { ftst(@_, "-d") }
2859sub pp_ftpipe { ftst(@_, "-p") }
2860sub pp_ftlink { ftst(@_, "-l") }
2861sub pp_ftsuid { ftst(@_, "-u") }
2862sub pp_ftsgid { ftst(@_, "-g") }
2863sub pp_ftsvtx { ftst(@_, "-k") }
2864sub pp_fttty { ftst(@_, "-t") }
2865sub pp_fttext { ftst(@_, "-T") }
6e90668e
SM
2866sub pp_ftbinary { ftst(@_, "-B") }
2867
a798dbf2 2868sub SWAP_CHILDREN () { 1 }
6e90668e 2869sub ASSIGN () { 2 } # has OP= variant
7013e6ae 2870sub LIST_CONTEXT () { 4 } # Assignment is in list context
6e90668e 2871
9d2c6865
SM
2872my(%left, %right);
2873
2874sub assoc_class {
2875 my $op = shift;
3f872cb9
GS
2876 my $name = $op->name;
2877 if ($name eq "concat" and $op->first->name eq "concat") {
e38ccfd9 2878 # avoid spurious '=' -- see comment in pp_concat
3f872cb9 2879 return "concat";
9d2c6865 2880 }
3f872cb9
GS
2881 if ($name eq "null" and class($op) eq "UNOP"
2882 and $op->first->name =~ /^(and|x?or)$/
9d2c6865
SM
2883 and null $op->first->sibling)
2884 {
2885 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2886 # with a null that's used as the common end point of the two
2887 # flows of control. For precedence purposes, ignore it.
2888 # (COND_EXPRs have these too, but we don't bother with
2889 # their associativity).
2890 return assoc_class($op->first);
2891 }
2892 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2893}
2894
e38ccfd9 2895# Left associative operators, like '+', for which
9d2c6865
SM
2896# $a + $b + $c is equivalent to ($a + $b) + $c
2897
2898BEGIN {
3f872cb9
GS
2899 %left = ('multiply' => 19, 'i_multiply' => 19,
2900 'divide' => 19, 'i_divide' => 19,
2901 'modulo' => 19, 'i_modulo' => 19,
2902 'repeat' => 19,
2903 'add' => 18, 'i_add' => 18,
2904 'subtract' => 18, 'i_subtract' => 18,
2905 'concat' => 18,
2906 'left_shift' => 17, 'right_shift' => 17,
27f31adf 2907 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13,
3f872cb9 2908 'bit_or' => 12, 'bit_xor' => 12,
27f31adf
FC
2909 'sbit_or' => 12, 'sbit_xor' => 12,
2910 'nbit_or' => 12, 'nbit_xor' => 12,
3f872cb9
GS
2911 'and' => 3,
2912 'or' => 2, 'xor' => 2,
9d2c6865
SM
2913 );
2914}
2915
2916sub deparse_binop_left {
2917 my $self = shift;
2918 my($op, $left, $prec) = @_;
58231d39 2919 if ($left{assoc_class($op)} && $left{assoc_class($left)}
9d2c6865
SM
2920 and $left{assoc_class($op)} == $left{assoc_class($left)})
2921 {
2922 return $self->deparse($left, $prec - .00001);
2923 } else {
2924 return $self->deparse($left, $prec);
2925 }
2926}
2927
e38ccfd9 2928# Right associative operators, like '=', for which
9d2c6865
SM
2929# $a = $b = $c is equivalent to $a = ($b = $c)
2930
2931BEGIN {
3f872cb9
GS
2932 %right = ('pow' => 22,
2933 'sassign=' => 7, 'aassign=' => 7,
2934 'multiply=' => 7, 'i_multiply=' => 7,
2935 'divide=' => 7, 'i_divide=' => 7,
2936 'modulo=' => 7, 'i_modulo=' => 7,
9187b6e4 2937 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
3f872cb9
GS
2938 'add=' => 7, 'i_add=' => 7,
2939 'subtract=' => 7, 'i_subtract=' => 7,
2940 'concat=' => 7,
2941 'left_shift=' => 7, 'right_shift=' => 7,
27f31adf
FC
2942 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7,
2943 'nbit_or=' => 7, 'nbit_xor=' => 7,
2944 'sbit_or=' => 7, 'sbit_xor=' => 7,
3f872cb9
GS
2945 'andassign' => 7,
2946 'orassign' => 7,
9d2c6865
SM
2947 );
2948}
2949
2950sub deparse_binop_right {
2951 my $self = shift;
2952 my($op, $right, $prec) = @_;
58231d39 2953 if ($right{assoc_class($op)} && $right{assoc_class($right)}
9d2c6865
SM
2954 and $right{assoc_class($op)} == $right{assoc_class($right)})
2955 {
2956 return $self->deparse($right, $prec - .00001);
2957 } else {
2958 return $self->deparse($right, $prec);
2959 }
2960}
2961
a798dbf2 2962sub binop {
6e90668e 2963 my $self = shift;
9d2c6865 2964 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
a798dbf2
MB
2965 my $left = $op->first;
2966 my $right = $op->last;
9d2c6865
SM
2967 my $eq = "";
2968 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2969 $eq = "=";
2970 $prec = 7;
2971 }
a798dbf2
MB
2972 if ($flags & SWAP_CHILDREN) {
2973 ($left, $right) = ($right, $left);
2974 }
6a861075 2975 my $leftop = $left;
9d2c6865 2976 $left = $self->deparse_binop_left($op, $left, $prec);
90c0eb26 2977 $left = "($left)" if $flags & LIST_CONTEXT
c4874d8a 2978 and $left !~ /^(my|our|local|state|)\s*[\@%\(]/
6a861075
FC
2979 || do {
2980 # Parenthesize if the left argument is a
2981 # lone repeat op.
2982 my $left = $leftop->first->sibling;
2983 $left->name eq 'repeat'
2984 && null($left->sibling);
2985 };
9d2c6865
SM
2986 $right = $self->deparse_binop_right($op, $right, $prec);
2987 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2988}
2989
3ed82cfc
GS
2990sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2991sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2992sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2993sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2994sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2995sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2996sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2997sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2998sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2999sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
3000sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
3001
3002sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
3003sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
3004sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
3005sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
3006sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
27f31adf
FC
3007*pp_nbit_and = *pp_bit_and;
3008*pp_nbit_or = *pp_bit_or;
3009*pp_nbit_xor = *pp_bit_xor;
3010sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) }
3011sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) }
3012sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) }
9d2c6865
SM
3013
3014sub pp_eq { binop(@_, "==", 14) }
3015sub pp_ne { binop(@_, "!=", 14) }
3016sub pp_lt { binop(@_, "<", 15) }
3017sub pp_gt { binop(@_, ">", 15) }
3018sub pp_ge { binop(@_, ">=", 15) }
3019sub pp_le { binop(@_, "<=", 15) }
3020sub pp_ncmp { binop(@_, "<=>", 14) }
3021sub pp_i_eq { binop(@_, "==", 14) }
3022sub pp_i_ne { binop(@_, "!=", 14) }
3023sub pp_i_lt { binop(@_, "<", 15) }
3024sub pp_i_gt { binop(@_, ">", 15) }
3025sub pp_i_ge { binop(@_, ">=", 15) }
3026sub pp_i_le { binop(@_, "<=", 15) }
d1455c67 3027sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) }
9d2c6865
SM
3028
3029sub pp_seq { binop(@_, "eq", 14) }
3030sub pp_sne { binop(@_, "ne", 14) }
3031sub pp_slt { binop(@_, "lt", 15) }
3032sub pp_sgt { binop(@_, "gt", 15) }
3033sub pp_sge { binop(@_, "ge", 15) }
3034sub pp_sle { binop(@_, "le", 15) }
d1455c67 3035sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) }
9d2c6865
SM
3036
3037sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
7013e6ae 3038sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
6e90668e 3039
7896dde7
Z
3040sub pp_smartmatch {
3041 my ($self, $op, $cx) = @_;
3042 if (($op->flags & OPf_SPECIAL) && $self->{expand} < 2) {
3043 return $self->deparse($op->last, $cx);
3044 }
3045 else {
3046 binop(@_, "~~", 14);
3047 }
3048}
3049
e38ccfd9 3050# '.' is special because concats-of-concats are optimized to save copying
6e90668e 3051# by making all but the first concat stacked. The effect is as if the
e38ccfd9 3052# programmer had written '($a . $b) .= $c', except legal.
3ed82cfc
GS
3053sub pp_concat { maybe_targmy(@_, \&real_concat) }
3054sub real_concat {
6e90668e 3055 my $self = shift;
9d2c6865 3056 my($op, $cx) = @_;
6e90668e
SM
3057 my $left = $op->first;
3058 my $right = $op->last;
3059 my $eq = "";
9d2c6865 3060 my $prec = 18;
4b75096e
DM
3061 if (($op->flags & OPf_STACKED) and !($op->private & OPpCONCAT_NESTED)) {
3062 # '.=' rather than optimised '.'
6e90668e 3063 $eq = "=";
9d2c6865 3064 $prec = 7;
6e90668e 3065 }
9d2c6865
SM
3066 $left = $self->deparse_binop_left($op, $left, $prec);
3067 $right = $self->deparse_binop_right($op, $right, $prec);
3068 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
6e90668e
SM
3069}
3070
6402d4ee
FC
3071sub pp_repeat { maybe_targmy(@_, \&repeat) }
3072
e38ccfd9 3073# 'x' is weird when the left arg is a list
6402d4ee 3074sub repeat {
6e90668e 3075 my $self = shift;
9d2c6865 3076 my($op, $cx) = @_;
6e90668e
SM
3077 my $left = $op->first;
3078 my $right = $op->last;
9d2c6865
SM
3079 my $eq = "";
3080 my $prec = 19;
3081 if ($op->flags & OPf_STACKED) {
3082 $eq = "=";
3083 $prec = 7;
3084 }
6e90668e 3085 if (null($right)) { # list repeat; count is inside left-side ex-list
5e462669 3086 # in 5.21.5 and earlier
6e90668e
SM
3087 my $kid = $left->first->sibling; # skip pushmark
3088 my @exprs;
3089 for (; !null($kid->sibling); $kid = $kid->sibling) {
9d2c6865 3090 push @exprs, $self->deparse($kid, 6);
6e90668e
SM
3091 }
3092 $right = $kid;
3093 $left = "(" . join(", ", @exprs). ")";
3094 } else {
5e462669
FC
3095 my $dolist = $op->private & OPpREPEAT_DOLIST;
3096 $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
3097 if ($dolist) {
3098 $left = "($left)";
3099 }
6e90668e 3100 }
9d2c6865
SM
3101 $right = $self->deparse_binop_right($op, $right, $prec);
3102 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
6e90668e
SM
3103}
3104
3105sub range {
3106 my $self = shift;
9d2c6865 3107 my ($op, $cx, $type) = @_;
6e90668e
SM
3108 my $left = $op->first;
3109 my $right = $left->sibling;
9d2c6865
SM
3110 $left = $self->deparse($left, 9);
3111 $right = $self->deparse($right, 9);
3112 return $self->maybe_parens("$left $type $right", $cx, 9);
6e90668e
SM
3113}
3114
3115sub pp_flop {
3116 my $self = shift;
9d2c6865 3117 my($op, $cx) = @_;
6e90668e
SM
3118 my $flip = $op->first;
3119 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
9d2c6865 3120 return $self->range($flip->first, $cx, $type);
6e90668e
SM
3121}
3122
3123# one-line while/until is handled in pp_leave
3124
3125sub logop {
3126 my $self = shift;
9d2c6865 3127 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
6e90668e
SM
3128 my $left = $op->first;
3129 my $right = $op->first->sibling;
7741ceed 3130 $blockname &&= $self->keyword($blockname);
d989cdac 3131 if ($cx < 1 and is_scope($right) and $blockname
58cccf98
SM
3132 and $self->{'expand'} < 7)
3133 { # if ($a) {$b}
9d2c6865
SM
3134 $left = $self->deparse($left, 1);
3135 $right = $self->deparse($right, 0);
3136 return "$blockname ($left) {\n\t$right\n\b}\cK";
d989cdac 3137 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
58cccf98 3138 and $self->{'expand'} < 7) { # $b if $a
9d2c6865
SM
3139 $right = $self->deparse($right, 1);
3140 $left = $self->deparse($left, 1);
3141 return "$right $blockname $left";
3142 } elsif ($cx > $lowprec and $highop) { # $a && $b
3143 $left = $self->deparse_binop_left($op, $left, $highprec);
3144 $right = $self->deparse_binop_right($op, $right, $highprec);
3145 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
3146 } else { # $a and $b
3147 $left = $self->deparse_binop_left($op, $left, $lowprec);
3148 $right = $self->deparse_binop_right($op, $right, $lowprec);
d989cdac 3149 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
9d2c6865
SM
3150 }
3151}
3152
3153sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
f4a44678 3154sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
5b99f273 3155sub pp_dor { logop(@_, "//", 10) }
3ed82cfc
GS
3156
3157# xor is syntactically a logop, but it's really a binop (contrary to
3158# old versions of opcode.pl). Syntax is what matters here.
9d2c6865 3159sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
6e90668e
SM
3160
3161sub logassignop {
3162 my $self = shift;
9d2c6865 3163 my ($op, $cx, $opname) = @_;
6e90668e
SM
3164 my $left = $op->first;
3165 my $right = $op->first->sibling->first; # skip sassign
9d2c6865
SM
3166 $left = $self->deparse($left, 7);
3167 $right = $self->deparse($right, 7);
3168 return $self->maybe_parens("$left $opname $right", $cx, 7);
a798dbf2
MB
3169}
3170
6e90668e 3171sub pp_andassign { logassignop(@_, "&&=") }
c963b151
BD
3172sub pp_orassign { logassignop(@_, "||=") }
3173sub pp_dorassign { logassignop(@_, "//=") }
6e90668e 3174
b89b7257
FC
3175sub rv2gv_or_string {
3176 my($self,$op) = @_;
3177 if ($op->name eq "gv") { # could be open("open") or open("###")
be6cf5cf 3178 my($name,$quoted) =
1db94eeb 3179 $self->stash_variable_name("", $self->gv_or_padgv($op));
be6cf5cf 3180 $quoted ? $name : "*$name";
b89b7257
FC
3181 }
3182 else {
3183 $self->deparse($op, 6);
3184 }
3185}
3186
6e90668e
SM
3187sub listop {
3188 my $self = shift;
9c56d9ea 3189 my($op, $cx, $name, $kid, $nollafr) = @_;
9d2c6865
SM
3190 my(@exprs);
3191 my $parens = ($cx >= 5) || $self->{'parens'};
24fcb59f 3192 $kid ||= $op->first->sibling;
4d8ac5c7
FC
3193 # If there are no arguments, add final parentheses (or parenthesize the
3194 # whole thing if the llafr does not apply) to account for cases like
3195 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
3196 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
3197 if (null $kid) {
3198 return $nollafr
3199 ? $self->maybe_parens($self->keyword($name), $cx, 7)
3200 : $self->keyword($name) . '()' x (7 < $cx);
3201 }
e31885a0 3202 my $first;
4a1ac32e 3203 my $fullname = $self->keyword($name);
b72c97e8 3204 my $proto = prototype("CORE::$name");
bc1cc2c3
DM
3205 if (
3206 ( (defined $proto && $proto =~ /^;?\*/)
3207 || $name eq 'select' # select(F) doesn't have a proto
3208 )
3209 && $kid->name eq "rv2gv"
3210 && !($kid->private & OPpLVAL_INTRO)
3211 ) {
b89b7257 3212 $first = $self->rv2gv_or_string($kid->first);
e31885a0
RH
3213 }
3214 else {
3215 $first = $self->deparse($kid, 6);
3216 }
e99ebc55 3217 if ($name eq "chmod" && $first =~ /^\d+$/) {
a0035eb8 3218 $first = sprintf("%#o", $first);
e99ebc55 3219 }
9c56d9ea
FC
3220 $first = "+$first"
3221 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
9d2c6865
SM
3222 push @exprs, $first;
3223 $kid = $kid->sibling;
564cd6cb
FC
3224 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
3225 && !($kid->private & OPpLVAL_INTRO)) {
b89b7257 3226 push @exprs, $first = $self->rv2gv_or_string($kid->first);
b72c97e8
RGS
3227 $kid = $kid->sibling;
3228 }
9d2c6865
SM
3229 for (; !null($kid); $kid = $kid->sibling) {
3230 push @exprs, $self->deparse($kid, 6);
3231 }
689e417f 3232 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
4a1ac32e
FC
3233 return "$exprs[0] = $fullname"
3234 . ($parens ? "($exprs[0])" : " $exprs[0]");
689e417f 3235 }
327088eb 3236
9c56d9ea
FC
3237 if ($parens && $nollafr) {
3238 return "($fullname " . join(", ", @exprs) . ")";
3239 } elsif ($parens) {
4a1ac32e 3240 return "$fullname(" . join(", ", @exprs) . ")";
9d2c6865 3241 } else {
4a1ac32e 3242 return "$fullname " . join(", ", @exprs);
6e90668e 3243 }
6e90668e 3244}
a798dbf2 3245
6e90668e 3246sub pp_bless { listop(@_, "bless") }
3ed82cfc 3247sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
24fcb59f
FC
3248sub pp_substr {
3249 my ($self,$op,$cx) = @_;
3250 if ($op->private & OPpSUBSTR_REPL_FIRST) {
3251 return
3252 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
3253 . " = "
3254 . $self->deparse($op->first->sibling, 7);
3255 }
3256 maybe_local(@_, listop(@_, "substr"))
3257}
7e8d786b
DM
3258
3259sub pp_index {
3260 # Also handles pp_rindex.
3261 #
3262 # The body of this function includes an unrolled maybe_targmy(),
3263 # since the two parts of that sub's actions need to have have the
3264 # '== -1' bit in between
3265
3266 my($self, $op, $cx) = @_;
3267
3268 my $lex = ($op->private & OPpTARGET_MY);
3269 my $bool = ($op->private & OPpTRUEBOOL);
3270
3271 my $val = $self->listop($op, ($bool ? 14 : $lex ? 7 : $cx), $op->name);
3272
3273 # (index() == -1) has op_eq and op_const optimised away
3274 if ($bool) {
3275 $val .= ($op->private & OPpINDEX_BOOLNEG) ? " == -1" : " != -1";
3276 $val = "($val)" if ($op->flags & OPf_PARENS);
3277 }
3278 if ($lex) {
3279 my $var = $self->padname($op->targ);
3280 $val = $self->maybe_parens("$var = $val", $cx, 7);
3281 }
3282 $val;
3283}
3284
3285sub pp_rindex { pp_index(@_); }
6402d4ee 3286sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
3ed82cfc 3287sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
6e90668e 3288sub pp_formline { listop(@_, "formline") } # see also deparse_format
3ed82cfc 3289sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
6e90668e
SM
3290sub pp_unpack { listop(@_, "unpack") }
3291sub pp_pack { listop(@_, "pack") }
3ed82cfc 3292sub pp_join { maybe_targmy(@_, \&listop, "join") }
6e90668e 3293sub pp_splice { listop(@_, "splice") }
3ed82cfc
GS
3294sub pp_push { maybe_targmy(@_, \&listop, "push") }
3295sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
6e90668e
SM
3296sub pp_reverse { listop(@_, "reverse") }
3297sub pp_warn { listop(@_, "warn") }
3298sub pp_die { listop(@_, "die") }
9c56d9ea 3299sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
6e90668e
SM
3300sub pp_open { listop(@_, "open") }
3301sub pp_pipe_op { listop(@_, "pipe") }
3302sub pp_tie { listop(@_, "tie") }
82bafd27 3303sub pp_binmode { listop(@_, "binmode") }
6e90668e
SM
3304sub pp_dbmopen { listop(@_, "dbmopen") }
3305sub pp_sselect { listop(@_, "select") }
3306sub pp_select { listop(@_, "select") }
3307sub pp_read { listop(@_, "read") }
3308sub pp_sysopen { listop(@_, "sysopen") }
3309sub pp_sysseek { listop(@_, "sysseek") }
3310sub pp_sysread { listop(@_, "sysread") }
3311sub pp_syswrite { listop(@_, "syswrite") }
3312sub pp_send { listop(@_, "send") }
3313sub pp_recv { listop(@_, "recv") }
3314sub pp_seek { listop(@_, "seek") }
6e90668e
SM
3315sub pp_fcntl { listop(@_, "fcntl") }
3316sub pp_ioctl { listop(@_, "ioctl") }
3ed82cfc 3317sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
6e90668e 3318sub pp_socket { listop(@_, "socket") }
5deb1341 3319sub pp_sockpair { listop(@_, "socketpair") }
6e90668e
SM
3320sub pp_bind { listop(@_, "bind") }
3321sub pp_connect { listop(@_, "connect") }
3322sub pp_listen { listop(@_, "listen") }
3323sub pp_accept { listop(@_, "accept") }
3324sub pp_shutdown { listop(@_, "shutdown") }
3325sub pp_gsockopt { listop(@_, "getsockopt") }
3326sub pp_ssockopt { listop(@_, "setsockopt") }
3ed82cfc
GS
3327sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
3328sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
3329sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
3330sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
3331sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
3332sub pp_link { maybe_targmy(@_, \&listop, "link") }
3333sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
3334sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
6e90668e
SM
3335sub pp_open_dir { listop(@_, "opendir") }
3336sub pp_seekdir { listop(@_, "seekdir") }
3ed82cfc 3337sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
9d52f6f3
FC
3338sub pp_system { maybe_targmy(@_, \&indirop, "system") }
3339sub pp_exec { maybe_targmy(@_, \&indirop, "exec") }
3ed82cfc
GS
3340sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
3341sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
3342sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
3343sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
6e90668e
SM
3344sub pp_shmget { listop(@_, "shmget") }
3345sub pp_shmctl { listop(@_, "shmctl") }
3346sub pp_shmread { listop(@_, "shmread") }
3347sub pp_shmwrite { listop(@_, "shmwrite") }
3348sub pp_msgget { listop(@_, "msgget") }
3349sub pp_msgctl { listop(@_, "msgctl") }
3350sub pp_msgsnd { listop(@_, "msgsnd") }
3351sub pp_msgrcv { listop(@_, "msgrcv") }
3352sub pp_semget { listop(@_, "semget") }
3353sub pp_semctl { listop(@_, "semctl") }
3354sub pp_semop { listop(@_, "semop") }
3355sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
3356sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
3357sub pp_gpbynumber { listop(@_, "getprotobynumber") }
3358sub pp_gsbyname { listop(@_, "getservbyname") }
3359sub pp_gsbyport { listop(@_, "getservbyport") }
3360sub pp_syscall { listop(@_, "syscall") }
3361
3362sub pp_glob {
3363 my $self = shift;
9d2c6865 3364 my($op, $cx) = @_;
93860275 3365 my $kid = $op->first->sibling; # skip pushmark
a32fbbd8
FC
3366 my $keyword =
3367 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
18371617
LM
3368 my $text = $self->deparse($kid);
3369 return $cx >= 5 || $self->{'parens'}
3370 ? "$keyword($text)"
3371 : "$keyword $text";
6e90668e
SM
3372}
3373
f5aa8f4e
SM
3374# Truncate is special because OPf_SPECIAL makes a bareword first arg
3375# be a filehandle. This could probably be better fixed in the core
3376# by moving the GV lookup into ck_truc.
3377
3378sub pp_truncate {
3379 my $self = shift;
3380 my($op, $cx) = @_;
3381 my(@exprs);
3382 my $parens = ($cx >= 5) || $self->{'parens'};
3383 my $kid = $op->first->sibling;
acba1d67 3384 my $fh;
f5aa8f4e
SM
3385 if ($op->flags & OPf_SPECIAL) {
3386 # $kid is an OP_CONST
18228111 3387 $fh = $self->const_sv($kid)->PV;
f5aa8f4e
SM
3388 } else {
3389 $fh = $self->deparse($kid, 6);
3390 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
3391 }
3392 my $len = $self->deparse($kid->sibling, 6);
4a1ac32e 3393 my $name = $self->keyword('truncate');
f5aa8f4e 3394 if ($parens) {
4a1ac32e 3395 return "$name($fh, $len)";
f5aa8f4e 3396 } else {
4a1ac32e 3397 return "$name $fh, $len";
f5aa8f4e 3398 }
f5aa8f4e
SM
3399}
3400
6e90668e
SM
3401sub indirop {
3402 my $self = shift;
9d2c6865 3403 my($op, $cx, $name) = @_;
6e90668e 3404 my($expr, @exprs);
521795fe 3405 my $firstkid = my $kid = $op->first->sibling;
6e90668e
SM
3406 my $indir = "";
3407 if ($op->flags & OPf_STACKED) {
3408 $indir = $kid;
3409 $indir = $indir->first; # skip rv2gv
3410 if (is_scope($indir)) {
9d2c6865 3411 $indir = "{" . $self->deparse($indir, 0) . "}";
d989cdac 3412 $indir = "{;}" if $indir eq "{}";
c73811ab
RH
3413 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
3414 $indir = $self->const_sv($indir)->PV;
6e90668e 3415 } else {
9d2c6865 3416 $indir = $self->deparse($indir, 24);
6e90668e
SM
3417 }
3418 $indir = $indir . " ";
3419 $kid = $kid->sibling;
3420 }
7e80da18 3421 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3ac6e0f9 3422 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
7e80da18
RH
3423 : '{$a <=> $b} ';
3424 }
3ac6e0f9 3425 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
7e80da18
RH
3426 $indir = '{$b cmp $a} ';
3427 }
6e90668e 3428 for (; !null($kid); $kid = $kid->sibling) {
521795fe 3429 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
6e90668e
SM
3430 push @exprs, $expr;
3431 }
4a1ac32e 3432 my $name2;
3ac6e0f9 3433 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
4a1ac32e 3434 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3ac6e0f9 3435 }
4a1ac32e 3436 else { $name2 = $self->keyword($name) }
2b6e98cb 3437 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3ac6e0f9 3438 return "$exprs[0] = $name2 $indir $exprs[0]";
2b6e98cb
DM
3439 }
3440
d989cdac 3441 my $args = $indir . join(", ", @exprs);
521795fe 3442 if ($indir ne "" && $name eq "sort") {
d989cdac
SM
3443 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
3444 # give bareword warnings in that case. Therefore if context
3445 # requires, we'll put parens around the outside "(sort f 1, 2,
3446 # 3)". Unfortunately, we'll currently think the parens are
3c4b39be 3447 # necessary more often that they really are, because we don't
d989cdac
SM
3448 # distinguish which side of an assignment we're on.
3449 if ($cx >= 5) {
3ac6e0f9 3450 return "($name2 $args)";
d989cdac 3451 } else {
3ac6e0f9 3452 return "$name2 $args";
d989cdac 3453 }
521795fe
FC
3454 } elsif (
3455 !$indir && $name eq "sort"
ca331985 3456 && !null($op->first->sibling)
521795fe
FC
3457 && $op->first->sibling->name eq 'entersub'
3458 ) {
3459 # We cannot say sort foo(bar), as foo will be interpreted as a
3460 # comparison routine. We have to say sort(...) in that case.
3461 return "$name2($args)";
d989cdac 3462 } else {
9d52f6f3
FC
3463 return length $args
3464 ? $self->maybe_parens_func($name2, $args, $cx, 5)
3465 : $name2 . '()' x (7 < $cx);
d989cdac
SM
3466 }
3467
6e90668e
SM
3468}
3469
3470sub pp_prtf { indirop(@_, "printf") }
3471sub pp_print { indirop(@_, "print") }
9b08e3d3 3472sub pp_say { indirop(@_, "say") }
6e90668e
SM
3473sub pp_sort { indirop(@_, "sort") }