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