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