This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Direct optree implementations of builtin:: functions
[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
852c1a84 55$VERSION = '1.60';
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
S
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
f34acfec 282sub DEBUG { 0 }
8914f6f0 283use if DEBUG, 'Data::Dumper';
f34acfec 284
a7fd8ef6
DM
285sub _pessimise_walk {
286 my ($self, $startop) = @_;
287
288 return unless $$startop;
289 my ($op, $prevop);
290 for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) {
291 my $ppname = $op->name;
292
293 # pessimisations start here
294
295 if ($ppname eq "padrange") {
296 # remove PADRANGE:
d5524600 297 # the original optimisation either (1) changed this:
a7fd8ef6 298 # pushmark -> (various pad and list and null ops) -> the_rest
d5524600
DM
299 # or (2), for the = @_ case, changed this:
300 # pushmark -> gv[_] -> rv2av -> (pad stuff) -> the_rest
a7fd8ef6
DM
301 # into this:
302 # padrange ----------------------------------------> the_rest
303 # so we just need to convert the padrange back into a
d5524600
DM
304 # pushmark, and in case (1), set its op_next to op_sibling,
305 # which is the head of the original chain of optimised-away
306 # pad ops, or for (2), set it to sibling->first, which is
307 # the original gv[_].
a7fd8ef6
DM
308
309 $B::overlay->{$$op} = {
76e14ed3 310 type => OP_PUSHMARK,
a7fd8ef6
DM
311 name => 'pushmark',
312 private => ($op->private & OPpLVAL_INTRO),
a7fd8ef6
DM
313 };
314 }
315
316 # pessimisations end here
317
b814db67
DM
318 if (class($op) eq 'PMOP') {
319 if (ref($op->pmreplroot)
320 && ${$op->pmreplroot}
321 && $op->pmreplroot->isa( 'B::OP' ))
322 {
323 $self-> _pessimise_walk($op->pmreplroot);
324 }
325
326 # pessimise any /(?{...})/ code blocks
327 my ($re, $cv);
328 my $code_list = $op->code_list;
329 if ($$code_list) {
330 $self->_pessimise_walk($code_list);
331 }
332 elsif (${$re = $op->pmregexp} && ${$cv = $re->qr_anoncv}) {
333 $code_list = $cv->ROOT # leavesub
334 ->first # qr
335 ->code_list; # list
336 $self->_pessimise_walk($code_list);
337 }
338 }
a7fd8ef6
DM
339
340 if ($op->flags & OPf_KIDS) {
341 $self-> _pessimise_walk($op->first);
342 }
343
344 }
345}
346
347
348# _pessimise_walk_exe(): recursively walk the op_next chain of a sub,
349# possibly undoing optimisations along the way.
350
351sub _pessimise_walk_exe {
352 my ($self, $startop, $visited) = @_;
353
f7f169a8
DM
354 no warnings 'recursion';
355
a7fd8ef6
DM
356 return unless $$startop;
357 return if $visited->{$$startop};
358 my ($op, $prevop);
359 for ($op = $startop; $$op; $prevop = $op, $op = $op->next) {
360 last if $visited->{$$op};
361 $visited->{$$op} = 1;
362 my $ppname = $op->name;
363 if ($ppname =~
364 /^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/
365 # entertry is also a logop, but its op_other invariably points
366 # into the same chain as the main execution path, so we skip it
367 ) {
368 $self->_pessimise_walk_exe($op->other, $visited);
369 }
370 elsif ($ppname eq "subst") {
371 $self->_pessimise_walk_exe($op->pmreplstart, $visited);
372 }
373 elsif ($ppname =~ /^(enter(loop|iter))$/) {
374 # redoop and nextop will already be covered by the main block
375 # of the loop
376 $self->_pessimise_walk_exe($op->lastop, $visited);
377 }
378
379 # pessimisations start here
380 }
381}
382
e63cc694 383# Go through an optree and "remove" some optimisations by using an
a7fd8ef6
DM
384# overlay to selectively modify or un-null some ops. Deparsing in the
385# absence of those optimisations is then easier.
386#
387# Note that older optimisations are not removed, as Deparse was already
388# written to recognise them before the pessimise/overlay system was added.
389
390sub pessimise {
391 my ($self, $root, $start) = @_;
392
097e9660 393 no warnings 'recursion';
a7fd8ef6
DM
394 # walk tree in root-to-branch order
395 $self->_pessimise_walk($root);
396
397 my %visited;
398 # walk tree in execution order
399 $self->_pessimise_walk_exe($start, \%visited);
400}
401
402
6e90668e
SM
403sub null {
404 my $op = shift;
405 return class($op) eq "NULL";
406}
407
097e9660
DM
408
409# Add a CV to the list of subs that still need deparsing.
410
6e90668e
SM
411sub todo {
412 my $self = shift;
c310a5ab 413 my($cv, $is_form, $name) = @_;
62ae7cfb
FC
414 my $cvfile = $cv->FILE//'';
415 return unless ($cvfile eq $0 || exists $self->{files}{$cvfile});
6e90668e 416 my $seq;
d989cdac
SM
417 if ($cv->OUTSIDE_SEQ) {
418 $seq = $cv->OUTSIDE_SEQ;
419 } elsif (!null($cv->START) and is_state($cv->START)) {
6e90668e
SM
420 $seq = $cv->START->cop_seq;
421 } else {
422 $seq = 0;
423 }
a9cafc78
FC
424 my $stash = $cv->STASH;
425 if (class($stash) eq 'HV') {
426 $self->{packs}{$stash->NAME}++;
427 }
c310a5ab 428 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form, $name];
6e90668e
SM
429}
430
097e9660
DM
431
432# Pop the next sub from the todo list and deparse it
433
6e90668e
SM
434sub next_todo {
435 my $self = shift;
436 my $ent = shift @{$self->{'subs_todo'}};
c80ee1fe
DM
437 my ($seq, $cv, $is_form, $name) = @$ent;
438
e276dec7
DM
439 # any 'use strict; package foo' that should come before the sub
440 # declaration to sync with the first COP of the sub
441 my $pragmata = '';
442 if ($cv and !null($cv->START) and is_state($cv->START)) {
443 $pragmata = $self->pragmata($cv->START);
444 }
445
c80ee1fe 446 if (ref $name) { # lexical sub
bc304ab2 447 # emit the sub.
d4f1bfe7 448 my @text;
c80ee1fe 449 my $flags = $name->FLAGS;
d4f1bfe7 450 push @text,
c80ee1fe 451 !$cv || $seq <= $name->COP_SEQ_RANGE_LOW
d4f1bfe7
FC
452 ? $self->keyword($flags & SVpad_OUR
453 ? "our"
454 : $flags & SVpad_STATE
455 ? "state"
456 : "my") . " "
457 : "";
458 # XXX We would do $self->keyword("sub"), but ‘my CORE::sub’
459 # doesn’t work and ‘my sub’ ignores a &sub in scope. I.e.,
460 # we have a core bug here.
c80ee1fe 461 push @text, "sub " . substr $name->PVX, 1;
d4f1bfe7
FC
462 if ($cv) {
463 # my sub foo { }
464 push @text, " " . $self->deparse_sub($cv);
465 $text[-1] =~ s/ ;$/;/;
466 }
467 else {
468 # my sub foo;
469 push @text, ";\n";
470 }
e276dec7 471 return $pragmata . join "", @text;
d4f1bfe7 472 }
bc304ab2 473
34a48b4b 474 my $gv = $cv->GV;
c80ee1fe
DM
475 $name //= $self->gv_name($gv);
476 if ($is_form) {
e276dec7 477 return $pragmata . $self->keyword("format") . " $name =\n"
c80ee1fe 478 . $self->deparse_format($cv). "\n";
6e90668e 479 } else {
d98ae4a6 480 my $use_dec;
34a48b4b 481 if ($name eq "BEGIN") {
d98ae4a6 482 $use_dec = $self->begin_is_use($cv);
d989cdac 483 if (defined ($use_dec) and $self->{'expand'} < 5) {
e276dec7 484 return $pragmata if 0 == length($use_dec);
80719733
DM
485
486 # XXX bit of a hack: Test::More's use_ok() method
487 # builds a fake use statement which deparses as, e.g.
488 # use Net::Ping (@{$args[0];});
489 # As well as being superfluous (the use_ok() is deparsed
490 # too) and ugly, it fails under use strict and otherwise
491 # makes use of a lexical var that's not in scope.
492 # So strip it out.
493 return $pragmata
7a4a81c9
DM
494 if $use_dec =~
495 m/
496 \A
497 use \s \S+ \s \(\@\{
498 (
499 \s*\#line\ \d+\ \".*"\s*
500 )?
501 \$args\[0\];\}\);
502 \n
503 \Z
504 /x;
80719733 505
7741ceed 506 $use_dec =~ s/^(use|no)\b/$self->keyword($1)/e;
0e7fe0f0 507 }
34a48b4b 508 }
a0035eb8
RH
509 my $l = '';
510 if ($self->{'linenums'}) {
511 my $line = $gv->LINE;
512 my $file = $gv->FILE;
513 $l = "\n\f#line $line \"$file\"\n";
514 }
127212b2 515 my $p = '';
d49c3562 516 my $stash;
127212b2 517 if (class($cv->STASH) ne "SPECIAL") {
d49c3562 518 $stash = $cv->STASH->NAME;
127212b2 519 if ($stash ne $self->{'curstash'}) {
7741ceed 520 $p = $self->keyword("package") . " $stash;\n";
127212b2
DM
521 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
522 $self->{'curstash'} = $stash;
523 }
127212b2 524 }
d98ae4a6 525 if ($use_dec) {
e276dec7 526 return "$pragmata$p$l$use_dec";
d98ae4a6 527 }
d49c3562
FC
528 if ( $name !~ /::/ and $self->lex_in_scope("&$name")
529 || $self->lex_in_scope("&$name", 1) )
530 {
531 $name = "$self->{'curstash'}::$name";
532 } elsif (defined $stash) {
533 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
534 }
e276dec7 535 my $ret = "$pragmata${p}${l}" . $self->keyword("sub") . " $name "
7741ceed 536 . $self->deparse_sub($cv);
f518ad75
FC
537 $self->{'subs_declared'}{$name} = 1;
538 return $ret;
34a48b4b
RH
539 }
540}
541
c80ee1fe 542
34a48b4b
RH
543# Return a "use" declaration for this BEGIN block, if appropriate
544sub begin_is_use {
545 my ($self, $cv) = @_;
546 my $root = $cv->ROOT;
80dc0729 547 local @$self{qw'curcv curcvlex'} = ($cv);
a7fd8ef6
DM
548 local $B::overlay = {};
549 $self->pessimise($root, $cv->START);
34a48b4b
RH
550#require B::Debug;
551#B::walkoptree($cv->ROOT, "debug");
552 my $lineseq = $root->first;
553 return if $lineseq->name ne "lineseq";
554
555 my $req_op = $lineseq->first->sibling;
556 return if $req_op->name ne "require";
557
0a30b526
DM
558 # maybe it's C<require expr> rather than C<require 'foo'>
559 return if ($req_op->first->name ne 'const');
560
34a48b4b
RH
561 my $module;
562 if ($req_op->first->private & OPpCONST_BARE) {
563 # Actually it should always be a bareword
564 $module = $self->const_sv($req_op->first)->PV;
565 $module =~ s[/][::]g;
566 $module =~ s/.pm$//;
567 }
568 else {
d989cdac 569 $module = $self->const($self->const_sv($req_op->first), 6);
34a48b4b
RH
570 }
571
572 my $version;
573 my $version_op = $req_op->sibling;
574 return if class($version_op) eq "NULL";
575 if ($version_op->name eq "lineseq") {
576 # We have a version parameter; skip nextstate & pushmark
577 my $constop = $version_op->first->next->next;
578
579 return unless $self->const_sv($constop)->PV eq $module;
580 $constop = $constop->sibling;
a58644de 581 $version = $self->const_sv($constop);
d989cdac
SM
582 if (class($version) eq "IV") {
583 $version = $version->int_value;
584 } elsif (class($version) eq "NV") {
585 $version = $version->NV;
586 } elsif (class($version) ne "PVMG") {
587 # Includes PVIV and PVNV
a58644de
RGS
588 $version = $version->PV;
589 } else {
590 # version specified as a v-string
591 $version = 'v'.join '.', map ord, split //, $version->PV;
592 }
34a48b4b
RH
593 $constop = $constop->sibling;
594 return if $constop->name ne "method_named";
b46e009d 595 return if $self->meth_sv($constop)->PV ne "VERSION";
34a48b4b
RH
596 }
597
598 $lineseq = $version_op->sibling;
599 return if $lineseq->name ne "lineseq";
600 my $entersub = $lineseq->first->sibling;
601 if ($entersub->name eq "stub") {
602 return "use $module $version ();\n" if defined $version;
603 return "use $module ();\n";
604 }
605 return if $entersub->name ne "entersub";
606
607 # See if there are import arguments
608 my $args = '';
609
6ec152c3
RH
610 my $svop = $entersub->first->sibling; # Skip over pushmark
611 return unless $self->const_sv($svop)->PV eq $module;
34a48b4b
RH
612
613 # Pull out the arguments
7d6c333c 614 for ($svop=$svop->sibling; index($svop->name, "method_") != 0;
6ec152c3 615 $svop = $svop->sibling) {
34a48b4b 616 $args .= ", " if length($args);
6ec152c3 617 $args .= $self->deparse($svop, 6);
34a48b4b
RH
618 }
619
620 my $use = 'use';
6ec152c3 621 my $method_named = $svop;
34a48b4b 622 return if $method_named->name ne "method_named";
b46e009d 623 my $method_name = $self->meth_sv($method_named)->PV;
34a48b4b
RH
624
625 if ($method_name eq "unimport") {
626 $use = 'no';
627 }
628
629 # Certain pragmas are dealt with using hint bits,
630 # so we ignore them here
631 if ($module eq 'strict' || $module eq 'integer'
0ced6c29
RGS
632 || $module eq 'bytes' || $module eq 'warnings'
633 || $module eq 'feature') {
34a48b4b
RH
634 return "";
635 }
636
637 if (defined $version && length $args) {
638 return "$use $module $version ($args);\n";
639 } elsif (defined $version) {
640 return "$use $module $version;\n";
641 } elsif (length $args) {
642 return "$use $module ($args);\n";
643 } else {
644 return "$use $module;\n";
6e90668e
SM
645 }
646}
647
6e90668e 648sub stash_subs {
894e98ac 649 my ($self, $pack, $seen) = @_;
34a48b4b
RH
650 my (@ret, $stash);
651 if (!defined $pack) {
652 $pack = '';
653 $stash = \%::;
f5aa8f4e 654 }
34a48b4b
RH
655 else {
656 $pack =~ s/(::)?$/::/;
657 no strict 'refs';
d1dc589d 658 $stash = \%{"main::$pack"};
34a48b4b 659 }
894e98ac
FC
660 return
661 if ($seen ||= {})->{
662 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
663 }++;
7d9a919c
DM
664 my $stashobj = svref_2object($stash);
665 my %stash = $stashobj->ARRAY;
34a48b4b 666 while (my ($key, $val) = each %stash) {
de001ba0
FC
667 my $flags = $val->FLAGS;
668 if ($flags & SVf_ROK) {
03b8f76d
FC
669 # A reference. Dump this if it is a reference to a CV. If it
670 # is a constant acting as a proxy for a full subroutine, then
671 # we may or may not have to dump it. If some form of perl-
672 # space visible code must have created it, be it a use
67359f08 673 # statement, or some direct symbol-table manipulation code that
03b8f76d
FC
674 # we will deparse, then we don’t want to dump it. If it is the
675 # result of a declaration like sub f () { 42 } then we *do*
676 # want to dump it. The only way to distinguish these seems
677 # to be the SVs_PADTMP flag on the constant, which is admit-
678 # tedly a hack.
679 my $class = class(my $referent = $val->RV);
680 if ($class eq "CV") {
681 $self->todo($referent, 0);
682 } elsif (
5e965771 683 $class !~ /^(AV|HV|CV|FM|IO|SPECIAL)\z/
03b8f76d
FC
684 # A more robust way to write that would be this, but B does
685 # not provide the SVt_ constants:
686 # ($referent->FLAGS & B::SVTYPEMASK) < B::SVt_PVAV
687 and $referent->FLAGS & SVs_PADTMP
688 ) {
689 push @{$self->{'protos_todo'}}, [$pack . $key, $val];
67359f08 690 }
de001ba0 691 } elsif ($flags & (SVf_POK|SVf_IOK)) {
a0035eb8
RH
692 # Just a prototype. As an ugly but fairly effective way
693 # to find out if it belongs here is to see if the AUTOLOAD
694 # (if any) for the stash was defined in one of our files.
695 my $A = $stash{"AUTOLOAD"};
696 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
697 && class($A->CV) eq "CV") {
698 my $AF = $A->FILE;
699 next unless $AF eq $0 || exists $self->{'files'}{$AF};
700 }
de001ba0
FC
701 push @{$self->{'protos_todo'}},
702 [$pack . $key, $flags & SVf_POK ? $val->PV: undef];
703 } elsif (class($val) eq "GV") {
34a48b4b 704 if (class(my $cv = $val->CV) ne "SPECIAL") {
f5aa8f4e 705 next if $self->{'subs_done'}{$$val}++;
7d9a919c
DM
706
707 # Ignore imposters (aliases etc)
708 my $name = $cv->NAME_HEK;
709 if(defined $name) {
710 # avoid using $cv->GV here because if the $val GV is
711 # an alias, CvGV() could upgrade the real stash entry
712 # from an RV to a GV
713 next unless $name eq $key;
714 next unless $$stashobj == ${$cv->STASH};
715 }
716 else {
717 next if $$val != ${$cv->GV};
718 }
719
8510e997 720 $self->todo($cv, 0);
f5aa8f4e 721 }
e31885a0 722 if (class(my $cv = $val->FORM) ne "SPECIAL") {
f5aa8f4e 723 next if $self->{'forms_done'}{$$val}++;
e31885a0
RH
724 next if $$val != ${$cv->GV}; # Ignore imposters
725 $self->todo($cv, 1);
f5aa8f4e 726 }
34a48b4b 727 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
74cd21ba 728 $self->stash_subs($pack . $key, $seen);
34a48b4b 729 }
6e90668e
SM
730 }
731 }
732}
a798dbf2 733
f5aa8f4e
SM
734sub print_protos {
735 my $self = shift;
736 my $ar;
737 my @ret;
738 foreach $ar (@{$self->{'protos_todo'}}) {
a9cafc78
FC
739 if (ref $ar->[1]) {
740 # Only print a constant if it occurs in the same package as a
741 # dumped sub. This is not perfect, but a heuristic that will
742 # hopefully work most of the time. Ideally we would use
743 # CvFILE, but a constant stub has no CvFILE.
744 my $pack = ($ar->[0] =~ /(.*)::/)[0];
745 next if $pack and !$self->{packs}{$pack}
746 }
03b8f76d
FC
747 my $body = defined $ar->[1]
748 ? ref $ar->[1]
749 ? " () {\n " . $self->const($ar->[1]->RV,0) . ";\n}"
750 : " (". $ar->[1] . ");"
751 : ";";
752 push @ret, "sub " . $ar->[0] . "$body\n";
f5aa8f4e
SM
753 }
754 delete $self->{'protos_todo'};
755 return @ret;
756}
757
9d2c6865
SM
758sub style_opts {
759 my $self = shift;
760 my $opts = shift;
761 my $opt;
762 while (length($opt = substr($opts, 0, 1))) {
763 if ($opt eq "C") {
764 $self->{'cuddle'} = " ";
f4a44678
SM
765 $opts = substr($opts, 1);
766 } elsif ($opt eq "i") {
767 $opts =~ s/^i(\d+)//;
768 $self->{'indent_size'} = $1;
769 } elsif ($opt eq "T") {
770 $self->{'use_tabs'} = 1;
771 $opts = substr($opts, 1);
772 } elsif ($opt eq "v") {
773 $opts =~ s/^v([^.]*)(.|$)//;
774 $self->{'ex_const'} = $1;
9d2c6865 775 }
9d2c6865
SM
776 }
777}
778
f4a44678
SM
779sub new {
780 my $class = shift;
781 my $self = bless {}, $class;
f4a44678 782 $self->{'cuddle'} = "\n";
d989cdac
SM
783 $self->{'curcop'} = undef;
784 $self->{'curstash'} = "main";
785 $self->{'ex_const'} = "'???'";
793e2a70 786 $self->{'expand'} = 0;
d989cdac 787 $self->{'files'} = {};
a9cafc78 788 $self->{'packs'} = {};
d989cdac 789 $self->{'indent_size'} = 4;
793e2a70
RH
790 $self->{'linenums'} = 0;
791 $self->{'parens'} = 0;
d989cdac
SM
792 $self->{'subs_todo'} = [];
793 $self->{'unquote'} = 0;
794 $self->{'use_dumper'} = 0;
795 $self->{'use_tabs'} = 0;
08c6f5ec 796
e31885a0 797 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
a0405c92 798 $self->{'ambient_hints'} = 0;
0ced6c29 799 $self->{'ambient_hinthash'} = undef;
08c6f5ec
RH
800 $self->init();
801
f4a44678 802 while (my $arg = shift @_) {
d989cdac
SM
803 if ($arg eq "-d") {
804 $self->{'use_dumper'} = 1;
805 require Data::Dumper;
806 } elsif ($arg =~ /^-f(.*)/) {
34a48b4b 807 $self->{'files'}{$1} = 1;
d989cdac
SM
808 } elsif ($arg eq "-l") {
809 $self->{'linenums'} = 1;
f4a44678
SM
810 } elsif ($arg eq "-p") {
811 $self->{'parens'} = 1;
acaaef34
RGS
812 } elsif ($arg eq "-P") {
813 $self->{'noproto'} = 1;
f4a44678
SM
814 } elsif ($arg eq "-q") {
815 $self->{'unquote'} = 1;
816 } elsif (substr($arg, 0, 2) eq "-s") {
817 $self->style_opts(substr $arg, 2);
58cccf98
SM
818 } elsif ($arg =~ /^-x(\d)$/) {
819 $self->{'expand'} = $1;
f4a44678
SM
820 }
821 }
822 return $self;
823}
824
810aef70
RH
825{
826 # Mask out the bits that L<warnings::register> uses
827 my $WARN_MASK;
828 BEGIN {
829 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
830 }
831 sub WARN_MASK () {
832 return $WARN_MASK;
833 }
34a48b4b
RH
834}
835
08c6f5ec
RH
836# Initialise the contextual information, either from
837# defaults provided with the ambient_pragmas method,
838# or from perl's own defaults otherwise.
839sub init {
840 my $self = shift;
841
e31885a0
RH
842 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
843 ? $self->{'ambient_warnings'} & WARN_MASK
844 : undef;
d5ec2987 845 $self->{'hints'} = $self->{'ambient_hints'};
0ced6c29 846 $self->{'hinthash'} = $self->{'ambient_hinthash'};
217aba5d
RH
847
848 # also a convenient place to clear out subs_declared
849 delete $self->{'subs_declared'};
08c6f5ec
RH
850}
851
a798dbf2 852sub compile {
6e90668e 853 my(@args) = @_;
d989cdac 854 return sub {
f4a44678 855 my $self = B::Deparse->new(@args);
d2bc402e
RGS
856 # First deparse command-line args
857 if (defined $^I) { # deparse -i
51a5edaf 858 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
d2bc402e
RGS
859 }
860 if ($^W) { # deparse -w
861 print qq(BEGIN { \$^W = $^W; }\n);
862 }
863 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
51a5edaf
RGS
864 my $fs = perlstring($/) || 'undef';
865 my $bs = perlstring($O::savebackslash) || 'undef';
d2bc402e
RGS
866 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
867 }
34a48b4b 868 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
676456c2
AG
869 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
870 ? B::unitcheck_av->ARRAY
871 : ();
ece599bd 872 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
34a48b4b
RH
873 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
874 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
c310a5ab
FC
875 my @names = qw(BEGIN UNITCHECK CHECK INIT END);
876 my @blocks = \(@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs);
877 while (@names) {
878 my ($name, $blocks) = (shift @names, shift @blocks);
879 for my $block (@$blocks) {
880 $self->todo($block, 0, $name);
881 }
34a48b4b
RH
882 }
883 $self->stash_subs();
d989cdac
SM
884 local($SIG{"__DIE__"}) =
885 sub {
886 if ($self->{'curcop'}) {
887 my $cop = $self->{'curcop'};
888 my($line, $file) = ($cop->line, $cop->file);
889 print STDERR "While deparsing $file near line $line,\n";
890 }
891 };
6e90668e 892 $self->{'curcv'} = main_cv;
8510e997 893 $self->{'curcvlex'} = undef;
f5aa8f4e 894 print $self->print_protos;
6e90668e 895 @{$self->{'subs_todo'}} =
f4a44678 896 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
a7fd8ef6
DM
897 my $root = main_root;
898 local $B::overlay = {};
899 unless (null $root) {
d4f1bfe7 900 $self->pad_subs($self->{'curcv'});
6436970c
FC
901 # Check for a stub-followed-by-ex-cop, resulting from a program
902 # consisting solely of sub declarations. For backward-compati-
903 # bility (and sane output) we don’t want to emit the stub.
904 # leave
905 # enter
906 # stub
907 # ex-nextstate (or ex-dbstate)
908 my $kid;
909 if ( $root->name eq 'leave'
910 and ($kid = $root->first)->name eq 'enter'
911 and !null($kid = $kid->sibling) and $kid->name eq 'stub'
912 and !null($kid = $kid->sibling) and $kid->name eq 'null'
913 and class($kid) eq 'COP' and null $kid->sibling )
914 {
915 # ignore
916 } else {
917 $self->pessimise($root, main_start);
918 print $self->indent($self->deparse_root($root)), "\n";
919 }
a7fd8ef6 920 }
6e90668e
SM
921 my @text;
922 while (scalar(@{$self->{'subs_todo'}})) {
923 push @text, $self->next_todo;
924 }
6f611a1a 925 print $self->indent(join("", @text)), "\n" if @text;
e31885a0
RH
926
927 # Print __DATA__ section, if necessary
928 no strict 'refs';
96c57f7e
RGS
929 my $laststash = defined $self->{'curcop'}
930 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
931 if (defined *{$laststash."::DATA"}{IO}) {
7741ceed 932 print $self->keyword("package") . " $laststash;\n"
127212b2 933 unless $laststash eq $self->{'curstash'};
7741ceed 934 print $self->keyword("__DATA__") . "\n";
96c57f7e 935 print readline(*{$laststash."::DATA"});
e31885a0 936 }
a798dbf2 937 }
a798dbf2
MB
938}
939
f4a44678
SM
940sub coderef2text {
941 my $self = shift;
942 my $sub = shift;
0853f172 943 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
08c6f5ec
RH
944
945 $self->init();
de4fa237 946 local $self->{in_coderef2text} = 1;
f4a44678
SM
947 return $self->indent($self->deparse_sub(svref_2object($sub)));
948}
949
415d4c68 950my %strict_bits = do {
d1718a7c 951 local $^H;
415d4c68
FC
952 map +($_ => strict::bits($_)), qw/refs subs vars/
953};
954
08c6f5ec
RH
955sub ambient_pragmas {
956 my $self = shift;
8a38acca 957 my ($hint_bits, $warning_bits, $hinthash) = (0);
08c6f5ec
RH
958
959 while (@_ > 1) {
960 my $name = shift();
961 my $val = shift();
962
963 if ($name eq 'strict') {
964 require strict;
965
966 if ($val eq 'none') {
415d4c68 967 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
08c6f5ec
RH
968 next();
969 }
970
971 my @names;
972 if ($val eq "all") {
973 @names = qw/refs subs vars/;
974 }
975 elsif (ref $val) {
976 @names = @$val;
977 }
978 else {
a0405c92 979 @names = split' ', $val;
08c6f5ec 980 }
415d4c68 981 $hint_bits |= $strict_bits{$_} for @names;
08c6f5ec
RH
982 }
983
a0405c92
RH
984 elsif ($name eq 'integer'
985 || $name eq 'bytes'
986 || $name eq 'utf8') {
987 require "$name.pm";
08c6f5ec 988 if ($val) {
a0405c92
RH
989 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
990 }
991 else {
992 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
993 }
994 }
995
996 elsif ($name eq 're') {
997 require re;
998 if ($val eq 'none') {
2570cdf1 999 $hint_bits &= ~re::bits(qw/taint eval/);
a0405c92
RH
1000 next();
1001 }
1002
1003 my @names;
1004 if ($val eq 'all') {
2570cdf1 1005 @names = qw/taint eval/;
a0405c92
RH
1006 }
1007 elsif (ref $val) {
1008 @names = @$val;
08c6f5ec
RH
1009 }
1010 else {
a0405c92 1011 @names = split' ',$val;
08c6f5ec 1012 }
a0405c92 1013 $hint_bits |= re::bits(@names);
08c6f5ec
RH
1014 }
1015
1016 elsif ($name eq 'warnings') {
08c6f5ec 1017 if ($val eq 'none') {
810aef70 1018 $warning_bits = $warnings::NONE;
08c6f5ec
RH
1019 next();
1020 }
1021
1022 my @names;
1023 if (ref $val) {
1024 @names = @$val;
1025 }
1026 else {
1027 @names = split/\s+/, $val;
1028 }
1029
810aef70 1030 $warning_bits = $warnings::NONE if !defined ($warning_bits);
08c6f5ec
RH
1031 $warning_bits |= warnings::bits(@names);
1032 }
1033
1034 elsif ($name eq 'warning_bits') {
1035 $warning_bits = $val;
1036 }
1037
1038 elsif ($name eq 'hint_bits') {
1039 $hint_bits = $val;
1040 }
1041
0ced6c29
RGS
1042 elsif ($name eq '%^H') {
1043 $hinthash = $val;
1044 }
1045
08c6f5ec
RH
1046 else {
1047 croak "Unknown pragma type: $name";
1048 }
1049 }
1050 if (@_) {
1051 croak "The ambient_pragmas method expects an even number of args";
1052 }
1053
08c6f5ec 1054 $self->{'ambient_warnings'} = $warning_bits;
a0405c92 1055 $self->{'ambient_hints'} = $hint_bits;
0ced6c29 1056 $self->{'ambient_hinthash'} = $hinthash;
08c6f5ec
RH
1057}
1058
d989cdac 1059# This method is the inner loop, so try to keep it simple
6e90668e
SM
1060sub deparse {
1061 my $self = shift;
d989cdac 1062 my($op, $cx) = @_;
34a48b4b
RH
1063
1064 Carp::confess("Null op in deparse") if !defined($op)
1065 || class($op) eq "NULL";
3f872cb9 1066 my $meth = "pp_" . $op->name;
9d2c6865 1067 return $self->$meth($op, $cx);
a798dbf2
MB
1068}
1069
6e90668e 1070sub indent {
f4a44678 1071 my $self = shift;
6e90668e 1072 my $txt = shift;
5e617af5
FC
1073 # \cK also swallows a preceding line break when followed by a
1074 # semicolon.
1075 $txt =~ s/\n\cK;//g;
6e90668e
SM
1076 my @lines = split(/\n/, $txt);
1077 my $leader = "";
f4a44678 1078 my $level = 0;
6e90668e
SM
1079 my $line;
1080 for $line (@lines) {
f4a44678
SM
1081 my $cmd = substr($line, 0, 1);
1082 if ($cmd eq "\t" or $cmd eq "\b") {
1083 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
1084 if ($self->{'use_tabs'}) {
1085 $leader = "\t" x ($level / 8) . " " x ($level % 8);
1086 } else {
1087 $leader = " " x $level;
1088 }
6e90668e
SM
1089 $line = substr($line, 1);
1090 }
f2734596
HE
1091 if (index($line, "\f") > 0) {
1092 $line =~ s/\f/\n/;
1093 }
f5aa8f4e
SM
1094 if (substr($line, 0, 1) eq "\f") {
1095 $line = substr($line, 1); # no indent
1096 } else {
1097 $line = $leader . $line;
1098 }
9d2c6865 1099 $line =~ s/\cK;?//g;
6e90668e
SM
1100 }
1101 return join("\n", @lines);
1102}
1103
d4f1bfe7
FC
1104sub pad_subs {
1105 my ($self, $cv) = @_;
1106 my $padlist = $cv->PADLIST;
1107 my @names = $padlist->ARRAYelt(0)->ARRAY;
1108 my @values = $padlist->ARRAYelt(1)->ARRAY;
1109 my @todo;
2c5ddcd3 1110 PADENTRY:
d4f1bfe7
FC
1111 for my $ix (0.. $#names) { for $_ ($names[$ix]) {
1112 next if class($_) eq "SPECIAL";
1113 my $name = $_->PVX;
679f2252 1114 if (defined $name && $name =~ /^&./) {
d4f1bfe7
FC
1115 my $low = $_->COP_SEQ_RANGE_LOW;
1116 my $flags = $_->FLAGS;
494a4b9c 1117 my $outer = $flags & PADNAMEt_OUTER;
d4f1bfe7 1118 if ($flags & SVpad_OUR) {
bb9bfaa4 1119 push @todo, [$low, undef, 0, $_]
d4f1bfe7 1120 # [seq, no cv, not format, padname]
494a4b9c 1121 unless $outer;
d4f1bfe7
FC
1122 next;
1123 }
1124 my $protocv = $flags & SVpad_STATE
1125 ? $values[$ix]
97d78f94 1126 : $_->PROTOCV;
2c5ddcd3
FC
1127 if (class ($protocv) ne 'CV') {
1128 my $flags = $flags;
1129 my $cv = $cv;
1130 my $name = $_;
1131 while ($flags & PADNAMEt_OUTER && class ($protocv) ne 'CV')
1132 {
1133 $cv = $cv->OUTSIDE;
1134 next PADENTRY if class($cv) eq 'SPECIAL'; # XXX freed?
1135 my $padlist = $cv->PADLIST;
1136 my $ix = $name->PARENT_PAD_INDEX;
1137 $name = $padlist->NAMES->ARRAYelt($ix);
1138 $flags = $name->FLAGS;
1139 $protocv = $flags & SVpad_STATE
1140 ? $padlist->ARRAYelt(1)->ARRAYelt($ix)
1141 : $name->PROTOCV;
1142 }
1143 }
494a4b9c
FC
1144 my $defined_in_this_sub = ${$protocv->OUTSIDE} == $$cv || do {
1145 my $other = $protocv->PADLIST;
1146 $$other && $other->outid == $padlist->id;
1147 };
bb9bfaa4 1148 if ($flags & PADNAMEt_OUTER) {
494a4b9c 1149 next unless $defined_in_this_sub;
bb9bfaa4
FC
1150 push @todo, [$protocv->OUTSIDE_SEQ, $protocv, 0, $_];
1151 next;
1152 }
d4f1bfe7
FC
1153 my $outseq = $protocv->OUTSIDE_SEQ;
1154 if ($outseq <= $low) {
1155 # defined before its name is visible, so it’s gotta be
1156 # declared and defined at once: my sub foo { ... }
1157 push @todo, [$low, $protocv, 0, $_];
1158 }
1159 else {
1160 # declared and defined separately: my sub f; sub f { ... }
494a4b9c
FC
1161 push @todo, [$low, undef, 0, $_];
1162 push @todo, [$outseq, $protocv, 0, $_]
1163 if $defined_in_this_sub;
d4f1bfe7
FC
1164 }
1165 }
1166 }}
1167 @{$self->{'subs_todo'}} =
1168 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}}, @todo
1169}
1170
60f638af
DM
1171
1172# deparse_argops(): deparse, if possible, a sequence of argcheck + argelem
1173# ops into a subroutine signature. If successful, return the first op
1174# following the signature ops plus the signature string; else return the
1175# empty list.
1176#
1177# Normally a bunch of argelem ops will have been generated by the
1178# signature parsing, but it's possible that ops have been added manually
894f226e 1179# or altered. In this case we return "()" and fall back to general
60f638af
DM
1180# deparsing of the individual sigelems as 'my $x = $_[N]' etc.
1181#
4df85778
DM
1182# We're only called if the top is an ex-argcheck, which is a placeholder
1183# indicating a signature subtree.
1184#
1185# Return a signature string, or an empty list if no deparseable as a
1186# signature
60f638af
DM
1187
1188sub deparse_argops {
4df85778 1189 my ($self, $topop, $cv) = @_;
60f638af
DM
1190
1191 my @sig;
4df85778
DM
1192
1193
1194 $topop = $topop->first;
1195 return unless $$topop and $topop->name eq 'lineseq';
1196
1197
1198 # last op should be nextstate
1199 my $last = $topop->last;
1200 return unless $$last
1201 and ( _op_is_or_was($last, OP_NEXTSTATE)
1202 or _op_is_or_was($last, OP_DBSTATE));
1203
1204 # first OP_NEXTSTATE
1205
1206 my $o = $topop->first;
1207 return unless $$o;
1208 return if $o->label;
60f638af
DM
1209
1210 # OP_ARGCHECK
1211
1212 $o = $o->sibling;
4df85778
DM
1213 return unless $$o and $o->name eq 'argcheck';
1214
60f638af
DM
1215 my ($params, $opt_params, $slurpy) = $o->aux_list($cv);
1216 my $mandatory = $params - $opt_params;
1217 my $seen_slurpy = 0;
1218 my $last_ix = -1;
1219
4df85778
DM
1220 # keep looking for valid nextstate + argelem pairs, terminated
1221 # by a final nextstate
60f638af
DM
1222
1223 while (1) {
60f638af 1224 $o = $o->sibling;
4df85778
DM
1225 return unless $$o;
1226
1227 # skip trailing nextstate
1228 last if $$o == $$last;
1229
1230 # OP_NEXTSTATE
1231 return unless $o->name =~ /^(next|db)state$/;
1232 return if $o->label;
60f638af
DM
1233
1234 # OP_ARGELEM
4df85778
DM
1235 $o = $o->sibling;
1236 last unless $$o;
60f638af 1237
4df85778
DM
1238 if ($o->name eq 'argelem') {
1239 my $ix = $o->string($cv);
60f638af
DM
1240 while (++$last_ix < $ix) {
1241 push @sig, $last_ix < $mandatory ? '$' : '$=';
1242 }
4df85778 1243 my $var = $self->padname($o->targ);
60f638af
DM
1244 if ($var =~ /^[@%]/) {
1245 return if $seen_slurpy;
1246 $seen_slurpy = 1;
1247 return if $ix != $params or !$slurpy
1248 or substr($var,0,1) ne $slurpy;
1249 }
1250 else {
1251 return if $ix >= $params;
1252 }
4df85778
DM
1253 if ($o->flags & OPf_KIDS) {
1254 my $kid = $o->first;
60f638af
DM
1255 return unless $$kid and $kid->name eq 'argdefelem';
1256 my $def = $self->deparse($kid->first, 7);
1257 $def = "($def)" if $kid->first->flags & OPf_PARENS;
1258 $var .= " = $def";
1259 }
1260 push @sig, $var;
1261 }
4df85778
DM
1262 elsif ($o->name eq 'null'
1263 and ($o->flags & OPf_KIDS)
1264 and $o->first->name eq 'argdefelem')
60f638af
DM
1265 {
1266 # special case - a void context default expression: $ = expr
1267
4df85778 1268 my $defop = $o->first;
60f638af
DM
1269 my $ix = $defop->targ;
1270 while (++$last_ix < $ix) {
1271 push @sig, $last_ix < $mandatory ? '$' : '$=';
1272 }
1273 return if $last_ix >= $params
1274 or $last_ix < $mandatory;
1275 my $def = $self->deparse($defop->first, 7);
1276 $def = "($def)" if $defop->first->flags & OPf_PARENS;
1277 push @sig, '$ = ' . $def;
1278 }
1279 else {
4df85778 1280 return;
60f638af
DM
1281 }
1282
60f638af
DM
1283 }
1284
1285 while (++$last_ix < $params) {
1286 push @sig, $last_ix < $mandatory ? '$' : '$=';
1287 }
1288 push @sig, $slurpy if $slurpy and !$seen_slurpy;
1289
4df85778 1290 return (join(', ', @sig));
60f638af
DM
1291}
1292
4df85778 1293
097e9660
DM
1294# Deparse a sub. Returns everything except the 'sub foo',
1295# e.g. ($$) : method { ...; }
894f226e 1296# or : prototype($$) lvalue ($a, $b) { ...; };
60f638af 1297
6e90668e
SM
1298sub deparse_sub {
1299 my $self = shift;
1300 my $cv = shift;
9fe5784b 1301 my @attrs;
894f226e
DM
1302 my $proto;
1303 my $sig;
9fe5784b 1304
ce4e655d 1305Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
34a48b4b
RH
1306Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1307 local $self->{'curcop'} = $self->{'curcop'};
9fe5784b
DM
1308
1309 my $has_sig = $self->{hinthash}{feature_signatures};
6e90668e 1310 if ($cv->FLAGS & SVf_POK) {
894f226e 1311 my $myproto = $cv->PV;
9fe5784b 1312 if ($has_sig) {
894f226e 1313 push @attrs, "prototype($myproto)";
9fe5784b
DM
1314 }
1315 else {
894f226e 1316 $proto = $myproto;
9fe5784b 1317 }
6e90668e 1318 }
b77472f9 1319 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE|CVf_ANONCONST)) {
9fe5784b 1320 push @attrs, "lvalue" if $cv->CvFLAGS & CVf_LVALUE;
9fe5784b
DM
1321 push @attrs, "method" if $cv->CvFLAGS & CVf_METHOD;
1322 push @attrs, "const" if $cv->CvFLAGS & CVf_ANONCONST;
6aaf4108
SC
1323 }
1324
6e90668e 1325 local($self->{'curcv'}) = $cv;
8510e997 1326 local($self->{'curcvlex'});
0ced6c29
RGS
1327 local(@$self{qw'curstash warnings hints hinthash'})
1328 = @$self{qw'curstash warnings hints hinthash'};
ce4e655d 1329 my $body;
a7fd8ef6
DM
1330 my $root = $cv->ROOT;
1331 local $B::overlay = {};
1332 if (not null $root) {
d4f1bfe7 1333 $self->pad_subs($cv);
a7fd8ef6
DM
1334 $self->pessimise($root, $cv->START);
1335 my $lineseq = $root->first;
4df85778
DM
1336
1337 # stub sub may have single op rather than list of ops
1338 my $is_list = ($lineseq->name eq "lineseq");
1339 my $firstop = $is_list ? $lineseq->first : $lineseq;
1340
1341 # Try to deparse first subtree as a signature if possible.
1342 # Top of signature subtree has an ex-argcheck as a placeholder
1343 if ( $has_sig
1344 and $$firstop
1345 and $firstop->name eq 'null'
1346 and $firstop->targ == OP_ARGCHECK
1347 ) {
1348 my ($mysig) = $self->deparse_argops($firstop, $cv);
1349 if (defined $mysig) {
1350 $sig = $mysig;
1351 $firstop = $is_list ? $firstop->sibling : undef;
60f638af 1352 }
4df85778 1353 }
60f638af 1354
4df85778 1355 if ($is_list && $firstop) {
60f638af
DM
1356 my @ops;
1357 for (my $o = $firstop; $$o; $o=$o->sibling) {
ce4e655d
RH
1358 push @ops, $o;
1359 }
93a8ff62 1360 $body = $self->lineseq(undef, 0, @ops).";";
60f638af 1361 if (!$has_sig and $ops[-1]->name =~ /^(next|db)state$/) {
4fa06845
DM
1362 # this handles void context in
1363 # use feature signatures; sub ($=1) {}
1364 $body .= "\n()";
1365 }
ce4e655d
RH
1366 my $scope_en = $self->find_scope_en($lineseq);
1367 if (defined $scope_en) {
1368 my $subs = join"", $self->seq_subs($scope_en);
1369 $body .= ";\n$subs" if length($subs);
1370 }
1371 }
4df85778 1372 elsif ($firstop) {
a7fd8ef6 1373 $body = $self->deparse($root->first, 0);
ce4e655d 1374 }
4df85778
DM
1375 else {
1376 $body = ';'; # stub sub
1377 }
bce0f226
DM
1378
1379 my $l = '';
1380 if ($self->{'linenums'}) {
1381 # a glob's gp_line is set from the line containing a
1382 # sub's closing '}' if the CV is the first use of the GV.
1383 # So make sure the linenum is set correctly for '}'
1384 my $gv = $cv->GV;
1385 my $line = $gv->LINE;
1386 my $file = $gv->FILE;
1387 $l = "\f#line $line \"$file\"\n";
1388 }
1389 $body = "{\n\t$body\n$l\b}";
de3f1649 1390 }
ce4e655d
RH
1391 else {
1392 my $sv = $cv->const_sv;
1393 if ($$sv) {
1394 # uh-oh. inlinable sub... format it differently
9fe5784b 1395 $body = "{ " . $self->const($sv, 0) . " }\n";
ce4e655d 1396 } else { # XSUB? (or just a declaration)
9fe5784b 1397 $body = ';'
ce4e655d 1398 }
6e90668e 1399 }
894f226e
DM
1400 $proto = defined $proto ? "($proto) " : "";
1401 $sig = defined $sig ? "($sig) " : "";
9fe5784b
DM
1402 my $attrs = '';
1403 $attrs = ': ' . join('', map "$_ ", @attrs) if @attrs;
894f226e 1404 return "$proto$attrs$sig$body\n";
6e90668e
SM
1405}
1406
1407sub deparse_format {
1408 my $self = shift;
1409 my $form = shift;
1410 my @text;
1411 local($self->{'curcv'}) = $form;
8510e997 1412 local($self->{'curcvlex'});
67fc2416 1413 local($self->{'in_format'}) = 1;
0ced6c29
RGS
1414 local(@$self{qw'curstash warnings hints hinthash'})
1415 = @$self{qw'curstash warnings hints hinthash'};
6e90668e 1416 my $op = $form->ROOT;
a7fd8ef6
DM
1417 local $B::overlay = {};
1418 $self->pessimise($op, $form->START);
6e90668e 1419 my $kid;
fb725297
RGS
1420 return "\f." if $op->first->name eq 'stub'
1421 || $op->first->name eq 'nextstate';
6e90668e
SM
1422 $op = $op->first->first; # skip leavewrite, lineseq
1423 while (not null $op) {
1424 $op = $op->sibling; # skip nextstate
1425 my @exprs;
1426 $kid = $op->first->sibling; # skip pushmark
a5b0cd91 1427 push @text, "\f".$self->const_sv($kid)->PV;
6e90668e
SM
1428 $kid = $kid->sibling;
1429 for (; not null $kid; $kid = $kid->sibling) {
93a8ff62 1430 push @exprs, $self->deparse($kid, -1);
31c26a0a 1431 $exprs[-1] =~ s/;\z//;
6e90668e 1432 }
a5b0cd91 1433 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
6e90668e
SM
1434 $op = $op->sibling;
1435 }
a5b0cd91 1436 return join("", @text) . "\f.";
6e90668e
SM
1437}
1438
6e90668e 1439sub is_scope {
a798dbf2 1440 my $op = shift;
3f872cb9
GS
1441 return $op->name eq "leave" || $op->name eq "scope"
1442 || $op->name eq "lineseq"
d989cdac 1443 || ($op->name eq "null" && class($op) eq "UNOP"
3f872cb9 1444 && (is_scope($op->first) || $op->first->name eq "enter"));
6e90668e
SM
1445}
1446
1447sub is_state {
3f872cb9
GS
1448 my $name = $_[0]->name;
1449 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
6e90668e
SM
1450}
1451
e38ccfd9 1452sub is_miniwhile { # check for one-line loop ('foo() while $y--')
6e90668e 1453 my $op = shift;
d989cdac 1454 return (!null($op) and null($op->sibling)
3f872cb9
GS
1455 and $op->name eq "null" and class($op) eq "UNOP"
1456 and (($op->first->name =~ /^(and|or)$/
1457 and $op->first->first->sibling->name eq "lineseq")
1458 or ($op->first->name eq "lineseq"
6e90668e 1459 and not null $op->first->first->sibling
3f872cb9 1460 and $op->first->first->sibling->name eq "unstack")
6e90668e
SM
1461 ));
1462}
1463
d989cdac
SM
1464# Check if the op and its sibling are the initialization and the rest of a
1465# for (..;..;..) { ... } loop
1466sub is_for_loop {
1467 my $op = shift;
1468 # This OP might be almost anything, though it won't be a
1469 # nextstate. (It's the initialization, so in the canonical case it
eae48c89
Z
1470 # will be an sassign.) The sibling is (old style) a lineseq whose
1471 # first child is a nextstate and whose second is a leaveloop, or
1472 # (new style) an unstack whose sibling is a leaveloop.
d989cdac 1473 my $lseq = $op->sibling;
eae48c89
Z
1474 return 0 unless !is_state($op) and !null($lseq);
1475 if ($lseq->name eq "lineseq") {
d989cdac
SM
1476 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1477 && (my $sib = $lseq->first->sibling)) {
1478 return (!null($sib) && $sib->name eq "leaveloop");
1479 }
eae48c89
Z
1480 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1481 my $sib = $lseq->sibling;
1482 return $sib && !null($sib) && $sib->name eq "leaveloop";
d989cdac
SM
1483 }
1484 return 0;
1485}
1486
6e90668e
SM
1487sub is_scalar {
1488 my $op = shift;
3f872cb9
GS
1489 return ($op->name eq "rv2sv" or
1490 $op->name eq "padsv" or
1491 $op->name eq "gv" or # only in array/hash constructs
bd0865ec 1492 $op->flags & OPf_KIDS && !null($op->first)
3f872cb9 1493 && $op->first->name eq "gvsv");
6e90668e
SM
1494}
1495
9d2c6865
SM
1496sub maybe_parens {
1497 my $self = shift;
1498 my($text, $cx, $prec) = @_;
1499 if ($prec < $cx # unary ops nest just fine
1500 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1501 or $self->{'parens'})
1502 {
1503 $text = "($text)";
1504 # In a unop, let parent reuse our parens; see maybe_parens_unop
1505 $text = "\cS" . $text if $cx == 16;
1506 return $text;
1507 } else {
1508 return $text;
1509 }
1510}
1511
e38ccfd9 1512# same as above, but get around the 'if it looks like a function' rule
9d2c6865
SM
1513sub maybe_parens_unop {
1514 my $self = shift;
1515 my($name, $kid, $cx) = @_;
1516 if ($cx > 16 or $self->{'parens'}) {
a0035eb8
RH
1517 $kid = $self->deparse($kid, 1);
1518 if ($name eq "umask" && $kid =~ /^\d+$/) {
1519 $kid = sprintf("%#o", $kid);
1520 }
4a1ac32e 1521 return $self->keyword($name) . "($kid)";
9d2c6865
SM
1522 } else {
1523 $kid = $self->deparse($kid, 16);
a0035eb8
RH
1524 if ($name eq "umask" && $kid =~ /^\d+$/) {
1525 $kid = sprintf("%#o", $kid);
1526 }
4a1ac32e 1527 $name = $self->keyword($name);
9d2c6865
SM
1528 if (substr($kid, 0, 1) eq "\cS") {
1529 # use kid's parens
1530 return $name . substr($kid, 1);
1531 } elsif (substr($kid, 0, 1) eq "(") {
1532 # avoid looks-like-a-function trap with extra parens
e38ccfd9 1533 # ('+' can lead to ambiguities)
9d2c6865
SM
1534 return "$name(" . $kid . ")";
1535 } else {
1536 return "$name $kid";
1537 }
1538 }
1539}
1540
1541sub maybe_parens_func {
1542 my $self = shift;
1543 my($func, $text, $cx, $prec) = @_;
1544 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1545 return "$func($text)";
1546 } else {
1547 return "$func $text";
1548 }
1549}
1550
56cd2ef8
FC
1551sub find_our_type {
1552 my ($self, $name) = @_;
1553 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
5afbd733 1554 my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0;
56cd2ef8
FC
1555 for my $a (@{$self->{'curcvlex'}{"o$name"}}) {
1556 my ($st, undef, $padname) = @$a;
5afbd733 1557 if ($st >= $seq && $padname->FLAGS & SVpad_TYPED) {
56cd2ef8
FC
1558 return $padname->SvSTASH->NAME;
1559 }
1560 }
1561 return '';
1562}
1563
6e90668e
SM
1564sub maybe_local {
1565 my $self = shift;
9d2c6865 1566 my($op, $cx, $text) = @_;
c8ec376c 1567 my $name = $op->name;
9187b6e4
FC
1568 my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign
1569 |lv(?:av)?ref)$/x)
de183bbb
FC
1570 ? OPpOUR_INTRO
1571 : 0;
1572 my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO;
c8ec376c
FC
1573 # The @a in \(@a) isn't in ref context, but only when the
1574 # parens are there.
1575 my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/
1576 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
de183bbb 1577 if ((my $priv = $op->private) & ($lval_intro|$our_intro)) {
f3515641 1578 my @our_local;
de183bbb 1579 push @our_local, "local" if $priv & $lval_intro;
f3515641 1580 push @our_local, "our" if $priv & $our_intro;
3188a821 1581 my $our_local = join " ", map $self->keyword($_), @our_local;
f3515641 1582 if( $our_local[-1] eq 'our' ) {
640d5d41
FC
1583 if ( $text !~ /^\W(\w+::)*\w+\z/
1584 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1585 ) {
1586 die "Unexpected our($text)\n";
1587 }
d989cdac 1588 $text =~ s/(\w+::)+//;
56cd2ef8
FC
1589
1590 if (my $type = $self->find_our_type($text)) {
1591 $our_local .= ' ' . $type;
1592 }
8e3542b6 1593 }
c8ec376c
FC
1594 return $need_parens ? "($text)" : $text
1595 if $self->{'avoid_local'}{$$op};
1596 if ($need_parens) {
1597 return "$our_local($text)";
d2a5d473 1598 } elsif (want_scalar($op) || $our_local eq 'our') {
ce4e655d 1599 return "$our_local $text";
e8d3f51b 1600 } else {
ce4e655d 1601 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
e8d3f51b 1602 }
6e90668e 1603 } else {
c8ec376c 1604 return $need_parens ? "($text)" : $text;
a798dbf2 1605 }
a798dbf2
MB
1606}
1607
3ed82cfc
GS
1608sub maybe_targmy {
1609 my $self = shift;
1610 my($op, $cx, $func, @args) = @_;
1611 if ($op->private & OPpTARGET_MY) {
1612 my $var = $self->padname($op->targ);
1613 my $val = $func->($self, $op, 7, @args);
1614 return $self->maybe_parens("$var = $val", $cx, 7);
1615 } else {
1616 return $func->($self, $op, $cx, @args);
1617 }
1618}
1619
6e90668e
SM
1620sub padname_sv {
1621 my $self = shift;
1622 my $targ = shift;
d989cdac 1623 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
6e90668e
SM
1624}
1625
1626sub maybe_my {
1627 my $self = shift;
8db6f480 1628 my($op, $cx, $text, $padname, $forbid_parens) = @_;
c8ec376c
FC
1629 # The @a in \(@a) isn't in ref context, but only when the
1630 # parens are there.
1631 my $need_parens = !$forbid_parens && $self->{'in_refgen'}
1632 && $op->name =~ /[ah]v\z/
1633 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
0ed5b3c8
FC
1634 # The @a in \my @a must not have parens.
1635 if (!$need_parens && $self->{'in_refgen'}) {
1636 $forbid_parens = 1;
1637 }
4c1f658f 1638 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
bcff4148
FC
1639 # Check $padname->FLAGS for statehood, rather than $op->private,
1640 # because enteriter ops do not carry the flag.
3188a821 1641 my $my =
bcff4148 1642 $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my");
56cd2ef8
FC
1643 if ($padname->FLAGS & SVpad_TYPED) {
1644 $my .= ' ' . $padname->SvSTASH->NAME;
1645 }
c8ec376c
FC
1646 if ($need_parens) {
1647 return "$my($text)";
1648 } elsif ($forbid_parens || want_scalar($op)) {
3462b4ac 1649 return "$my $text";
e8d3f51b 1650 } else {
3462b4ac 1651 return $self->maybe_parens_func($my, $text, $cx, 16);
e8d3f51b 1652 }
6e90668e 1653 } else {
c8ec376c 1654 return $need_parens ? "($text)" : $text;
6e90668e
SM
1655 }
1656}
1657
9d2c6865
SM
1658# The following OPs don't have functions:
1659
1660# pp_padany -- does not exist after parsing
9d2c6865 1661
2ae48fff
RGS
1662sub AUTOLOAD {
1663 if ($AUTOLOAD =~ s/^.*::pp_//) {
5e8c3db2
FC
1664 warn "unexpected OP_".
1665 ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD);
2ae48fff
RGS
1666 return "XXX";
1667 } else {
1668 die "Undefined subroutine $AUTOLOAD called";
1669 }
9d2c6865 1670}
6e90668e 1671
611c1e95
IZ
1672sub DESTROY {} # Do not AUTOLOAD
1673
ce4e655d
RH
1674# $root should be the op which represents the root of whatever
1675# we're sequencing here. If it's undefined, then we don't append
1676# any subroutine declarations to the deparsed ops, otherwise we
1677# append appropriate declarations.
58cccf98 1678sub lineseq {
93a8ff62 1679 my($self, $root, $cx, @ops) = @_;
58cccf98 1680 my($expr, @exprs);
ce4e655d
RH
1681
1682 my $out_cop = $self->{'curcop'};
1683 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1684 my $limit_seq;
1685 if (defined $root) {
1686 $limit_seq = $out_seq;
76df5e8f
DM
1687 my $nseq;
1688 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
ce4e655d
RH
1689 $limit_seq = $nseq if !defined($limit_seq)
1690 or defined($nseq) && $nseq < $limit_seq;
1691 }
1692 $limit_seq = $self->{'limit_seq'}
1693 if defined($self->{'limit_seq'})
1694 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1695 local $self->{'limit_seq'} = $limit_seq;
09d856fb
CK
1696
1697 $self->walk_lineseq($root, \@ops,
1698 sub { push @exprs, $_[0]} );
1699
93a8ff62
FC
1700 my $sep = $cx ? '; ' : ";\n";
1701 my $body = join($sep, grep {length} @exprs);
ce4e655d 1702 my $subs = "";
67fc2416 1703 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
ce4e655d
RH
1704 $subs = join "\n", $self->seq_subs($limit_seq);
1705 }
93a8ff62 1706 return join($sep, grep {length} $body, $subs);
6e90668e
SM
1707}
1708
58cccf98 1709sub scopeop {
d989cdac 1710 my($real_block, $self, $op, $cx) = @_;
58cccf98
SM
1711 my $kid;
1712 my @kids;
a0405c92 1713
0ced6c29
RGS
1714 local(@$self{qw'curstash warnings hints hinthash'})
1715 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
58cccf98
SM
1716 if ($real_block) {
1717 $kid = $op->first->sibling; # skip enter
1718 if (is_miniwhile($kid)) {
1719 my $top = $kid->first;
1720 my $name = $top->name;
1721 if ($name eq "and") {
7741ceed 1722 $name = $self->keyword("while");
58cccf98 1723 } elsif ($name eq "or") {
7741ceed 1724 $name = $self->keyword("until");
58cccf98 1725 } else { # no conditional -> while 1 or until 0
7741ceed
FC
1726 return $self->deparse($top->first, 1) . " "
1727 . $self->keyword("while") . " 1";
58cccf98
SM
1728 }
1729 my $cond = $top->first;
1730 my $body = $cond->sibling->first; # skip lineseq
1731 $cond = $self->deparse($cond, 1);
1732 $body = $self->deparse($body, 1);
1733 return "$body $name $cond";
6e90668e 1734 }
58cccf98
SM
1735 } else {
1736 $kid = $op->first;
1737 }
1738 for (; !null($kid); $kid = $kid->sibling) {
1739 push @kids, $kid;
6e90668e 1740 }
d989cdac 1741 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
73582821 1742 my $body = $self->lineseq($op, 0, @kids);
3188a821
FC
1743 return is_lexical_subs(@kids)
1744 ? $body
1745 : ($self->lex_in_scope("&do") ? "CORE::do" : "do")
1746 . " {\n\t$body\n\b}";
9d2c6865 1747 } else {
93a8ff62 1748 my $lineseq = $self->lineseq($op, $cx, @kids);
7a9b44b9 1749 return (length ($lineseq) ? "$lineseq;" : "");
6e90668e 1750 }
6e90668e
SM
1751}
1752
ce4e655d 1753sub pp_scope { scopeop(0, @_); }
58cccf98
SM
1754sub pp_lineseq { scopeop(0, @_); }
1755sub pp_leave { scopeop(1, @_); }
9d2c6865 1756
d989cdac
SM
1757# This is a special case of scopeop and lineseq, for the case of the
1758# main_root. The difference is that we print the output statements as
1759# soon as we get them, for the sake of impatient users.
1760sub deparse_root {
1761 my $self = shift;
1762 my($op) = @_;
0ced6c29
RGS
1763 local(@$self{qw'curstash warnings hints hinthash'})
1764 = @$self{qw'curstash warnings hints hinthash'};
d989cdac 1765 my @kids;
4ca8de37 1766 return if null $op->first; # Can happen, e.g., for Bytecode without -k
d989cdac
SM
1767 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1768 push @kids, $kid;
1769 }
09d856fb 1770 $self->walk_lineseq($op, \@kids,
4b1385ee 1771 sub { return unless length $_[0];
5e617af5 1772 print $self->indent($_[0].';');
4b1385ee 1773 print "\n"
5e617af5 1774 unless $_[1] == $#kids;
09d856fb
CK
1775 });
1776}
1777
1778sub walk_lineseq {
1779 my ($self, $op, $kids, $callback) = @_;
1780 my @kids = @$kids;
d989cdac
SM
1781 for (my $i = 0; $i < @kids; $i++) {
1782 my $expr = "";
1783 if (is_state $kids[$i]) {
09d856fb 1784 $expr = $self->deparse($kids[$i++], 0);
d989cdac 1785 if ($i > $#kids) {
09d856fb 1786 $callback->($expr, $i);
d989cdac
SM
1787 last;
1788 }
1789 }
1790 if (is_for_loop($kids[$i])) {
eae48c89
Z
1791 $callback->($expr . $self->for_loop($kids[$i], 0),
1792 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
d989cdac
SM
1793 next;
1794 }
6b6b21da 1795 my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2);
34b54951 1796 $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise
6b6b21da 1797 $expr .= $expr2;
09d856fb 1798 $callback->($expr, $i);
d989cdac
SM
1799 }
1800}
1801
6e90668e
SM
1802# The BEGIN {} is used here because otherwise this code isn't executed
1803# when you run B::Deparse on itself.
1804my %globalnames;
1805BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1806 "ENV", "ARGV", "ARGVOUT", "_"); }
1807
1808sub gv_name {
1809 my $self = shift;
1810 my $gv = shift;
b89b7257 1811 my $raw = shift;
32cc5cd1
FC
1812#Carp::confess() unless ref($gv) eq "B::GV";
1813 my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0;
1814 my $stash = ($cv || $gv)->STASH->NAME;
1815 my $name = $raw
1816 ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME
1817 : $cv
1818 ? B::safename($cv->NAME_HEK || $cv->GV->NAME)
1819 : $gv->SAFENAME;
8b2d6640
FC
1820 if ($stash eq 'main' && $name =~ /^::/) {
1821 $stash = '::';
1822 }
b861b87f
FC
1823 elsif (($stash eq 'main'
1824 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
8b2d6640
FC
1825 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1826 && ($stash eq 'main' || $name !~ /::/))
b861b87f 1827 )
9d2c6865 1828 {
6e90668e
SM
1829 $stash = "";
1830 } else {
1831 $stash = $stash . "::";
a798dbf2 1832 }
b89b7257 1833 if (!$raw and $name =~ /^(\^..|{)/) {
083bda02 1834 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
6e90668e
SM
1835 }
1836 return $stash . $name;
a798dbf2
MB
1837}
1838
8510e997 1839# Return the name to use for a stash variable.
415d4c68
FC
1840# If a lexical with the same name is in scope, or
1841# if strictures are enabled, it may need to be
8510e997
RH
1842# fully-qualified.
1843sub stash_variable {
bb8996b8 1844 my ($self, $prefix, $name, $cx) = @_;
8510e997 1845
dd666160 1846 return $prefix.$self->maybe_qualify($prefix, $name) if $name =~ /::/;
8510e997 1847
d49c3562 1848 unless ($prefix eq '$' || $prefix eq '@' || $prefix eq '&' || #'
8510e997
RH
1849 $prefix eq '%' || $prefix eq '$#') {
1850 return "$prefix$name";
1851 }
1852
b6bba886 1853 if ($name =~ /^[^[:alpha:]_+-]$/) {
61154ac0
FC
1854 if (defined $cx && $cx == 26) {
1855 if ($prefix eq '@') {
bb8996b8
HY
1856 return "$prefix\{$name}";
1857 }
61154ac0
FC
1858 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1859 }
1860 if ($prefix eq '$#') {
6ec73527 1861 return "\$#{$name}";
61154ac0 1862 }
6ec73527 1863 }
bb8996b8 1864
415d4c68 1865 return $prefix . $self->maybe_qualify($prefix, $name);
8510e997
RH
1866}
1867
93e453e2
KW
1868my %unctrl = # portable to EBCDIC
1869 (
dd405ed7
KW
1870 "\c@" => '@', # unused
1871 "\cA" => 'A',
1872 "\cB" => 'B',
1873 "\cC" => 'C',
1874 "\cD" => 'D',
1875 "\cE" => 'E',
1876 "\cF" => 'F',
1877 "\cG" => 'G',
1878 "\cH" => 'H',
1879 "\cI" => 'I',
1880 "\cJ" => 'J',
1881 "\cK" => 'K',
1882 "\cL" => 'L',
1883 "\cM" => 'M',
1884 "\cN" => 'N',
1885 "\cO" => 'O',
1886 "\cP" => 'P',
1887 "\cQ" => 'Q',
1888 "\cR" => 'R',
1889 "\cS" => 'S',
1890 "\cT" => 'T',
1891 "\cU" => 'U',
1892 "\cV" => 'V',
1893 "\cW" => 'W',
1894 "\cX" => 'X',
1895 "\cY" => 'Y',
1896 "\cZ" => 'Z',
1897 "\c[" => '[', # unused
1898 "\c\\" => '\\', # unused
1899 "\c]" => ']', # unused
1900 "\c_" => '_', # unused
93e453e2
KW
1901 );
1902
be6cf5cf
FC
1903# Return just the name, without the prefix. It may be returned as a quoted
1904# string. The second return value is a boolean indicating that.
1905sub stash_variable_name {
1906 my($self, $prefix, $gv) = @_;
1907 my $name = $self->gv_name($gv, 1);
415d4c68 1908 $name = $self->maybe_qualify($prefix,$name);
be6cf5cf 1909 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
dd405ed7 1910 $name =~ s/^([\ca-\cz])/'^' . $unctrl{$1}/e;
be6cf5cf
FC
1911 $name =~ /^(\^..|{)/ and $name = "{$name}";
1912 return $name, 0; # not quoted
1913 }
1914 else {
7741ceed 1915 single_delim("q", "'", $name, $self), 1;
be6cf5cf
FC
1916 }
1917}
1918
415d4c68
FC
1919sub maybe_qualify {
1920 my ($self,$prefix,$name) = @_;
1921 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
dd666160
Z
1922 if ($prefix eq "") {
1923 $name .= "::" if $name =~ /(?:\ACORE::[^:]*|::)\z/;
1924 return $name;
1925 }
1926 return $name if $name =~ /::/;
415d4c68
FC
1927 return $self->{'curstash'}.'::'. $name
1928 if
36727b53
FC
1929 $name =~ /^(?!\d)\w/ # alphabetic
1930 && $v !~ /^\$[ab]\z/ # not $a or $b
257296eb 1931 && $v =~ /\A[\$\@\%\&]/ # scalar, array, hash, or sub
415d4c68
FC
1932 && !$globalnames{$name} # not a global name
1933 && $self->{hints} & $strict_bits{vars} # strict vars
1934 && !$self->lex_in_scope($v,1) # no "our"
1935 or $self->lex_in_scope($v); # conflicts with "my" variable
1936 return $name;
1937}
1938
8510e997 1939sub lex_in_scope {
415d4c68
FC
1940 my ($self, $name, $our) = @_;
1941 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
8510e997
RH
1942 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1943
6ec152c3 1944 return 0 if !defined($self->{'curcop'});
8510e997
RH
1945 my $seq = $self->{'curcop'}->cop_seq;
1946 return 0 if !exists $self->{'curcvlex'}{$name};
1947 for my $a (@{$self->{'curcvlex'}{$name}}) {
1948 my ($st, $en) = @$a;
1949 return 1 if $seq > $st && $seq <= $en;
1950 }
1951 return 0;
1952}
1953
1954sub populate_curcvlex {
1955 my $self = shift;
ce4e655d 1956 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
7dafbf52
DM
1957 my $padlist = $cv->PADLIST;
1958 # an undef CV still in lexical chain
1959 next if class($padlist) eq "SPECIAL";
1960 my @padlist = $padlist->ARRAY;
8510e997
RH
1961 my @ns = $padlist[0]->ARRAY;
1962
1963 for (my $i=0; $i<@ns; ++$i) {
1964 next if class($ns[$i]) eq "SPECIAL";
0f2fe21d
RH
1965 if (class($ns[$i]) eq "PV") {
1966 # Probably that pesky lexical @_
1967 next;
1968 }
8510e997 1969 my $name = $ns[$i]->PVX;
679f2252 1970 next unless defined $name;
7dafbf52
DM
1971 my ($seq_st, $seq_en) =
1972 ($ns[$i]->FLAGS & SVf_FAKE)
1973 ? (0, 999999)
809abb02 1974 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
8510e997 1975
415d4c68
FC
1976 push @{$self->{'curcvlex'}{
1977 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
56cd2ef8 1978 }}, [$seq_st, $seq_en, $ns[$i]];
8510e997
RH
1979 }
1980 }
1981}
1982
ce4e655d
RH
1983sub find_scope_st { ((find_scope(@_))[0]); }
1984sub find_scope_en { ((find_scope(@_))[1]); }
1985
1986# Recurses down the tree, looking for pad variable introductions and COPs
1987sub find_scope {
1988 my ($self, $op, $scope_st, $scope_en) = @_;
ff97752d 1989 carp("Undefined op in find_scope") if !defined $op;
ce4e655d
RH
1990 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1991
b6b46d6f
AB
1992 my @queue = ($op);
1993 while(my $op = shift @queue ) {
1994 for (my $o=$op->first; $$o; $o=$o->sibling) {
1995 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1996 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1997 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1998 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1999 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
2000 return ($scope_st, $scope_en);
2001 }
2002 elsif (is_state($o)) {
2003 my $c = $o->cop_seq;
2004 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
2005 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
2006 return ($scope_st, $scope_en);
2007 }
2008 elsif ($o->flags & OPf_KIDS) {
2009 unshift (@queue, $o);
2010 }
34a48b4b
RH
2011 }
2012 }
ce4e655d
RH
2013
2014 return ($scope_st, $scope_en);
34a48b4b
RH
2015}
2016
2017# Returns a list of subs which should be inserted before the COP
2018sub cop_subs {
2019 my ($self, $op, $out_seq) = @_;
2020 my $seq = $op->cop_seq;
34a48b4b
RH
2021 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
2022 return $self->seq_subs($seq);
2023}
2024
2025sub seq_subs {
2026 my ($self, $seq) = @_;
2027 my @text;
2028#push @text, "# ($seq)\n";
2029
ce4e655d 2030 return "" if !defined $seq;
d88d1fe0 2031 my @pending;
34a48b4b
RH
2032 while (scalar(@{$self->{'subs_todo'}})
2033 and $seq > $self->{'subs_todo'}[0][0]) {
d88d1fe0 2034 my $cv = $self->{'subs_todo'}[0][1];
d4f1bfe7
FC
2035 # Skip the OUTSIDE check for lexical subs. We may be deparsing a
2036 # cloned anon sub with lexical subs declared in it, in which case
2037 # the OUTSIDE pointer points to the anon protosub.
c310a5ab 2038 my $lexical = ref $self->{'subs_todo'}[0][3];
d4f1bfe7
FC
2039 my $outside = !$lexical && $cv && $cv->OUTSIDE;
2040 if (!$lexical and $cv
2041 and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}})
2042 {
d88d1fe0
FC
2043 push @pending, shift @{$self->{'subs_todo'}};
2044 next;
2045 }
34a48b4b
RH
2046 push @text, $self->next_todo;
2047 }
d88d1fe0 2048 unshift @{$self->{'subs_todo'}}, @pending;
34a48b4b
RH
2049 return @text;
2050}
2051
95c04cde
NC
2052sub _features_from_bundle {
2053 my ($hints, $hh) = @_;
1873980a 2054 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
95c04cde
NC
2055 $hh->{$feature::feature{$_}} = 1;
2056 }
2057 return $hh;
2058}
2059
d5994d07
DM
2060# generate any pragmas, 'package foo' etc needed to synchronise
2061# with the given cop
2062
2063sub pragmata {
6e90668e 2064 my $self = shift;
d5994d07
DM
2065 my($op) = @_;
2066
6e90668e 2067 my @text;
bc304ab2 2068
11faa288 2069 my $stash = $op->stashpv;
6e90668e 2070 if ($stash ne $self->{'curstash'}) {
7741ceed 2071 push @text, $self->keyword("package") . " $stash;\n";
6e90668e
SM
2072 $self->{'curstash'} = $stash;
2073 }
08c6f5ec 2074
7a9b44b9
RH
2075 my $warnings = $op->warnings;
2076 my $warning_bits;
2077 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
810aef70 2078 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
7a9b44b9 2079 }
e31885a0 2080 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
810aef70 2081 $warning_bits = $warnings::NONE;
7a9b44b9 2082 }
e31885a0
RH
2083 elsif ($warnings->isa("B::SPECIAL")) {
2084 $warning_bits = undef;
2085 }
7a9b44b9 2086 else {
34a48b4b 2087 $warning_bits = $warnings->PV & WARN_MASK;
7a9b44b9
RH
2088 }
2089
e31885a0
RH
2090 if (defined ($warning_bits) and
2091 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
7741ceed
FC
2092 push @text,
2093 $self->declare_warnings($self->{'warnings'}, $warning_bits);
7a9b44b9
RH
2094 $self->{'warnings'} = $warning_bits;
2095 }
2096
843835bc 2097 my $hints = $op->hints;
0bb01b05 2098 my $old_hints = $self->{'hints'};
2be95ceb 2099 if ($self->{'hints'} != $hints) {
7741ceed 2100 push @text, $self->declare_hints($self->{'hints'}, $hints);
2be95ceb 2101 $self->{'hints'} = $hints;
a0405c92
RH
2102 }
2103
0bb01b05 2104 my $newhh;
843835bc 2105 $newhh = $op->hints_hash->HASH;
0bb01b05 2106
843835bc 2107 {
0bb01b05 2108 # feature bundle hints
149758b3
NC
2109 my $from = $old_hints & $feature::hint_mask;
2110 my $to = $ hints & $feature::hint_mask;
0bb01b05 2111 if ($from != $to) {
149758b3 2112 if ($to == $feature::hint_mask) {
0bb01b05
FC
2113 if ($self->{'hinthash'}) {
2114 delete $self->{'hinthash'}{$_}
2115 for grep /^feature_/, keys %{$self->{'hinthash'}};
2116 }
2117 else { $self->{'hinthash'} = {} }
95c04cde
NC
2118 $self->{'hinthash'}
2119 = _features_from_bundle($from, $self->{'hinthash'});
0bb01b05
FC
2120 }
2121 else {
2122 my $bundle =
2123 $feature::hint_bundles[$to >> $feature::hint_shift];
2124 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
7741ceed 2125 push @text,
127ce1cd 2126 $self->keyword("no") . " feature ':all';\n",
7741ceed 2127 $self->keyword("use") . " feature ':$bundle';\n";
0bb01b05
FC
2128 }
2129 }
2130 }
2131
843835bc 2132 {
7741ceed 2133 push @text, $self->declare_hinthash(
0bb01b05
FC
2134 $self->{'hinthash'}, $newhh,
2135 $self->{indent_size}, $self->{hints},
2136 );
2137 $self->{'hinthash'} = $newhh;
0ced6c29
RGS
2138 }
2139
d5994d07
DM
2140 return join("", @text);
2141}
2142
2143
2144# Notice how subs and formats are inserted between statements here;
2145# also $[ assignments and pragmas.
2146sub pp_nextstate {
2147 my $self = shift;
2148 my($op, $cx) = @_;
2149 $self->{'curcop'} = $op;
2150
e276dec7 2151 my @text;
d5994d07 2152
bc304ab2
DM
2153 my @subs = $self->cop_subs($op);
2154 if (@subs) {
2155 # Special marker to swallow up the semicolon
2156 push @subs, "\cK";
2157 }
2158 push @text, @subs;
2159
e276dec7 2160 push @text, $self->pragmata($op);
d5994d07 2161
bc304ab2 2162
d989cdac
SM
2163 # This should go after of any branches that add statements, to
2164 # increase the chances that it refers to the same line it did in
2165 # the original program.
e56a605e 2166 if ($self->{'linenums'} && $cx != .5) { # $cx == .5 means in a format
d989cdac
SM
2167 push @text, "\f#line " . $op->line .
2168 ' "' . $op->file, qq'"\n';
2169 }
2170
98a1a137
Z
2171 push @text, $op->label . ": " if $op->label;
2172
6e90668e
SM
2173 return join("", @text);
2174}
2175
08c6f5ec 2176sub declare_warnings {
7741ceed 2177 my ($self, $from, $to) = @_;
66cc68c1
DM
2178 $from //= '';
2179 my $all = (warnings::bits("all") & WARN_MASK);
2180 unless ((($from & WARN_MASK) & ~$all) =~ /[^\0]/) {
2181 # no FATAL bits need turning off
2182 if ( ($to & WARN_MASK) eq $all) {
2183 return $self->keyword("use") . " warnings;\n";
2184 }
2185 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
2186 return $self->keyword("no") . " warnings;\n";
2187 }
a0405c92 2188 }
66cc68c1 2189
74b899ae
KW
2190 return "BEGIN {\${^WARNING_BITS} = \""
2191 . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
2192 . "\"}\n\cK";
a0405c92
RH
2193}
2194
2195sub declare_hints {
7741ceed 2196 my ($self, $from, $to) = @_;
a0035eb8
RH
2197 my $use = $to & ~$from;
2198 my $no = $from & ~$to;
2199 my $decls = "";
2200 for my $pragma (hint_pragmas($use)) {
7741ceed 2201 $decls .= $self->keyword("use") . " $pragma;\n";
a0035eb8
RH
2202 }
2203 for my $pragma (hint_pragmas($no)) {
7741ceed 2204 $decls .= $self->keyword("no") . " $pragma;\n";
a0035eb8
RH
2205 }
2206 return $decls;
2207}
2208
493c23c6
NC
2209# Internal implementation hints that the core sets automatically, so don't need
2210# (or want) to be passed back to the user
2211my %ignored_hints = (
2212 'open<' => 1,
2213 'open>' => 1,
dca6062a 2214 ':' => 1,
1c74777c
FC
2215 'strict/refs' => 1,
2216 'strict/subs' => 1,
2217 'strict/vars' => 1,
17446f3b 2218 'feature/bits' => 1,
2e8342de 2219);
493c23c6 2220
a8095af7
FC
2221my %rev_feature;
2222
0ced6c29 2223sub declare_hinthash {
7741ceed 2224 my ($self, $from, $to, $indent, $hints) = @_;
a8095af7 2225 my $doing_features =
149758b3 2226 ($hints & $feature::hint_mask) == $feature::hint_mask;
0ced6c29 2227 my @decls;
a8095af7
FC
2228 my @features;
2229 my @unfeatures; # bugs?
0bb01b05 2230 for my $key (sort keys %$to) {
493c23c6 2231 next if $ignored_hints{$key};
843835bc 2232 my $is_feature = $key =~ /^feature_/;
a8095af7 2233 next if $is_feature and not $doing_features;
04be0204 2234 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
a8095af7 2235 push(@features, $key), next if $is_feature;
035146a3 2236 push @decls,
7741ceed 2237 qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
035146a3
FC
2238 . (
2239 defined $to->{$key}
7741ceed 2240 ? single_delim("q", "'", $to->{$key}, $self)
035146a3
FC
2241 : 'undef'
2242 )
04be0204 2243 . qq(;);
0ced6c29
RGS
2244 }
2245 }
0bb01b05 2246 for my $key (sort keys %$from) {
493c23c6 2247 next if $ignored_hints{$key};
843835bc 2248 my $is_feature = $key =~ /^feature_/;
a8095af7 2249 next if $is_feature and not $doing_features;
0ced6c29 2250 if (!exists $to->{$key}) {
a8095af7 2251 push(@unfeatures, $key), next if $is_feature;
0ced6c29
RGS
2252 push @decls, qq(delete \$^H{'$key'};);
2253 }
2254 }
a8095af7
FC
2255 my @ret;
2256 if (@features || @unfeatures) {
a8095af7
FC
2257 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
2258 }
2259 if (@features) {
7741ceed 2260 push @ret, $self->keyword("use") . " feature "
a8095af7
FC
2261 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
2262 }
2263 if (@unfeatures) {
7741ceed 2264 push @ret, $self->keyword("no") . " feature "
a8095af7
FC
2265 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
2266 . ";\n";
2267 }
2268 @decls and
2269 push @ret,
5e617af5 2270 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
a8095af7 2271 return @ret;
0ced6c29
RGS
2272}
2273
a0035eb8
RH
2274sub hint_pragmas {
2275 my ($bits) = @_;
415d4c68 2276 my (@pragmas, @strict);
a0035eb8 2277 push @pragmas, "integer" if $bits & 0x1;
415d4c68
FC
2278 for (sort keys %strict_bits) {
2279 push @strict, "'$_'" if $bits & $strict_bits{$_};
2280 }
2281 if (@strict == keys %strict_bits) {
2282 push @pragmas, "strict";
2283 }
2284 elsif (@strict) {
2285 push @pragmas, "strict " . join ', ', @strict;
2286 }
a0035eb8
RH
2287 push @pragmas, "bytes" if $bits & 0x8;
2288 return @pragmas;
08c6f5ec
RH
2289}
2290
6e90668e 2291sub pp_dbstate { pp_nextstate(@_) }
3f872cb9 2292sub pp_setstate { pp_nextstate(@_) }
6e90668e
SM
2293
2294sub pp_unstack { return "" } # see also leaveloop
2295
80e3f4ad
FC
2296my %feature_keywords = (
2297 # keyword => 'feature',
2298 state => 'state',
2299 say => 'say',
2300 given => 'switch',
7896dde7
Z
2301 when => 'switch',
2302 default => 'switch',
2303 break => 'switch',
7d789282 2304 evalbytes=>'evalbytes',
84ed0108 2305 __SUB__ => '__SUB__',
838f2281 2306 fc => 'fc',
a1325b90
PE
2307 try => 'try',
2308 catch => 'try',
f79e2ff9 2309 defer => 'defer',
80e3f4ad
FC
2310);
2311
3ac5308a
DM
2312# keywords that are strong and also have a prototype
2313#
2314my %strong_proto_keywords = map { $_ => 1 } qw(
3ac5308a
DM
2315 pos
2316 prototype
2317 scalar
2318 study
2319 undef
2320);
2321
a958cfbb
FC
2322sub feature_enabled {
2323 my($self,$name) = @_;
223b1722 2324 my $hh;
149758b3
NC
2325 my $hints = $self->{hints} & $feature::hint_mask;
2326 if ($hints && $hints != $feature::hint_mask) {
1873980a 2327 $hh = _features_from_bundle($hints);
223b1722
FC
2328 }
2329 elsif ($hints) { $hh = $self->{'hinthash'} }
a958cfbb
FC
2330 return $hh && $hh->{"feature_$feature_keywords{$name}"}
2331}
2332
2333sub keyword {
2334 my $self = shift;
2335 my $name = shift;
2336 return $name if $name =~ /^CORE::/; # just in case
2337 if (exists $feature_keywords{$name}) {
2338 return "CORE::$name" if not $self->feature_enabled($name);
80e3f4ad 2339 }
7741ceed
FC
2340 # This sub may be called for a program that has no nextstate ops. In
2341 # that case we may have a lexical sub named no/use/sub in scope but
a3815e44 2342 # $self->lex_in_scope will return false because it depends on the
7741ceed
FC
2343 # current nextstate op. So we need this alternate method if there is
2344 # no current cop.
2345 if (!$self->{'curcop'}) {
2346 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
2347 return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
2348 || exists $self->{'curcvlex'}{"o&$name"};
2349 } elsif ($self->lex_in_scope("&$name")
2350 || $self->lex_in_scope("&$name", 1)) {
3188a821
FC
2351 return "CORE::$name";
2352 }
3ac5308a
DM
2353 if ($strong_proto_keywords{$name}
2354 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
2355 && !defined eval{prototype "CORE::$name"})
4a1ac32e
FC
2356 ) { return $name }
2357 if (
2358 exists $self->{subs_declared}{$name}
2359 or
2360 exists &{"$self->{curstash}::$name"}
2361 ) {
2362 return "CORE::$name"
2363 }
2364 return $name;
2365}
2366
6e90668e
SM
2367sub baseop {
2368 my $self = shift;
9d2c6865 2369 my($op, $cx, $name) = @_;
4a1ac32e 2370 return $self->keyword($name);
6e90668e
SM
2371}
2372
ddb55548 2373sub pp_stub { "()" }
6e90668e
SM
2374sub pp_wantarray { baseop(@_, "wantarray") }
2375sub pp_fork { baseop(@_, "fork") }
3ed82cfc
GS
2376sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
2377sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
2378sub pp_time { maybe_targmy(@_, \&baseop, "time") }
6e90668e
SM
2379sub pp_tms { baseop(@_, "times") }
2380sub pp_ghostent { baseop(@_, "gethostent") }
2381sub pp_gnetent { baseop(@_, "getnetent") }
2382sub pp_gprotoent { baseop(@_, "getprotoent") }
2383sub pp_gservent { baseop(@_, "getservent") }
2384sub pp_ehostent { baseop(@_, "endhostent") }
2385sub pp_enetent { baseop(@_, "endnetent") }
2386sub pp_eprotoent { baseop(@_, "endprotoent") }
2387sub pp_eservent { baseop(@_, "endservent") }
2388sub pp_gpwent { baseop(@_, "getpwent") }
2389sub pp_spwent { baseop(@_, "setpwent") }
2390sub pp_epwent { baseop(@_, "endpwent") }
2391sub pp_ggrent { baseop(@_, "getgrent") }
2392sub pp_sgrent { baseop(@_, "setgrent") }
2393sub pp_egrent { baseop(@_, "endgrent") }
2394sub pp_getlogin { baseop(@_, "getlogin") }
2395
2396sub POSTFIX () { 1 }
2397
9d2c6865
SM
2398# I couldn't think of a good short name, but this is the category of
2399# symbolic unary operators with interesting precedence
2400
2401sub pfixop {
2402 my $self = shift;
2403 my($op, $cx, $name, $prec, $flags) = (@_, 0);
2404 my $kid = $op->first;
2405 $kid = $self->deparse($kid, $prec);
843b15cc
FC
2406 return $self->maybe_parens(($flags & POSTFIX)
2407 ? "$kid$name"
2408 # avoid confusion with filetests
2409 : $name eq '-'
2410 && $kid =~ /^[a-zA-Z](?!\w)/
2411 ? "$name($kid)"
2412 : "$name$kid",
9d2c6865
SM
2413 $cx, $prec);
2414}
2415
2416sub pp_preinc { pfixop(@_, "++", 23) }
2417sub pp_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2418sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2419sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
9d2c6865
SM
2420sub pp_i_preinc { pfixop(@_, "++", 23) }
2421sub pp_i_predec { pfixop(@_, "--", 23) }
3ed82cfc
GS
2422sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2423sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
68cc8748 2424sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
27f31adf
FC
2425*pp_ncomplement = *pp_complement;
2426sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) }
9d2c6865 2427
3ed82cfc
GS
2428sub pp_negate { maybe_targmy(@_, \&real_negate) }
2429sub real_negate {
9d2c6865
SM
2430 my $self = shift;
2431 my($op, $cx) = @_;
3f872cb9 2432 if ($op->first->name =~ /^(i_)?negate$/) {
9d2c6865
SM
2433 # avoid --$x
2434 $self->pfixop($op, $cx, "-", 21.5);
2435 } else {
2436 $self->pfixop($op, $cx, "-", 21);
2437 }
2438}
2439sub pp_i_negate { pp_negate(@_) }
2440
2441sub pp_not {
2442 my $self = shift;
2443 my($op, $cx) = @_;
2444 if ($cx <= 4) {
1cabb3b3 2445 $self->listop($op, $cx, "not", $op->first);
9d2c6865
SM
2446 } else {
2447 $self->pfixop($op, $cx, "!", 21);
2448 }
2449}
2450
6e90668e
SM
2451sub unop {
2452 my $self = shift;
9c56d9ea 2453 my($op, $cx, $name, $nollafr) = @_;
6e90668e 2454 my $kid;
9d2c6865 2455 if ($op->flags & OPf_KIDS) {
aaf643ce 2456 $kid = $op->first;
1c85afce
YO
2457 if (not $name) {
2458 # this deals with 'boolkeys' right now
2459 return $self->deparse($kid,$cx);
2460 }
deb20ba3
RGS
2461 my $builtinname = $name;
2462 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2463 if (defined prototype($builtinname)
9cef6114 2464 && $builtinname ne 'CORE::readline'
deb20ba3 2465 && prototype($builtinname) =~ /^;?\*/
e31885a0
RH
2466 && $kid->name eq "rv2gv") {
2467 $kid = $kid->first;
2468 }
2469
9c56d9ea 2470 if ($nollafr) {
917a8f4f
FC
2471 if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) {
2472 # require foo() is a syntax error.
2473 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2474 }
9c56d9ea
FC
2475 return $self->maybe_parens(
2476 $self->keyword($name) . " $kid", $cx, 16
2477 );
23f1d933 2478 }
9d2c6865 2479 return $self->maybe_parens_unop($name, $kid, $cx);
6e90668e 2480 } else {
4d8ac5c7
FC
2481 return $self->maybe_parens(
2482 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
2483 $cx, 16,
2484 );
6e90668e 2485 }
6e90668e
SM
2486}
2487
3ed82cfc
GS
2488sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
2489sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
2490sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
2491sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
6e90668e
SM
2492sub pp_defined { unop(@_, "defined") }
2493sub pp_undef { unop(@_, "undef") }
2494sub pp_study { unop(@_, "study") }
6e90668e
SM
2495sub pp_ref { unop(@_, "ref") }
2496sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
2497
3ed82cfc
GS
2498sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
2499sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
2500sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
6e90668e 2501sub pp_srand { unop(@_, "srand") }
3ed82cfc
GS
2502sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
2503sub pp_log { maybe_targmy(@_, \&unop, "log") }
2504sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
2505sub pp_int { maybe_targmy(@_, \&unop, "int") }
2506sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
2507sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
2508sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
2509
2510sub pp_length { maybe_targmy(@_, \&unop, "length") }
2511sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2512sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
6e90668e
SM
2513
2514sub pp_each { unop(@_, "each") }
2515sub pp_values { unop(@_, "values") }
2516sub pp_keys { unop(@_, "keys") }
09dcfa7d 2517{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
23f1d933 2518sub pp_boolkeys {
1c85afce
YO
2519 # no name because its an optimisation op that has no keyword
2520 unop(@_,"");
2521}
644741fd
NC
2522sub pp_aeach { unop(@_, "each") }
2523sub pp_avalues { unop(@_, "values") }
2524sub pp_akeys { unop(@_, "keys") }
6e90668e
SM
2525sub pp_pop { unop(@_, "pop") }
2526sub pp_shift { unop(@_, "shift") }
2527
2528sub pp_caller { unop(@_, "caller") }
2529sub pp_reset { unop(@_, "reset") }
2530sub pp_exit { unop(@_, "exit") }
2531sub pp_prototype { unop(@_, "prototype") }
2532
2533sub pp_close { unop(@_, "close") }
2534sub pp_fileno { unop(@_, "fileno") }
2535sub pp_umask { unop(@_, "umask") }
6e90668e
SM
2536sub pp_untie { unop(@_, "untie") }
2537sub pp_tied { unop(@_, "tied") }
2538sub pp_dbmclose { unop(@_, "dbmclose") }
2539sub pp_getc { unop(@_, "getc") }
2540sub pp_eof { unop(@_, "eof") }
2541sub pp_tell { unop(@_, "tell") }
2542sub pp_getsockname { unop(@_, "getsockname") }
2543sub pp_getpeername { unop(@_, "getpeername") }
2544
0175f038
FC
2545sub pp_chdir {
2546 my ($self, $op, $cx) = @_;
3c4a43a5 2547 if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) {
0175f038
FC
2548 my $kw = $self->keyword("chdir");
2549 my $kid = $self->const_sv($op->first)->PV;
2550 my $code = $kw
2551 . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid");
2552 maybe_targmy(@_, sub { $_[3] }, $code);
2553 } else {
2554 maybe_targmy(@_, \&unop, "chdir")
2555 }
2556}
2557
3ed82cfc 2558sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
6e90668e 2559sub pp_readlink { unop(@_, "readlink") }
3ed82cfc 2560sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
6e90668e
SM
2561sub pp_readdir { unop(@_, "readdir") }
2562sub pp_telldir { unop(@_, "telldir") }
2563sub pp_rewinddir { unop(@_, "rewinddir") }
2564sub pp_closedir { unop(@_, "closedir") }
3ed82cfc 2565sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
6e90668e
SM
2566sub pp_localtime { unop(@_, "localtime") }
2567sub pp_gmtime { unop(@_, "gmtime") }
2568sub pp_alarm { unop(@_, "alarm") }
3ed82cfc 2569sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
6e90668e 2570
94bb57f9 2571sub pp_dofile {
9c56d9ea 2572 my $code = unop(@_, "do", 1); # llafr does not apply
8b46c09b 2573 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
94bb57f9
FC
2574 $code;
2575}
7d789282
FC
2576sub pp_entereval {
2577 unop(
2578 @_,
c7c39989 2579 $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval"
7d789282
FC
2580 )
2581}
6e90668e
SM
2582
2583sub pp_ghbyname { unop(@_, "gethostbyname") }
2584sub pp_gnbyname { unop(@_, "getnetbyname") }
2585sub pp_gpbyname { unop(@_, "getprotobyname") }
2586sub pp_shostent { unop(@_, "sethostent") }
2587sub pp_snetent { unop(@_, "setnetent") }
2588sub pp_sprotoent { unop(@_, "setprotoent") }
2589sub pp_sservent { unop(@_, "setservent") }
2590sub pp_gpwnam { unop(@_, "getpwnam") }
2591sub pp_gpwuid { unop(@_, "getpwuid") }
2592sub pp_ggrnam { unop(@_, "getgrnam") }
2593sub pp_ggrgid { unop(@_, "getgrgid") }
2594
2595sub pp_lock { unop(@_, "lock") }
2596
0d863452 2597sub pp_continue { unop(@_, "continue"); }
7896dde7 2598sub pp_break { unop(@_, "break"); }
0d863452 2599
7896dde7
Z
2600sub givwhen {
2601 my $self = shift;
2602 my($op, $cx, $givwhen) = @_;
0d863452
RH
2603
2604 my $enterop = $op->first;
7896dde7
Z
2605 my ($head, $block);
2606 if ($enterop->flags & OPf_SPECIAL) {
2607 $head = $self->keyword("default");
2608 $block = $self->deparse($enterop->first, 0);
0d863452 2609 }
7896dde7
Z
2610 else {
2611 my $cond = $enterop->first;
2612 my $cond_str = $self->deparse($cond, 1);
2613 $head = "$givwhen ($cond_str)";
2614 $block = $self->deparse($cond->sibling, 0);
2615 }
2616
2617 return "$head {\n".
2618 "\t$block\n".
2619 "\b}\cK";
0d863452
RH
2620}
2621
7896dde7
Z
2622sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2623sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
2624
6e90668e
SM
2625sub pp_exists {
2626 my $self = shift;
9d2c6865 2627 my($op, $cx) = @_;
34a48b4b 2628 my $arg;
3188a821 2629 my $name = $self->keyword("exists");
34a48b4b
RH
2630 if ($op->private & OPpEXISTS_SUB) {
2631 # Checking for the existence of a subroutine
3188a821 2632 return $self->maybe_parens_func($name,
34a48b4b
RH
2633 $self->pp_rv2cv($op->first, 16), $cx, 16);
2634 }
2635 if ($op->flags & OPf_SPECIAL) {
2636 # Array element, not hash element
3188a821 2637 return $self->maybe_parens_func($name,
34a48b4b
RH
2638 $self->pp_aelem($op->first, 16), $cx, 16);
2639 }
3188a821 2640 return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
9d2c6865 2641 $cx, 16);
6e90668e
SM
2642}
2643
6e90668e
SM
2644sub pp_delete {
2645 my $self = shift;
9d2c6865 2646 my($op, $cx) = @_;
6e90668e 2647 my $arg;
3188a821 2648 my $name = $self->keyword("delete");
ac1e5644 2649 if ($op->private & (OPpSLICE|OPpKVSLICE)) {
34a48b4b
RH
2650 if ($op->flags & OPf_SPECIAL) {
2651 # Deleting from an array, not a hash
3188a821 2652 return $self->maybe_parens_func($name,
34a48b4b
RH
2653 $self->pp_aslice($op->first, 16),
2654 $cx, 16);
2655 }
3188a821 2656 return $self->maybe_parens_func($name,
9d2c6865
SM
2657 $self->pp_hslice($op->first, 16),
2658 $cx, 16);
6e90668e 2659 } else {
34a48b4b
RH
2660 if ($op->flags & OPf_SPECIAL) {
2661 # Deleting from an array, not a hash
3188a821 2662 return $self->maybe_parens_func($name,
34a48b4b
RH
2663 $self->pp_aelem($op->first, 16),
2664 $cx, 16);
2665 }
3188a821 2666 return $self->maybe_parens_func($name,
9d2c6865
SM
2667 $self->pp_helem($op->first, 16),
2668 $cx, 16);
6e90668e 2669 }
6e90668e
SM
2670}
2671
6e90668e
SM
2672sub pp_require {
2673 my $self = shift;
9d2c6865 2674 my($op, $cx) = @_;
d5889722 2675 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
5e7acd25
FC
2676 my $kid = $op->first;
2677 if ($kid->name eq 'const') {
2678 my $priv = $kid->private;
2679 my $sv = $self->const_sv($kid);
2680 my $arg;
2681 if ($priv & OPpCONST_BARE) {
2682 $arg = $sv->PV;
2683 $arg =~ s[/][::]g;
2684 $arg =~ s/\.pm//g;
2685 } elsif ($priv & OPpCONST_NOVER) {
2686 $opname = $self->keyword('no');
2687 $arg = $self->const($sv, 16);
2688 } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) {
2689 $arg = $tmp;
2690 }
2691 if ($arg) {
2692 return $self->maybe_parens("$opname $arg", $cx, 16);
2693 }
2694 }
2695 $self->unop(
41df74e3 2696 $op, $cx,
5e7acd25 2697 $opname,
41df74e3 2698 1, # llafr does not apply
5e7acd25 2699 );
6e90668e
SM
2700}
2701
d989cdac 2702sub pp_scalar {
9d2c6865 2703 my $self = shift;
d9002312 2704 my($op, $cx) = @_;
9d2c6865
SM
2705 my $kid = $op->first;
2706 if (not null $kid->sibling) {
2707 # XXX Was a here-doc
2708 return $self->dquote($op);
2709 }
2710 $self->unop(@_, "scalar");
2711}
2712
2713
6e90668e
SM
2714sub padval {
2715 my $self = shift;
2716 my $targ = shift;
d989cdac 2717 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
6e90668e
SM
2718}
2719
78c72037
NC
2720sub anon_hash_or_list {
2721 my $self = shift;
d9002312 2722 my($op, $cx) = @_;
78c72037
NC
2723
2724 my($pre, $post) = @{{"anonlist" => ["[","]"],
2725 "anonhash" => ["{","}"]}->{$op->name}};
2726 my($expr, @exprs);
2727 $op = $op->first->sibling; # skip pushmark
2728 for (; !null($op); $op = $op->sibling) {
2729 $expr = $self->deparse($op, 6);
2730 push @exprs, $expr;
2731 }
d9002312
SM
2732 if ($pre eq "{" and $cx < 1) {
2733 # Disambiguate that it's not a block
2734 $pre = "+{";
2735 }
78c72037
NC
2736 return $pre . join(", ", @exprs) . $post;
2737}
2738
2739sub pp_anonlist {
d9002312
SM
2740 my $self = shift;
2741 my ($op, $cx) = @_;
78c72037 2742 if ($op->flags & OPf_SPECIAL) {
d9002312 2743 return $self->anon_hash_or_list($op, $cx);
78c72037
NC
2744 }
2745 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2746 return 'XXX';
2747}
2748
2749*pp_anonhash = \&pp_anonlist;
2750
6e90668e
SM
2751sub pp_refgen {
2752 my $self = shift;
9d2c6865 2753 my($op, $cx) = @_;
6e90668e 2754 my $kid = $op->first;
3f872cb9 2755 if ($kid->name eq "null") {
01762542 2756 my $anoncode = $kid = $kid->first;
b77472f9
FC
2757 if ($anoncode->name eq "anonconst") {
2758 $anoncode = $anoncode->first->first->sibling;
2759 }
01762542
FC
2760 if ($anoncode->name eq "anoncode"
2761 or !null($anoncode = $kid->sibling) and
2762 $anoncode->name eq "anoncode") {
2763 return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
3f872cb9
GS
2764 } elsif ($kid->name eq "pushmark") {
2765 my $sib_name = $kid->sibling->name;
c8ec376c 2766 if ($sib_name eq 'entersub') {
c8c62db7
AD
2767 my $text = $self->deparse($kid->sibling, 1);
2768 # Always show parens for \(&func()), but only with -p otherwise
2769 $text = "($text)" if $self->{'parens'}
2770 or $kid->sibling->private & OPpENTERSUB_AMPER;
2771 return "\\$text";
2772 }
2773 }
6e90668e 2774 }
c8ec376c 2775 local $self->{'in_refgen'} = 1;
9d2c6865 2776 $self->pfixop($op, $cx, "\\", 20);
6e90668e
SM
2777}
2778
09d856fb
CK
2779sub e_anoncode {
2780 my ($self, $info) = @_;
2781 my $text = $self->deparse_sub($info->{code});
7741ceed 2782 return $self->keyword("sub") . " $text";
09d856fb
CK
2783}
2784
6e90668e
SM
2785sub pp_srefgen { pp_refgen(@_) }
2786
2787sub pp_readline {
2788 my $self = shift;
9d2c6865 2789 my($op, $cx) = @_;
6e90668e 2790 my $kid = $op->first;
18371617
LM
2791 if (is_scalar($kid)
2792 and $op->flags & OPf_SPECIAL
2793 and $self->deparse($kid, 1) eq 'ARGV')
2794 {
2795 return '<<>>';
65ef2c3e 2796 }
e31885a0 2797 return $self->unop($op, $cx, "readline");
6e90668e
SM
2798}
2799
ad8caead
RGS
2800sub pp_rcatline {
2801 my $self = shift;
2802 my($op) = @_;
d989cdac 2803 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
ad8caead
RGS
2804}
2805
bd0865ec
GS
2806# Unary operators that can occur as pseudo-listops inside double quotes
2807sub dq_unop {
2808 my $self = shift;
2809 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2810 my $kid;
2811 if ($op->flags & OPf_KIDS) {
2812 $kid = $op->first;
2813 # If there's more than one kid, the first is an ex-pushmark.
2814 $kid = $kid->sibling if not null $kid->sibling;
2815 return $self->maybe_parens_unop($name, $kid, $cx);
2816 } else {
d989cdac 2817 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
bd0865ec
GS
2818 }
2819}
2820
2821sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2822sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2823sub pp_uc { dq_unop(@_, "uc") }
2824sub pp_lc { dq_unop(@_, "lc") }
3ed82cfc 2825sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
838f2281 2826sub pp_fc { dq_unop(@_, "fc") }
bd0865ec 2827
6e90668e
SM
2828sub loopex {
2829 my $self = shift;
9d2c6865 2830 my ($op, $cx, $name) = @_;
6e90668e 2831 if (class($op) eq "PVOP") {
41df74e3 2832 $name .= " " . $op->pv;
9d2c6865 2833 } elsif (class($op) eq "OP") {
41df74e3 2834 # no-op
6e90668e 2835 } elsif (class($op) eq "UNOP") {
1eb0b7be 2836 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
df465735
FC
2837 # last foo() is a syntax error.
2838 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
41df74e3 2839 $name .= " $kid";
6e90668e 2840 }
1eb0b7be 2841 return $self->maybe_parens($name, $cx, 7);
6e90668e
SM
2842}
2843
2844sub pp_last { loopex(@_, "last") }
2845sub pp_next { loopex(@_, "next") }
2846sub pp_redo { loopex(@_, "redo") }
2847sub pp_goto { loopex(@_, "goto") }
266da325 2848sub pp_dump { loopex(@_, "CORE::dump") }
6e90668e
SM
2849
2850sub ftst {
2851 my $self = shift;
9d2c6865 2852 my($op, $cx, $name) = @_;
6e90668e 2853 if (class($op) eq "UNOP") {
e38ccfd9 2854 # Genuine '-X' filetests are exempt from the LLAFR, but not
5830412d
FC
2855 # l?stat()
2856 if ($name =~ /^-/) {
2857 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2858 return $self->maybe_parens("$name $kid", $cx, 16);
2859 }
9d2c6865 2860 return $self->maybe_parens_unop($name, $op->first, $cx);
d989cdac 2861 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
9d2c6865 2862 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
6e90668e 2863 } else { # I don't think baseop filetests ever survive ck_ftst, but...
9d2c6865 2864 return $name;
6e90668e 2865 }
6e90668e
SM
2866}
2867
d989cdac
SM
2868sub pp_lstat { ftst(@_, "lstat") }
2869sub pp_stat { ftst(@_, "stat") }
2870sub pp_ftrread { ftst(@_, "-R") }
6e90668e 2871sub pp_ftrwrite { ftst(@_, "-W") }
d989cdac
SM
2872sub pp_ftrexec { ftst(@_, "-X") }
2873sub pp_fteread { ftst(@_, "-r") }
e31885a0 2874sub pp_ftewrite { ftst(@_, "-w") }
d989cdac
SM
2875sub pp_fteexec { ftst(@_, "-x") }
2876sub pp_ftis { ftst(@_, "-e") }
6e90668e
SM
2877sub pp_fteowned { ftst(@_, "-O") }
2878sub pp_ftrowned { ftst(@_, "-o") }
d989cdac
SM
2879sub pp_ftzero { ftst(@_, "-z") }
2880sub pp_ftsize { ftst(@_, "-s") }
2881sub pp_ftmtime { ftst(@_, "-M") }
2882sub pp_ftatime { ftst(@_, "-A") }
2883sub pp_ftctime { ftst(@_, "-C") }
2884sub pp_ftsock { ftst(@_, "-S") }
2885sub pp_ftchr { ftst(@_, "-c") }
2886sub pp_ftblk { ftst(@_, "-b") }
2887sub pp_ftfile { ftst(@_, "-f") }
2888sub pp_ftdir { ftst(@_, "-d") }
2889sub pp_ftpipe { ftst(@_, "-p") }
2890sub pp_ftlink { ftst(@_, "-l") }
2891sub pp_ftsuid { ftst(@_, "-u") }
2892sub pp_ftsgid { ftst(@_, "-g") }
2893sub pp_ftsvtx { ftst(@_, "-k") }
2894sub pp_fttty { ftst(@_, "-t") }
2895sub pp_fttext { ftst(@_, "-T") }
6e90668e
SM
2896sub pp_ftbinary { ftst(@_, "-B") }
2897
a798dbf2 2898sub SWAP_CHILDREN () { 1 }
6e90668e 2899sub ASSIGN () { 2 } # has OP= variant
7013e6ae 2900sub LIST_CONTEXT () { 4 } # Assignment is in list context
6e90668e 2901
9d2c6865
SM
2902my(%left, %right);
2903
2904sub assoc_class {
2905 my $op = shift;
3f872cb9
GS
2906 my $name = $op->name;
2907 if ($name eq "concat" and $op->first->name eq "concat") {
e38ccfd9 2908 # avoid spurious '=' -- see comment in pp_concat
3f872cb9 2909 return "concat";
9d2c6865 2910 }
3f872cb9
GS
2911 if ($name eq "null" and class($op) eq "UNOP"
2912 and $op->first->name =~ /^(and|x?or)$/
9d2c6865
SM
2913 and null $op->first->sibling)
2914 {
2915 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2916 # with a null that's used as the common end point of the two
2917 # flows of control. For precedence purposes, ignore it.
2918 # (COND_EXPRs have these too, but we don't bother with
2919 # their associativity).
2920 return assoc_class($op->first);
2921 }
2922 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2923}
2924
e38ccfd9 2925# Left associative operators, like '+', for which
9d2c6865
SM
2926# $a + $b + $c is equivalent to ($a + $b) + $c
2927
2928BEGIN {
3f872cb9
GS
2929 %left = ('multiply' => 19, 'i_multiply' => 19,
2930 'divide' => 19, 'i_divide' => 19,
2931 'modulo' => 19, 'i_modulo' => 19,
2932 'repeat' => 19,
2933 'add' => 18, 'i_add' => 18,
2934 'subtract' => 18, 'i_subtract' => 18,
2935 'concat' => 18,
2936 'left_shift' => 17, 'right_shift' => 17,
27f31adf 2937 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13,
3f872cb9 2938 'bit_or' => 12, 'bit_xor' => 12,
27f31adf
FC
2939 'sbit_or' => 12, 'sbit_xor' => 12,
2940 'nbit_or' => 12, 'nbit_xor' => 12,
3f872cb9
GS
2941 'and' => 3,
2942 'or' => 2, 'xor' => 2,
9d2c6865
SM
2943 );
2944}
2945
2946sub deparse_binop_left {
2947 my $self = shift;
2948 my($op, $left, $prec) = @_;
58231d39 2949 if ($left{assoc_class($op)} && $left{assoc_class($left)}
9d2c6865
SM
2950 and $left{assoc_class($op)} == $left{assoc_class($left)})
2951 {
2952 return $self->deparse($left, $prec - .00001);
2953 } else {
2954 return $self->deparse($left, $prec);
2955 }
2956}
2957
e38ccfd9 2958# Right associative operators, like '=', for which
9d2c6865
SM
2959# $a = $b = $c is equivalent to $a = ($b = $c)
2960
2961BEGIN {
3f872cb9
GS
2962 %right = ('pow' => 22,
2963 'sassign=' => 7, 'aassign=' => 7,
2964 'multiply=' => 7, 'i_multiply=' => 7,
2965 'divide=' => 7, 'i_divide=' => 7,
2966 'modulo=' => 7, 'i_modulo=' => 7,
9187b6e4 2967 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
3f872cb9
GS
2968 'add=' => 7, 'i_add=' => 7,
2969 'subtract=' => 7, 'i_subtract=' => 7,
2970 'concat=' => 7,
2971 'left_shift=' => 7, 'right_shift=' => 7,
27f31adf
FC
2972 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7,
2973 'nbit_or=' => 7, 'nbit_xor=' => 7,
2974 'sbit_or=' => 7, 'sbit_xor=' => 7,
3f872cb9
GS
2975 'andassign' => 7,
2976 'orassign' => 7,
9d2c6865
SM
2977 );
2978}
2979
2980sub deparse_binop_right {
2981 my $self = shift;
2982 my($op, $right, $prec) = @_;
58231d39 2983 if ($right{assoc_class($op)} && $right{assoc_class($right)}
9d2c6865
SM
2984 and $right{assoc_class($op)} == $right{assoc_class($right)})
2985 {
2986 return $self->deparse($right, $prec - .00001);
2987 } else {
2988 return $self->deparse($right, $prec);
2989 }
2990}
2991
a798dbf2 2992sub binop {
6e90668e 2993 my $self = shift;
9d2c6865 2994 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
a798dbf2
MB
2995 my $left = $op->first;
2996 my $right = $op->last;
9d2c6865
SM
2997 my $eq = "";
2998 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2999 $eq = "=";
3000 $prec = 7;
3001 }
a798dbf2
MB
3002 if ($flags & SWAP_CHILDREN) {
3003 ($left, $right) = ($right, $left);
3004 }
6a861075 3005 my $leftop = $left;
9d2c6865 3006 $left = $self->deparse_binop_left($op, $left, $prec);
90c0eb26 3007 $left = "($left)" if $flags & LIST_CONTEXT
c4874d8a 3008 and $left !~ /^(my|our|local|state|)\s*[\@%\(]/
6a861075
FC
3009 || do {
3010 # Parenthesize if the left argument is a
3011 # lone repeat op.
3012 my $left = $leftop->first->sibling;
3013 $left->name eq 'repeat'
3014 && null($left->sibling);
3015 };
9d2c6865
SM
3016 $right = $self->deparse_binop_right($op, $right, $prec);
3017 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
3018}
3019
3ed82cfc
GS
3020sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
3021sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
3022sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
3023sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
3024sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
3025sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
3026sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
3027sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
3028sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
3029sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
3030sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
3031
3032sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
3033sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
3034sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
3035sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
3036sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
27f31adf
FC
3037*pp_nbit_and = *pp_bit_and;
3038*pp_nbit_or = *pp_bit_or;
3039*pp_nbit_xor = *pp_bit_xor;
3040sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) }
3041sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) }
3042sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) }
9d2c6865
SM
3043
3044sub pp_eq { binop(@_, "==", 14) }
3045sub pp_ne { binop(@_, "!=", 14) }
3046sub pp_lt { binop(@_, "<", 15) }
3047sub pp_gt { binop(@_, ">", 15) }
3048sub pp_ge { binop(@_, ">=", 15) }
3049sub pp_le { binop(@_, "<=", 15) }
3050sub pp_ncmp { binop(@_, "<=>", 14) }
3051sub pp_i_eq { binop(@_, "==", 14) }
3052sub pp_i_ne { binop(@_, "!=", 14) }
3053sub pp_i_lt { binop(@_, "<", 15) }
3054sub pp_i_gt { binop(@_, ">", 15) }
3055sub pp_i_ge { binop(@_, ">=", 15) }
3056sub pp_i_le { binop(@_, "<=", 15) }
d1455c67 3057sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) }
9d2c6865
SM
3058
3059sub pp_seq { binop(@_, "eq", 14) }
3060sub pp_sne { binop(@_, "ne", 14) }
3061sub pp_slt { binop(@_, "lt", 15) }
3062sub pp_sgt { binop(@_, "gt", 15) }
3063sub pp_sge { binop(@_, "ge", 15) }
3064sub pp_sle { binop(@_, "le", 15) }
d1455c67 3065sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) }
9d2c6865 3066
813e85a0
PE
3067sub pp_isa { binop(@_, "isa", 15) }
3068
9d2c6865 3069sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
7013e6ae 3070sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
6e90668e 3071
7896dde7
Z
3072sub pp_smartmatch {
3073 my ($self, $op, $cx) = @_;
3074 if (($op->flags & OPf_SPECIAL) && $self->{expand} < 2) {
3075 return $self->deparse($op->last, $cx);
3076 }
3077 else {
3078 binop(@_, "~~", 14);
3079 }
3080}
3081
e38ccfd9 3082# '.' is special because concats-of-concats are optimized to save copying
6e90668e 3083# by making all but the first concat stacked. The effect is as if the
e38ccfd9 3084# programmer had written '($a . $b) .= $c', except legal.
3ed82cfc
GS
3085sub pp_concat { maybe_targmy(@_, \&real_concat) }
3086sub real_concat {
6e90668e 3087 my $self = shift;
9d2c6865 3088 my($op, $cx) = @_;
6e90668e
SM
3089 my $left = $op->first;
3090 my $right = $op->last;
3091 my $eq = "";
9d2c6865 3092 my $prec = 18;
4b75096e
DM
3093 if (($op->flags & OPf_STACKED) and !($op->private & OPpCONCAT_NESTED)) {
3094 # '.=' rather than optimised '.'
6e90668e 3095 $eq = "=";
9d2c6865 3096 $prec = 7;
6e90668e 3097 }
9d2c6865
SM
3098 $left = $self->deparse_binop_left($op, $left, $prec);
3099 $right = $self->deparse_binop_right($op, $right, $prec);
3100 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
6e90668e
SM
3101}
3102
6402d4ee
FC
3103sub pp_repeat { maybe_targmy(@_, \&repeat) }
3104
e38ccfd9 3105# 'x' is weird when the left arg is a list
6402d4ee 3106sub repeat {
6e90668e 3107 my $self = shift;
9d2c6865 3108 my($op, $cx) = @_;
6e90668e
SM
3109 my $left = $op->first;
3110 my $right = $op->last;
9d2c6865
SM
3111 my $eq = "";
3112 my $prec = 19;
3113 if ($op->flags & OPf_STACKED) {
3114 $eq = "=";
3115 $prec = 7;
3116 }
6e90668e 3117 if (null($right)) { # list repeat; count is inside left-side ex-list
5e462669 3118 # in 5.21.5 and earlier
6e90668e
SM
3119 my $kid = $left->first->sibling; # skip pushmark
3120 my @exprs;
3121 for (; !null($kid->sibling); $kid = $kid->sibling) {
9d2c6865 3122 push @exprs, $self->deparse($kid, 6);
6e90668e
SM
3123 }
3124 $right = $kid;
3125 $left = "(" . join(", ", @exprs). ")";
3126 } else {
5e462669
FC
3127 my $dolist = $op->private & OPpREPEAT_DOLIST;
3128 $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
3129 if ($dolist) {
3130 $left = "($left)";
3131 }
6e90668e 3132 }
9d2c6865
SM
3133 $right = $self->deparse_binop_right($op, $right, $prec);
3134 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
6e90668e
SM
3135}
3136
3137sub range {
3138 my $self = shift;
9d2c6865 3139 my ($op, $cx, $type) = @_;
6e90668e
SM
3140 my $left = $op->first;
3141 my $right = $left->sibling;
9d2c6865
SM
3142 $left = $self->deparse($left, 9);
3143 $right = $self->deparse($right, 9);
3144 return $self->maybe_parens("$left $type $right", $cx, 9);
6e90668e
SM
3145}
3146
3147sub pp_flop {
3148 my $self = shift;
9d2c6865 3149 my($op, $cx) = @_;
6e90668e
SM
3150 my $flip = $op->first;
3151 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
9d2c6865 3152 return $self->range($flip->first, $cx, $type);
6e90668e
SM
3153}
3154
3155# one-line while/until is handled in pp_leave
3156
3157sub logop {
3158 my $self = shift;
9d2c6865 3159 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
6e90668e
SM
3160 my $left = $op->first;
3161 my $right = $op->first->sibling;
7741ceed 3162 $blockname &&= $self->keyword($blockname);
d989cdac 3163 if ($cx < 1 and is_scope($right) and $blockname
58cccf98
SM
3164 and $self->{'expand'} < 7)
3165 { # if ($a) {$b}
9d2c6865
SM
3166 $left = $self->deparse($left, 1);
3167 $right = $self->deparse($right, 0);
3168 return "$blockname ($left) {\n\t$right\n\b}\cK";
d989cdac 3169 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
58cccf98 3170 and $self->{'expand'} < 7) { # $b if $a
9d2c6865
SM
3171 $right = $self->deparse($right, 1);
3172 $left = $self->deparse($left, 1);
3173 return "$right $blockname $left";
3174 } elsif ($cx > $lowprec and $highop) { # $a && $b
3175 $left = $self->deparse_binop_left($op, $left, $highprec);
3176 $right = $self->deparse_binop_right($op, $right, $highprec);
3177 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
3178 } else { # $a and $b
3179 $left = $self->deparse_binop_left($op, $left, $lowprec);
3180 $right = $self->deparse_binop_right($op, $right, $lowprec);
d989cdac 3181 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
9d2c6865
SM
3182 }
3183}
3184
3185sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
f4a44678 3186sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
5b99f273 3187sub pp_dor { logop(@_, "//", 10) }
3ed82cfc
GS
3188
3189# xor is syntactically a logop, but it's really a binop (contrary to
3190# old versions of opcode.pl). Syntax is what matters here.
9d2c6865 3191sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
6e90668e
SM
3192
3193sub logassignop {
3194 my $self = shift;
9d2c6865 3195 my ($op, $cx, $opname) = @_;
6e90668e
SM
3196 my $left = $op->first;
3197 my $right = $op->first->sibling->first; # skip sassign
9d2c6865
SM
3198 $left = $self->deparse($left, 7);
3199 $right = $self->deparse($right, 7);
3200 return $self->maybe_parens("$left $opname $right", $cx, 7);
a798dbf2
MB
3201}
3202
6e90668e 3203sub pp_andassign { logassignop(@_, "&&=") }
c963b151
BD
3204sub pp_orassign { logassignop(@_, "||=") }
3205sub pp_dorassign { logassignop(@_, "//=") }
6e90668e 3206
02b85d3d
Z
3207my %cmpchain_cmpops = (
3208 eq => ["==", 14],
3209 i_eq => ["==", 14],
3210 ne => ["!=", 14],
3211 i_ne => ["!=", 14],
3212 seq => ["eq", 14],
3213 sne => ["ne", 14],
3214 lt => ["<", 15],
3215 i_lt => ["<", 15],
3216 gt => [">", 15],
3217 i_gt => [">", 15],
3218 le => ["<=", 15],
3219 i_le => ["<=", 15],
3220 ge => [">=", 15],
3221 i_ge => [">=", 15],
3222 slt => ["lt", 15],
3223 sgt => ["gt", 15],
3224 sle => ["le", 15],
3225 sge => ["ge", 15],
3226);
3227sub pp_cmpchain_and {
3228 my($self, $op, $cx) = @_;
3229 my($prec, $dep);
3230 while(1) {
3231 my($thiscmp, $rightcond);
3232 if($op->name eq "cmpchain_and") {
3233 $thiscmp = $op->first;
3234 $rightcond = $thiscmp->sibling;
3235 } else {
3236 $thiscmp = $op;
3237 }
3238 my $thiscmptype = $cmpchain_cmpops{$thiscmp->name} // (return "XXX");
3239 if(defined $prec) {
3240 $thiscmptype->[1] == $prec or return "XXX";
3241 $thiscmp->first->name eq "null" &&
3242 !($thiscmp->first->flags & OPf_KIDS)
3243 or return "XXX";
3244 } else {
3245 $prec = $thiscmptype->[1];
3246 $dep = $self->deparse($thiscmp->first, $prec);
3247 }
3248 $dep .= " ".$thiscmptype->[0]." ";
3249 my $operand = $thiscmp->last;
3250 if(defined $rightcond) {
3251 $operand->name eq "cmpchain_dup" or return "XXX";
3252 $operand = $operand->first;
3253 }
3254 $dep .= $self->deparse($operand, $prec);
3255 last unless defined $rightcond;
3256 if($rightcond->name eq "null" && ($rightcond->flags & OPf_KIDS) &&
3257 $rightcond->first->name eq "cmpchain_and") {
3258 $rightcond = $rightcond->first;
3259 }
3260 $op = $rightcond;
3261 }
3262 return $self->maybe_parens($dep, $cx, $prec);
3263}
3264
b89b7257
FC
3265sub rv2gv_or_string {
3266 my($self,$op) = @_;
3267 if ($op->name eq "gv") { # could be open("open") or open("###")
be6cf5cf 3268 my($name,$quoted) =
1db94eeb 3269 $self->stash_variable_name("", $self->gv_or_padgv($op));
be6cf5cf 3270 $quoted ? $name : "*$name";
b89b7257
FC
3271 }
3272 else {
3273 $self->deparse($op, 6);
3274 }
3275}
3276
6e90668e
SM
3277sub listop {
3278 my $self = shift;
9c56d9ea 3279 my($op, $cx, $name, $kid, $nollafr) = @_;
9d2c6865
SM
3280 my(@exprs);
3281 my $parens = ($cx >= 5) || $self->{'parens'};
24fcb59f 3282 $kid ||= $op->first->sibling;
4d8ac5c7
FC
3283 # If there are no arguments, add final parentheses (or parenthesize the
3284 # whole thing if the llafr does not apply) to account for cases like
3285 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
3286 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
3287 if (null $kid) {
3288 return $nollafr
3289 ? $self->maybe_parens($self->keyword($name), $cx, 7)
3290 : $self->keyword($name) . '()' x (7 < $cx);
3291 }
e31885a0 3292 my $first;
4a1ac32e 3293 my $fullname = $self->keyword($name);
b72c97e8 3294 my $proto = prototype("CORE::$name");
bc1cc2c3
DM
3295 if (
3296 ( (defined $proto && $proto =~ /^;?\*/)
3297 || $name eq 'select' # select(F) doesn't have a proto
3298 )
3299 && $kid->name eq "rv2gv"
3300 && !($kid->private & OPpLVAL_INTRO)
3301 ) {
b89b7257 3302 $first = $self->rv2gv_or_string($kid->first);
e31885a0
RH
3303 }
3304 else {
3305 $first = $self->deparse($kid, 6);
3306 }
e99ebc55 3307 if ($name eq "chmod" && $first =~ /^\d+$/) {
a0035eb8 3308 $first = sprintf("%#o", $first);
e99ebc55 3309 }
9c56d9ea
FC
3310 $first = "+$first"
3311 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
9d2c6865
SM
3312 push @exprs, $first;
3313 $kid = $kid->sibling;
564cd6cb
FC
3314 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
3315 && !($kid->private & OPpLVAL_INTRO)) {
b89b7257 3316 push @exprs, $first = $self->rv2gv_or_string($kid->first);
b72c97e8
RGS
3317 $kid = $kid->sibling;
3318 }
9d2c6865
SM
3319 for (; !null($kid); $kid = $kid->sibling) {
3320 push @exprs, $self->deparse($kid, 6);
3321 }
689e417f 3322 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
4a1ac32e
FC
3323 return "$exprs[0] = $fullname"
3324 . ($parens ? "($exprs[0])" : " $exprs[0]");
689e417f 3325 }
327088eb 3326
9c56d9ea
FC
3327 if ($parens && $nollafr) {
3328 return "($fullname " . join(", ", @exprs) . ")";
3329 } elsif ($parens) {
4a1ac32e 3330 return "$fullname(" . join(", ", @exprs) . ")";
9d2c6865 3331 } else {
4a1ac32e 3332 return "$fullname " . join(", ", @exprs);
6e90668e 3333 }
6e90668e 3334}
a798dbf2 3335
6e90668e 3336sub pp_bless { listop(@_, "bless") }
3ed82cfc 3337sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
24fcb59f
FC
3338sub pp_substr {
3339 my ($self,$op,$cx) = @_;
3340 if ($op->private & OPpSUBSTR_REPL_FIRST) {
3341 return
3342 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
3343 . " = "
3344 . $self->deparse($op->first->sibling, 7);
3345 }
3346 maybe_local(@_, listop(@_, "substr"))
3347}
7e8d786b
DM
3348
3349sub pp_index {
3350 # Also handles pp_rindex.
3351 #
3352 # The body of this function includes an unrolled maybe_targmy(),
3353 # since the two parts of that sub's actions need to have have the
3354 # '== -1' bit in between
3355
3356 my($self, $op, $cx) = @_;
3357
3358 my $lex = ($op->private & OPpTARGET_MY);
3359 my $bool = ($op->private & OPpTRUEBOOL);
3360
3361 my $val = $self->listop($op, ($bool ? 14 : $lex ? 7 : $cx), $op->name);
3362
3363 # (index() == -1) has op_eq and op_const optimised away
3364 if ($bool) {
3365 $val .= ($op->private & OPpINDEX_BOOLNEG) ? " == -1" : " != -1";
3366 $val = "($val)" if ($op->flags & OPf_PARENS);
3367 }
3368 if ($lex) {
3369 my $var = $self->padname($op->targ);
3370 $val = $self->maybe_parens("$var = $val", $cx, 7);
3371 }
3372 $val;
3373}
3374
3375sub pp_rindex { pp_index(@_); }
6402d4ee 3376sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
3ed82cfc 3377sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
6e90668e 3378sub pp_formline { listop(@_, "formline") } # see also deparse_format
3ed82cfc 3379sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
6e90668e
SM
3380sub pp_unpack { listop(@_, "unpack") }
3381sub pp_pack { listop(@_, "pack") }
3ed82cfc 3382sub pp_join { maybe_targmy(@_, \&listop, "join") }
6e90668e 3383sub pp_splice { listop(@_, "splice") }
3ed82cfc
GS
3384sub pp_push { maybe_targmy(@_, \&listop, "push") }
3385sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
6e90668e
SM
3386sub pp_reverse { listop(@_, "reverse") }
3387sub pp_warn { listop(@_, "warn") }
3388sub pp_die { listop(@_, "die") }
9c56d9ea 3389sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
6e90668e
SM
3390sub pp_open { listop(@_, "open") }
3391sub pp_pipe_op { listop(@_, "pipe") }
3392sub pp_tie { listop(@_, "tie") }
82bafd27 3393sub pp_binmode { listop(@_, "binmode") }
6e90668e
SM
3394sub pp_dbmopen { listop(@_, "dbmopen") }
3395sub pp_sselect { listop(@_, "select") }
3396sub pp_select { listop(@_, "select") }
3397sub pp_read { listop(@_, "read") }
3398sub pp_sysopen { listop(@_, "sysopen") }
3399sub pp_sysseek { listop(@_, "sysseek") }
3400sub pp_sysread { listop(@_, "sysread") }
3401sub pp_syswrite { listop(@_, "syswrite") }
3402sub pp_send { listop(@_, "send") }
3403sub pp_recv { listop(@_, "recv") }
3404sub pp_seek { listop(@_, "seek") }
6e90668e
SM
3405sub pp_fcntl { listop(@_, "fcntl") }
3406sub pp_ioctl { listop(@_, "ioctl") }
3ed82cfc 3407sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
6e90668e 3408sub pp_socket { listop(@_, "socket") }
5deb1341 3409sub pp_sockpair { listop(@_, "socketpair") }
6e90668e
SM
3410sub pp_bind { listop(@_, "bind") }
3411sub pp_connect { listop(@_, "connect") }
3412sub pp_listen { listop(@_, "listen") }
3413sub pp_accept { listop(@_, "accept") }
3414sub pp_shutdown { listop(@_, "shutdown") }
3415sub pp_gsockopt { listop(@_, "getsockopt") }
3416sub pp_ssockopt { listop(@_, "setsockopt") }
3ed82cfc
GS
3417sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
3418sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
3419sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
3420sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
3421sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
3422sub pp_link { maybe_targmy(@_, \&listop, "link") }
3423sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
3424sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
6e90668e
SM
3425sub pp_open_dir { listop(@_, "opendir") }
3426sub pp_seekdir { listop(@_, "seekdir") }
3ed82cfc 3427sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
9d52f6f3
FC
3428sub pp_system { maybe_targmy(@_, \&indirop, "system") }
3429sub pp_exec { maybe_targmy(@_, \&indirop, "exec") }
3ed82cfc
GS
3430sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
3431sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
3432sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
3433sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
6e90668e
SM
3434sub pp_shmget { listop(@_, "shmget") }
3435sub pp_shmctl { listop(@_, "shmctl") }
3436sub pp_shmread { listop(@_, "shmread") }
3437sub pp_shmwrite { listop(@_, "shmwrite") }
3438sub pp_msgget { listop(@_, "msgget") }
3439sub pp_msgctl { listop(@_, "msgctl") }
3440sub pp_msgsnd { listop(@_, "msgsnd") }
3441sub pp_msgrcv { listop(@_, "msgrcv") }
3442sub pp_semget { listop(@_, "semget") }
3443sub pp_semctl { listop(@_, "semctl") }
3444sub pp_semop { listop(@_, "semop") }
3445sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
3446sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
3447sub pp_gpbynumber { listop(@_, "getprotobynumber") }
3448sub pp_gsbyname { listop(@_, "getservbyname") }
3449sub pp_gsbyport { listop(@_, "getservbyport") }
3450sub pp_syscall { listop(@_, "syscall") }
3451
3452sub pp_glob {
3453 my $self = shift;
9d2c6865 3454 my($op, $cx) = @_;
93860275 3455 my $kid = $op->first->sibling; # skip pushmark
a32fbbd8
FC
3456 my $keyword =
3457 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
fbe6adf2 3458 my $text = $self->deparse($kid, $cx);
18371617
LM
3459 return $cx >= 5 || $self->{'parens'}
3460 ? "$keyword($text)"
3461 : "$keyword $text";
6e90668e
SM
3462}
3463
f5aa8f4e
SM
3464# Truncate is special because OPf_SPECIAL makes a bareword first arg
3465# be a filehandle. This could probably be better fixed in the core
3466# by moving the GV lookup into ck_truc.
3467
3468sub pp_truncate {
3469 my $self = shift;
3470 my($op, $cx) = @_;
3471 my(@exprs);
3472 my $parens = ($cx >= 5) || $self->{'parens'};
3473 my $kid = $op->first->sibling;
acba1d67 3474 my $fh;
f5aa8f4e
SM
3475 if ($op->flags & OPf_SPECIAL) {
3476 # $kid is an OP_CONST
18228111 3477 $fh = $self->const_sv($kid)->PV;
f5aa8f4e
SM
3478 } else {
3479 $fh = $self->deparse($kid, 6);
3480 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
3481 }
3482 my $len = $self->deparse($kid->sibling, 6);
4a1ac32e 3483 my $name = $self->keyword('truncate');
f5aa8f4e 3484 if ($parens) {
4a1ac32e 3485 return "$name($fh, $len)";
f5aa8f4e 3486 } else {
4a1ac32e 3487 return "$name $fh, $len";
f5aa8f4e 3488 }
f5aa8f4e
SM
3489}
3490
6e90668e
SM
3491sub indirop {
3492 my $self = shift;
9d2c6865 3493 my($op, $cx, $name) = @_;
6e90668e 3494 my($expr, @exprs);
521795fe 3495 my $firstkid = my $kid = $op->first->sibling;
6e90668e
SM
3496 my $indir = "";
3497 if ($op->flags & OPf_STACKED) {
3498 $indir = $kid;
3499 $indir = $indir->first; # skip rv2gv
3500 if (is_scope($indir)) {
9d2c6865 3501 $indir = "{" . $self->deparse($indir, 0) . "}";
d989cdac 3502 $indir = "{;}" if $indir eq "{}";
c73811ab
RH
3503 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
3504 $indir = $self->const_sv($indir)->PV;
6e90668e 3505 } else {
9d2c6865 3506 $indir = $self->deparse($indir, 24);
6e90668e
SM
3507 }
3508 $indir = $indir . " ";
3509 $kid = $kid->sibling;
3510 }
7e80da18 3511 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3ac6e0f9 3512 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
7e80da18
RH
3513 : '{$a <=> $b} ';
3514 }
3ac6e0f9 3515 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
7e80da18
RH
3516 $indir = '{$b cmp $a} ';
3517 }
6e90668e 3518 for (; !null($kid); $kid = $kid->sibling) {
521795fe 3519 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
6e90668e
SM
3520 push @exprs, $expr;
3521 }
4a1ac32e 3522 my $name2;
3ac6e0f9 3523 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
4a1ac32e 3524 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3ac6e0f9 3525 }
4a1ac32e 3526 else { $name2 = $self->keyword($name) }
2b6e98cb 3527 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3ac6e0f9 3528 return "$exprs[0] = $name2 $indir $exprs[0]";
2b6e98cb
DM
3529 }
3530
d989cdac 3531 my $args = $indir . join(", ", @exprs);
521795fe 3532 if ($indir ne "" && $name eq "sort") {
d989cdac
SM
3533 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
3534 # give bareword warnings in that case. Therefore if context
3535 # requires, we'll put parens around the outside "(sort f 1, 2,
3536 # 3)". Unfortunately, we'll currently think the parens are
3c4b39be 3537 # necessary more often that they really are, because we don't
d989cdac
SM
3538 # distinguish which side of an assignment we're on.
3539 if ($cx >= 5) {
3ac6e0f9 3540 return "($name2 $args)";
d989cdac 3541 } else {
3ac6e0f9 3542 return "$name2 $args";
d989cdac 3543 }
521795fe
FC
3544 } elsif (
3545 !$indir && $name eq "sort"
ca331985 3546 && !null($op->first->sibling)
521795fe
FC
3547 && $op->first->sibling->name eq 'entersub'
3548 ) {
3549 # We cannot say sort foo(bar), as foo will be interpreted as a
3550 # comparison routine. We have to say sort(...) in that case.
3551 return "$name2($args)";
d989cdac 3552 } else {
9d52f6f3
FC
3553 return length $args
3554 ? $self->maybe_parens_func($name2, $args, $cx, 5)
3555 : $name2 . '()' x (7 < $cx);
d989cdac
SM
3556 }
3557
6e90668e
SM
3558}
3559
3560sub pp_prtf { indirop(@_, "printf") }
3561sub pp_print { indirop(@_, "print") }
9b08e3d3 3562sub pp_say { indirop(@_, "say") }
6e90668e
SM
3563sub pp_sort { indirop(@_, "sort") }
3564
3565sub mapop {
3566 my $self = shift;
9d2c6865 3567 my($op, $cx, $name) = @_;
6e90668e
SM
3568 my($expr, @exprs);
3569 my $kid = $op->first; # this is the (map|grep)start
3570 $kid = $kid->first->sibling; # skip a pushmark
3571 my $code = $kid->first; # skip a null
3572 if (is_scope $code) {
f4a44678 3573 $code = "{" . $self->deparse($code, 0) . "} ";
6e90668e 3574 } else {
6d08f7b3
DM
3575 $code = $self->deparse($code, 24);
3576 $code .= ", " if !null($kid->sibling);
6e90668e
SM
3577 }
3578 $kid = $kid->sibling;
3579 for (; !null($kid); $kid = $kid->sibling) {
9d2c6865 3580 $expr = $self->deparse($kid, 6);
9a58b761 3581 push @exprs, $expr if defined $expr;
6e90668e 3582 }
3188a821
FC
3583 return $self->maybe_parens_func($self->keyword($name),
3584 $code . join(", ", @exprs), $cx, 5);
6e90668e
SM
3585}
3586
d989cdac
SM
3587sub pp_mapwhile { mapop(@_, "map") }
3588sub pp_grepwhile { mapop(@_, "grep") }
11e09183
SP
3589sub pp_mapstart { baseop(@_, "map") }
3590sub pp_grepstart { baseop(@_, "grep") }
6e90668e 3591
12cea2fa
FC
3592my %uses_intro;
3593BEGIN {
3594 @uses_intro{
3595 eval { require B::Op_private }
e58dedd3 3596 ? @{$B::Op_private::ops_using{OPpLVAL_INTRO}}
12cea2fa
FC
3597 : qw(gvsv rv2sv rv2hv rv2gv rv2av aelem helem aslice
3598 hslice delete padsv padav padhv enteriter entersub padrange
3599 pushmark cond_expr refassign list)
3600 } = ();
bba4f5ff 3601 delete @uses_intro{qw( lvref lvrefslice lvavref entersub )};
12cea2fa
FC
3602}
3603
82ab48fa 3604
4a4aa6e0
DM
3605# Look for a my/state attribute declaration in a list or ex-list.
3606# Returns undef if not found, 'my($x, @a) :Foo(bar)' etc otherwise.
82ab48fa
DM
3607#
3608# There are three basic tree structs that are expected:
3609#
3610# my $x :foo;
3611# <1> ex-list vK/LVINTRO ->c
3612# <0> ex-pushmark v ->3
3613# <1> entersub[t2] vKRS*/TARG ->b
3614# ....
3615# <0> padsv[$x:64,65] vM/LVINTRO ->c
3616#
3617# my @a :foo;
3618# my %h :foo;
3619#
3620# <1> ex-list vK ->c
3621# <0> ex-pushmark v ->3
3622# <0> padav[@a:64,65] vM/LVINTRO ->4
3623# <1> entersub[t2] vKRS*/TARG ->c
3624# ....
3625#
3626# my ($x,@a,%h) :foo;
3627#
3628# <;> nextstate(main 64 -e:1) v:{ ->3
3629# <@> list vKP ->w
3630# <0> pushmark vM/LVINTRO ->4
3631# <0> padsv[$x:64,65] vM/LVINTRO ->5
3632# <0> padav[@a:64,65] vM/LVINTRO ->6
3633# <0> padhv[%h:64,65] vM/LVINTRO ->7
3634# <1> entersub[t4] vKRS*/TARG ->f
3635# ....
3636# <1> entersub[t5] vKRS*/TARG ->n
3637# ....
3638# <1> entersub[t6] vKRS*/TARG ->v
3639# ....
3640# where the entersub in all cases looks like
3641# <1> entersub[t2] vKRS*/TARG ->c
3642# <0> pushmark s ->5
3643# <$> const[PV "attributes"] sM ->6
3644# <$> const[PV "main"] sM ->7
3645# <1> srefgen sKM/1 ->9
3646# <1> ex-list lKRM ->8
3647# <0> padsv[@a:64,65] sRM ->8
3648# <$> const[PV "foo"] sM ->a
3649# <.> method_named[PV "import"] ->b
3650
4a4aa6e0 3651sub maybe_var_attr {
82ab48fa
DM
3652 my ($self, $op, $cx) = @_;
3653
3654 my $kid = $op->first->sibling; # skip pushmark
3655 return if class($kid) eq 'NULL';
3656
3657 my $lop;
3658 my $type;
3659
3660 # Extract out all the pad ops and entersub ops into
3661 # @padops and @entersubops. Return if anything else seen.
3662 # Also determine what class (if any) all the pad vars belong to
3663 my $class;
4a4aa6e0 3664 my $decl; # 'my' or 'state'
82ab48fa
DM
3665 my (@padops, @entersubops);
3666 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3667 my $lopname = $lop->name;
3668 my $loppriv = $lop->private;
3669 if ($lopname =~ /^pad[sah]v$/) {
3670 return unless $loppriv & OPpLVAL_INTRO;
82ab48fa
DM
3671
3672 my $padname = $self->padname_sv($lop->targ);
3673 my $thisclass = ($padname->FLAGS & SVpad_TYPED)
3674 ? $padname->SvSTASH->NAME : 'main';
3675
3676 # all pad vars must be in the same class
3677 $class //= $thisclass;
3678 return unless $thisclass eq $class;
3679
4a4aa6e0
DM
3680 # all pad vars must be the same sort of declaration
3681 # (all my, all state, etc)
3682 my $this = ($loppriv & OPpPAD_STATE) ? 'state' : 'my';
3683 if (defined $decl) {
3684 return unless $this eq $decl;
3685 }
3686 $decl = $this;
3687
82ab48fa
DM
3688 push @padops, $lop;
3689 }
3690 elsif ($lopname eq 'entersub') {
3691 push @entersubops, $lop;
3692 }
3693 else {
3694 return;
3695 }
3696 }
3697
3698 return unless @padops && @padops == @entersubops;
3699
3700 # there should be a balance: each padop has a corresponding
3701 # 'attributes'->import() method call, in the same order.
3702
3703 my @varnames;
3704 my $attr_text;
3705
3706 for my $i (0..$#padops) {
3707 my $padop = $padops[$i];
3708 my $esop = $entersubops[$i];
3709
3710 push @varnames, $self->padname($padop->targ);
3711
3712 return unless ($esop->flags & OPf_KIDS);
3713
3714 my $kid = $esop->first;
3715 return unless $kid->type == OP_PUSHMARK;
3716
3717 $kid = $kid->sibling;
3718 return unless $$kid && $kid->type == OP_CONST;
3719 return unless $self->const_sv($kid)->PV eq 'attributes';
3720
3721 $kid = $kid->sibling;
3722 return unless $$kid && $kid->type == OP_CONST; # __PACKAGE__
3723
3724 $kid = $kid->sibling;
3725 return unless $$kid
3726 && $kid->name eq "srefgen"
3727 && ($kid->flags & OPf_KIDS)
3728 && ($kid->first->flags & OPf_KIDS)
3729 && $kid->first->first->name =~ /^pad[sah]v$/
3730 && $kid->first->first->targ == $padop->targ;
3731
3732 $kid = $kid->sibling;
3733 my @attr;
3734 while ($$kid) {
3735 last if ($kid->type != OP_CONST);
3736 push @attr, $self->const_sv($kid)->PV;
3737 $kid = $kid->sibling;
3738 }
3739 return unless @attr;
3740 my $thisattr = ":" . join(' ', @attr);
3741 $attr_text //= $thisattr;
3742 # all import calls must have the same list of attributes
3743 return unless $attr_text eq $thisattr;
3744
3745 return unless $kid->name eq 'method_named';
3746 return unless $self->meth_sv($kid)->PV eq 'import';
3747
3748 $kid = $kid->sibling;
3749 return if $$kid;
3750 }
3751
4a4aa6e0 3752 my $res = $decl;
82ab48fa
DM
3753 $res .= " $class " if $class ne 'main';
3754 $res .=
3755 (@varnames > 1)
3756 ? "(" . join(', ', @varnames) . ')'
3757 : " $varnames[0]";
3758
3759 return "$res $attr_text";
3760}
3761
3762
6e90668e
SM
3763sub pp_list {
3764 my $self = shift;
9d2c6865 3765 my($op, $cx) = @_;
82ab48fa
DM
3766
3767 {
3768 # might be my ($s,@a,%h) :Foo(bar);
4a4aa6e0 3769 my $my_attr = maybe_var_attr($self, $op, $cx);
82ab48fa
DM
3770 return $my_attr if defined $my_attr;
3771 }
3772
6e90668e
SM
3773 my($expr, @exprs);
3774 my $kid = $op->first->sibling; # skip pushmark
958ed56b 3775 return '' if class($kid) eq 'NULL';
6e90668e 3776 my $lop;
3462b4ac 3777 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
56cd2ef8 3778 my $type;
6e90668e 3779 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3b4e80b8 3780 my $lopname = $lop->name;
5f4d8496 3781 my $loppriv = $lop->private;
56cd2ef8 3782 my $newtype;
12cea2fa 3783 if ($lopname =~ /^pad[ash]v$/ && $loppriv & OPpLVAL_INTRO) {
5f4d8496
FC
3784 if ($loppriv & OPpPAD_STATE) { # state()
3785 ($local = "", last) if $local !~ /^(?:either|state)$/;
3462b4ac
RGS
3786 $local = "state";
3787 } else { # my()
5f4d8496 3788 ($local = "", last) if $local !~ /^(?:either|my)$/;
3462b4ac
RGS
3789 $local = "my";
3790 }
56cd2ef8
FC
3791 my $padname = $self->padname_sv($lop->targ);
3792 if ($padname->FLAGS & SVpad_TYPED) {
3793 $newtype = $padname->SvSTASH->NAME;
3794 }
3b4e80b8 3795 } elsif ($lopname =~ /^(?:gv|rv2)([ash])v$/
5f4d8496 3796 && $loppriv & OPpOUR_INTRO
40ced2f4
FC
3797 or $lopname eq "null" && class($lop) eq 'UNOP'
3798 && $lop->first->name eq "gvsv"
b8e103fc 3799 && $lop->first->private & OPpOUR_INTRO) { # our()
5f4d8496
FC
3800 my $newlocal = "local " x !!($loppriv & OPpLVAL_INTRO) . "our";
3801 ($local = "", last)
3802 if $local ne 'either' && $local ne $newlocal;
3803 $local = $newlocal;
56cd2ef8
FC
3804 my $funny = !$1 || $1 eq 's' ? '$' : $1 eq 'a' ? '@' : '%';
3805 if (my $t = $self->find_our_type(
3806 $funny . $self->gv_or_padgv($lop->first)->NAME
3807 )) {
3808 $newtype = $t;
3809 }
12cea2fa
FC
3810 } elsif ($lopname ne 'undef'
3811 and !($loppriv & OPpLVAL_INTRO)
3812 || !exists $uses_intro{$lopname eq 'null'
3813 ? substr B::ppname($lop->targ), 3
3814 : $lopname})
3815 {
3816 $local = ""; # or not
3817 last;
3818 } elsif ($lopname ne "undef")
3ac6e0f9
RGS
3819 {
3820 # local()
5f4d8496 3821 ($local = "", last) if $local !~ /^(?:either|local)$/;
6e90668e
SM
3822 $local = "local";
3823 }
56cd2ef8
FC
3824 if (defined $type && defined $newtype && $newtype ne $type) {
3825 $local = '';
3826 last;
3827 }
3828 $type = $newtype;
6e90668e
SM
3829 }
3830 $local = "" if $local eq "either"; # no point if it's all undefs
5f4d8496 3831 $local &&= join ' ', map $self->keyword($_), split / /, $local;
56cd2ef8 3832 $local .= " $type " if $local && length $type;
f5aa8f4e 3833 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
6e90668e
SM
3834 for (; !null($kid); $kid = $kid->sibling) {
3835 if ($local) {
3f872cb9 3836 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
6e90668e
SM
3837 $lop = $kid->first;
3838 } else {
3839 $lop = $kid;
3840 }
3841 $self->{'avoid_local'}{$$lop}++;
9d2c6865 3842 $expr = $self->deparse($kid, 6);
6e90668e
SM
3843 delete $self->{'avoid_local'}{$$lop};
3844 } else {
9d2c6865 3845 $expr = $self->deparse($kid, 6);
6e90668e
SM
3846 }
3847 push @exprs, $expr;
3848 }
9d2c6865 3849 if ($local) {
c4874d8a
DM
3850 if (@exprs == 1 && ($local eq 'state' || $local eq 'CORE::state')) {
3851 # 'state @a = ...' is legal, while 'state(@a) = ...' currently isn't
3852 return "$local $exprs[0]";
3853 }
9d2c6865
SM
3854 return "$local(" . join(", ", @exprs) . ")";
3855 } else {
3856 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
3857 }
6e90668e
SM
3858}
3859
6f611a1a
GS
3860sub is_ifelse_cont {
3861 my $op = shift;
3862 return ($op->name eq "null" and class($op) eq "UNOP"
3863 and $op->first->name =~ /^(and|cond_expr)$/
3864 and is_scope($op->first->first->sibling));
3865}
3866
6e90668e
SM
3867sub pp_cond_expr {
3868 my $self = shift;
9d2c6865 3869 my($op, $cx) = @_;
6e90668e
SM
3870 my $cond = $op->first;
3871 my $true = $cond->sibling;
3872 my $false = $true->sibling;
9d2c6865 3873 my $cuddle = $self->{'cuddle'};
d989cdac 3874 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
58cccf98
SM
3875 (is_scope($false) || is_ifelse_cont($false))
3876 and $self->{'expand'} < 7) {
f5aa8f4e 3877 $cond = $self->deparse($cond, 8);
cfaba469 3878 $true = $self->deparse($true, 6);
9d2c6865
SM
3879 $false = $self->deparse($false, 8);
3880 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
6f611a1a
GS
3881 }
3882
f5aa8f4e 3883 $cond = $self->deparse($cond, 1);
d989cdac 3884 $true = $self->deparse($true, 0);
7741ceed 3885 my $head = $self->keyword("if") . " ($cond) {\n\t$true\n\b}";
6f611a1a 3886 my @elsifs;
7741ceed 3887 my $elsif;
6f611a1a
GS
3888 while (!null($false) and is_ifelse_cont($false)) {
3889 my $newop = $false->first;
3890 my $newcond = $newop->first;
3891 my $newtrue = $newcond->sibling;
3892 $false = $newtrue->sibling; # last in chain is OP_AND => no else
7ecdd211
PJ
3893 if ($newcond->name eq "lineseq")
3894 {
3895 # lineseq to ensure correct line numbers in elsif()
3896 # Bug #37302 fixed by change #33710.
3897 $newcond = $newcond->first->sibling;
3898 }
6f611a1a
GS
3899 $newcond = $self->deparse($newcond, 1);
3900 $newtrue = $self->deparse($newtrue, 0);
7741ceed
FC
3901 $elsif ||= $self->keyword("elsif");
3902 push @elsifs, "$elsif ($newcond) {\n\t$newtrue\n\b}";
6f611a1a 3903 }
d989cdac 3904 if (!null($false)) {
7741ceed 3905 $false = $cuddle . $self->keyword("else") . " {\n\t" .
6f611a1a
GS
3906 $self->deparse($false, 0) . "\n\b}\cK";
3907 } else {
3908 $false = "\cK";
6e90668e 3909 }
d989cdac 3910 return $head . join($cuddle, "", @elsifs) . $false;
6e90668e
SM
3911}
3912
95562366
NC
3913sub pp_once {
3914 my ($self, $op, $cx) = @_;
3915 my $cond = $op->first;
3916 my $true = $cond->sibling;
3917
a1b22abd
FC
3918 my $ret = $self->deparse($true, $cx);
3919 $ret =~ s/^(\(?)\$/$1 . $self->keyword("state") . ' $'/e;
3920 $ret;
95562366
NC
3921}
3922
58cccf98 3923sub loop_common {
6e90668e 3924 my $self = shift;
58cccf98 3925 my($op, $cx, $init) = @_;
6e90668e
SM
3926 my $enter = $op->first;
3927 my $kid = $enter->sibling;
0ced6c29
RGS
3928 local(@$self{qw'curstash warnings hints hinthash'})
3929 = @$self{qw'curstash warnings hints hinthash'};
6e90668e 3930 my $head = "";
9d2c6865 3931 my $bare = 0;
58cccf98
SM
3932 my $body;
3933 my $cond = undef;
22584011 3934 my $name;
d989cdac 3935 if ($kid->name eq "lineseq") { # bare or infinite loop
241416b8 3936 if ($kid->last->name eq "unstack") { # infinite
e99ebc55 3937 $head = "while (1) "; # Can't use for(;;) if there's a continue
58cccf98 3938 $cond = "";
9d2c6865
SM
3939 } else {
3940 $bare = 1;
6e90668e 3941 }
58cccf98 3942 $body = $kid;
3f872cb9 3943 } elsif ($enter->name eq "enteriter") { # foreach
6e90668e
SM
3944 my $ary = $enter->first->sibling; # first was pushmark
3945 my $var = $ary->sibling;
36d57d93
RGS
3946 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
3947 # "reverse" was optimised away
aae53c41 3948 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
36d57d93 3949 } elsif ($enter->flags & OPf_STACKED
f5aa8f4e
SM
3950 and not null $ary->first->sibling->sibling)
3951 {
d7f5b6da
SM
3952 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
3953 $self->deparse($ary->first->sibling->sibling, 9);
d8d95777
GA
3954 } else {
3955 $ary = $self->deparse($ary, 1);
3956 }
bf6e71ff
NC
3957 my $iter_targ = $kid->first->first->targ;
3958 if ($iter_targ) {
3959 # for my ($foo, $bar) () stores the count (less 1) in the targ of
3960 # the ITER op.
3961 my @vars;
3962 my $targ = $enter->targ;
3963 while ($iter_targ-- >= 0) {
3964 push @vars, $self->padname_sv($targ)->PVX;
3965 ++$targ;
3966 }
3967 $var = 'my (' . join(', ', @vars) . ')';
3968 } elsif (null $var) {
dacd2ca7 3969 $var = $self->pp_padsv($enter, 1, 1);
3f872cb9 3970 } elsif ($var->name eq "rv2gv") {
9d2c6865 3971 $var = $self->pp_rv2sv($var, 1);
241416b8
DM
3972 if ($enter->private & OPpOUR_INTRO) {
3973 # our declarations don't have package names
3974 $var =~ s/^(.).*::/$1/;
3975 $var = "our $var";
3976 }
3f872cb9 3977 } elsif ($var->name eq "gv") {
9d2c6865 3978 $var = "\$" . $self->deparse($var, 1);
9187b6e4
FC
3979 } else {
3980 $var = $self->deparse($var, 1);
6e90668e 3981 }
58cccf98 3982 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
afb60448 3983 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
cf24a840
SM
3984 confess unless $var eq '$_';
3985 $body = $body->first;
7741ceed
FC
3986 return $self->deparse($body, 2) . " "
3987 . $self->keyword("foreach") . " ($ary)";
cf24a840
SM
3988 }
3989 $head = "foreach $var ($ary) ";
3f872cb9 3990 } elsif ($kid->name eq "null") { # while/until
6e90668e 3991 $kid = $kid->first;
22584011
FC
3992 $name = {"and" => "while", "or" => "until"}->{$kid->name};
3993 $cond = $kid->first;
58cccf98 3994 $body = $kid->first->sibling;
3f872cb9 3995 } elsif ($kid->name eq "stub") { # bare and empty
9d2c6865 3996 return "{;}"; # {} could be a hashref
6e90668e 3997 }
58cccf98 3998 # If there isn't a continue block, then the next pointer for the loop
241416b8 3999 # will point to the unstack, which is kid's last child, except
58cccf98 4000 # in a bare loop, when it will point to the leaveloop. When neither of
241416b8 4001 # these conditions hold, then the second-to-last child is the continue
58cccf98
SM
4002 # block (or the last in a bare loop).
4003 my $cont_start = $enter->nextop;
4004 my $cont;
22584011
FC
4005 my $precond;
4006 my $postcond;
241416b8 4007 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
58cccf98
SM
4008 if ($bare) {
4009 $cont = $body->last;
4010 } else {
4011 $cont = $body->first;
241416b8 4012 while (!null($cont->sibling->sibling)) {
58cccf98
SM
4013 $cont = $cont->sibling;
4014 }
4015 }
4016 my $state = $body->first;
4017 my $cuddle = $self->{'cuddle'};
4018 my @states;
4019 for (; $$state != $$cont; $state = $state->sibling) {
4020 push @states, $state;
4021 }
93a8ff62 4022 $body = $self->lineseq(undef, 0, @states);
58cccf98 4023 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
22584011
FC
4024 $precond = "for ($init; ";
4025 $postcond = "; " . $self->deparse($cont, 1) .") ";
58cccf98
SM
4026 $cont = "\cK";
4027 } else {
4028 $cont = $cuddle . "continue {\n\t" .
4029 $self->deparse($cont, 0) . "\n\b}\cK";
6e90668e 4030 }
6e90668e 4031 } else {
7a9b44b9 4032 return "" if !defined $body;
c73811ab 4033 if (length $init) {
22584011
FC
4034 $precond = "for ($init; ";
4035 $postcond = ";) ";
c73811ab 4036 }
9d2c6865 4037 $cont = "\cK";
58cccf98 4038 $body = $self->deparse($body, 0);
6e90668e 4039 }
22584011 4040 if ($precond) { # for(;;)
88a758b5
FC
4041 $cond &&= $name eq 'until'
4042 ? listop($self, undef, 1, "not", $cond->first)
4043 : $self->deparse($cond, 1);
22584011
FC
4044 $head = "$precond$cond$postcond";
4045 }
4046 if ($name && !$head) {
4047 ref $cond and $cond = $self->deparse($cond, 1);
4048 $head = "$name ($cond) ";
4049 }
7741ceed 4050 $head =~ s/^(for(?:each)?|while|until)/$self->keyword($1)/e;
ce4e655d 4051 $body =~ s/;?$/;\n/;
34a48b4b
RH
4052
4053 return $head . "{\n\t" . $body . "\b}" . $cont;
58cccf98
SM
4054}
4055
09d856fb 4056sub pp_leaveloop { shift->loop_common(@_, "") }
58cccf98
SM
4057
4058sub for_loop {
4059 my $self = shift;
4060 my($op, $cx) = @_;
4061 my $init = $self->deparse($op, 1);
eae48c89
Z
4062 my $s = $op->sibling;
4063 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
4064 return $self->loop_common($ll, $cx, $init);
6e90668e
SM
4065}
4066
4067sub pp_leavetry {
4068 my $self = shift;
9d2c6865 4069 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
bd0865ec 4070}
6e90668e 4071
683e0651
PE
4072sub pp_leavetrycatch {
4073 my $self = shift;
4074 my ($op) = @_;
4075
4076 # Expect that the first three kids should be (entertrycatch, poptry, catch)
4077 my $entertrycatch = $op->first;
4078 $entertrycatch->name eq "entertrycatch" or die "Expected entertrycatch as first child of leavetrycatch";
4079
4080 my $tryblock = $entertrycatch->sibling;
4081 $tryblock->name eq "poptry" or die "Expected poptry as second child of leavetrycatch";
4082
4083 my $catch = $tryblock->sibling;
4084 $catch->name eq "catch" or die "Expected catch as third child of leavetrycatch";
4085
4086 my $catchblock = $catch->first->sibling;
846e32eb
MH
4087 my $name = $catchblock->name;
4088 unless ($name eq "scope" || $name eq "leave") {
4089 die "Expected scope or leave as second child of catch, got $name instead";
4090 }
683e0651
PE
4091
4092 my $trycode = scopeop(0, $self, $tryblock);
4093 my $catchvar = $self->padname($catch->targ);
846e32eb
MH
4094 my $catchcode = $name eq 'scope' ? scopeop(0, $self, $catchblock)
4095 : scopeop(1, $self, $catchblock);
683e0651
PE
4096
4097 return "try {\n\t$trycode\n\b}\n" .
4098 "catch($catchvar) {\n\t$catchcode\n\b}\cK";
4099}
4100
7d3c8a68
S
4101sub _op_is_or_was {
4102 my ($op, $expect_type) = @_;
4103 my $type = $op->type;
4104 return($type == $expect_type
4105 || ($type == OP_NULL && $op->targ == $expect_type));
4106}
4107
a798dbf2 4108sub pp_null {
34b54951 4109 my($self, $op, $cx) = @_;
82ab48fa
DM
4110
4111 # might be 'my $s :Foo(bar);'
4112 if ($op->targ == OP_LIST) {
4a4aa6e0 4113 my $my_attr = maybe_var_attr($self, $op, $cx);
82ab48fa
DM
4114 return $my_attr if defined $my_attr;
4115 }
4116
6e90668e 4117 if (class($op) eq "OP") {
f4a44678
SM
4118 # old value is lost
4119 return $self->{'ex_const'} if $op->targ == OP_CONST;
619dadb5 4120 } elsif (class ($op) eq "COP") {
34b54951 4121 return &pp_nextstate;
7d3c8a68
S
4122 } elsif ($op->first->name eq 'pushmark'
4123 or $op->first->name eq 'null'
4124 && $op->first->targ == OP_PUSHMARK
4125 && _op_is_or_was($op, OP_LIST)) {
9d2c6865 4126 return $self->pp_list($op, $cx);
3f872cb9 4127 } elsif ($op->first->name eq "enter") {
9d2c6865 4128 return $self->pp_leave($op, $cx);
31c6271a
RD
4129 } elsif ($op->first->name eq "leave") {
4130 return $self->pp_leave($op->first, $cx);
4131 } elsif ($op->first->name eq "scope") {
4132 return $self->pp_scope($op->first, $cx);
bd0865ec 4133 } elsif ($op->targ == OP_STRINGIFY) {
6f611a1a 4134 return $self->dquote($op, $cx);
f4002a4b
FC
4135 } elsif ($op->targ == OP_GLOB) {
4136 return $self->pp_glob(
4137 $op->first # entersub
4138 ->first # ex-list
4139 ->first # pushmark
4140 ->sibling, # glob
4141 $cx
4142 );
6e90668e 4143 } elsif (!null($op->first->sibling) and
3f872cb9 4144 $op->first->sibling->name eq "readline" and
6e90668e 4145 $op->first->sibling->flags & OPf_STACKED) {
9d2c6865
SM
4146 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
4147 . $self->deparse($op->first->sibling, 7),
4148 $cx, 7);
6e90668e 4149 } elsif (!null($op->first->sibling) and
d52196e1 4150 $op->first->sibling->name =~ /^transr?\z/ and
6e90668e 4151 $op->first->sibling->flags & OPf_STACKED) {
9d2c6865
SM
4152 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
4153 . $self->deparse($op->first->sibling, 20),
4154 $cx, 20);
d989cdac 4155 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3188a821
FC
4156 return ($self->lex_in_scope("&do") ? "CORE::do" : "do")
4157 . " {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
ad8caead
RGS
4158 } elsif (!null($op->first->sibling) and
4159 $op->first->sibling->name eq "null" and
4160 class($op->first->sibling) eq "UNOP" and
4161 $op->first->sibling->first->flags & OPf_STACKED and
4162 $op->first->sibling->first->name eq "rcatline") {
4163 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
4164 . $self->deparse($op->first->sibling, 18),
4165 $cx, 18);
6e90668e 4166 } else {
9d2c6865 4167 return $self->deparse($op->first, $cx);
6e90668e 4168 }
a798dbf2
MB
4169}
4170
6e90668e
SM
4171sub padname {
4172 my $self = shift;
4173 my $targ = shift;
68223ea3 4174 return $self->padname_sv($targ)->PVX;
6e90668e
SM
4175}
4176
4177sub padany {
4178 my $self = shift;
4179 my $op = shift;
4180 return substr($self->padname($op->targ), 1); # skip $/@/%
4181}
4182
4183sub pp_padsv {
4184 my $self = shift;
4da9a2ca 4185 my($op, $cx, $forbid_parens) = @_;
8db6f480
FC
4186 my $targ = $op->targ;
4187 return $self->maybe_my($op, $cx, $self->padname($targ),
4188 $self->padname_sv($targ),
4da9a2ca 4189 $forbid_parens);
6e90668e
SM
4190}
4191
4192sub pp_padav { pp_padsv(@_) }
748f2c65 4193
ed34dca8
DM
4194# prepend 'keys' where its been optimised away, with suitable handling
4195# of CORE:: and parens
4196
4197sub add_keys_keyword {
4198 my ($self, $str, $cx) = @_;
4199 $str = $self->maybe_parens($str, $cx, 16);
4200 # 'keys %h' versus 'keys(%h)'
4201 $str = " $str" unless $str =~ /^\(/;
4202 return $self->keyword("keys") . $str;
4203}
4204
748f2c65 4205sub pp_padhv {
ed34dca8
DM
4206 my ($self, $op, $cx) = @_;
4207 my $str = pp_padsv(@_);
6f2dc9a6
DM
4208 # with OPpPADHV_ISKEYS the keys op is optimised away, except
4209 # in scalar context the old op is kept (but not executed) so its targ
4210 # can be used.
ed34dca8
DM
4211 if ( ($op->private & OPpPADHV_ISKEYS)
4212 && !(($op->flags & OPf_WANT) == OPf_WANT_SCALAR))
4213 {
4214 $str = $self->add_keys_keyword($str, $cx);
4215 }
4216 $str;
748f2c65 4217}
6e90668e 4218
6f611a1a 4219sub gv_or_padgv {
18228111
GS
4220 my $self = shift;
4221 my $op = shift;
6f611a1a
GS
4222 if (class($op) eq "PADOP") {
4223 return $self->padval($op->padix);
4224 } else { # class($op) eq "SVOP"
4225 return $op->gv;
18228111 4226 }
18228111
GS
4227}
4228
6e90668e
SM
4229sub pp_gvsv {
4230 my $self = shift;
9d2c6865 4231 my($op, $cx) = @_;
6f611a1a 4232 my $gv = $self->gv_or_padgv($op);
8510e997 4233 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
bb8996b8 4234 $self->gv_name($gv), $cx));
6e90668e
SM
4235}
4236
4237sub pp_gv {
4238 my $self = shift;
9d2c6865 4239 my($op, $cx) = @_;
6f611a1a 4240 my $gv = $self->gv_or_padgv($op);
dd666160 4241 return $self->maybe_qualify("", $self->gv_name($gv));
6e90668e
SM
4242}
4243
93bad3fd
NC
4244sub pp_aelemfast_lex {
4245 my $self = shift;
4246 my($op, $cx) = @_;
4247 my $name = $self->padname($op->targ);
4248 $name =~ s/^@/\$/;
b024352e
DM
4249 my $i = $op->private;
4250 $i -= 256 if $i > 127;
8a38acca 4251 return $name . "[$i]";
93bad3fd
NC
4252}
4253
6e90668e
SM
4254sub pp_aelemfast {
4255 my $self = shift;
9d2c6865 4256 my($op, $cx) = @_;
93bad3fd
NC
4257 # optimised PADAV, pre 5.15
4258 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
ce4e655d 4259
93bad3fd 4260 my $gv = $self->gv_or_padgv($op);
be6cf5cf
FC
4261 my($name,$quoted) = $self->stash_variable_name('@',$gv);
4262 $name = $quoted ? "$name->" : '$' . $name;
b024352e
DM
4263 my $i = $op->private;
4264 $i -= 256 if $i > 127;
8a38acca 4265 return $name . "[$i]";
6e90668e
SM
4266}
4267
4268sub rv2x {
4269 my $self = shift;
9d2c6865 4270 my($op, $cx, $type) = @_;
90c0eb26
RH
4271
4272 if (class($op) eq 'NULL' || !$op->can("first")) {
ff97752d 4273 carp("Unexpected op in pp_rv2x");
90c0eb26
RH
4274 return 'XXX';
4275 }
6e90668e 4276 my $kid = $op->first;
d989cdac 4277 if ($kid->name eq "gv") {
dd666160
Z
4278 return $self->stash_variable($type,
4279 $self->gv_name($self->gv_or_padgv($kid)), $cx);
d989cdac
SM
4280 } elsif (is_scalar $kid) {
4281 my $str = $self->deparse($kid, 0);
4282 if ($str =~ /^\$([^\w\d])\z/) {
4283 # "$$+" isn't a legal way to write the scalar dereference
4284 # of $+, since the lexer can't tell you aren't trying to
4285 # do something like "$$ + 1" to get one more than your
4286 # PID. Either "${$+}" or "$${+}" are workable
4287 # disambiguations, but if the programmer did the former,
4288 # they'd be in the "else" clause below rather than here.
4289 # It's not clear if this should somehow be unified with
4290 # the code in dq and re_dq that also adds lexer
4291 # disambiguation braces.
4292 $str = '$' . "{$1}"; #'
4293 }
4294 return $type . $str;
4295 } else {
4296 return $type . "{" . $self->deparse($kid, 0) . "}";
4297 }
6e90668e
SM
4298}
4299
4300sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
6e90668e
SM
4301sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
4302
748f2c65 4303sub pp_rv2hv {
ed34dca8
DM
4304 my ($self, $op, $cx) = @_;
4305 my $str = rv2x(@_, "%");
4306 if ($op->private & OPpRV2HV_ISKEYS) {
4307 $str = $self->add_keys_keyword($str, $cx);
4308 }
4309 return maybe_local(@_, $str);
748f2c65
DM
4310}
4311
6e90668e
SM
4312# skip rv2av
4313sub pp_av2arylen {
4314 my $self = shift;
9d2c6865 4315 my($op, $cx) = @_;
89a395f4
DM
4316 my $kid = $op->first;
4317 if ($kid->name eq "padav") {
4318 return $self->maybe_local($op, $cx, '$#' . $self->padany($kid));
6e90668e 4319 } else {
89a395f4
DM
4320 my $kkid;
4321 if ( $kid->name eq "rv2av"
4322 && ($kkid = $kid->first)
4323 && $kkid->name !~ /^(scope|leave|gv)$/)
4324 {
4325 # handle (expr)->$#* postfix form
4326 my $expr;
4327 $expr = $self->deparse($kkid, 24); # 24 is '->'
4328 $expr = "$expr->\$#*";
4329 # XXX maybe_local is probably wrong here: local($#-expression)
4330 # doesn't "do" local (the is no INTRO flag set)
4331 return $self->maybe_local($op, $cx, $expr);
4332 }
4333 else {
4334 # handle $#{expr} form
4335 # XXX see maybe_local comment above
4336 return $self->maybe_local($op, $cx, $self->rv2x($kid, $cx, '$#'));
4337 }
6e90668e
SM
4338 }
4339}
4340
4341# skip down to the old, ex-rv2cv
90c0eb26
RH
4342sub pp_rv2cv {
4343 my ($self, $op, $cx) = @_;
4344 if (!null($op->first) && $op->first->name eq 'null' &&
76e14ed3 4345 $op->first->targ == OP_LIST)
90c0eb26
RH
4346 {
4347 return $self->rv2x($op->first->first->sibling, $cx, "&")
4348 }
4349 else {
4350 return $self->rv2x($op, $cx, "")
4351 }
4352}
6e90668e 4353
d989cdac
SM
4354sub list_const {
4355 my $self = shift;
4356 my($cx, @list) = @_;
4357 my @a = map $self->const($_, 6), @list;
4358 if (@a == 0) {
4359 return "()";
4360 } elsif (@a == 1) {
4361 return $a[0];
4362 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
4363 # collapse (-1,0,1,2) into (-1..2)
4364 my ($s, $e) = @a[0,-1];
4365 my $i = $s;
4366 return $self->maybe_parens("$s..$e", $cx, 9)
4367 unless grep $i++ != $_, @a;
4368 }
4369 return $self->maybe_parens(join(", ", @a), $cx, 6);
4370}
4371
6e90668e
SM
4372sub pp_rv2av {
4373 my $self = shift;
9d2c6865 4374 my($op, $cx) = @_;
6e90668e 4375 my $kid = $op->first;
3f872cb9 4376 if ($kid->name eq "const") { # constant list
18228111 4377 my $av = $self->const_sv($kid);
d989cdac 4378 return $self->list_const($cx, $av->ARRAY);
6e90668e 4379 } else {
9d2c6865 4380 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
6e90668e
SM
4381 }
4382 }
4383
3ed82cfc
GS
4384sub is_subscriptable {
4385 my $op = shift;
fedf30e1 4386 if ($op->name =~ /^([ahg]elem|multideref$)/) {
3ed82cfc
GS
4387 return 1;
4388 } elsif ($op->name eq "entersub") {
4389 my $kid = $op->first;
4390 return 0 unless null $kid->sibling;
4391 $kid = $kid->first;
4392 $kid = $kid->sibling until null $kid->sibling;
4393 return 0 if is_scope($kid);
4394 $kid = $kid->first;
73582821 4395 return 0 if $kid->name eq "gv" || $kid->name eq "padcv";
3ed82cfc
GS
4396 return 0 if is_scalar($kid);
4397 return is_subscriptable($kid);
4398 } else {
4399 return 0;
4400 }
4401}
6e90668e 4402
21b7468a
BL
4403sub elem_or_slice_array_name
4404{
6e90668e 4405 my $self = shift;
21b7468a
BL
4406 my ($array, $left, $padname, $allow_arrow) = @_;
4407
3f872cb9 4408 if ($array->name eq $padname) {
21b7468a 4409 return $self->padany($array);
6e90668e 4410 } elsif (is_scope($array)) { # ${expr}[0]
21b7468a 4411 return "{" . $self->deparse($array, 0) . "}";
ce4e655d 4412 } elsif ($array->name eq "gv") {
10e8e32b
FC
4413 ($array, my $quoted) =
4414 $self->stash_variable_name(
4415 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
4416 );
4417 if (!$allow_arrow && $quoted) {
4418 # This cannot happen.
4419 die "Invalid variable name $array for slice";
ce4e655d 4420 }
10e8e32b 4421 return $quoted ? "$array->" : $array;
21b7468a
BL
4422 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
4423 return $self->deparse($array, 24);
6e90668e 4424 } else {
21b7468a 4425 return undef;
6e90668e 4426 }
21b7468a
BL
4427}
4428
4429sub elem_or_slice_single_index
4430{
4431 my $self = shift;
4432 my ($idx) = @_;
4433
9d2c6865 4434 $idx = $self->deparse($idx, 1);
7a9b44b9
RH
4435
4436 # Outer parens in an array index will confuse perl
4437 # if we're interpolating in a regular expression, i.e.
4438 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
4439 #
4440 # If $self->{parens}, then an initial '(' will
4441 # definitely be paired with a final ')'. If
4442 # !$self->{parens}, the misleading parens won't
4443 # have been added in the first place.
4444 #
4445 # [You might think that we could get "(...)...(...)"
4446 # where the initial and final parens do not match
4447 # each other. But we can't, because the above would
4448 # only happen if there's an infix binop between the
4449 # two pairs of parens, and *that* means that the whole
4450 # expression would be parenthesized as well.]
4451 #
4452 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
4453
098251bc
RH
4454 # Hash-element braces will autoquote a bareword inside themselves.
4455 # We need to make sure that C<$hash{warn()}> doesn't come out as
4456 # C<$hash{warn}>, which has a quite different meaning. Currently
4457 # B::Deparse will always quote strings, even if the string was a
4458 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
4459 # for constant strings.) So we can cheat slightly here - if we see
4460 # a bareword, we know that it is supposed to be a function call.
4461 #
4462 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
4463
21b7468a
BL
4464 return $idx;
4465}
4466
4467sub elem {
4468 my $self = shift;
4469 my ($op, $cx, $left, $right, $padname) = @_;
4470 my($array, $idx) = ($op->first, $op->first->sibling);
4471
4472 $idx = $self->elem_or_slice_single_index($idx);
4473
4474 unless ($array->name eq $padname) { # Maybe this has been fixed
4475 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
4476 }
4477 if (my $array_name=$self->elem_or_slice_array_name
4478 ($array, $left, $padname, 1)) {
bcbe2b27
FC
4479 return ($array_name =~ /->\z/
4480 ? $array_name
4481 : $array_name eq '#' ? '${#}' : "\$" . $array_name)
10e8e32b 4482 . $left . $idx . $right;
21b7468a
BL
4483 } else {
4484 # $x[20][3]{hi} or expr->[20]
4485 my $arrow = is_subscriptable($array) ? "" : "->";
4486 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
4487 }
4488
6e90668e
SM
4489}
4490
fedf30e1
DM
4491# a simplified version of elem_or_slice_array_name()
4492# for the use of pp_multideref
4493
4494sub multideref_var_name {
4495 my $self = shift;
4496 my ($gv, $is_hash) = @_;
4497
4498 my ($name, $quoted) =
4499 $self->stash_variable_name( $is_hash ? '%' : '@', $gv);
4500 return $quoted ? "$name->"
4501 : $name eq '#'
4502 ? '${#}' # avoid ${#}[1] => $#[1]
4503 : '$' . $name;
4504}
4505
4506
e839e6ed
DM
4507# deparse an OP_MULTICONCAT. If $in_dq is 1, we're within
4508# a double-quoted string, so for example.
4509# "abc\Qdef$x\Ebar"
4510# might get compiled as
4511# multiconcat("abc", metaquote(multiconcat("def", $x)), "bar")
4512# and the inner multiconcat should be deparsed as C<def$x> rather than
4513# the normal C<def . $x>
4514# Ditto if $in_dq is 2, handle qr/...\Qdef$x\E.../.
4515
4516sub do_multiconcat {
4517 my $self = shift;
4518 my($op, $cx, $in_dq) = @_;
4519
4520 my $kid;
4521 my @kids;
4522 my $assign;
4523 my $append;
4524 my $lhs = "";
4525
4526 for ($kid = $op->first; !null $kid; $kid = $kid->sibling) {
4527 # skip the consts and/or padsv we've optimised away
4528 push @kids, $kid
4529 unless $kid->type == OP_NULL
4530 && ( $kid->targ == OP_PADSV
4531 || $kid->targ == OP_CONST
4532 || $kid->targ == OP_PUSHMARK);
4533 }
4534
4535 $append = ($op->private & OPpMULTICONCAT_APPEND);
4536
4537 if ($op->private & OPpTARGET_MY) {
4538 # '$lex = ...' or '$lex .= ....' or 'my $lex = '
4539 $lhs = $self->padname($op->targ);
4540 $lhs = "my $lhs" if ($op->private & OPpLVAL_INTRO);
4541 $assign = 1;
4542 }
4543 elsif ($op->flags & OPf_STACKED) {
4544 # 'expr = ...' or 'expr .= ....'
4545 my $expr = $append ? shift(@kids) : pop(@kids);
4546 $lhs = $self->deparse($expr, 7);
4547 $assign = 1;
4548 }
4549
4550 if ($assign) {
4551 $lhs .= $append ? ' .= ' : ' = ';
4552 }
4553
4554 my ($nargs, $const_str, @const_lens) = $op->aux_list($self->{curcv});
4555
4556 my @consts;
4557 my $i = 0;
4558 for (@const_lens) {
4559 if ($_ == -1) {
4560 push @consts, undef;
4561 }
4562 else {
4563 push @consts, substr($const_str, $i, $_);
4564 my @args;
4565 $i += $_;
4566 }
4567 }
4568
4569 my $rhs = "";
4570
4571 if ( $in_dq
4572 || (($op->private & OPpMULTICONCAT_STRINGIFY) && !$self->{'unquote'}))
4573 {
4574 # "foo=$foo bar=$bar "
4575 my $not_first;
4576 while (@consts) {
b2362f9c
DM
4577 if ($not_first) {
4578 my $s = $self->dq(shift(@kids), 18);
4579 # don't deparse "a${$}b" as "a$$b"
4580 $s = '${$}' if $s eq '$$';
4581 $rhs = dq_disambiguate($rhs, $s);
4582 }
e839e6ed
DM
4583 $not_first = 1;
4584 my $c = shift @consts;
4585 if (defined $c) {
4586 if ($in_dq == 2) {
4587 # in pattern: don't convert newline to '\n' etc etc
4588 my $s = re_uninterp(escape_re(re_unback($c)));
4589 $rhs = re_dq_disambiguate($rhs, $s)
4590 }
4591 else {
4592 my $s = uninterp(escape_str(unback($c)));
4593 $rhs = dq_disambiguate($rhs, $s)
4594 }
4595 }
4596 }
4597 return $rhs if $in_dq;
4598 $rhs = single_delim("qq", '"', $rhs, $self);
4599 }
4600 elsif ($op->private & OPpMULTICONCAT_FAKE) {
4601 # sprintf("foo=%s bar=%s ", $foo, $bar)
4602
4603 my @all;
4604 @consts = map { $_ //= ''; s/%/%%/g; $_ } @consts;
4605 my $fmt = join '%s', @consts;
4606 push @all, $self->quoted_const_str($fmt);
4607
4608 # the following is a stripped down copy of sub listop {}
4609 my $parens = $assign || ($cx >= 5) || $self->{'parens'};
4610 my $fullname = $self->keyword('sprintf');
4611 push @all, map $self->deparse($_, 6), @kids;
4612
4613 $rhs = $parens
4614 ? "$fullname(" . join(", ", @all) . ")"
4615 : "$fullname " . join(", ", @all);
4616 }
4617 else {
4618 # "foo=" . $foo . " bar=" . $bar
4619 my @all;
4620 my $not_first;
4621 while (@consts) {
4622 push @all, $self->deparse(shift(@kids), 18) if $not_first;
4623 $not_first = 1;
4624 my $c = shift @consts;
4625 if (defined $c) {
4626 push @all, $self->quoted_const_str($c);
4627 }
4628 }
4629 $rhs .= join ' . ', @all;
4630 }
4631
4632 my $text = $lhs . $rhs;
4633
4634 $text = "($text)" if ($cx >= (($assign) ? 7 : 18+1))
4635 || $self->{'parens'};
4636
4637 return $text;
4638}
4639
4640
4641sub pp_multiconcat {
4642 my $self = shift;
4643 $self->do_multiconcat(@_, 0);
4644}
4645
4646
fedf30e1
DM
4647sub pp_multideref {
4648 my $self = shift;
4649 my($op, $cx) = @_;
4650 my $text = "";
4651
4652 if ($op->private & OPpMULTIDEREF_EXISTS) {
4653 $text = $self->keyword("exists"). " ";
4654 }
4655 elsif ($op->private & OPpMULTIDEREF_DELETE) {
4656 $text = $self->keyword("delete"). " ";
4657 }
4658 elsif ($op->private & OPpLVAL_INTRO) {
4659 $text = $self->keyword("local"). " ";
4660 }
4661
4662 if ($op->first && ($op->first->flags & OPf_KIDS)) {
4663 # arbitrary initial expression, e.g. f(1,2,3)->[...]
29e6e3b9
DM
4664 my $expr = $self->deparse($op->first, 24);
4665 # stop "exists (expr)->{...}" being interpreted as
4666 #"(exists (expr))->{...}"
4667 $expr = "+$expr" if $expr =~ /^\(/;
4668 $text .= $expr;
fedf30e1
DM
4669 }
4670
4671 my @items = $op->aux_list($self->{curcv});
4672 my $actions = shift @items;
4673
4674 my $is_hash;
4675 my $derefs = 0;
4676
4677 while (1) {
4678 if (($actions & MDEREF_ACTION_MASK) == MDEREF_reload) {
4679 $actions = shift @items;
4680 next;
4681 }
4682
4683 $is_hash = (
4684 ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_pop_rv2hv_helem
4685 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvsv_vivify_rv2hv_helem
4686 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padsv_vivify_rv2hv_helem
4687 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_vivify_rv2hv_helem
4688 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padhv_helem
4689 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvhv_helem
4690 );
4691
4692 if ( ($actions & MDEREF_ACTION_MASK) == MDEREF_AV_padav_aelem
4693 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padhv_helem)
4694 {
4695 $derefs = 1;
4696 $text .= '$' . substr($self->padname(shift @items), 1);
4697 }
4698 elsif ( ($actions & MDEREF_ACTION_MASK) == MDEREF_AV_gvav_aelem
4699 || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvhv_helem)
4700 {
4701 $derefs = 1;
4702 $text .= $self->multideref_var_name(shift @items, $is_hash);
4703 }
4704 else {
4705 if ( ($actions & MDEREF_ACTION_MASK) ==
4706 MDEREF_AV_padsv_vivify_rv2av_aelem
4707 || ($actions & MDEREF_ACTION_MASK) ==
4708 MDEREF_HV_padsv_vivify_rv2hv_helem)
4709 {
4710 $text .= $self->padname(shift @items);
4711 }
4712 elsif ( ($actions & MDEREF_ACTION_MASK) ==
4713 MDEREF_AV_gvsv_vivify_rv2av_aelem
4714 || ($actions & MDEREF_ACTION_MASK) ==
4715 MDEREF_HV_gvsv_vivify_rv2hv_helem)
4716 {
4717 $text .= $self->multideref_var_name(shift @items, $is_hash);
4718 }
4719 elsif ( ($actions & MDEREF_ACTION_MASK) ==
4720 MDEREF_AV_pop_rv2av_aelem
4721 || ($actions & MDEREF_ACTION_MASK) ==
4722 MDEREF_HV_pop_rv2hv_helem)
4723 {
4724 if ( ($op->flags & OPf_KIDS)
4725 && ( _op_is_or_was($op->first, OP_RV2AV)
4726 || _op_is_or_was($op->first, OP_RV2HV))
4727 && ($op->first->flags & OPf_KIDS)
4728 && ( _op_is_or_was($op->first->first, OP_AELEM)
4729 || _op_is_or_was($op->first->first, OP_HELEM))
4730 )
4731 {
4732 $derefs++;
4733 }
4734 }
4735
4736 $text .= '->' if !$derefs++;
4737 }
4738
4739
4740 if (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_none) {
4741 last;
4742 }
4743
4744 $text .= $is_hash ? '{' : '[';
4745
4746 if (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_const) {
4747 my $key = shift @items;
4748 if ($is_hash) {
4749 $text .= $self->const($key, $cx);
4750 }
4751 else {
4752 $text .= $key;
4753 }
4754 }
4755 elsif (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_padsv) {
4756 $text .= $self->padname(shift @items);
4757 }
4758 elsif (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_gvsv) {
4759 $text .= '$' . ($self->stash_variable_name('$', shift @items))[0];
4760 }
4761
4762 $text .= $is_hash ? '}' : ']';
4763
4764 if ($actions & MDEREF_FLAG_last) {
4765 last;
4766 }
4767 $actions >>= MDEREF_SHIFT;
4768 }
4769
4770 return $text;
4771}
4772
4773
3f872cb9
GS
4774sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
4775sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
6e90668e
SM
4776
4777sub pp_gelem {
4778 my $self = shift;
9d2c6865 4779 my($op, $cx) = @_;
6e90668e
SM
4780 my($glob, $part) = ($op->first, $op->last);
4781 $glob = $glob->first; # skip rv2gv
3f872cb9 4782 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
9d2c6865
SM
4783 my $scope = is_scope($glob);
4784 $glob = $self->deparse($glob, 0);
4785 $part = $self->deparse($part, 1);
dd666160 4786 $glob =~ s/::\z// unless $scope;
6e90668e
SM
4787 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
4788}
4789
4790sub slice {
4791 my $self = shift;
9d2c6865 4792 my ($op, $cx, $left, $right, $regname, $padname) = @_;
6e90668e
SM
4793 my $last;
4794 my(@elems, $kid, $array, $list);
4795 if (class($op) eq "LISTOP") {
4796 $last = $op->last;
4797 } else { # ex-hslice inside delete()
4798 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
4799 $last = $kid;
4800 }
4801 $array = $last;
4802 $array = $array->first
3f872cb9 4803 if $array->name eq $regname or $array->name eq "null";
21b7468a 4804 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
6e90668e 4805 $kid = $op->first->sibling; # skip pushmark
3f872cb9 4806 if ($kid->name eq "list") {
6e90668e
SM
4807 $kid = $kid->first->sibling; # skip list, pushmark
4808 for (; !null $kid; $kid = $kid->sibling) {
9d2c6865 4809 push @elems, $self->deparse($kid, 6);
6e90668e
SM
4810 }
4811 $list = join(", ", @elems);
4812 } else {
21b7468a 4813 $list = $self->elem_or_slice_single_index($kid);
6e90668e 4814 }
ac1e5644
DM
4815 my $lead = ( _op_is_or_was($op, OP_KVHSLICE)
4816 || _op_is_or_was($op, OP_KVASLICE))
4817 ? '%' : '@';
5cae3edb 4818 return $lead . $array . $left . $list . $right;
6e90668e
SM
4819}
4820
5cae3edb 4821sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
6dd3e0f2 4822sub pp_kvaslice { slice(@_, "[", "]", "rv2av", "padav") }
5cae3edb
RZ
4823sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
4824sub pp_kvhslice { slice(@_, "{", "}", "rv2hv", "padhv") }
6e90668e
SM
4825
4826sub pp_lslice {
4827 my $self = shift;
9d2c6865 4828 my($op, $cx) = @_;
6e90668e
SM
4829 my $idx = $op->first;
4830 my $list = $op->last;
4831 my(@elems, $kid);
9d2c6865
SM
4832 $list = $self->deparse($list, 1);
4833 $idx = $self->deparse($idx, 1);
4834 return "($list)" . "[$idx]";
6e90668e
SM
4835}
4836
6e90668e
SM
4837sub want_scalar {
4838 my $op = shift;
4839 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
4840}
4841
bd0865ec
GS
4842sub want_list {
4843 my $op = shift;
4844 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
4845}
4846
09d856fb 4847sub _method {
6e90668e 4848 my $self = shift;
9d2c6865 4849 my($op, $cx) = @_;
bd0865ec
GS
4850 my $kid = $op->first->sibling; # skip pushmark
4851 my($meth, $obj, @exprs);
3f872cb9 4852 if ($kid->name eq "list" and want_list $kid) {
bd0865ec
GS
4853 # When an indirect object isn't a bareword but the args are in
4854 # parens, the parens aren't part of the method syntax (the LLAFR
4855 # doesn't apply), but they make a list with OPf_PARENS set that
4856 # doesn't get flattened by the append_elem that adds the method,
4857 # making a (object, arg1, arg2, ...) list where the object
d989cdac 4858 # usually is. This can be distinguished from
e38ccfd9 4859 # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
bd0865ec
GS
4860 # object) because in the later the list is in scalar context
4861 # as the left side of -> always is, while in the former
4862 # the list is in list context as method arguments always are.
4863 # (Good thing there aren't method prototypes!)
3ed82cfc 4864 $meth = $kid->sibling;
bd0865ec
GS
4865 $kid = $kid->first->sibling; # skip pushmark
4866 $obj = $kid;
6e90668e 4867 $kid = $kid->sibling;
bd0865ec 4868 for (; not null $kid; $kid = $kid->sibling) {
09d856fb 4869 push @exprs, $kid;
6e90668e 4870 }
bd0865ec
GS
4871 } else {
4872 $obj = $kid;
4873 $kid = $kid->sibling;
35a99a08 4874 for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
90c0eb26 4875 $kid = $kid->sibling) {
09d856fb 4876 push @exprs, $kid
6e90668e 4877 }
3ed82cfc 4878 $meth = $kid;
bd0865ec 4879 }
09d856fb 4880
3ed82cfc 4881 if ($meth->name eq "method_named") {
b46e009d 4882 $meth = $self->meth_sv($meth)->PV;
7d6c333c 4883 } elsif ($meth->name eq "method_super") {
4884 $meth = "SUPER::".$self->meth_sv($meth)->PV;
810bd8b7 4885 } elsif ($meth->name eq "method_redir") {
4886 $meth = $self->meth_rclass_sv($meth)->PV.'::'.$self->meth_sv($meth)->PV;
4887 } elsif ($meth->name eq "method_redir_super") {
4888 $meth = $self->meth_rclass_sv($meth)->PV.'::SUPER::'.
4889 $self->meth_sv($meth)->PV;
bd0865ec 4890 } else {
3ed82cfc
GS
4891 $meth = $meth->first;
4892 if ($meth->name eq "const") {
4893 # As of 5.005_58, this case is probably obsoleted by the
4894 # method_named case above
18228111 4895 $meth = $self->const_sv($meth)->PV; # needs to be bare
3ed82cfc 4896 }
bd0865ec 4897 }
09d856fb
CK
4898
4899 return { method => $meth, variable_method => ref($meth),
1bf8bbb0
FC
4900 object => $obj, args => \@exprs },
4901 $cx;
09d856fb
CK
4902}
4903
4904# compat function only
4905sub method {
4906 my $self = shift;
4907 my $info = $self->_method(@_);
4908 return $self->e_method( $self->_method(@_) );
4909}
4910
4911sub e_method {
1bf8bbb0 4912 my ($self, $info, $cx) = @_;
09d856fb
CK
4913 my $obj = $self->deparse($info->{object}, 24);
4914
4915 my $meth = $info->{method};
4916 $meth = $self->deparse($meth, 1) if $info->{variable_method};
4917 my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
1bf8bbb0
FC
4918 if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
4919 # method { $object }
4920 # This must be deparsed this way to preserve list context
4921 # of $object.
4922 my $need_paren = $cx >= 6;
4923 return '(' x $need_paren
4924 . $meth . substr($obj,2) # chop off the "do"
4925 . " $args"
4926 . ')' x $need_paren;
4927 }
09d856fb 4928 my $kid = $obj . "->" . $meth;
145eb477 4929 if (length $args) {
bd0865ec
GS
4930 return $kid . "(" . $args . ")"; # parens mandatory
4931 } else {
4932 return $kid;
4933 }
4934}
4935
4936# returns "&" if the prototype doesn't match the args,
4937# or ("", $args_after_prototype_demunging) if it does.
4938sub check_proto {
4939 my $self = shift;
acaaef34 4940 return "&" if $self->{'noproto'};
bd0865ec
GS
4941 my($proto, @args) = @_;
4942 my($arg, $real);
4943 my $doneok = 0;
4944 my @reals;
4945 # An unbackslashed @ or % gobbles up the rest of the args
2ae48fff 4946 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
c4cf781e 4947 $proto =~ s/^\s*//;
bd0865ec 4948 while ($proto) {
fd8be4a1 4949 $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;|)\s*//;
bd0865ec
GS
4950 my $chr = $1;
4951 if ($chr eq "") {
4952 return "&" if @args;
4953 } elsif ($chr eq ";") {
4954 $doneok = 1;
4955 } elsif ($chr eq "@" or $chr eq "%") {
4956 push @reals, map($self->deparse($_, 6), @args);
4957 @args = ();
6e90668e 4958 } else {
bd0865ec
GS
4959 $arg = shift @args;
4960 last unless $arg;
21b52158 4961 if ($chr eq "\$" || $chr eq "_") {
bd0865ec
GS
4962 if (want_scalar $arg) {
4963 push @reals, $self->deparse($arg, 6);
4964 } else {
4965 return "&";
4966 }
4967 } elsif ($chr eq "&") {
3f872cb9 4968 if ($arg->name =~ /^(s?refgen|undef)$/) {
bd0865ec
GS
4969 push @reals, $self->deparse($arg, 6);
4970 } else {
4971 return "&";
4972 }
4973 } elsif ($chr eq "*") {
3f872cb9
GS
4974 if ($arg->name =~ /^s?refgen$/
4975 and $arg->first->first->name eq "rv2gv")
bd0865ec
GS
4976 {
4977 $real = $arg->first->first; # skip refgen, null
3f872cb9 4978 if ($real->first->name eq "gv") {
bd0865ec
GS
4979 push @reals, $self->deparse($real, 6);
4980 } else {
4981 push @reals, $self->deparse($real->first, 6);
4982 }
4983 } else {
4984 return "&";
4985 }
4986 } elsif (substr($chr, 0, 1) eq "\\") {
2ae48fff 4987 $chr =~ tr/\\[]//d;
3f872cb9 4988 if ($arg->name =~ /^s?refgen$/ and
bd0865ec 4989 !null($real = $arg->first) and
2ae48fff
RGS
4990 ($chr =~ /\$/ && is_scalar($real->first)
4991 or ($chr =~ /@/
4992 && class($real->first->sibling) ne 'NULL'
3f872cb9
GS
4993 && $real->first->sibling->name
4994 =~ /^(rv2|pad)av$/)
2ae48fff
RGS
4995 or ($chr =~ /%/
4996 && class($real->first->sibling) ne 'NULL'
3f872cb9
GS
4997 && $real->first->sibling->name
4998 =~ /^(rv2|pad)hv$/)
2ae48fff 4999 #or ($chr =~ /&/ # This doesn't work
3f872cb9 5000 # && $real->first->name eq "rv2cv")
2ae48fff 5001 or ($chr =~ /\*/
3f872cb9 5002 && $real->first->name eq "rv2gv")))
bd0865ec
GS
5003 {
5004 push @reals, $self->deparse($real, 6);
5005 } else {
5006 return "&";
5007 }
5008 }
5009 }
9d2c6865 5010 }
e38ccfd9 5011 return "&" if $proto and !$doneok; # too few args and no ';'
bd0865ec
GS
5012 return "&" if @args; # too many args
5013 return ("", join ", ", @reals);
5014}
5015
c65b7c4d
FC
5016sub retscalar {
5017 my $name = $_[0]->name;
5018 # XXX There has to be a better way of doing this scalar-op check.
5019 # Currently PL_opargs is not exposed.
5020 if ($name eq 'null') {
5021 $name = substr B::ppname($_[0]->targ), 3
5022 }
5023 $name =~ /^(?:scalar|pushmark|wantarray|const|gvsv|gv|padsv|rv2gv
5024 |rv2sv|av2arylen|anoncode|prototype|srefgen|ref|bless
5025 |regcmaybe|regcreset|regcomp|qr|subst|substcont|trans
5026 |transr|sassign|chop|schop|chomp|schomp|defined|undef
5027 |study|pos|preinc|i_preinc|predec|i_predec|postinc
5028 |i_postinc|postdec|i_postdec|pow|multiply|i_multiply
5029 |divide|i_divide|modulo|i_modulo|add|i_add|subtract
e839e6ed 5030 |i_subtract|concat|multiconcat|stringify|left_shift|right_shift|lt
c65b7c4d 5031 |i_lt|gt|i_gt|le|i_le|ge|i_ge|eq|i_eq|ne|i_ne|ncmp|i_ncmp
27f31adf
FC
5032 |slt|sgt|sle|sge|seq|sne|scmp|[sn]?bit_(?:and|x?or)|negate
5033 |i_negate|not|[sn]?complement|smartmatch|atan2|sin|cos
c65b7c4d
FC
5034 |rand|srand|exp|log|sqrt|int|hex|oct|abs|length|substr
5035 |vec|index|rindex|sprintf|formline|ord|chr|crypt|ucfirst
5036 |lcfirst|uc|lc|quotemeta|aelemfast|aelem|exists|helem
5037 |pack|join|anonlist|anonhash|push|pop|shift|unshift|xor
5038 |andassign|orassign|dorassign|warn|die|reset|nextstate
5039 |dbstate|unstack|last|next|redo|dump|goto|exit|open|close
5040 |pipe_op|fileno|umask|binmode|tie|untie|tied|dbmopen
5041 |dbmclose|select|getc|read|enterwrite|prtf|print|say
5042 |sysopen|sysseek|sysread|syswrite|eof|tell|seek|truncate
5043 |fcntl|ioctl|flock|send|recv|socket|sockpair|bind|connect
5044 |listen|accept|shutdown|gsockopt|ssockopt|getsockname
5045 |getpeername|ftrread|ftrwrite|ftrexec|fteread|ftewrite
5046 |fteexec|ftis|ftsize|ftmtime|ftatime|ftctime|ftrowned
5047 |fteowned|ftzero|ftsock|ftchr|ftblk|ftfile|ftdir|ftpipe
5048 |ftsuid|ftsgid|ftsvtx|ftlink|fttty|fttext|ftbinary|chdir
5049 |chown|chroot|unlink|chmod|utime|rename|link|symlink
5050 |readlink|mkdir|rmdir|open_dir|telldir|seekdir|rewinddir
5051 |closedir|fork|wait|waitpid|system|exec|kill|getppid
5052 |getpgrp|setpgrp|getpriority|setpriority|time|alarm|sleep
5053 |shmget|shmctl|shmread|shmwrite|msgget|msgctl|msgsnd
5054 |msgrcv|semop|semget|semctl|hintseval|shostent|snetent
5055 |sprotoent|sservent|ehostent|enetent|eprotoent|eservent
5056 |spwent|epwent|sgrent|egrent|getlogin|syscall|lock|runcv
5057 |fc)\z/x
5058}
5059
bd0865ec
GS
5060sub pp_entersub {
5061 my $self = shift;
5062 my($op, $cx) = @_;
09d856fb
CK
5063 return $self->e_method($self->_method($op, $cx))
5064 unless null $op->first->sibling;
bd0865ec
GS
5065 my $prefix = "";
5066 my $amper = "";
5067 my($kid, @exprs);
90c0eb26 5068 if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
9d2c6865
SM
5069 $prefix = "do ";
5070 } elsif ($op->private & OPpENTERSUB_AMPER) {
5071 $amper = "&";
5072 }
5073 $kid = $op->first;
5074 $kid = $kid->first->sibling; # skip ex-list, pushmark
5075 for (; not null $kid->sibling; $kid = $kid->sibling) {
5076 push @exprs, $kid;
5077 }
bd0865ec
GS
5078 my $simple = 0;
5079 my $proto = undef;
bb9bfaa4 5080 my $lexical;
9d2c6865
SM
5081 if (is_scope($kid)) {
5082 $amper = "&";
5083 $kid = "{" . $self->deparse($kid, 0) . "}";
3f872cb9 5084 } elsif ($kid->first->name eq "gv") {
6f611a1a 5085 my $gv = $self->gv_or_padgv($kid->first);
32cc5cd1
FC
5086 my $cv;
5087 if (class($gv) eq 'GV' && class($cv = $gv->CV) ne "SPECIAL"
5088 || $gv->FLAGS & SVf_ROK && class($cv = $gv->RV) eq 'CV') {
5089 $proto = $cv->PV if $cv->FLAGS & SVf_POK;
9d2c6865 5090 }
bd0865ec 5091 $simple = 1; # only calls of named functions can be prototyped
257296eb 5092 $kid = $self->maybe_qualify("!", $self->gv_name($gv));
d49c3562
FC
5093 my $fq;
5094 # Fully qualify any sub name that conflicts with a lexical.
5095 if ($self->lex_in_scope("&$kid")
5096 || $self->lex_in_scope("&$kid", 1))
5097 {
5098 $fq++;
5099 } elsif (!$amper) {
8b2d6640
FC
5100 if ($kid eq 'main::') {
5101 $kid = '::';
a958cfbb
FC
5102 }
5103 else {
5104 if ($kid !~ /::/ && $kid ne 'x') {
5105 # Fully qualify any sub name that is also a keyword. While
5106 # we could check the import flag, we cannot guarantee that
5107 # the code deparsed so far would set that flag, so we qual-
5108 # ify the names regardless of importation.
a958cfbb
FC
5109 if (exists $feature_keywords{$kid}) {
5110 $fq++ if $self->feature_enabled($kid);
e54915d6
FC
5111 } elsif (do { local $@; local $SIG{__DIE__};
5112 eval { () = prototype "CORE::$kid"; 1 } }) {
a958cfbb
FC
5113 $fq++
5114 }
a958cfbb
FC
5115 }
5116 if ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
7741ceed 5117 $kid = single_delim("q", "'", $kid, $self) . '->';
a958cfbb 5118 }
8b2d6640
FC
5119 }
5120 }
d49c3562 5121 $fq and substr $kid, 0, 0, = $self->{'curstash'}.'::';
90c0eb26 5122 } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
9d2c6865
SM
5123 $amper = "&";
5124 $kid = $self->deparse($kid, 24);
5125 } else {
5126 $prefix = "";
bb9bfaa4
FC
5127 my $grandkid = $kid->first;
5128 my $arrow = ($lexical = $grandkid->name eq "padcv")
5129 || is_subscriptable($grandkid)
5130 ? ""
5131 : "->";
3ed82cfc 5132 $kid = $self->deparse($kid, 24) . $arrow;
bb9bfaa4
FC
5133 if ($lexical) {
5134 my $padlist = $self->{'curcv'}->PADLIST;
5135 my $padoff = $grandkid->targ;
5136 my $padname = $padlist->ARRAYelt(0)->ARRAYelt($padoff);
5137 my $protocv = $padname->FLAGS & SVpad_STATE
5138 ? $padlist->ARRAYelt(1)->ARRAYelt($padoff)
5139 : $padname->PROTOCV;
5140 if ($protocv->FLAGS & SVf_POK) {
5141 $proto = $protocv->PV
5142 }
5143 $simple = 1;
5144 }
9d2c6865 5145 }
0ca62a8e
RH
5146
5147 # Doesn't matter how many prototypes there are, if
5148 # they haven't happened yet!
bb9bfaa4 5149 my $declared = $lexical || exists $self->{'subs_declared'}{$kid};
de4fa237
FC
5150 if (not $declared and $self->{'in_coderef2text'}) {
5151 no strict 'refs';
5152 no warnings 'uninitialized';
5153 $declared =
5154 (
5155 defined &{ ${$self->{'curstash'}."::"}{$kid} }
5156 && !exists
5157 $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
5158 && defined prototype $self->{'curstash'}."::".$kid
5159 );
5160 }
f2279a62
FC
5161 if (!$declared && defined($proto)) {
5162 # Avoid "too early to check prototype" warning
5163 ($amper, $proto) = ('&');
e99ebc55 5164 }
0ca62a8e 5165
bd0865ec 5166 my $args;
e16ceb94 5167 my $listargs = 1;
0ca62a8e 5168 if ($declared and defined $proto and not $amper) {
bd0865ec 5169 ($amper, $args) = $self->check_proto($proto, @exprs);
e16ceb94
FC
5170 $listargs = $amper;
5171 }
5172 if ($listargs) {
c65b7c4d
FC
5173 $args = join(", ", map(
5174 ($_->flags & OPf_WANT) == OPf_WANT_SCALAR
5175 && !retscalar($_)
5176 ? $self->maybe_parens_unop('scalar', $_, 6)
5177 : $self->deparse($_, 6),
5178 @exprs
5179 ));
6e90668e 5180 }
9d2c6865 5181 if ($prefix or $amper) {
1b38d782 5182 if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
9d2c6865
SM
5183 if ($op->flags & OPf_STACKED) {
5184 return $prefix . $amper . $kid . "(" . $args . ")";
5185 } else {
5186 return $prefix . $amper. $kid;
5187 }
6e90668e 5188 } else {
7969d523 5189 # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
34a48b4b
RH
5190 # so it must have been translated from a keyword call. Translate
5191 # it back.
5192 $kid =~ s/^CORE::GLOBAL:://;
5193
d989cdac 5194 my $dproto = defined($proto) ? $proto : "undefined";
fd8be4a1 5195 my $scalar_proto = $dproto =~ /^;*(?:[\$*_+]|\\.|\\\[[^]]\])\z/;
0ca62a8e
RH
5196 if (!$declared) {
5197 return "$kid(" . $args . ")";
c4cf781e 5198 } elsif ($dproto =~ /^\s*\z/) {
9d2c6865 5199 return $kid;
fd8be4a1 5200 } elsif ($scalar_proto and is_scalar($exprs[0])) {
d989cdac
SM
5201 # is_scalar is an excessively conservative test here:
5202 # really, we should be comparing to the precedence of the
5203 # top operator of $exprs[0] (ala unop()), but that would
5204 # take some major code restructuring to do right.
9d2c6865 5205 return $self->maybe_parens_func($kid, $args, $cx, 16);
fd8be4a1 5206 } elsif (not $scalar_proto and defined($proto) || $simple) { #'
9d2c6865
SM
5207 return $self->maybe_parens_func($kid, $args, $cx, 5);
5208 } else {
5209 return "$kid(" . $args . ")";
5210 }
6e90668e
SM
5211 }
5212}
5213
5214sub pp_enterwrite { unop(@_, "write") }
5215
5216# escape things that cause interpolation in double quotes,
5217# but not character escapes
5218sub uninterp {
5219 my($str) = @_;
3f766ba3 5220 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
9d2c6865
SM
5221 return $str;
5222}
5223
b7dad2dc
RH
5224{
5225my $bal;
5226BEGIN {
cdf8218f
RH
5227 use re "eval";
5228 # Matches any string which is balanced with respect to {braces}
b7dad2dc 5229 $bal = qr(
cdf8218f
RH
5230 (?:
5231 [^\\{}]
5232 | \\\\
5233 | \\[{}]
5234 | \{(??{$bal})\}
5235 )*
5236 )x;
b7dad2dc
RH
5237}
5238
5239# the same, but treat $|, $), $( and $ at the end of the string differently
ba0372a0 5240# and leave comments unmangled for the sake of /x and (?x).
b7dad2dc
RH
5241sub re_uninterp {
5242 my($str) = @_;
cdf8218f
RH
5243
5244 $str =~ s/
5245 ( ^|\G # $1
5246 | [^\\]
5247 )
5248
5249 ( # $2
5250 (?:\\\\)*
5251 )
5252
5253 ( # $3
b7dad2dc
RH
5254 ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
5255 | \#[^\n]* # (skip over comments)
5256 )
5257 | [\$\@]
9a58b761 5258 (?!\||\)|\(|$|\s)
b7dad2dc
RH
5259 | \\[uUlLQE]
5260 )
5261
c7de4c66 5262 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
b7dad2dc 5263
a9760014
RH
5264 return $str;
5265}
b7dad2dc 5266}
a9760014 5267
6e90668e 5268# character escapes, but not delimiters that might need to be escaped
746698c5 5269sub escape_str { # ASCII, UTF8
6e90668e 5270 my($str) = @_;
cef22867 5271 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
6e90668e 5272 $str =~ s/\a/\\a/g;
78425176
KW
5273# $str =~ s/\cH/\\b/g; # \b means something different in a regex; and \cH
5274 # isn't a backspace in EBCDIC
6e90668e
SM
5275 $str =~ s/\t/\\t/g;
5276 $str =~ s/\n/\\n/g;
5277 $str =~ s/\e/\\e/g;
5278 $str =~ s/\f/\\f/g;
5279 $str =~ s/\r/\\r/g;
dd405ed7 5280 $str =~ s/([\cA-\cZ])/'\\c' . $unctrl{$1}/ge;
2d5b99ed 5281 $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/age;
6e90668e
SM
5282 return $str;
5283}
5284
ba0372a0
FC
5285# For regexes. Leave whitespace unmangled in case of /x or (?x).
5286sub escape_re {
a9760014 5287 my($str) = @_;
cef22867 5288 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
aee8fd8d 5289 $str =~ s/([[:^print:]])/
2d5b99ed 5290 ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/age;
a9760014
RH
5291 $str =~ s/\n/\n\f/g;
5292 return $str;
5293}
5294
9d2c6865
SM
5295# Don't do this for regexen
5296sub unback {
5297 my($str) = @_;
5298 $str =~ s/\\/\\\\/g;
5299 return $str;
5300}
5301
08c6f5ec
RH
5302# Remove backslashes which precede literal control characters,
5303# to avoid creating ambiguity when we escape the latter.
4d7ac81a
DM
5304#
5305# Don't remove a backslash from escaped whitespace: where the T represents
5306# a literal tab character, /T/x is not equivalent to /\T/x
5307
08c6f5ec
RH
5308sub re_unback {
5309 my($str) = @_;
5310
5311 # the insane complexity here is due to the behaviour of "\c\"
27daf566
DM
5312 $str =~ s/
5313 # these two lines ensure that the backslash we're about to
5ab5717f 5314 # remove isn't preceded by something which makes it part
27daf566
DM
5315 # of a \c
5316
5317 (^ | [^\\] | \\c\\) # $1
5318 (?<!\\c)
5319
5320 # the backslash to remove
5321 \\
5322
5323 # keep pairs of backslashes
5324 (\\\\)* # $2
5325
5326 # only remove if the thing following is a control char
5327 (?=[[:^print:]])
4d7ac81a
DM
5328 # and not whitespace
5329 (?=\S)
27daf566 5330 /$1$2/xg;
08c6f5ec
RH
5331 return $str;
5332}
5333
6e90668e
SM
5334sub balanced_delim {
5335 my($str) = @_;
5336 my @str = split //, $str;
80b7d6d2 5337 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
6e90668e
SM
5338 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
5339 ($open, $close) = @$ar;
80b7d6d2 5340 $fail = 0; $cnt = 0; $last_bs = 0;
6e90668e
SM
5341 for $c (@str) {
5342 if ($c eq $open) {
80b7d6d2 5343 $fail = 1 if $last_bs;
6e90668e
SM
5344 $cnt++;
5345 } elsif ($c eq $close) {
80b7d6d2 5346 $fail = 1 if $last_bs;
6e90668e
SM
5347 $cnt--;
5348 if ($cnt < 0) {
bd0865ec 5349 # qq()() isn't ")("
6e90668e
SM
5350 $fail = 1;
5351 last;
5352 }
5353 }
80b7d6d2 5354 $last_bs = $c eq '\\';
6e90668e
SM
5355 }
5356 $fail = 1 if $cnt != 0;
5357 return ($open, "$open$str$close") if not $fail;
5358 }
5359 return ("", $str);
5360}
5361
5362sub single_delim {
7741ceed 5363 my($q, $default, $str, $self) = @_;
90be192f 5364 return "$default$str$default" if $default and index($str, $default) == -1;
7741ceed 5365 my $coreq = $self->keyword($q); # maybe CORE::q
8347ad86
RGS
5366 if ($q ne 'qr') {
5367 (my $succeed, $str) = balanced_delim($str);
7741ceed 5368 return "$coreq$str" if $succeed;
8347ad86
RGS
5369 }
5370 for my $delim ('/', '"', '#') {
7741ceed 5371 return "$coreq$delim" . $str . $delim if index($str, $delim) == -1;
6e90668e 5372 }
90be192f
SM
5373 if ($default) {
5374 $str =~ s/$default/\\$default/g;
5375 return "$default$str$default";
5376 } else {
5377 $str =~ s[/][\\/]g;
7741ceed 5378 return "$coreq/$str/";
90be192f 5379 }
6e90668e
SM
5380}
5381
d989cdac
SM
5382my $max_prec;
5383BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
5384
5385# Split a floating point number into an integer mantissa and a binary
5386# exponent. Assumes you've already made sure the number isn't zero or
5387# some weird infinity or NaN.
5388sub split_float {
5389 my($f) = @_;
5390 my $exponent = 0;
5391 if ($f == int($f)) {
5392 while ($f % 2 == 0) {
5393 $f /= 2;
5394 $exponent++;
5395 }
5396 } else {
5397 while ($f != int($f)) {
5398 $f *= 2;
5399 $exponent--;
5400 }
5401 }
5402 my $mantissa = sprintf("%.0f", $f);
5403 return ($mantissa, $exponent);
5404}
5405
e839e6ed
DM
5406
5407# suitably single- or double-quote a literal constant string
5408
5409sub quoted_const_str {
5410 my ($self, $str) =@_;
5411 if ($str =~ /[[:^print:]]/a) {
5412 return single_delim("qq", '"',
5413 uninterp(escape_str unback $str), $self);
5414 } else {
5415 return single_delim("q", "'", unback($str), $self);
5416 }
5417}
5418
5419
6e90668e 5420sub const {
d989cdac
SM
5421 my $self = shift;
5422 my($sv, $cx) = @_;
5423 if ($self->{'use_dumper'}) {
5424 return $self->const_dumper($sv, $cx);
5425 }
6e90668e 5426 if (class($sv) eq "SPECIAL") {
d989cdac 5427 # sv_undef, sv_yes, sv_no
ea36157c
FC
5428 return $$sv == 3 ? $self->maybe_parens("!1", $cx, 21)
5429 : ('undef', '1')[$$sv-1];
805b1011
DM
5430 }
5431 if (class($sv) eq "NULL") {
7a9b44b9 5432 return 'undef';
805b1011 5433 }
127212b2
DM
5434 # convert a version object into the "v1.2.3" string in its V magic
5435 if ($sv->FLAGS & SVs_RMG) {
5436 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
5437 return $mg->PTR if $mg->TYPE eq 'V';
5438 }
5439 }
5440
5441 if ($sv->FLAGS & SVf_IOK) {
d989cdac
SM
5442 my $str = $sv->int_value;
5443 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
5444 return $str;
6e90668e 5445 } elsif ($sv->FLAGS & SVf_NOK) {
d989cdac
SM
5446 my $nv = $sv->NV;
5447 if ($nv == 0) {
5448 if (pack("F", $nv) eq pack("F", 0)) {
5449 # positive zero
5450 return "0";
5451 } else {
5452 # negative zero
5453 return $self->maybe_parens("-.0", $cx, 21);
5454 }
5455 } elsif (1/$nv == 0) {
5456 if ($nv > 0) {
5457 # positive infinity
5458 return $self->maybe_parens("9**9**9", $cx, 22);
5459 } else {
5460 # negative infinity
5461 return $self->maybe_parens("-9**9**9", $cx, 21);
5462 }
5463 } elsif ($nv != $nv) {
5464 # NaN
5465 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
5466 # the normal kind
5467 return "sin(9**9**9)";
5468 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
5469 # the inverted kind
5470 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
5471 } else {
5472 # some other kind
5473 my $hex = unpack("h*", pack("F", $nv));
5474 return qq'unpack("F", pack("h*", "$hex"))';
5475 }
fecea806 5476 }
d989cdac
SM
5477 # first, try the default stringification
5478 my $str = "$nv";
5479 if ($str != $nv) {
5480 # failing that, try using more precision
5481 $str = sprintf("%.${max_prec}g", $nv);
5482# if (pack("F", $str) ne pack("F", $nv)) {
5483 if ($str != $nv) {
5484 # not representable in decimal with whatever sprintf()
5485 # and atof() Perl is using here.
5486 my($mant, $exp) = split_float($nv);
5487 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
5488 }
5489 }
5490 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
5491 return $str;
7a9b44b9 5492 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
d989cdac 5493 my $ref = $sv->RV;
5e965771
FC
5494 my $class = class($ref);
5495 if ($class eq "AV") {
d989cdac 5496 return "[" . $self->list_const(2, $ref->ARRAY) . "]";
5e965771 5497 } elsif ($class eq "HV") {
d989cdac
SM
5498 my %hash = $ref->ARRAY;
5499 my @elts;
5500 for my $k (sort keys %hash) {
5501 push @elts, "$k => " . $self->const($hash{$k}, 6);
5502 }
5503 return "{" . join(", ", @elts) . "}";
5e965771 5504 } elsif ($class eq "CV") {
843835bc
Z
5505 no overloading;
5506 if ($self->{curcv} &&
1a35f9ff
FC
5507 $self->{curcv}->object_2svref == $ref->object_2svref) {
5508 return $self->keyword("__SUB__");
5509 }
d989cdac
SM
5510 return "sub " . $self->deparse_sub($ref);
5511 }
5e965771 5512 if ($class ne 'SPECIAL' and $ref->FLAGS & SVs_SMG) {
d989cdac
SM
5513 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
5514 if ($mg->TYPE eq 'r') {
ba0372a0 5515 my $re = re_uninterp(escape_re(re_unback($mg->precomp)));
7741ceed 5516 return single_delim("qr", "", $re, $self);
d989cdac
SM
5517 }
5518 }
5519 }
5520
9f125c4a
FC
5521 my $const = $self->const($ref, 20);
5522 if ($self->{in_subst_repl} && $const =~ /^[0-9]/) {
5523 $const = "($const)";
5524 }
5525 return $self->maybe_parens("\\$const", $cx, 20);
34768ba5 5526 } elsif ($sv->FLAGS & SVf_POK) {
6e90668e 5527 my $str = $sv->PV;
e839e6ed 5528 return $self->quoted_const_str($str);
34768ba5
RH
5529 } else {
5530 return "undef";
a798dbf2
MB
5531 }
5532}
5533
d989cdac
SM
5534sub const_dumper {
5535 my $self = shift;
5536 my($sv, $cx) = @_;
5537 my $ref = $sv->object_2svref();
5538 my $dumper = Data::Dumper->new([$$ref], ['$v']);
5539 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
5540 my $str = $dumper->Dump();
5541 if ($str =~ /^\$v/) {
5542 return '${my ' . $str . ' \$v}';
5543 } else {
5544 return $str;
5545 }
5546}
5547
18228111
GS
5548sub const_sv {
5549 my $self = shift;
5550 my $op = shift;
5551 my $sv = $op->sv;
5552 # the constant could be in the pad (under useithreads)
5553 $sv = $self->padval($op->targ) unless $$sv;
5554 return $sv;
5555}
5556
b46e009d 5557sub meth_sv {
5558 my $self = shift;
5559 my $op = shift;
5560 my $sv = $op->meth_sv;
5561 # the constant could be in the pad (under useithreads)
5562 $sv = $self->padval($op->targ) unless $$sv;
5563 return $sv;
5564}
5565
810bd8b7 5566sub meth_rclass_sv {
5567 my $self = shift;
5568 my $op = shift;
5569 my $sv = $op->rclass;
5570 # the constant could be in the pad (under useithreads)
5571 $sv = $self->padval($sv) unless ref $sv;
5572 return $sv;
5573}
5574
6e90668e
SM
5575sub pp_const {
5576 my $self = shift;
9d2c6865 5577 my($op, $cx) = @_;
e38ccfd9 5578# if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
18228111 5579# return $self->const_sv($op)->PV;
6e90668e 5580# }
18228111 5581 my $sv = $self->const_sv($op);
d989cdac 5582 return $self->const($sv, $cx);
6e90668e
SM
5583}
5584
e839e6ed
DM
5585
5586# Join two components of a double-quoted string, disambiguating
5587# "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
5588
5589sub dq_disambiguate {
5590 my ($first, $last) = @_;
5591 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
5592 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
5593 || ($last =~ /^[:'{\[\w_]/ && #'
5594 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
5595 return $first . $last;
5596}
5597
5598
5599# Deparse a double-quoted optree. For example, "$a[0]\Q$b\Efo\"o" gets
5600# compiled to concat(concat($[0],quotemeta($b)),const("fo\"o")), and this
5601# sub deparses it back to $a[0]\Q$b\Efo"o
5602# (It does not add delimiters)
5603
6e90668e
SM
5604sub dq {
5605 my $self = shift;
5606 my $op = shift;
3f872cb9
GS
5607 my $type = $op->name;
5608 if ($type eq "const") {
f3402b25 5609 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
3f872cb9 5610 } elsif ($type eq "concat") {
e839e6ed
DM
5611 return dq_disambiguate($self->dq($op->first), $self->dq($op->last));
5612 } elsif ($type eq "multiconcat") {
5613 return $self->do_multiconcat($op, 26, 1);
3f872cb9 5614 } elsif ($type eq "uc") {
6e90668e 5615 return '\U' . $self->dq($op->first->sibling) . '\E';
3f872cb9 5616 } elsif ($type eq "lc") {
6e90668e 5617 return '\L' . $self->dq($op->first->sibling) . '\E';
3f872cb9 5618 } elsif ($type eq "ucfirst") {
6e90668e 5619 return '\u' . $self->dq($op->first->sibling);
3f872cb9 5620 } elsif ($type eq "lcfirst") {
6e90668e 5621 return '\l' . $self->dq($op->first->sibling);
3f872cb9 5622 } elsif ($type eq "quotemeta") {
6e90668e 5623 return '\Q' . $self->dq($op->first->sibling) . '\E';
838f2281
BF
5624 } elsif ($type eq "fc") {
5625 return '\F' . $self->dq($op->first->sibling) . '\E';
3f872cb9 5626 } elsif ($type eq "join") {
9d2c6865 5627 return $self->deparse($op->last, 26); # was join($", @ary)
a798dbf2 5628 } else {
9d2c6865 5629 return $self->deparse($op, 26);
6e90668e
SM
5630 }
5631}
5632
5633sub pp_backtick {
5634 my $self = shift;
9d2c6865 5635 my($op, $cx) = @_;
85675c4c
RGS
5636 # skip pushmark if it exists (readpipe() vs ``)
5637 my $child = $op->first->sibling->isa('B::NULL')
c53941b4 5638 ? $op->first : $op->first->sibling;
5d8c42c2 5639 if ($self->pure_string($child)) {
7741ceed 5640 return single_delim("qx", '`', $self->dq($child, 1), $self);
5d8c42c2
FC
5641 }
5642 unop($self, @_, "readpipe");
6e90668e
SM
5643}
5644
5645sub dquote {
5646 my $self = shift;
6f611a1a 5647 my($op, $cx) = @_;
3ed82cfc
GS
5648 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
5649 return $self->deparse($kid, $cx) if $self->{'unquote'};
5650 $self->maybe_targmy($kid, $cx,
7741ceed
FC
5651 sub {single_delim("qq", '"', $self->dq($_[1]),
5652 $self)});
6e90668e
SM
5653}
5654
bd0865ec 5655# OP_STRINGIFY is a listop, but it only ever has one arg
3b4e2a4d
FC
5656sub pp_stringify {
5657 my ($self, $op, $cx) = @_;
5658 my $kid = $op->first->sibling;
5659 while ($kid->name eq 'null' && !null($kid->first)) {
5660 $kid = $kid->first;
5661 }
fedf30e1 5662 if ($kid->name =~ /^(?:const|padsv|rv2sv|av2arylen|gvsv|multideref
3b4e2a4d
FC
5663 |aelemfast(?:_lex)?|[ah]elem|join|concat)\z/x) {
5664 maybe_targmy(@_, \&dquote);
5665 }
5666 else {
5667 # Actually an optimised join.
5668 my $result = listop(@_,"join");
5669 $result =~ s/join([( ])/join$1$self->{'ex_const'}, /;
5670 $result;
5671 }
5672}
6e90668e
SM
5673
5674# tr/// and s/// (and tr[][], tr[]//, tr###, etc)
5675# note that tr(from)/to/ is OK, but not tr/from/(to)
5676sub double_delim {
5677 my($from, $to) = @_;
5678 my($succeed, $delim);
5679 if ($from !~ m[/] and $to !~ m[/]) {
5680 return "/$from/$to/";
5681 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
5682 if (($succeed, $to) = balanced_delim($to) and $succeed) {
5683 return "$from$to";
5684 } else {
6b0bcbb1 5685 for $delim ('/', '"', '#') { # note no "'" -- s''' is special
6e90668e
SM
5686 return "$from$delim$to$delim" if index($to, $delim) == -1;
5687 }
5688 $to =~ s[/][\\/]g;
5689 return "$from/$to/";
5690 }
5691 } else {
5692 for $delim ('/', '"', '#') { # note no '
5693 return "$delim$from$delim$to$delim"
5694 if index($to . $from, $delim) == -1;
5695 }
5696 $from =~ s[/][\\/]g;
5697 $to =~ s[/][\\/]g;
5698 return "/$from/$to/";
5699 }
5700}
5701
5a92c677 5702# Escape a characrter.
2a9e2f8a 5703# Only used by tr///, so backslashes hyphens
5a92c677 5704
664c1f42 5705sub pchr {
6e90668e 5706 my($n) = @_;
664c1f42 5707 return sprintf("\\x{%X}", $n) if $n > 255;
9b324f0c
KW
5708 return '\\\\' if $n == ord '\\';
5709 return "\\-" if $n == ord "-";
5710 # I'm presuming a regex is not ok here, otherwise we could have used
5711 # /[[:print:]]/a to get here
5712 return chr($n) if ( utf8::native_to_unicode($n)
5713 >= utf8::native_to_unicode(ord(' '))
5714 and utf8::native_to_unicode($n)
5715 <= utf8::native_to_unicode(ord('~')));
5716
5717 my $mnemonic_pos = index("\a\b\e\f\n\r\t", chr($n));
5718 return "\\" . substr("abefnrt", $mnemonic_pos, 1) if $mnemonic_pos >= 0;
5719
5720 return '\\c' . $unctrl{chr $n} if $n >= ord("\cA") and $n <= ord("\cZ");
5721# return '\x' . sprintf("%02x", $n);
5722 return '\\' . sprintf("%03o", $n);
6e90668e
SM
5723}
5724
5a92c677
DM
5725# Convert a list of characters into a string suitable for tr/// search or
5726# replacement, with suitable escaping and collapsing of ranges
5727
6e90668e
SM
5728sub collapse {
5729 my(@chars) = @_;
23db111c 5730 my($str, $c, $tr) = ("");
6e90668e
SM
5731 for ($c = 0; $c < @chars; $c++) {
5732 $tr = $chars[$c];
5733 $str .= pchr($tr);
5734 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
5735 $chars[$c + 2] == $tr + 2)
5736 {
f4a44678
SM
5737 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
5738 {}
6e90668e
SM
5739 $str .= "-";
5740 $str .= pchr($chars[$c]);
5741 }
5742 }
5743 return $str;
5744}
5745
f4a44678
SM
5746sub tr_decode_byte {
5747 my($table, $flags) = @_;
6d63cc8e 5748 my $ssize_t = $Config{ptrsize} == 8 ? 'q' : 'l';
0b9a13c3 5749 my ($size, @table) = unpack("${ssize_t}s*", $table);
0b9a13c3 5750 pop @table; # remove the wildcard final entry
c923a699 5751
6e90668e 5752 my($c, $tr, @from, @to, @delfrom, $delhyphen);
d989cdac 5753 if ($table[ord "-"] != -1 and
6e90668e
SM
5754 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
5755 {
5756 $tr = $table[ord "-"];
5757 $table[ord "-"] = -1;
5758 if ($tr >= 0) {
5759 @from = ord("-");
5760 @to = $tr;
5761 } else { # -2 ==> delete
5762 $delhyphen = 1;
5763 }
5764 }
2a9e2f8a 5765 for ($c = 0; $c < @table; $c++) {
6e90668e
SM
5766 $tr = $table[$c];
5767 if ($tr >= 0) {
5768 push @from, $c; push @to, $tr;
5769 } elsif ($tr == -2) {
5770 push @delfrom, $c;
5771 }
5772 }
6e90668e 5773 @from = (@from, @delfrom);
4fc9437a 5774
f4a44678 5775 if ($flags & OPpTRANS_COMPLEMENT) {
4fc9437a
DM
5776 unless ($flags & OPpTRANS_DELETE) {
5777 @to = () if ("@from" eq "@to");
5778 }
5779
6e90668e
SM
5780 my @newfrom = ();
5781 my %from;
5782 @from{@from} = (1) x @from;
5783 for ($c = 0; $c < 256; $c++) {
5784 push @newfrom, $c unless $from{$c};
5785 }
5786 @from = @newfrom;
5787 }
56d8b52c 5788 unless ($flags & OPpTRANS_DELETE || !@to) {
6e90668e
SM
5789 pop @to while $#to and $to[$#to] == $to[$#to -1];
5790 }
6e90668e
SM
5791 my($from, $to);
5792 $from = collapse(@from);
5793 $to = collapse(@to);
5794 $from .= "-" if $delhyphen;
f4a44678
SM
5795 return ($from, $to);
5796}
5797
8914f6f0 5798my $infinity = ~0 >> 1; # IV_MAX
760febe4 5799
8914f6f0
KW
5800sub tr_append_to_invlist {
5801 my ($list_ref, $current, $next) = @_;
f4a44678 5802
8914f6f0 5803 # Appends the range $current..$next-1 to the inversion list $list_ref
f34acfec 5804
8914f6f0
KW
5805 printf STDERR "%d: %d..%d %s", __LINE__, $current, $next, Dumper $list_ref if DEBUG;
5806
5807 if (@$list_ref && $list_ref->[-1] == $current) {
5808
5809 # The new range extends the current final one. If it is a finite
5810 # rane, replace the current final by the new ending.
5811 if (defined $next) {
5812 $list_ref->[-1] = $next;
f34acfec 5813 }
8914f6f0
KW
5814 else {
5815 # The new range extends to infinity, which means the current end
5816 # of the inversion list is dangling. Removing it causes things to
5817 # work.
5818 pop @$list_ref;
f34acfec 5819 }
8914f6f0
KW
5820 }
5821 else { # The new range starts after the current final one; add it as a
5822 # new range
5823 push @$list_ref, $current;
5824 push @$list_ref, $next if defined $next;
5825 }
5826
5827 print STDERR __LINE__, ": ", Dumper $list_ref if DEBUG;
5828}
5829
5830sub tr_invlist_to_string {
5831 my ($list_ref, $to_complement) = @_;
5832
5833 # Stringify the inversion list $list_ref, possibly complementing it first.
5834 # CAUTION: this can modify $list_ref.
5835
5836 print STDERR __LINE__, ": ", Dumper $list_ref if DEBUG;
5837
5838 if ($to_complement) {
5839
5840 # Complementing an inversion list is done by prepending a 0 if it
5841 # doesn't have one there already; otherwise removing the leading 0.
5842 if ($list_ref->[0] == 0) {
5843 shift @$list_ref;
f34acfec
KW
5844 }
5845 else {
8914f6f0 5846 unshift @$list_ref, 0;
f34acfec 5847 }
8914f6f0
KW
5848
5849 print STDERR __LINE__, ": ", Dumper $list_ref if DEBUG;
f4a44678 5850 }
f34acfec 5851
8914f6f0
KW
5852 my $output = "";
5853
5854 # Every other element is in the list.
5855 for (my $i = 0; $i < @$list_ref; $i += 2) {
5856 my $base = $list_ref->[$i];
5857 $output .= pchr($base);
5858 last unless defined $list_ref->[$i+1];
5859
5860 # The beginning of the next element starts the range of items not in
5861 # the list.
5862 my $upper = $list_ref->[$i+1] - 1;
5863 my $range = $upper - $base;
5864 $output .= '-' if $range > 1; # Adjacent characters don't have a
5865 # minus, though it would be legal to do
5866 # so
5867 $output .= pchr($upper) if $range > 0;
5868 }
5869
5870 print STDERR __LINE__, ": tr_invlist_to_string() returning '$output'\n"
5871 if DEBUG;
5872 return $output;
f34acfec
KW
5873}
5874
8914f6f0
KW
5875my $unmapped = ~0;
5876my $special_handling = ~0 - 1;
5877
a5158e4f
KW
5878sub dump_invmap {
5879 my ($invlist_ref, $map_ref) = @_;
5880
5881 for my $i (0 .. @$invlist_ref - 1) {
5882 printf STDERR "[%d]\t%x\t", $i, $invlist_ref->[$i];
5883 my $map = $map_ref->[$i];
5884 if ($map == $unmapped) {
5885 print STDERR "TR_UNMAPPED\n";
5886 }
5887 elsif ($map == $special_handling) {
5888 print STDERR "TR_SPECIAL\n";
5889 }
5890 else {
5891 printf STDERR "%x\n", $map;
5892 }
5893 }
5894}
5895
f34acfec
KW
5896sub tr_decode_utf8 {
5897 my($tr_av, $flags) = @_;
8914f6f0
KW
5898
5899 printf STDERR "\n%s: %d: flags=0x%x\n", __FILE__, __LINE__, $flags if DEBUG;
5900
f34acfec
KW
5901 my $invlist = $tr_av->ARRAYelt(0);
5902 my @invlist = unpack("J*", $invlist->PV);
5903 my @map = unpack("J*", $tr_av->ARRAYelt(1)->PV);
5904
a5158e4f 5905 dump_invmap(\@invlist, \@map) if DEBUG;
f34acfec 5906
8914f6f0
KW
5907 my @from;
5908 my @to;
f34acfec 5909
8914f6f0
KW
5910 # Go through the whole map
5911 for (my $i = 0; $i < @invlist; $i++) {
5912 my $map = $map[$i];
5913 printf STDERR "%d: i=%d, source=%x, map=%x\n",
5914 __LINE__, $i, $invlist[$i], $map if DEBUG;
5915
5916 # Ignore any lines that are unmapped
5917 next if $map == $unmapped;
5918
5919 # Calculate this component of the mapping; First the lhs
5920 my $this_from = $invlist[$i];
5921 my $next_from = $invlist[$i+1] if $i < @invlist - 1;
5922
5923 # The length of the rhs is the same as the lhs, except when special
5924 my $next_map = $map - $this_from + $next_from
5925 if $map != $special_handling && defined $next_from;
5926
5927 if (DEBUG) {
5928 printf STDERR "%d: i=%d, from=%x, to=%x",
5929 __LINE__, $i, $this_from, $map;
5930 printf STDERR ", next_from=%x,", $next_from if defined $next_from;
5931 printf STDERR ", next_map=%x", $next_map if defined $next_map;
5932 print STDERR "\n";
5933 }
5934
5935 # Add the lhs.
5936 tr_append_to_invlist(\@from, $this_from, $next_from);
5937
5938 # And, the rhs; special handling doesn't get output as it really is an
5939 # unmatched rhs
5940 tr_append_to_invlist(\@to, $map, $next_map) if $map != $special_handling;
f4a44678 5941 }
f34acfec 5942
8914f6f0
KW
5943 # Done with the input.
5944
5945 my $to;
5946 if (join("", @from) eq join("", @to)) {
5947
5948 # the rhs is suppressed if identical to the left. That's because
5949 # tr/ABC/ABC/ can be written as tr/ABC//. (Do this comparison before
5950 # any complementing)
5951 $to = "";
5952 }
5953 else {
5954 $to = tr_invlist_to_string(\@to, 0); # rhs not complemented
f4a44678 5955 }
8914f6f0
KW
5956
5957 my $from = tr_invlist_to_string(\@from,
5958 ($flags & OPpTRANS_COMPLEMENT) != 0);
5959
5960 print STDERR "Returning ", escape_str($from), "/",
5961 escape_str($to), "\n" if DEBUG;
f4a44678
SM
5962 return (escape_str($from), escape_str($to));
5963}
5964
5965sub pp_trans {
5966 my $self = shift;
05a502dc 5967 my($op, $cx, $morflags) = @_;
f4a44678 5968 my($from, $to);
cb8157e3 5969 my $class = class($op);
b031d0e6 5970 my $priv_flags = $op->private;
cb8157e3 5971 if ($class eq "PVOP") {
b031d0e6 5972 ($from, $to) = tr_decode_byte($op->pv, $priv_flags);
cb8157e3
FC
5973 } elsif ($class eq "PADOP") {
5974 ($from, $to)
f34acfec 5975 = tr_decode_utf8($self->padval($op->padix), $priv_flags);
f4a44678 5976 } else { # class($op) eq "SVOP"
f34acfec 5977 ($from, $to) = tr_decode_utf8($op->sv, $priv_flags);
f4a44678
SM
5978 }
5979 my $flags = "";
42b824d2
FC
5980 $flags .= "c" if $priv_flags & OPpTRANS_COMPLEMENT;
5981 $flags .= "d" if $priv_flags & OPpTRANS_DELETE;
f4a44678 5982 $to = "" if $from eq $to and $flags eq "";
42b824d2 5983 $flags .= "s" if $priv_flags & OPpTRANS_SQUASH;
05a502dc
FC
5984 $flags .= $morflags if defined $morflags;
5985 my $ret = $self->keyword("tr") . double_delim($from, $to) . $flags;
5986 if (my $targ = $op->targ) {
5987 return $self->maybe_parens($self->padname($targ) . " =~ $ret",
5988 $cx, 20);
5989 }
5990 return $ret;
6e90668e
SM
5991}
5992
05a502dc 5993sub pp_transr { push @_, 'r'; goto &pp_trans }
bb16bae8 5994
e839e6ed
DM
5995# Join two components of a double-quoted re, disambiguating
5996# "${foo}bar", "${foo}{bar}", "${foo}[1]".
5997
03b22f1b
RGS
5998sub re_dq_disambiguate {
5999 my ($first, $last) = @_;
03b22f1b
RGS
6000 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
6001 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
6002 || ($last =~ /^[{\[\w_]/ &&
6003 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
6004 return $first . $last;
6005}
6006
6e90668e
SM
6007# Like dq(), but different
6008sub re_dq {
6009 my $self = shift;
ba0372a0 6010 my ($op) = @_;
a9760014 6011
3f872cb9
GS
6012 my $type = $op->name;
6013 if ($type eq "const") {
a9760014 6014 my $unbacked = re_unback($self->const_sv($op)->as_string);
ba0372a0 6015 return re_uninterp(escape_re($unbacked));
3f872cb9 6016 } elsif ($type eq "concat") {
ba0372a0
FC
6017 my $first = $self->re_dq($op->first);
6018 my $last = $self->re_dq($op->last);
03b22f1b 6019 return re_dq_disambiguate($first, $last);
e839e6ed
DM
6020 } elsif ($type eq "multiconcat") {
6021 return $self->do_multiconcat($op, 26, 2);
3f872cb9 6022 } elsif ($type eq "uc") {
ba0372a0 6023 return '\U' . $self->re_dq($op->first->sibling) . '\E';
3f872cb9 6024 } elsif ($type eq "lc") {
ba0372a0 6025 return '\L' . $self->re_dq($op->first->sibling) . '\E';
3f872cb9 6026 } elsif ($type eq "ucfirst") {
ba0372a0 6027 return '\u' . $self->re_dq($op->first->sibling);
3f872cb9 6028 } elsif ($type eq "lcfirst") {
ba0372a0 6029 return '\l' . $self->re_dq($op->first->sibling);
3f872cb9 6030 } elsif ($type eq "quotemeta") {
ba0372a0 6031 return '\Q' . $self->re_dq($op->first->sibling) . '\E';
838f2281 6032 } elsif ($type eq "fc") {
ba0372a0 6033 return '\F' . $self->re_dq($op->first->sibling) . '\E';
3f872cb9 6034 } elsif ($type eq "join") {
9d2c6865 6035 return $self->deparse($op->last, 26); # was join($", @ary)
6e90668e 6036 } else {
337d7381 6037 my $ret = $self->deparse($op, 26);
3f193e55
FC
6038 $ret =~ s/^\$([(|)])\z/\${$1}/ # $( $| $) need braces
6039 or $ret =~ s/^\@([-+])\z/\@{$1}/; # @- @+ need braces
337d7381 6040 return $ret;
6e90668e
SM
6041 }
6042}
6043
a9760014
RH
6044sub pure_string {
6045 my ($self, $op) = @_;
64b007ad 6046 return 0 if null $op;
a9760014
RH
6047 my $type = $op->name;
6048
36727b53 6049 if ($type eq 'const' || $type eq 'av2arylen') {
a9760014
RH
6050 return 1;
6051 }
838f2281 6052 elsif ($type =~ /^(?:[ul]c(first)?|fc)$/ || $type eq 'quotemeta') {
a9760014
RH
6053 return $self->pure_string($op->first->sibling);
6054 }
6055 elsif ($type eq 'join') {
6056 my $join_op = $op->first->sibling; # Skip pushmark
76e14ed3 6057 return 0 unless $join_op->name eq 'null' && $join_op->targ == OP_RV2SV;
a9760014
RH
6058
6059 my $gvop = $join_op->first;
6060 return 0 unless $gvop->name eq 'gvsv';
6061 return 0 unless '"' eq $self->gv_name($self->gv_or_padgv($gvop));
6062
6063 return 0 unless ${$join_op->sibling} eq ${$op->last};
21b7468a 6064 return 0 unless $op->last->name =~ /^(?:[ah]slice|(?:rv2|pad)av)$/;
a9760014
RH
6065 }
6066 elsif ($type eq 'concat') {
6067 return $self->pure_string($op->first)
6068 && $self->pure_string($op->last);
6069 }
e839e6ed
DM
6070 elsif ($type eq 'multiconcat') {
6071 my ($kid, @kids);
6072 for ($kid = $op->first; !null $kid; $kid = $kid->sibling) {
6073 # skip the consts and/or padsv we've optimised away
6074 push @kids, $kid
6075 unless $kid->type == OP_NULL
6076 && ( $kid->targ == OP_PADSV
6077 || $kid->targ == OP_CONST
6078 || $kid->targ == OP_PUSHMARK);
6079 }
6080
6081 if ($op->flags & OPf_STACKED) {
6082 # remove expr from @kids where 'expr = ...' or 'expr .= ....'
6083 if ($op->private & OPpMULTICONCAT_APPEND) {
6084 shift(@kids);
6085 }
6086 else {
6087 pop(@kids);
6088 }
6089 }
6090 for (@kids) {
6091 return 0 unless $self->pure_string($_);
6092 }
6093 return 1;
6094 }
d989cdac
SM
6095 elsif (is_scalar($op) || $type =~ /^[ah]elem$/) {
6096 return 1;
6097 }
fedf30e1
DM
6098 elsif ($type eq "null" and $op->can('first') and not null $op->first) {
6099 my $first = $op->first;
6100
6101 return 1 if $first->name eq "multideref";
6102 return 1 if $first->name eq "aelemfast_lex";
6103
6104 if ( $first->name eq "null"
6105 and $first->can('first')
6106 and not null $first->first
6107 and $first->first->name eq "aelemfast"
6108 )
6109 {
6110 return 1;
6111 }
a9760014
RH
6112 }
6113
fedf30e1 6114 return 0;
a9760014
RH
6115}
6116
061bc525 6117sub code_list {
ba0372a0 6118 my ($self,$op,$cv) = @_;
061bc525
FC
6119
6120 # localise stuff relating to the current sub
6121 $cv and
6122 local($self->{'curcv'}) = $cv,
6123 local($self->{'curcvlex'}),
6124 local(@$self{qw'curstash warnings hints hinthash curcop'})
6125 = @$self{qw'curstash warnings hints hinthash curcop'};
6126
6127 my $re;
3e18cd1c 6128 for ($op = $op->first->sibling; !null($op); $op = $op->sibling) {
59d42aa0 6129 if ($op->name eq 'null' and $op->flags & OPf_SPECIAL) {
061bc525
FC
6130 my $scope = $op->first;
6131 # 0 context (last arg to scopeop) means statement context, so
6132 # the contents of the block will not be wrapped in do{...}.
6133 my $block = scopeop($scope->first->name eq "enter", $self,
6134 $scope, 0);
6135 # next op is the source code of the block
6136 $op = $op->sibling;
6137 $re .= ($self->const_sv($op)->PV =~ m|^(\(\?\??\{)|)[0];
6138 my $multiline = $block =~ /\n/;
6139 $re .= $multiline ? "\n\t" : ' ';
6140 $re .= $block;
6141 $re .= $multiline ? "\n\b})" : " })";
59d42aa0 6142 } else {
ba0372a0 6143 $re = re_dq_disambiguate($re, $self->re_dq($op));
061bc525
FC
6144 }
6145 }
6146 $re;
6147}
6148
a9760014 6149sub regcomp {
6e90668e 6150 my $self = shift;
ba0372a0 6151 my($op, $cx) = @_;
6e90668e 6152 my $kid = $op->first;
3f872cb9
GS
6153 $kid = $kid->first if $kid->name eq "regcmaybe";
6154 $kid = $kid->first if $kid->name eq "regcreset";
bae5b54e
FC
6155 my $kname = $kid->name;
6156 if ($kname eq "null" and !null($kid->first)
131b3ad0
DM
6157 and $kid->first->name eq 'pushmark')
6158 {
6159 my $str = '';
6160 $kid = $kid->first->sibling;
6161 while (!null($kid)) {
03b22f1b 6162 my $first = $str;
ba0372a0 6163 my $last = $self->re_dq($kid);
03b22f1b 6164 $str = re_dq_disambiguate($first, $last);
131b3ad0
DM
6165 $kid = $kid->sibling;
6166 }
6167 return $str, 1;
6168 }
6169
bae5b54e
FC
6170 return ($self->re_dq($kid), 1)
6171 if $kname =~ /^(?:rv2|pad)av/ or $self->pure_string($kid);
a9760014
RH
6172 return ($self->deparse($kid, $cx), 0);
6173}
6174
6175sub pp_regcomp {
6176 my ($self, $op, $cx) = @_;
6177 return (($self->regcomp($op, $cx, 0))[0]);
6e90668e
SM
6178}
6179
c3ae113d
FC
6180sub re_flags {
6181 my ($self, $op) = @_;
6182 my $flags = '';
6183 my $pmflags = $op->pmflags;
3b91d897
FC
6184 if (!$pmflags) {
6185 my $re = $op->pmregexp;
6186 if ($$re) {
6187 $pmflags = $re->compflags;
6188 }
6189 }
c3ae113d
FC
6190 $flags .= "g" if $pmflags & PMf_GLOBAL;
6191 $flags .= "i" if $pmflags & PMf_FOLD;
6192 $flags .= "m" if $pmflags & PMf_MULTILINE;
6193 $flags .= "o" if $pmflags & PMf_KEEP;
6194 $flags .= "s" if $pmflags & PMf_SINGLELINE;
6195 $flags .= "x" if $pmflags & PMf_EXTENDED;
334afb3e 6196 $flags .= "x" if $pmflags & PMf_EXTENDED_MORE;
dc6dfd62
LM
6197 $flags .= "p" if $pmflags & PMf_KEEPCOPY;
6198 $flags .= "n" if $pmflags & PMf_NOCAPTURE;
6199 if (my $charset = $pmflags & PMf_CHARSET) {
c3ae113d
FC
6200 # Hardcoding this is fragile, but B does not yet export the
6201 # constants we need.
fde14af1 6202 $flags .= qw(d l u a aa)[$charset >> 7]
c3ae113d
FC
6203 }
6204 # The /d flag is indicated by 0; only show it if necessary.
6205 elsif ($self->{hinthash} and
6206 $self->{hinthash}{reflags_charset}
dff5ffe4 6207 || $self->{hinthash}{feature_unicode}
149758b3
NC
6208 or $self->{hints} & $feature::hint_mask
6209 && ($self->{hints} & $feature::hint_mask)
6210 != $feature::hint_mask
dc6dfd62
LM
6211 && $self->{hints} & $feature::hint_uni8bit
6212 ) {
c3ae113d
FC
6213 $flags .= 'd';
6214 }
6215 $flags;
6216}
6217
6e90668e
SM
6218# osmic acid -- see osmium tetroxide
6219
6220my %matchwords;
6221map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs',
d989cdac 6222 'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic',
54421dd4 6223 'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi', 'soup', 'soupmix');
6e90668e 6224
59d42aa0
FC
6225# When deparsing a regular expression with code blocks, we have to look in
6226# various places to find the blocks.
6227#
6228# For qr/(?{...})/ without interpolation, the CV is under $qr->qr_anoncv
6229# and the code list (list of blocks and constants, maybe vars) is under
6230# $cv->ROOT->first->code_list:
6231# ./perl -Ilib -MB -e 'use O "Concise", B::svref_2object(sub {qr/(?{die})/})->ROOT->first->first->sibling->pmregexp->qr_anoncv->object_2svref'
6232#
6233# For qr/$a(?{...})/ with interpolation, the code list is more accessible,
6234# under $pmop->code_list, but the $cv is something you have to dig for in
6235# the regcomp op’s kids:
6236# ./perl -Ilib -mO=Concise -e 'qr/$a(?{die})/'
6237#
6238# For m// and split //, things are much simpler. There is no CV. The code
6239# list is under $pmop->code_list.
6240
90be192f 6241sub matchop {
6e90668e 6242 my $self = shift;
90be192f 6243 my($op, $cx, $name, $delim) = @_;
6e90668e 6244 my $kid = $op->first;
9d2c6865 6245 my ($binop, $var, $re) = ("", "", "");
5012eebe 6246 if ($op->name ne 'split' && $op->flags & OPf_STACKED) {
9d2c6865
SM
6247 $binop = 1;
6248 $var = $self->deparse($kid, 20);
6e90668e
SM
6249 $kid = $kid->sibling;
6250 }
9e32885a
FC
6251 # not $name; $name will be 'm' for both match and split
6252 elsif ($op->name eq 'match' and my $targ = $op->targ) {
05a502dc
FC
6253 $binop = 1;
6254 $var = $self->padname($targ);
6255 }
a9760014 6256 my $quote = 1;
86e39c78 6257 my $pmflags = $op->pmflags;
a539498a 6258 my $rhs_bound_to_defsv;
59d42aa0
FC
6259 my ($cv, $bregexp);
6260 my $have_kid = !null $kid;
6261 # Check for code blocks first
6262 if (not null my $code_list = $op->code_list) {
ba0372a0 6263 $re = $self->code_list($code_list,
59d42aa0
FC
6264 $op->name eq 'qr'
6265 ? $self->padval(
6266 $kid->first # ex-list
6267 ->first # pushmark
6268 ->sibling # entersub
6269 ->first # ex-list
6270 ->first # pushmark
6271 ->sibling # srefgen
6272 ->first # ex-list
6273 ->first # anoncode
6274 ->targ
6275 )
6276 : undef);
6277 } elsif (${$bregexp = $op->pmregexp} && ${$cv = $bregexp->qr_anoncv}) {
061bc525
FC
6278 my $patop = $cv->ROOT # leavesub
6279 ->first # qr
3e18cd1c 6280 ->code_list;# list
ba0372a0 6281 $re = $self->code_list($patop, $cv);
59d42aa0 6282 } elsif (!$have_kid) {
ba0372a0 6283 $re = re_uninterp(escape_re(re_unback($op->precomp)));
a9760014 6284 } elsif ($kid->name ne 'regcomp') {
5012eebe
DM
6285 if ($op->name eq 'split') {
6286 # split has other kids, not just regcomp
6287 $re = re_uninterp(escape_re(re_unback($op->precomp)));
6288 }
6289 else {
6290 carp("found ".$kid->name." where regcomp expected");
6291 }
6e90668e 6292 } else {
ba0372a0 6293 ($re, $quote) = $self->regcomp($kid, 21);
59d42aa0
FC
6294 }
6295 if ($have_kid and $kid->name eq 'regcomp') {
7fb31b92 6296 my $matchop = $kid->first;
d02d1323 6297 if ($matchop->name eq 'regcreset') {
7fb31b92
DM
6298 $matchop = $matchop->first;
6299 }
5e5a1632
FC
6300 if ($matchop->name =~ /^(?:match|transr?|subst)\z/
6301 && $matchop->flags & OPf_SPECIAL) {
6302 $rhs_bound_to_defsv = 1;
6303 }
6e90668e
SM
6304 }
6305 my $flags = "";
5992ca2b 6306 $flags .= "c" if $pmflags & PMf_CONTINUE;
c3ae113d
FC
6307 $flags .= $self->re_flags($op);
6308 $flags = join '', sort split //, $flags;
6e90668e 6309 $flags = $matchwords{$flags} if $matchwords{$flags};
5992ca2b 6310 if ($pmflags & PMf_ONCE) { # only one kind of delimiter works here
6e90668e 6311 $re =~ s/\?/\\?/g;
7741ceed 6312 $re = $self->keyword("m") . "?$re?"; # explicit 'm' is required
a9760014 6313 } elsif ($quote) {
7741ceed 6314 $re = single_delim($name, $delim, $re, $self);
9d2c6865 6315 }
a9760014 6316 $re = $re . $flags if $quote;
9d2c6865 6317 if ($binop) {
a539498a
FC
6318 return
6319 $self->maybe_parens(
6320 $rhs_bound_to_defsv
6321 ? "$var =~ (\$_ =~ $re)"
6322 : "$var =~ $re",
6323 $cx, 20
6324 );
9d2c6865
SM
6325 } else {
6326 return $re;
6e90668e 6327 }
6e90668e
SM
6328}
6329
90be192f 6330sub pp_match { matchop(@_, "m", "/") }
90be192f 6331sub pp_qr { matchop(@_, "qr", "") }
6e90668e 6332
84ed0108
FC
6333sub pp_runcv { unop(@_, "__SUB__"); }
6334
6e90668e
SM
6335sub pp_split {
6336 my $self = shift;
9d2c6865 6337 my($op, $cx) = @_;
6e90668e 6338 my($kid, @exprs, $ary, $expr);
5012eebe
DM
6339 my $stacked = $op->flags & OPf_STACKED;
6340
6e90668e 6341 $kid = $op->first;
5012eebe
DM
6342 $kid = $kid->sibling if $kid->name eq 'regcomp';
6343 for (; !null($kid); $kid = $kid->sibling) {
6344 push @exprs, $self->deparse($kid, 6);
6345 }
c6e79e55 6346
5012eebe
DM
6347 unshift @exprs, $self->matchop($op, $cx, "m", "/");
6348
6349 if ($op->private & OPpSPLIT_ASSIGN) {
6350 # With C<@array = split(/pat/, str);>,
6351 # array is stored in split's pmreplroot; either
6352 # as an integer index into the pad (for a lexical array)
6353 # or as GV for a package array (which will be a pad index
6354 # on threaded builds)
6355 # With my/our @array = split(/pat/, str), the array is instead
6356 # accessed via an extra padav/rv2av op at the end of the
6357 # split's kid ops.
6358
6359 if ($stacked) {
6360 $ary = pop @exprs;
6361 }
6362 else {
6363 if ($op->private & OPpSPLIT_LEX) {
6364 $ary = $self->padname($op->pmreplroot);
6365 }
6366 else {
6367 # union with op_pmtargetoff, op_pmtargetgv
6368 my $gv = $op->pmreplroot;
6369 $gv = $self->padval($gv) if !ref($gv);
6370 $ary = $self->maybe_local(@_,
de183bbb
FC
6371 $self->stash_variable('@',
6372 $self->gv_name($gv),
6373 $cx))
5012eebe 6374 }
692044df
DM
6375 if ($op->private & OPpLVAL_INTRO) {
6376 $ary = $op->private & OPpSPLIT_LEX ? "my $ary" : "local $ary";
6377 }
5012eebe 6378 }
6e90668e 6379 }
fcd95d64 6380
f86ea535 6381 # handle special case of split(), and split(' ') that compiles to /\s+/
5012eebe 6382 $exprs[0] = q{' '} if ($op->reflags // 0) & RXf_SKIPWHITE();
fcd95d64 6383
6e90668e
SM
6384 $expr = "split(" . join(", ", @exprs) . ")";
6385 if ($ary) {
9d2c6865 6386 return $self->maybe_parens("$ary = $expr", $cx, 7);
6e90668e
SM
6387 } else {
6388 return $expr;
6389 }
6390}
6391
6392# oxime -- any of various compounds obtained chiefly by the action of
6393# hydroxylamine on aldehydes and ketones and characterized by the
6394# bivalent grouping C=NOH [Webster's Tenth]
6395
6396my %substwords;
6397map($substwords{join "", sort split //, $_} = $_, 'ego', 'egoism', 'em',
6398 'es', 'ex', 'exes', 'gee', 'go', 'goes', 'ie', 'ism', 'iso', 'me',
6399 'meese', 'meso', 'mig', 'mix', 'os', 'ox', 'oxime', 'see', 'seem',
ddc6eb27 6400 'seg', 'sex', 'sig', 'six', 'smog', 'sog', 'some', 'xi', 'rogue',
4f4d7508
DC
6401 'sir', 'rise', 'smore', 'more', 'seer', 'rome', 'gore', 'grim', 'grime',
6402 'or', 'rose', 'rosie');
6e90668e
SM
6403
6404sub pp_subst {
6405 my $self = shift;
9d2c6865 6406 my($op, $cx) = @_;
6e90668e 6407 my $kid = $op->first;
9d2c6865 6408 my($binop, $var, $re, $repl) = ("", "", "", "");
6e90668e 6409 if ($op->flags & OPf_STACKED) {
9d2c6865
SM
6410 $binop = 1;
6411 $var = $self->deparse($kid, 20);
6e90668e
SM
6412 $kid = $kid->sibling;
6413 }
05a502dc
FC
6414 elsif (my $targ = $op->targ) {
6415 $binop = 1;
6416 $var = $self->padname($targ);
6417 }
d989cdac 6418 my $flags = "";
86e39c78 6419 my $pmflags = $op->pmflags;
6e90668e 6420 if (null($op->pmreplroot)) {
ef90d20a 6421 $repl = $kid;
6e90668e
SM
6422 $kid = $kid->sibling;
6423 } else {
6424 $repl = $op->pmreplroot->first; # skip substcont
ef90d20a
FC
6425 }
6426 while ($repl->name eq "entereval") {
6e90668e
SM
6427 $repl = $repl->first;
6428 $flags .= "e";
ef90d20a 6429 }
9f125c4a
FC
6430 {
6431 local $self->{in_subst_repl} = 1;
6432 if ($pmflags & PMf_EVAL) {
d989cdac 6433 $repl = $self->deparse($repl->first, 0);
9f125c4a 6434 } else {
bd0865ec 6435 $repl = $self->dq($repl);
9f125c4a 6436 }
6e90668e 6437 }
87ebe743 6438 if (not null my $code_list = $op->code_list) {
ba0372a0 6439 $re = $self->code_list($code_list);
87ebe743 6440 } elsif (null $kid) {
ba0372a0 6441 $re = re_uninterp(escape_re(re_unback($op->precomp)));
6e90668e 6442 } else {
ba0372a0 6443 ($re) = $self->regcomp($kid, 1);
a798dbf2 6444 }
86e39c78
FC
6445 $flags .= "r" if $pmflags & PMf_NONDESTRUCT;
6446 $flags .= "e" if $pmflags & PMf_EVAL;
c3ae113d
FC
6447 $flags .= $self->re_flags($op);
6448 $flags = join '', sort split //, $flags;
6e90668e 6449 $flags = $substwords{$flags} if $substwords{$flags};
7741ceed 6450 my $core_s = $self->keyword("s"); # maybe CORE::s
9d2c6865 6451 if ($binop) {
7741ceed 6452 return $self->maybe_parens("$var =~ $core_s"
9d2c6865
SM
6453 . double_delim($re, $repl) . $flags,
6454 $cx, 20);
6455 } else {
7741ceed 6456 return "$core_s". double_delim($re, $repl) . $flags;
9d2c6865 6457 }
a798dbf2
MB
6458}
6459
73582821
AC
6460sub is_lexical_subs {
6461 my (@ops) = shift;
6462 for my $op (@ops) {
6463 return 0 if $op->name !~ /\A(?:introcv|clonecv)\z/;
6464 }
6465 return 1;
6466}
6467
d4f1bfe7
FC
6468# Pretend these two ops do not exist. The perl parser adds them to the
6469# beginning of any block containing my-sub declarations, whereas we handle
6470# the subs in pad_subs and next_todo.
6471*pp_clonecv = *pp_introcv;
73582821
AC
6472sub pp_introcv {
6473 my $self = shift;
6474 my($op, $cx) = @_;
6475 # For now, deparsing doesn't worry about the distinction between introcv
6476 # and clonecv, so pretend this op doesn't exist:
6477 return '';
6478}
6479
73582821
AC
6480sub pp_padcv {
6481 my $self = shift;
6482 my($op, $cx) = @_;
6483 return $self->padany($op);
6484}
6485
9187b6e4
FC
6486my %lvref_funnies = (
6487 OPpLVREF_SV, => '$',
6488 OPpLVREF_AV, => '@',
6489 OPpLVREF_HV, => '%',
6490 OPpLVREF_CV, => '&',
6491);
6492
6493sub pp_refassign {
6494 my ($self, $op, $cx) = @_;
6495 my $left;
6496 if ($op->private & OPpLVREF_ELEM) {
3028eff1 6497 $left = $op->first->sibling;
9187b6e4
FC
6498 $left = maybe_local(@_, elem($self, $left, undef,
6499 $left->targ == OP_AELEM
6500 ? qw([ ] padav)
6501 : qw({ } padhv)));
6502 } elsif ($op->flags & OPf_STACKED) {
6503 $left = maybe_local(@_,
6504 $lvref_funnies{$op->private & OPpLVREF_TYPE}
6505 . $self->deparse($op->first->sibling));
6506 } else {
6507 $left = &pp_padsv;
6508 }
6509 my $right = $self->deparse_binop_right($op, $op->first, 7);
6510 return $self->maybe_parens("\\$left = $right", $cx, 7);
6511}
6512
6513sub pp_lvref {
6514 my ($self, $op, $cx) = @_;
6515 my $code;
6516 if ($op->private & OPpLVREF_ELEM) {
6517 $code = $op->first->name =~ /av\z/ ? &pp_aelem : &pp_helem;
6518 } elsif ($op->flags & OPf_STACKED) {
6519 $code = maybe_local(@_,
6520 $lvref_funnies{$op->private & OPpLVREF_TYPE}
6521 . $self->deparse($op->first));
6522 } else {
6523 $code = &pp_padsv;
6524 }
6525 "\\$code";
6526}
6527
6528sub pp_lvrefslice {
6529 my ($self, $op, $cx) = @_;
6530 '\\' . ($op->last->name =~ /av\z/ ? &pp_aslice : &pp_hslice);
6531}
6532
6533sub pp_lvavref {
6534 my ($self, $op, $cx) = @_;
6535 '\\(' . ($op->flags & OPf_STACKED
6536 ? maybe_local(@_, rv2x(@_, "\@"))
6537 : &pp_padsv) . ')'
6538}
6539
4fa06845
DM
6540
6541sub pp_argcheck {
6542 my $self = shift;
6543 my($op, $cx) = @_;
6544 my ($params, $opt_params, $slurpy) = $op->aux_list($self->{curcv});
6545 my $mandatory = $params - $opt_params;
6546 my $check = '';
6547
6548 $check .= <<EOF if !$slurpy;
6549die sprintf("Too many arguments for subroutine at %s line %d.\\n", (caller)[1, 2]) unless \@_ <= $params;
6550EOF
6551
6552 $check .= <<EOF if $mandatory > 0;
6553die sprintf("Too few arguments for subroutine at %s line %d.\\n", (caller)[1, 2]) unless \@_ >= $mandatory;
6554EOF
6555
6556 my $cond = ($params & 1) ? 'unless' : 'if';
6557 $check .= <<EOF if $slurpy eq '%';
6558die sprintf("Odd name/value argument for subroutine at %s line %d.\\n", (caller)[1, 2]) if \@_ > $params && ((\@_ - $params) & 1);
6559EOF
6560
6561 $check =~ s/;\n\z//;
6562 return $check;
6563}
6564
6565
6566sub pp_argelem {
6567 my $self = shift;
6568 my($op, $cx) = @_;
6569 my $var = $self->padname($op->targ);
6570 my $ix = $op->string($self->{curcv});
6571 my $expr;
6572 if ($op->flags & OPf_KIDS) {
6573 $expr = $self->deparse($op->first, 7);
6574 }
6575 elsif ($var =~ /^[@%]/) {
6576 $expr = $ix ? "\@_[$ix .. \$#_]" : '@_';
6577 }
6578 else {
6579 $expr = "\$_[$ix]";
6580 }
6581 return "my $var = $expr";
6582}
6583
6584
6585sub pp_argdefelem {
6586 my $self = shift;
6587 my($op, $cx) = @_;
6588 my $ix = $op->targ;
6589 my $expr = "\@_ >= " . ($ix+1) . " ? \$_[$ix] : ";
60f638af
DM
6590 my $def = $self->deparse($op->first, 7);
6591 $def = "($def)" if $op->first->flags & OPf_PARENS;
4fa06845
DM
6592 $expr .= $self->deparse($op->first, $cx);
6593 return $expr;
6594}
6595
6596
f79e2ff9
PE
6597sub pp_pushdefer {
6598 my $self = shift;
6599 my($op, $cx) = @_;
6600 # defer block body is stored in the ->first of an OP_NULL that is
6601 # ->first of OP_PUSHDEFER
6602 my $body = $self->deparse($op->first->first);
6603 return "defer {\n\t$body\n\b}\cK";
6604}
6605
852c1a84
PE
6606sub builtin1 {
6607 my $self = shift;
6608 my ($op, $cx, $name) = @_;
6609 my $arg = $self->deparse($op->first);
6610 # TODO: work out if lexical alias is present somehow...
6611 return "builtin::$name($arg)";
6612}
6613
6614sub pp_isbool { builtin1(@_, "isbool") }
6615
a798dbf2 66161;
f6f9bdb7
SM
6617__END__
6618
6619=head1 NAME
6620
6621B::Deparse - Perl compiler backend to produce perl code
6622
6623=head1 SYNOPSIS
6624
d989cdac 6625B<perl> B<-MO=Deparse>[B<,-d>][B<,-f>I<FILE>][B<,-p>][B<,-q>][B<,-l>]
646bba82 6626 [B<,-s>I<LETTERS>][B<,-x>I<LEVEL>] I<prog.pl>
f6f9bdb7
SM
6627
6628=head1 DESCRIPTION
6629
6630B::Deparse is a backend module for the Perl compiler that generates
6631perl source code, based on the internal compiled structure that perl
d4963d04 6632itself creates after parsing a program. The output of B::Deparse won't
f6f9bdb7
SM
6633be exactly the same as the original source, since perl doesn't keep
6634track of comments or whitespace, and there isn't a one-to-one
6635correspondence between perl's syntactical constructions and their
d4963d04 6636compiled form, but it will often be close. When you use the B<-p>
9d2c6865
SM
6637option, the output also includes parentheses even when they are not
6638required by precedence, which can make it easy to see if perl is
6639parsing your expressions the way you intended.
f6f9bdb7 6640
d989cdac
SM
6641While B::Deparse goes to some lengths to try to figure out what your
6642original program was doing, some parts of the language can still trip
d4963d04 6643it up; it still fails even on some parts of Perl's own test suite. If
d989cdac
SM
6644you encounter a failure other than the most common ones described in
6645the BUGS section below, you can help contribute to B::Deparse's
6646ongoing development by submitting a bug report with a small
6647example.
f6f9bdb7
SM
6648
6649=head1 OPTIONS
6650
9d2c6865
SM
6651As with all compiler backend options, these must follow directly after
6652the '-MO=Deparse', separated by a comma but not any white space.
f6f9bdb7
SM
6653
6654=over 4
6655
d989cdac
SM
6656=item B<-d>
6657
6658Output data values (when they appear as constants) using Data::Dumper.
6659Without this option, B::Deparse will use some simple routines of its
d4963d04 6660own for the same purpose. Currently, Data::Dumper is better for some
d989cdac
SM
6661kinds of data (such as complex structures with sharing and
6662self-reference) while the built-in routines are better for others
6663(such as odd floating-point values).
6664
6665=item B<-f>I<FILE>
6666
6667Normally, B::Deparse deparses the main code of a program, and all the subs
d4963d04
FC
6668defined in the same file. To include subs defined in
6669other files, pass the B<-f> option with the filename.
6670You can pass the B<-f> option several times, to
d989cdac
SM
6671include more than one secondary file. (Most of the time you don't want to
6672use it at all.) You can also use this option to include subs which are
6673defined in the scope of a B<#line> directive with two parameters.
6674
bd0865ec
GS
6675=item B<-l>
6676
6677Add '#line' declarations to the output based on the line and file
6678locations of the original code.
6679
9d2c6865
SM
6680=item B<-p>
6681
d4963d04 6682Print extra parentheses. Without this option, B::Deparse includes
9d2c6865 6683parentheses in its output only when they are needed, based on the
d4963d04
FC
6684structure of your program. With B<-p>, it uses parentheses (almost)
6685whenever they would be legal. This can be useful if you are used to
6686LISP, or if you want to see how perl parses your input. If you say
9d2c6865 6687
d989cdac 6688 if ($var & 0x7f == 65) {print "Gimme an A!"}
9d2c6865
SM
6689 print ($which ? $a : $b), "\n";
6690 $name = $ENV{USER} or "Bob";
6691
6692C<B::Deparse,-p> will print
6693
6694 if (($var & 0)) {
6695 print('Gimme an A!')
6696 };
6697 (print(($which ? $a : $b)), '???');
6698 (($name = $ENV{'USER'}) or '???')
6699
6700which probably isn't what you intended (the C<'???'> is a sign that
6701perl optimized away a constant value).
6702
acaaef34
RGS
6703=item B<-P>
6704
d4963d04
FC
6705Disable prototype checking. With this option, all function calls are
6706deparsed as if no prototype was defined for them. In other words,
acaaef34
RGS
6707
6708 perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x'
6709
6710will print
6711
6712 sub foo (\@) {
6713 1;
6714 }
6715 &foo(\@x);
6716
6717making clear how the parameters are actually passed to C<foo>.
6718
bd0865ec
GS
6719=item B<-q>
6720
6721Expand double-quoted strings into the corresponding combinations of
d4963d04 6722concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For
bd0865ec
GS
6723instance, print
6724
6725 print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";
6726
6727as
6728
6729 print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
6730 . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');
6731
6732Note that the expanded form represents the way perl handles such
6733constructions internally -- this option actually turns off the reverse
d4963d04 6734translation that B::Deparse usually does. On the other hand, note that
bd0865ec
GS
6735C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value
6736of $y into a string before doing the assignment.
6737
9d2c6865
SM
6738=item B<-s>I<LETTERS>
6739
d4963d04
FC
6740Tweak the style of B::Deparse's output. The letters should follow
6741directly after the 's', with no space or punctuation. The following
f4a44678 6742options are available:
9d2c6865
SM
6743
6744=over 4
6745
6746=item B<C>
6747
d4963d04 6748Cuddle C<elsif>, C<else>, and C<continue> blocks. For example, print
9d2c6865
SM
6749
6750 if (...) {
6751 ...
6752 } else {
6753 ...
6754 }
6755
6756instead of
6757
6758 if (...) {
6759 ...
6760 }
6761 else {
6762 ...
6763 }
6764
6765The default is not to cuddle.
6766
f4a44678
SM
6767=item B<i>I<NUMBER>
6768
d4963d04 6769Indent lines by multiples of I<NUMBER> columns. The default is 4 columns.
f4a44678
SM
6770
6771=item B<T>
6772
d4963d04 6773Use tabs for each 8 columns of indent. The default is to use only spaces.
f4a44678
SM
6774For instance, if the style options are B<-si4T>, a line that's indented
67753 times will be preceded by one tab and four spaces; if the options were
6776B<-si8T>, the same line would be preceded by three tabs.
6777
6778=item B<v>I<STRING>B<.>
6779
6780Print I<STRING> for the value of a constant that can't be determined
6781because it was optimized away (mnemonic: this happens when a constant
d4963d04 6782is used in B<v>oid context). The end of the string is marked by a period.
f4a44678
SM
6783The string should be a valid perl expression, generally a constant.
6784Note that unless it's a number, it probably needs to be quoted, and on
d4963d04 6785a command line quotes need to be protected from the shell. Some
f4a44678
SM
6786conventional values include 0, 1, 42, '', 'foo', and
6787'Useless use of constant omitted' (which may need to be
6788B<-sv"'Useless use of constant omitted'.">
d4963d04 6789or something similar depending on your shell). The default is '???'.
f4a44678
SM
6790If you're using B::Deparse on a module or other file that's require'd,
6791you shouldn't use a value that evaluates to false, since the customary
6792true constant at the end of a module will be in void context when the
6793file is compiled as a main program.
6794
9d2c6865
SM
6795=back
6796
58cccf98
SM
6797=item B<-x>I<LEVEL>
6798
6799Expand conventional syntax constructions into equivalent ones that expose
d4963d04
FC
6800their internal operation. I<LEVEL> should be a digit, with higher values
6801meaning more expansion. As with B<-q>, this actually involves turning off
58cccf98
SM
6802special cases in B::Deparse's normal operations.
6803
d989cdac 6804If I<LEVEL> is at least 3, C<for> loops will be translated into equivalent
646bba82 6805while loops with continue blocks; for instance
58cccf98
SM
6806
6807 for ($i = 0; $i < 10; ++$i) {
6808 print $i;
6809 }
6810
6811turns into
6812
6813 $i = 0;
6814 while ($i < 10) {
6815 print $i;
6816 } continue {
6817 ++$i
6818 }
6819
6820Note that in a few cases this translation can't be perfectly carried back
646bba82 6821into the source code -- if the loop's initializer declares a my variable,
58cccf98
SM
6822for instance, it won't have the correct scope outside of the loop.
6823
d989cdac
SM
6824If I<LEVEL> is at least 5, C<use> declarations will be translated into
6825C<BEGIN> blocks containing calls to C<require> and C<import>; for
6826instance,
6827
6828 use strict 'refs';
6829
6830turns into
6831
6832 sub BEGIN {
6833 require strict;
6834 do {
6835 'strict'->import('refs')
6836 };
6837 }
6838
6839If I<LEVEL> is at least 7, C<if> statements will be translated into
6840equivalent expressions using C<&&>, C<?:> and C<do {}>; for instance
58cccf98
SM
6841
6842 print 'hi' if $nice;
6843 if ($nice) {
6844 print 'hi';
6845 }
6846 if ($nice) {
6847 print 'hi';
6848 } else {
6849 print 'bye';
6850 }
6851
6852turns into
6853
6854 $nice and print 'hi';
6855 $nice and do { print 'hi' };
6856 $nice ? do { print 'hi' } : do { print 'bye' };
6857
6858Long sequences of elsifs will turn into nested ternary operators, which
6859B::Deparse doesn't know how to indent nicely.
6860
f6f9bdb7
SM
6861=back
6862
f4a44678
SM
6863=head1 USING B::Deparse AS A MODULE
6864
6865=head2 Synopsis
6866
6867 use B::Deparse;
6868 $deparse = B::Deparse->new("-p", "-sC");
6869 $body = $deparse->coderef2text(\&func);
6870 eval "sub func $body"; # the inverse operation
6871
6872=head2 Description
6873
6874B::Deparse can also be used on a sub-by-sub basis from other perl
6875programs.
6876
6877=head2 new
6878
6879 $deparse = B::Deparse->new(OPTIONS)
6880
6881Create an object to store the state of a deparsing operation and any
d4963d04 6882options. The options are the same as those that can be given on the
f4a44678 6883command line (see L</OPTIONS>); options that are separated by commas
7a07078a 6884after B<-MO=Deparse> should be given as separate strings.
f4a44678 6885
08c6f5ec
RH
6886=head2 ambient_pragmas
6887
bc6b2ef6 6888 $deparse->ambient_pragmas(strict => 'all', '$[' => $[);
08c6f5ec
RH
6889
6890The compilation of a subroutine can be affected by a few compiler
d4963d04 6891directives, B<pragmas>. These are:
08c6f5ec
RH
6892
6893=over 4
6894
6895=item *
6896
6897use strict;
6898
6899=item *
6900
6901use warnings;
6902
6903=item *
6904
bc6b2ef6
Z
6905Assigning to the special variable $[
6906
6907=item *
6908
08c6f5ec
RH
6909use integer;
6910
a0405c92
RH
6911=item *
6912
6913use bytes;
6914
6915=item *
6916
6917use utf8;
6918
6919=item *
6920
6921use re;
6922
08c6f5ec
RH
6923=back
6924
6925Ordinarily, if you use B::Deparse on a subroutine which has
6926been compiled in the presence of one or more of these pragmas,
6927the output will include statements to turn on the appropriate
d4963d04 6928directives. So if you then compile the code returned by coderef2text,
08c6f5ec
RH
6929it will behave the same way as the subroutine which you deparsed.
6930
6931However, you may know that you intend to use the results in a
d4963d04 6932particular context, where some pragmas are already in scope. In
08c6f5ec
RH
6933this case, you use the B<ambient_pragmas> method to describe the
6934assumptions you wish to make.
6935
d4963d04 6936Not all of the options currently have any useful effect. See
995e581f
RH
6937L</BUGS> for more details.
6938
08c6f5ec
RH
6939The parameters it accepts are:
6940
6941=over 4
6942
6943=item strict
6944
6945Takes a string, possibly containing several values separated
d4963d04 6946by whitespace. The special values "all" and "none" mean what you'd
08c6f5ec
RH
6947expect.
6948
6949 $deparse->ambient_pragmas(strict => 'subs refs');
6950
bc6b2ef6
Z
6951=item $[
6952
6953Takes a number, the value of the array base $[.
843835bc 6954Obsolete: cannot be non-zero.
bc6b2ef6 6955
a0405c92
RH
6956=item bytes
6957
6958=item utf8
6959
08c6f5ec
RH
6960=item integer
6961
a0405c92 6962If the value is true, then the appropriate pragma is assumed to
08c6f5ec
RH
6963be in the ambient scope, otherwise not.
6964
a0405c92
RH
6965=item re
6966
6967Takes a string, possibly containing a whitespace-separated list of
d4963d04 6968values. The values "all" and "none" are special. It's also permissible
a0405c92
RH
6969to pass an array reference here.
6970
6971 $deparser->ambient_pragmas(re => 'eval');
6972
6973
08c6f5ec
RH
6974=item warnings
6975
6976Takes a string, possibly containing a whitespace-separated list of
d4963d04 6977values. The values "all" and "none" are special, again. It's also
08c6f5ec
RH
6978permissible to pass an array reference here.
6979
6980 $deparser->ambient_pragmas(warnings => [qw[void io]]);
6981
6982If one of the values is the string "FATAL", then all the warnings
6983in that list will be considered fatal, just as with the B<warnings>
d4963d04 6984pragma itself. Should you need to specify that some warnings are
08c6f5ec
RH
6985fatal, and others are merely enabled, you can pass the B<warnings>
6986parameter twice:
6987
6988 $deparser->ambient_pragmas(
6989 warnings => 'all',
6990 warnings => [FATAL => qw/void io/],
6991 );
6992
44ecbbd8 6993See L<warnings> for more information about lexical warnings.
08c6f5ec
RH
6994
6995=item hint_bits
6996
6997=item warning_bits
6998
6999These two parameters are used to specify the ambient pragmas in
7000the format used by the special variables $^H and ${^WARNING_BITS}.
7001
7002They exist principally so that you can write code like:
7003
7004 { my ($hint_bits, $warning_bits);
7005 BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
7006 $deparser->ambient_pragmas (
7007 hint_bits => $hint_bits,
7008 warning_bits => $warning_bits,
bc6b2ef6 7009 '$[' => 0 + $[
08c6f5ec
RH
7010 ); }
7011
7012which specifies that the ambient pragmas are exactly those which
7013are in scope at the point of calling.
7014
0ced6c29
RGS
7015=item %^H
7016
7017This parameter is used to specify the ambient pragmas which are
7018stored in the special hash %^H.
7019
08c6f5ec
RH
7020=back
7021
f4a44678
SM
7022=head2 coderef2text
7023
7024 $body = $deparse->coderef2text(\&func)
7025 $body = $deparse->coderef2text(sub ($$) { ... })
7026
7027Return source code for the body of a subroutine (a block, optionally
7028preceded by a prototype in parens), given a reference to the
d4963d04 7029sub. Because a subroutine can have no names, or more than one name,
f4a44678
SM
7030this method doesn't return a complete subroutine definition -- if you
7031want to eval the result, you should prepend "sub subname ", or "sub "
d4963d04 7032for an anonymous function constructor. Unless the sub was defined in
f4a44678
SM
7033the main:: package, the code will include a package declaration.
7034
f6f9bdb7
SM
7035=head1 BUGS
7036
995e581f
RH
7037=over 4
7038
7039=item *
7040
843835bc 7041The only pragmas to
65eb3922 7042be completely supported are: C<use warnings>,
b1b6de96 7043C<use strict>, C<use bytes>, C<use integer>
843835bc 7044and C<use feature>.
995e581f
RH
7045
7046Excepting those listed above, we're currently unable to guarantee that
7047B::Deparse will produce a pragma at the correct point in the program.
d989cdac
SM
7048(Specifically, pragmas at the beginning of a block often appear right
7049before the start of the block instead.)
995e581f
RH
7050Since the effects of pragmas are often lexically scoped, this can mean
7051that the pragma holds sway over a different portion of the program
7052than in the input file.
7053
7054=item *
7055
c7f67cde
RH
7056In fact, the above is a specific instance of a more general problem:
7057we can't guarantee to produce BEGIN blocks or C<use> declarations in
d4963d04 7058exactly the right place. So if you use a module which affects compilation
c7f67cde
RH
7059(such as by over-riding keywords, overloading constants or whatever)
7060then the output code might not work as intended.
7061
c7f67cde
RH
7062=item *
7063
d989cdac
SM
7064Some constants don't print correctly either with or without B<-d>.
7065For instance, neither B::Deparse nor Data::Dumper know how to print
7066dual-valued scalars correctly, as in:
b7dad2dc 7067
d989cdac 7068 use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y;
b7dad2dc 7069
227375e1
RU
7070 use constant H => { "#" => 1 }; H->{"#"};
7071
2a9e2f8a
RH
7072=item *
7073
7074An input file that uses source filtering probably won't be deparsed into
7075runnable code, because it will still include the B<use> declaration
7076for the source filtering module, even though the code that is
7077produced is already ordinary Perl which shouldn't be filtered again.
7078
7079=item *
7080
e5fbaf13 7081Optimized-away statements are rendered as
d4963d04 7082'???'. This includes statements that
b64ba24c
RGS
7083have a compile-time side-effect, such as the obscure
7084
7085 my $x if 0;
7086
7087which is not, consequently, deparsed correctly.
7088
227375e1
RU
7089 foreach my $i (@_) { 0 }
7090 =>
7091 foreach my $i (@_) { '???' }
7092
b64ba24c
RGS
7093=item *
7094
8c1e32d8 7095Lexical (my) variables declared in scopes external to a subroutine
bc304ab2 7096appear in coderef2text output text as package variables. This is a tricky
c4a6f826 7097problem, as perl has no native facility for referring to a lexical variable
8c1e32d8
DN
7098defined within a different scope, although L<PadWalker> is a good start.
7099
4e3643b4
FC
7100See also L<Data::Dump::Streamer>, which combines B::Deparse and
7101L<PadWalker> to serialize closures properly.
7102
8c1e32d8
DN
7103=item *
7104
2a9e2f8a
RH
7105There are probably many more bugs on non-ASCII platforms (EBCDIC).
7106
995e581f 7107=back
f6f9bdb7
SM
7108
7109=head1 AUTHOR
7110
d989cdac
SM
7111Stephen McCamant <smcc@CSUA.Berkeley.EDU>, based on an earlier version
7112by Malcolm Beattie <mbeattie@sable.ox.ac.uk>, with contributions from
7113Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell,
7114Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael
7115Garcia-Suarez.
f6f9bdb7
SM
7116
7117=cut