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