xref: /openbsd-src/gnu/usr.bin/perl/lib/B/Deparse.pm (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1# B::Deparse.pm
2# Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
3# All rights reserved.
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
10package B::Deparse;
11use Carp;
12use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
13	 OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
14	 OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD
15	 OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
16	 OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
17	 OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER
18	 OPpSORT_REVERSE
19	 SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
20         CVf_METHOD CVf_LVALUE
21	 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
22	 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
23$VERSION = '1.26';
24use strict;
25use vars qw/$AUTOLOAD/;
26use warnings ();
27require feature;
28
29BEGIN {
30    # List version-specific constants here.
31    # Easiest way to keep this code portable between version looks to
32    # be to fake up a dummy constant that will never actually be true.
33    foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
34		OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
35		RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
36		CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
37		PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
38	eval { import B $_ };
39	no strict 'refs';
40	*{$_} = sub () {0} unless *{$_}{CODE};
41    }
42}
43
44# Changes between 0.50 and 0.51:
45# - fixed nulled leave with live enter in sort { }
46# - fixed reference constants (\"str")
47# - handle empty programs gracefully
48# - handle infinite loops (for (;;) {}, while (1) {})
49# - differentiate between 'for my $x ...' and 'my $x; for $x ...'
50# - various minor cleanups
51# - moved globals into an object
52# - added '-u', like B::C
53# - package declarations using cop_stash
54# - subs, formats and code sorted by cop_seq
55# Changes between 0.51 and 0.52:
56# - added pp_threadsv (special variables under USE_5005THREADS)
57# - added documentation
58# Changes between 0.52 and 0.53:
59# - many changes adding precedence contexts and associativity
60# - added '-p' and '-s' output style options
61# - various other minor fixes
62# Changes between 0.53 and 0.54:
63# - added support for new 'for (1..100)' optimization,
64#   thanks to Gisle Aas
65# Changes between 0.54 and 0.55:
66# - added support for new qr// construct
67# - added support for new pp_regcreset OP
68# Changes between 0.55 and 0.56:
69# - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
70# - fixed $# on non-lexicals broken in last big rewrite
71# - added temporary fix for change in opcode of OP_STRINGIFY
72# - fixed problem in 0.54's for() patch in 'for (@ary)'
73# - fixed precedence in conditional of ?:
74# - tweaked list paren elimination in 'my($x) = @_'
75# - made continue-block detection trickier wrt. null ops
76# - fixed various prototype problems in pp_entersub
77# - added support for sub prototypes that never get GVs
78# - added unquoting for special filehandle first arg in truncate
79# - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
80# - added semicolons at the ends of blocks
81# - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
82# Changes between 0.56 and 0.561:
83# - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
84# - used new B.pm symbolic constants (done by Nick Ing-Simmons)
85# Changes between 0.561 and 0.57:
86# - stylistic changes to symbolic constant stuff
87# - handled scope in s///e replacement code
88# - added unquote option for expanding "" into concats, etc.
89# - split method and proto parts of pp_entersub into separate functions
90# - various minor cleanups
91# Changes after 0.57:
92# - added parens in \&foo (patch by Albert Dvornik)
93# Changes between 0.57 and 0.58:
94# - fixed '0' statements that weren't being printed
95# - added methods for use from other programs
96#   (based on patches from James Duncan and Hugo van der Sanden)
97# - added -si and -sT to control indenting (also based on a patch from Hugo)
98# - added -sv to print something else instead of '???'
99# - preliminary version of utf8 tr/// handling
100# Changes after 0.58:
101# - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
102# - added support for Hugo's new OP_SETSTATE (like nextstate)
103# Changes between 0.58 and 0.59
104# - added support for Chip's OP_METHOD_NAMED
105# - added support for Ilya's OPpTARGET_MY optimization
106# - elided arrows before '()' subscripts when possible
107# Changes between 0.59 and 0.60
108# - support for method attributes was added
109# - some warnings fixed
110# - separate recognition of constant subs
111# - rewrote continue block handling, now recognizing for loops
112# - added more control of expanding control structures
113# Changes between 0.60 and 0.61 (mostly by Robin Houston)
114# - many bug-fixes
115# - support for pragmas and 'use'
116# - support for the little-used $[ variable
117# - support for __DATA__ sections
118# - UTF8 support
119# - BEGIN, CHECK, INIT and END blocks
120# - scoping of subroutine declarations fixed
121# - compile-time output from the input program can be suppressed, so that the
122#   output is just the deparsed code. (a change to O.pm in fact)
123# - our() declarations
124# - *all* the known bugs are now listed in the BUGS section
125# - comprehensive test mechanism (TEST -deparse)
126# Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
127# - bug-fixes
128# - new switch -P
129# - support for command-line switches (-l, -0, etc.)
130# Changes between 0.63 and 0.64
131# - support for //, CHECK blocks, and assertions
132# - improved handling of foreach loops and lexicals
133# - option to use Data::Dumper for constants
134# - more bug fixes
135# - discovered lots more bugs not yet fixed
136#
137# ...
138#
139# Changes between 0.72 and 0.73
140# - support new switch constructs
141
142# Todo:
143#  (See also BUGS section at the end of this file)
144#
145# - finish tr/// changes
146# - add option for even more parens (generalize \&foo change)
147# - left/right context
148# - copy comments (look at real text with $^P?)
149# - avoid semis in one-statement blocks
150# - associativity of &&=, ||=, ?:
151# - ',' => '=>' (auto-unquote?)
152# - break long lines ("\r" as discretionary break?)
153# - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
154# - more style options: brace style, hex vs. octal, quotes, ...
155# - print big ints as hex/octal instead of decimal (heuristic?)
156# - handle 'my $x if 0'?
157# - version using op_next instead of op_first/sibling?
158# - avoid string copies (pass arrays, one big join?)
159# - here-docs?
160
161# Current test.deparse failures
162# comp/hints 6 - location of BEGIN blocks wrt. block openings
163# run/switchI 1 - missing -I switches entirely
164#    perl -Ifoo -e 'print @INC'
165# op/caller 2 - warning mask propagates backwards before warnings::register
166#    'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
167# op/getpid 2 - can't assign to shared my() declaration (threads only)
168#    'my $x : shared = 5'
169# op/override 7 - parens on overridden require change v-string interpretation
170#    'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
171#    c.f. 'BEGIN { *f = sub {0} }; f 2'
172# op/pat 774 - losing Unicode-ness of Latin1-only strings
173#    'use charnames ":short"; $x="\N{latin:a with acute}"'
174# op/recurse 12 - missing parens on recursive call makes it look like method
175#    'sub f { f($x) }'
176# op/subst 90 - inconsistent handling of utf8 under "use utf8"
177# op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
178# op/tiehandle compile - "use strict" deparsed in the wrong place
179# uni/tr_ several
180# ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
181# ext/Data/Dumper/t/dumper compile
182# ext/DB_file/several
183# ext/Encode/several
184# ext/Ernno/Errno warnings
185# ext/IO/lib/IO/t/io_sel 23
186# ext/PerlIO/t/encoding compile
187# ext/POSIX/t/posix 6
188# ext/Socket/Socket 8
189# ext/Storable/t/croak compile
190# lib/Attribute/Handlers/t/multi compile
191# lib/bignum/ several
192# lib/charnames 35
193# lib/constant 32
194# lib/English 40
195# lib/ExtUtils/t/bytes 4
196# lib/File/DosGlob compile
197# lib/Filter/Simple/t/data 1
198# lib/Math/BigInt/t/constant 1
199# lib/Net/t/config Deparse-warning
200# lib/overload compile
201# lib/Switch/ several
202# lib/Symbol 4
203# lib/Test/Simple several
204# lib/Term/Complete
205# lib/Tie/File/t/29_downcopy 5
206# lib/vars 22
207
208# Object fields (were globals):
209#
210# avoid_local:
211# (local($a), local($b)) and local($a, $b) have the same internal
212# representation but the short form looks better. We notice we can
213# use a large-scale local when checking the list, but need to prevent
214# individual locals too. This hash holds the addresses of OPs that
215# have already had their local-ness accounted for. The same thing
216# is done with my().
217#
218# curcv:
219# CV for current sub (or main program) being deparsed
220#
221# curcvlex:
222# Cached hash of lexical variables for curcv: keys are
223# names prefixed with "m" or "o" (representing my/our), and
224# each value is an array of pairs, indicating the cop_seq of scopes
225# in which a var of that name is valid.
226#
227# curcop:
228# COP for statement being deparsed
229#
230# curstash:
231# name of the current package for deparsed code
232#
233# subs_todo:
234# array of [cop_seq, CV, is_format?] for subs and formats we still
235# want to deparse
236#
237# protos_todo:
238# as above, but [name, prototype] for subs that never got a GV
239#
240# subs_done, forms_done:
241# keys are addresses of GVs for subs and formats we've already
242# deparsed (or at least put into subs_todo)
243#
244# subs_declared
245# keys are names of subs for which we've printed declarations.
246# That means we can omit parentheses from the arguments. It also means we
247# need to put CORE:: on core functions of the same name.
248#
249# subs_deparsed
250# Keeps track of fully qualified names of all deparsed subs.
251#
252# in_subst_repl
253# True when deparsing the replacement part of a substitution.
254#
255# parens: -p
256# linenums: -l
257# unquote: -q
258# cuddle: ' ' or '\n', depending on -sC
259# indent_size: -si
260# use_tabs: -sT
261# ex_const: -sv
262
263# A little explanation of how precedence contexts and associativity
264# work:
265#
266# deparse() calls each per-op subroutine with an argument $cx (short
267# for context, but not the same as the cx* in the perl core), which is
268# a number describing the op's parents in terms of precedence, whether
269# they're inside an expression or at statement level, etc.  (see
270# chart below). When ops with children call deparse on them, they pass
271# along their precedence. Fractional values are used to implement
272# associativity ('($x + $y) + $z' => '$x + $y + $y') and related
273# parentheses hacks. The major disadvantage of this scheme is that
274# it doesn't know about right sides and left sides, so say if you
275# assign a listop to a variable, it can't tell it's allowed to leave
276# the parens off the listop.
277
278# Precedences:
279# 26             [TODO] inside interpolation context ("")
280# 25 left        terms and list operators (leftward)
281# 24 left        ->
282# 23 nonassoc    ++ --
283# 22 right       **
284# 21 right       ! ~ \ and unary + and -
285# 20 left        =~ !~
286# 19 left        * / % x
287# 18 left        + - .
288# 17 left        << >>
289# 16 nonassoc    named unary operators
290# 15 nonassoc    < > <= >= lt gt le ge
291# 14 nonassoc    == != <=> eq ne cmp
292# 13 left        &
293# 12 left        | ^
294# 11 left        &&
295# 10 left        ||
296#  9 nonassoc    ..  ...
297#  8 right       ?:
298#  7 right       = += -= *= etc.
299#  6 left        , =>
300#  5 nonassoc    list operators (rightward)
301#  4 right       not
302#  3 left        and
303#  2 left        or xor
304#  1             statement modifiers
305#  0.5           statements, but still print scopes as do { ... }
306#  0             statement level
307# -1             format body
308
309# Nonprinting characters with special meaning:
310# \cS - steal parens (see maybe_parens_unop)
311# \n - newline and indent
312# \t - increase indent
313# \b - decrease indent ('outdent')
314# \f - flush left (no indent)
315# \cK - kill following semicolon, if any
316
317
318
319BEGIN { for (qw[ const stringify rv2sv list glob pushmark null]) {
320    eval "sub OP_\U$_ () { " . opnumber($_) . "}"
321}}
322
323# _pessimise_walk(): recursively walk the optree of a sub,
324# possibly undoing optimisations along the way.
325
326sub _pessimise_walk {
327    my ($self, $startop) = @_;
328
329    return unless $$startop;
330    my ($op, $prevop);
331    for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) {
332	my $ppname = $op->name;
333
334	# pessimisations start here
335
336	if ($ppname eq "padrange") {
337	    # remove PADRANGE:
338	    # the original optimisation either (1) changed this:
339	    #    pushmark -> (various pad and list and null ops) -> the_rest
340	    # or (2), for the = @_ case, changed this:
341	    #    pushmark -> gv[_] -> rv2av -> (pad stuff)       -> the_rest
342	    # into this:
343	    #    padrange ----------------------------------------> the_rest
344	    # so we just need to convert the padrange back into a
345	    # pushmark, and in case (1), set its op_next to op_sibling,
346	    # which is the head of the original chain of optimised-away
347	    # pad ops, or for (2), set it to sibling->first, which is
348	    # the original gv[_].
349
350	    $B::overlay->{$$op} = {
351		    type => OP_PUSHMARK,
352		    name => 'pushmark',
353		    private => ($op->private & OPpLVAL_INTRO),
354		    next    => ($op->flags & OPf_SPECIAL)
355				    ? $op->sibling->first
356				    : $op->sibling,
357	    };
358	}
359
360	# pessimisations end here
361
362	if (class($op) eq 'PMOP'
363	    && ref($op->pmreplroot)
364	    && ${$op->pmreplroot}
365	    && $op->pmreplroot->isa( 'B::OP' ))
366	{
367	    $self-> _pessimise_walk($op->pmreplroot);
368	}
369
370	if ($op->flags & OPf_KIDS) {
371	    $self-> _pessimise_walk($op->first);
372	}
373
374    }
375}
376
377
378# _pessimise_walk_exe(): recursively walk the op_next chain of a sub,
379# possibly undoing optimisations along the way.
380
381sub _pessimise_walk_exe {
382    my ($self, $startop, $visited) = @_;
383
384    return unless $$startop;
385    return if $visited->{$$startop};
386    my ($op, $prevop);
387    for ($op = $startop; $$op; $prevop = $op, $op = $op->next) {
388	last if $visited->{$$op};
389	$visited->{$$op} = 1;
390	my $ppname = $op->name;
391	if ($ppname =~
392	    /^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/
393	    # entertry is also a logop, but its op_other invariably points
394	    # into the same chain as the main execution path, so we skip it
395	) {
396	    $self->_pessimise_walk_exe($op->other, $visited);
397	}
398	elsif ($ppname eq "subst") {
399	    $self->_pessimise_walk_exe($op->pmreplstart, $visited);
400	}
401	elsif ($ppname =~ /^(enter(loop|iter))$/) {
402	    # redoop and nextop will already be covered by the main block
403	    # of the loop
404	    $self->_pessimise_walk_exe($op->lastop, $visited);
405	}
406
407	# pessimisations start here
408    }
409}
410
411# Go through an optree and "remove" some optimisations by using an
412# overlay to selectively modify or un-null some ops. Deparsing in the
413# absence of those optimisations is then easier.
414#
415# Note that older optimisations are not removed, as Deparse was already
416# written to recognise them before the pessimise/overlay system was added.
417
418sub pessimise {
419    my ($self, $root, $start) = @_;
420
421    # walk tree in root-to-branch order
422    $self->_pessimise_walk($root);
423
424    my %visited;
425    # walk tree in execution order
426    $self->_pessimise_walk_exe($start, \%visited);
427}
428
429
430sub null {
431    my $op = shift;
432    return class($op) eq "NULL";
433}
434
435sub todo {
436    my $self = shift;
437    my($cv, $is_form) = @_;
438    return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
439    my $seq;
440    if ($cv->OUTSIDE_SEQ) {
441	$seq = $cv->OUTSIDE_SEQ;
442    } elsif (!null($cv->START) and is_state($cv->START)) {
443	$seq = $cv->START->cop_seq;
444    } else {
445	$seq = 0;
446    }
447    push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
448    unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
449	$self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
450    }
451}
452
453sub next_todo {
454    my $self = shift;
455    my $ent = shift @{$self->{'subs_todo'}};
456    my $cv = $ent->[1];
457    my $gv = $cv->GV;
458    my $name = $self->gv_name($gv);
459    if ($ent->[2]) {
460	return "format $name =\n"
461	    . $self->deparse_format($ent->[1]). "\n";
462    } else {
463	$self->{'subs_declared'}{$name} = 1;
464	if ($name eq "BEGIN") {
465	    my $use_dec = $self->begin_is_use($cv);
466	    if (defined ($use_dec) and $self->{'expand'} < 5) {
467		return () if 0 == length($use_dec);
468		return $use_dec;
469	    }
470	}
471	my $l = '';
472	if ($self->{'linenums'}) {
473	    my $line = $gv->LINE;
474	    my $file = $gv->FILE;
475	    $l = "\n\f#line $line \"$file\"\n";
476	}
477	my $p = '';
478	if (class($cv->STASH) ne "SPECIAL") {
479	    my $stash = $cv->STASH->NAME;
480	    if ($stash ne $self->{'curstash'}) {
481		$p = "package $stash;\n";
482		$name = "$self->{'curstash'}::$name" unless $name =~ /::/;
483		$self->{'curstash'} = $stash;
484	    }
485	    $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
486	}
487        return "${p}${l}sub $name " . $self->deparse_sub($cv);
488    }
489}
490
491# Return a "use" declaration for this BEGIN block, if appropriate
492sub begin_is_use {
493    my ($self, $cv) = @_;
494    my $root = $cv->ROOT;
495    local @$self{qw'curcv curcvlex'} = ($cv);
496    local $B::overlay = {};
497    $self->pessimise($root, $cv->START);
498#require B::Debug;
499#B::walkoptree($cv->ROOT, "debug");
500    my $lineseq = $root->first;
501    return if $lineseq->name ne "lineseq";
502
503    my $req_op = $lineseq->first->sibling;
504    return if $req_op->name ne "require";
505
506    my $module;
507    if ($req_op->first->private & OPpCONST_BARE) {
508	# Actually it should always be a bareword
509	$module = $self->const_sv($req_op->first)->PV;
510	$module =~ s[/][::]g;
511	$module =~ s/.pm$//;
512    }
513    else {
514	$module = $self->const($self->const_sv($req_op->first), 6);
515    }
516
517    my $version;
518    my $version_op = $req_op->sibling;
519    return if class($version_op) eq "NULL";
520    if ($version_op->name eq "lineseq") {
521	# We have a version parameter; skip nextstate & pushmark
522	my $constop = $version_op->first->next->next;
523
524	return unless $self->const_sv($constop)->PV eq $module;
525	$constop = $constop->sibling;
526	$version = $self->const_sv($constop);
527	if (class($version) eq "IV") {
528	    $version = $version->int_value;
529	} elsif (class($version) eq "NV") {
530	    $version = $version->NV;
531	} elsif (class($version) ne "PVMG") {
532	    # Includes PVIV and PVNV
533	    $version = $version->PV;
534	} else {
535	    # version specified as a v-string
536	    $version = 'v'.join '.', map ord, split //, $version->PV;
537	}
538	$constop = $constop->sibling;
539	return if $constop->name ne "method_named";
540	return if $self->const_sv($constop)->PV ne "VERSION";
541    }
542
543    $lineseq = $version_op->sibling;
544    return if $lineseq->name ne "lineseq";
545    my $entersub = $lineseq->first->sibling;
546    if ($entersub->name eq "stub") {
547	return "use $module $version ();\n" if defined $version;
548	return "use $module ();\n";
549    }
550    return if $entersub->name ne "entersub";
551
552    # See if there are import arguments
553    my $args = '';
554
555    my $svop = $entersub->first->sibling; # Skip over pushmark
556    return unless $self->const_sv($svop)->PV eq $module;
557
558    # Pull out the arguments
559    for ($svop=$svop->sibling; $svop->name ne "method_named";
560		$svop = $svop->sibling) {
561	$args .= ", " if length($args);
562	$args .= $self->deparse($svop, 6);
563    }
564
565    my $use = 'use';
566    my $method_named = $svop;
567    return if $method_named->name ne "method_named";
568    my $method_name = $self->const_sv($method_named)->PV;
569
570    if ($method_name eq "unimport") {
571	$use = 'no';
572    }
573
574    # Certain pragmas are dealt with using hint bits,
575    # so we ignore them here
576    if ($module eq 'strict' || $module eq 'integer'
577	|| $module eq 'bytes' || $module eq 'warnings'
578	|| $module eq 'feature') {
579	return "";
580    }
581
582    if (defined $version && length $args) {
583	return "$use $module $version ($args);\n";
584    } elsif (defined $version) {
585	return "$use $module $version;\n";
586    } elsif (length $args) {
587	return "$use $module ($args);\n";
588    } else {
589	return "$use $module;\n";
590    }
591}
592
593sub stash_subs {
594    my ($self, $pack, $seen) = @_;
595    my (@ret, $stash);
596    if (!defined $pack) {
597	$pack = '';
598	$stash = \%::;
599    }
600    else {
601	$pack =~ s/(::)?$/::/;
602	no strict 'refs';
603	$stash = \%{"main::$pack"};
604    }
605    return
606	if ($seen ||= {})->{
607	    $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
608	   }++;
609    my %stash = svref_2object($stash)->ARRAY;
610    while (my ($key, $val) = each %stash) {
611	my $class = class($val);
612	if ($class eq "PV") {
613	    # Just a prototype. As an ugly but fairly effective way
614	    # to find out if it belongs here is to see if the AUTOLOAD
615	    # (if any) for the stash was defined in one of our files.
616	    my $A = $stash{"AUTOLOAD"};
617	    if (defined ($A) && class($A) eq "GV" && defined($A->CV)
618		&& class($A->CV) eq "CV") {
619		my $AF = $A->FILE;
620		next unless $AF eq $0 || exists $self->{'files'}{$AF};
621	    }
622	    push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
623	} elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
624	    # Just a name. As above.
625	    # But skip proxy constant subroutines, as some form of perl-space
626	    # visible code must have created them, be it a use statement, or
627	    # some direct symbol-table manipulation code that we will Deparse
628	    my $A = $stash{"AUTOLOAD"};
629	    if (defined ($A) && class($A) eq "GV" && defined($A->CV)
630		&& class($A->CV) eq "CV") {
631		my $AF = $A->FILE;
632		next unless $AF eq $0 || exists $self->{'files'}{$AF};
633	    }
634	    push @{$self->{'protos_todo'}}, [$pack . $key, undef];
635	} elsif ($class eq "GV") {
636	    if (class(my $cv = $val->CV) ne "SPECIAL") {
637		next if $self->{'subs_done'}{$$val}++;
638		next if $$val != ${$cv->GV};   # Ignore imposters
639		$self->todo($cv, 0);
640	    }
641	    if (class(my $cv = $val->FORM) ne "SPECIAL") {
642		next if $self->{'forms_done'}{$$val}++;
643		next if $$val != ${$cv->GV};   # Ignore imposters
644		$self->todo($cv, 1);
645	    }
646	    if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
647		$self->stash_subs($pack . $key, $seen);
648	    }
649	}
650    }
651}
652
653sub print_protos {
654    my $self = shift;
655    my $ar;
656    my @ret;
657    foreach $ar (@{$self->{'protos_todo'}}) {
658	my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
659	push @ret, "sub " . $ar->[0] .  "$proto;\n";
660    }
661    delete $self->{'protos_todo'};
662    return @ret;
663}
664
665sub style_opts {
666    my $self = shift;
667    my $opts = shift;
668    my $opt;
669    while (length($opt = substr($opts, 0, 1))) {
670	if ($opt eq "C") {
671	    $self->{'cuddle'} = " ";
672	    $opts = substr($opts, 1);
673	} elsif ($opt eq "i") {
674	    $opts =~ s/^i(\d+)//;
675	    $self->{'indent_size'} = $1;
676	} elsif ($opt eq "T") {
677	    $self->{'use_tabs'} = 1;
678	    $opts = substr($opts, 1);
679	} elsif ($opt eq "v") {
680	    $opts =~ s/^v([^.]*)(.|$)//;
681	    $self->{'ex_const'} = $1;
682	}
683    }
684}
685
686sub new {
687    my $class = shift;
688    my $self = bless {}, $class;
689    $self->{'cuddle'} = "\n";
690    $self->{'curcop'} = undef;
691    $self->{'curstash'} = "main";
692    $self->{'ex_const'} = "'???'";
693    $self->{'expand'} = 0;
694    $self->{'files'} = {};
695    $self->{'indent_size'} = 4;
696    $self->{'linenums'} = 0;
697    $self->{'parens'} = 0;
698    $self->{'subs_todo'} = [];
699    $self->{'unquote'} = 0;
700    $self->{'use_dumper'} = 0;
701    $self->{'use_tabs'} = 0;
702
703    $self->{'ambient_arybase'} = 0;
704    $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
705    $self->{'ambient_hints'} = 0;
706    $self->{'ambient_hinthash'} = undef;
707    $self->init();
708
709    while (my $arg = shift @_) {
710	if ($arg eq "-d") {
711	    $self->{'use_dumper'} = 1;
712	    require Data::Dumper;
713	} elsif ($arg =~ /^-f(.*)/) {
714	    $self->{'files'}{$1} = 1;
715	} elsif ($arg eq "-l") {
716	    $self->{'linenums'} = 1;
717	} elsif ($arg eq "-p") {
718	    $self->{'parens'} = 1;
719	} elsif ($arg eq "-P") {
720	    $self->{'noproto'} = 1;
721	} elsif ($arg eq "-q") {
722	    $self->{'unquote'} = 1;
723	} elsif (substr($arg, 0, 2) eq "-s") {
724	    $self->style_opts(substr $arg, 2);
725	} elsif ($arg =~ /^-x(\d)$/) {
726	    $self->{'expand'} = $1;
727	}
728    }
729    return $self;
730}
731
732{
733    # Mask out the bits that L<warnings::register> uses
734    my $WARN_MASK;
735    BEGIN {
736	$WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
737    }
738    sub WARN_MASK () {
739	return $WARN_MASK;
740    }
741}
742
743# Initialise the contextual information, either from
744# defaults provided with the ambient_pragmas method,
745# or from perl's own defaults otherwise.
746sub init {
747    my $self = shift;
748
749    $self->{'arybase'}  = $self->{'ambient_arybase'};
750    $self->{'warnings'} = defined ($self->{'ambient_warnings'})
751				? $self->{'ambient_warnings'} & WARN_MASK
752				: undef;
753    $self->{'hints'}    = $self->{'ambient_hints'};
754    $self->{'hints'} &= 0xFF if $] < 5.009;
755    $self->{'hinthash'} = $self->{'ambient_hinthash'};
756
757    # also a convenient place to clear out subs_declared
758    delete $self->{'subs_declared'};
759}
760
761sub compile {
762    my(@args) = @_;
763    return sub {
764	my $self = B::Deparse->new(@args);
765	# First deparse command-line args
766	if (defined $^I) { # deparse -i
767	    print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
768	}
769	if ($^W) { # deparse -w
770	    print qq(BEGIN { \$^W = $^W; }\n);
771	}
772	if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
773	    my $fs = perlstring($/) || 'undef';
774	    my $bs = perlstring($O::savebackslash) || 'undef';
775	    print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
776	}
777	my @BEGINs  = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
778	my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
779	    ? B::unitcheck_av->ARRAY
780	    : ();
781	my @CHECKs  = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
782	my @INITs   = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
783	my @ENDs    = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
784	for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
785	    $self->todo($block, 0);
786	}
787	$self->stash_subs();
788	local($SIG{"__DIE__"}) =
789	  sub {
790	      if ($self->{'curcop'}) {
791		  my $cop = $self->{'curcop'};
792		  my($line, $file) = ($cop->line, $cop->file);
793		  print STDERR "While deparsing $file near line $line,\n";
794	      }
795	    };
796	$self->{'curcv'} = main_cv;
797	$self->{'curcvlex'} = undef;
798	print $self->print_protos;
799	@{$self->{'subs_todo'}} =
800	  sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
801	my $root = main_root;
802	local $B::overlay = {};
803	unless (null $root) {
804	    $self->pessimise($root, main_start);
805	    print $self->indent($self->deparse_root($root)), "\n";
806	}
807	my @text;
808	while (scalar(@{$self->{'subs_todo'}})) {
809	    push @text, $self->next_todo;
810	}
811	print $self->indent(join("", @text)), "\n" if @text;
812
813	# Print __DATA__ section, if necessary
814	no strict 'refs';
815	my $laststash = defined $self->{'curcop'}
816	    ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
817	if (defined *{$laststash."::DATA"}{IO}) {
818	    print "package $laststash;\n"
819		unless $laststash eq $self->{'curstash'};
820	    print "__DATA__\n";
821	    print readline(*{$laststash."::DATA"});
822	}
823    }
824}
825
826sub coderef2text {
827    my $self = shift;
828    my $sub = shift;
829    croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
830
831    $self->init();
832    return $self->indent($self->deparse_sub(svref_2object($sub)));
833}
834
835my %strict_bits = do {
836    local $^H;
837    map +($_ => strict::bits($_)), qw/refs subs vars/
838};
839
840sub ambient_pragmas {
841    my $self = shift;
842    my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
843
844    while (@_ > 1) {
845	my $name = shift();
846	my $val  = shift();
847
848	if ($name eq 'strict') {
849	    require strict;
850
851	    if ($val eq 'none') {
852		$hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
853		next();
854	    }
855
856	    my @names;
857	    if ($val eq "all") {
858		@names = qw/refs subs vars/;
859	    }
860	    elsif (ref $val) {
861		@names = @$val;
862	    }
863	    else {
864		@names = split' ', $val;
865	    }
866	    $hint_bits |= $strict_bits{$_} for @names;
867	}
868
869	elsif ($name eq '$[') {
870	    if (OPpCONST_ARYBASE) {
871		$arybase = $val;
872	    } else {
873		croak "\$[ can't be non-zero on this perl" unless $val == 0;
874	    }
875	}
876
877	elsif ($name eq 'integer'
878	    || $name eq 'bytes'
879	    || $name eq 'utf8') {
880	    require "$name.pm";
881	    if ($val) {
882		$hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
883	    }
884	    else {
885		$hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
886	    }
887	}
888
889	elsif ($name eq 're') {
890	    require re;
891	    if ($val eq 'none') {
892		$hint_bits &= ~re::bits(qw/taint eval/);
893		next();
894	    }
895
896	    my @names;
897	    if ($val eq 'all') {
898		@names = qw/taint eval/;
899	    }
900	    elsif (ref $val) {
901		@names = @$val;
902	    }
903	    else {
904		@names = split' ',$val;
905	    }
906	    $hint_bits |= re::bits(@names);
907	}
908
909	elsif ($name eq 'warnings') {
910	    if ($val eq 'none') {
911		$warning_bits = $warnings::NONE;
912		next();
913	    }
914
915	    my @names;
916	    if (ref $val) {
917		@names = @$val;
918	    }
919	    else {
920		@names = split/\s+/, $val;
921	    }
922
923	    $warning_bits = $warnings::NONE if !defined ($warning_bits);
924	    $warning_bits |= warnings::bits(@names);
925	}
926
927	elsif ($name eq 'warning_bits') {
928	    $warning_bits = $val;
929	}
930
931	elsif ($name eq 'hint_bits') {
932	    $hint_bits = $val;
933	}
934
935	elsif ($name eq '%^H') {
936	    $hinthash = $val;
937	}
938
939	else {
940	    croak "Unknown pragma type: $name";
941	}
942    }
943    if (@_) {
944	croak "The ambient_pragmas method expects an even number of args";
945    }
946
947    $self->{'ambient_arybase'} = $arybase;
948    $self->{'ambient_warnings'} = $warning_bits;
949    $self->{'ambient_hints'} = $hint_bits;
950    $self->{'ambient_hinthash'} = $hinthash;
951}
952
953# This method is the inner loop, so try to keep it simple
954sub deparse {
955    my $self = shift;
956    my($op, $cx) = @_;
957
958    Carp::confess("Null op in deparse") if !defined($op)
959					|| class($op) eq "NULL";
960    my $meth = "pp_" . $op->name;
961    return $self->$meth($op, $cx);
962}
963
964sub indent {
965    my $self = shift;
966    my $txt = shift;
967    my @lines = split(/\n/, $txt);
968    my $leader = "";
969    my $level = 0;
970    my $line;
971    for $line (@lines) {
972	my $cmd = substr($line, 0, 1);
973	if ($cmd eq "\t" or $cmd eq "\b") {
974	    $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
975	    if ($self->{'use_tabs'}) {
976		$leader = "\t" x ($level / 8) . " " x ($level % 8);
977	    } else {
978		$leader = " " x $level;
979	    }
980	    $line = substr($line, 1);
981	}
982	if (index($line, "\f") > 0) {
983		$line =~ s/\f/\n/;
984	}
985	if (substr($line, 0, 1) eq "\f") {
986	    $line = substr($line, 1); # no indent
987	} else {
988	    $line = $leader . $line;
989	}
990	$line =~ s/\cK;?//g;
991    }
992    return join("\n", @lines);
993}
994
995sub deparse_sub {
996    my $self = shift;
997    my $cv = shift;
998    my $proto = "";
999Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
1000Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1001    local $self->{'curcop'} = $self->{'curcop'};
1002    if ($cv->FLAGS & SVf_POK) {
1003	$proto = "(". $cv->PV . ") ";
1004    }
1005    if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
1006        $proto .= ": ";
1007        $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
1008        $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
1009        $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
1010    }
1011
1012    local($self->{'curcv'}) = $cv;
1013    local($self->{'curcvlex'});
1014    local(@$self{qw'curstash warnings hints hinthash'})
1015		= @$self{qw'curstash warnings hints hinthash'};
1016    my $body;
1017    my $root = $cv->ROOT;
1018    local $B::overlay = {};
1019    if (not null $root) {
1020	$self->pessimise($root, $cv->START);
1021	my $lineseq = $root->first;
1022	if ($lineseq->name eq "lineseq") {
1023	    my @ops;
1024	    for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
1025		push @ops, $o;
1026	    }
1027	    $body = $self->lineseq(undef, 0, @ops).";";
1028	    my $scope_en = $self->find_scope_en($lineseq);
1029	    if (defined $scope_en) {
1030		my $subs = join"", $self->seq_subs($scope_en);
1031		$body .= ";\n$subs" if length($subs);
1032	    }
1033	}
1034	else {
1035	    $body = $self->deparse($root->first, 0);
1036	}
1037    }
1038    else {
1039	my $sv = $cv->const_sv;
1040	if ($$sv) {
1041	    # uh-oh. inlinable sub... format it differently
1042	    return $proto . "{ " . $self->const($sv, 0) . " }\n";
1043	} else { # XSUB? (or just a declaration)
1044	    return "$proto;\n";
1045	}
1046    }
1047    return $proto ."{\n\t$body\n\b}" ."\n";
1048}
1049
1050sub deparse_format {
1051    my $self = shift;
1052    my $form = shift;
1053    my @text;
1054    local($self->{'curcv'}) = $form;
1055    local($self->{'curcvlex'});
1056    local($self->{'in_format'}) = 1;
1057    local(@$self{qw'curstash warnings hints hinthash'})
1058		= @$self{qw'curstash warnings hints hinthash'};
1059    my $op = $form->ROOT;
1060    local $B::overlay = {};
1061    $self->pessimise($op, $form->START);
1062    my $kid;
1063    return "\f." if $op->first->name eq 'stub'
1064                || $op->first->name eq 'nextstate';
1065    $op = $op->first->first; # skip leavewrite, lineseq
1066    while (not null $op) {
1067	$op = $op->sibling; # skip nextstate
1068	my @exprs;
1069	$kid = $op->first->sibling; # skip pushmark
1070	push @text, "\f".$self->const_sv($kid)->PV;
1071	$kid = $kid->sibling;
1072	for (; not null $kid; $kid = $kid->sibling) {
1073	    push @exprs, $self->deparse($kid, -1);
1074	    $exprs[-1] =~ s/;\z//;
1075	}
1076	push @text, "\f".join(", ", @exprs)."\n" if @exprs;
1077	$op = $op->sibling;
1078    }
1079    return join("", @text) . "\f.";
1080}
1081
1082sub is_scope {
1083    my $op = shift;
1084    return $op->name eq "leave" || $op->name eq "scope"
1085      || $op->name eq "lineseq"
1086	|| ($op->name eq "null" && class($op) eq "UNOP"
1087	    && (is_scope($op->first) || $op->first->name eq "enter"));
1088}
1089
1090sub is_state {
1091    my $name = $_[0]->name;
1092    return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
1093}
1094
1095sub is_miniwhile { # check for one-line loop ('foo() while $y--')
1096    my $op = shift;
1097    return (!null($op) and null($op->sibling)
1098	    and $op->name eq "null" and class($op) eq "UNOP"
1099	    and (($op->first->name =~ /^(and|or)$/
1100		  and $op->first->first->sibling->name eq "lineseq")
1101		 or ($op->first->name eq "lineseq"
1102		     and not null $op->first->first->sibling
1103		     and $op->first->first->sibling->name eq "unstack")
1104		 ));
1105}
1106
1107# Check if the op and its sibling are the initialization and the rest of a
1108# for (..;..;..) { ... } loop
1109sub is_for_loop {
1110    my $op = shift;
1111    # This OP might be almost anything, though it won't be a
1112    # nextstate. (It's the initialization, so in the canonical case it
1113    # will be an sassign.) The sibling is (old style) a lineseq whose
1114    # first child is a nextstate and whose second is a leaveloop, or
1115    # (new style) an unstack whose sibling is a leaveloop.
1116    my $lseq = $op->sibling;
1117    return 0 unless !is_state($op) and !null($lseq);
1118    if ($lseq->name eq "lineseq") {
1119	if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1120	    && (my $sib = $lseq->first->sibling)) {
1121	    return (!null($sib) && $sib->name eq "leaveloop");
1122	}
1123    } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1124	my $sib = $lseq->sibling;
1125	return $sib && !null($sib) && $sib->name eq "leaveloop";
1126    }
1127    return 0;
1128}
1129
1130sub is_scalar {
1131    my $op = shift;
1132    return ($op->name eq "rv2sv" or
1133	    $op->name eq "padsv" or
1134	    $op->name eq "gv" or # only in array/hash constructs
1135	    $op->flags & OPf_KIDS && !null($op->first)
1136	      && $op->first->name eq "gvsv");
1137}
1138
1139sub maybe_parens {
1140    my $self = shift;
1141    my($text, $cx, $prec) = @_;
1142    if ($prec < $cx              # unary ops nest just fine
1143	or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1144	or $self->{'parens'})
1145    {
1146	$text = "($text)";
1147	# In a unop, let parent reuse our parens; see maybe_parens_unop
1148	$text = "\cS" . $text if $cx == 16;
1149	return $text;
1150    } else {
1151	return $text;
1152    }
1153}
1154
1155# same as above, but get around the 'if it looks like a function' rule
1156sub maybe_parens_unop {
1157    my $self = shift;
1158    my($name, $kid, $cx) = @_;
1159    if ($cx > 16 or $self->{'parens'}) {
1160	$kid =  $self->deparse($kid, 1);
1161 	if ($name eq "umask" && $kid =~ /^\d+$/) {
1162	    $kid = sprintf("%#o", $kid);
1163	}
1164	return $self->keyword($name) . "($kid)";
1165    } else {
1166	$kid = $self->deparse($kid, 16);
1167 	if ($name eq "umask" && $kid =~ /^\d+$/) {
1168	    $kid = sprintf("%#o", $kid);
1169	}
1170	$name = $self->keyword($name);
1171	if (substr($kid, 0, 1) eq "\cS") {
1172	    # use kid's parens
1173	    return $name . substr($kid, 1);
1174	} elsif (substr($kid, 0, 1) eq "(") {
1175	    # avoid looks-like-a-function trap with extra parens
1176	    # ('+' can lead to ambiguities)
1177	    return "$name(" . $kid  . ")";
1178	} else {
1179	    return "$name $kid";
1180	}
1181    }
1182}
1183
1184sub maybe_parens_func {
1185    my $self = shift;
1186    my($func, $text, $cx, $prec) = @_;
1187    if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1188	return "$func($text)";
1189    } else {
1190	return "$func $text";
1191    }
1192}
1193
1194sub maybe_local {
1195    my $self = shift;
1196    my($op, $cx, $text) = @_;
1197    my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1198    if ($op->private & (OPpLVAL_INTRO|$our_intro)
1199	and not $self->{'avoid_local'}{$$op}) {
1200	my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1201	if( $our_local eq 'our' ) {
1202	    if ( $text !~ /^\W(\w+::)*\w+\z/
1203	     and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1204	    ) {
1205		die "Unexpected our($text)\n";
1206	    }
1207	    $text =~ s/(\w+::)+//;
1208	}
1209        if (want_scalar($op)) {
1210	    return "$our_local $text";
1211	} else {
1212	    return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1213	}
1214    } else {
1215	return $text;
1216    }
1217}
1218
1219sub maybe_targmy {
1220    my $self = shift;
1221    my($op, $cx, $func, @args) = @_;
1222    if ($op->private & OPpTARGET_MY) {
1223	my $var = $self->padname($op->targ);
1224	my $val = $func->($self, $op, 7, @args);
1225	return $self->maybe_parens("$var = $val", $cx, 7);
1226    } else {
1227	return $func->($self, $op, $cx, @args);
1228    }
1229}
1230
1231sub padname_sv {
1232    my $self = shift;
1233    my $targ = shift;
1234    return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1235}
1236
1237sub maybe_my {
1238    my $self = shift;
1239    my($op, $cx, $text, $forbid_parens) = @_;
1240    if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1241	my $my = $op->private & OPpPAD_STATE
1242	    ? $self->keyword("state")
1243	    : "my";
1244	if ($forbid_parens || want_scalar($op)) {
1245	    return "$my $text";
1246	} else {
1247	    return $self->maybe_parens_func($my, $text, $cx, 16);
1248	}
1249    } else {
1250	return $text;
1251    }
1252}
1253
1254# The following OPs don't have functions:
1255
1256# pp_padany -- does not exist after parsing
1257
1258sub AUTOLOAD {
1259    if ($AUTOLOAD =~ s/^.*::pp_//) {
1260	warn "unexpected OP_".uc $AUTOLOAD;
1261	return "XXX";
1262    } else {
1263	die "Undefined subroutine $AUTOLOAD called";
1264    }
1265}
1266
1267sub DESTROY {}	#	Do not AUTOLOAD
1268
1269# $root should be the op which represents the root of whatever
1270# we're sequencing here. If it's undefined, then we don't append
1271# any subroutine declarations to the deparsed ops, otherwise we
1272# append appropriate declarations.
1273sub lineseq {
1274    my($self, $root, $cx, @ops) = @_;
1275    my($expr, @exprs);
1276
1277    my $out_cop = $self->{'curcop'};
1278    my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1279    my $limit_seq;
1280    if (defined $root) {
1281	$limit_seq = $out_seq;
1282	my $nseq;
1283	$nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1284	$limit_seq = $nseq if !defined($limit_seq)
1285			   or defined($nseq) && $nseq < $limit_seq;
1286    }
1287    $limit_seq = $self->{'limit_seq'}
1288	if defined($self->{'limit_seq'})
1289	&& (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1290    local $self->{'limit_seq'} = $limit_seq;
1291
1292    $self->walk_lineseq($root, \@ops,
1293		       sub { push @exprs, $_[0]} );
1294
1295    my $sep = $cx ? '; ' : ";\n";
1296    my $body = join($sep, grep {length} @exprs);
1297    my $subs = "";
1298    if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1299	$subs = join "\n", $self->seq_subs($limit_seq);
1300    }
1301    return join($sep, grep {length} $body, $subs);
1302}
1303
1304sub scopeop {
1305    my($real_block, $self, $op, $cx) = @_;
1306    my $kid;
1307    my @kids;
1308
1309    local(@$self{qw'curstash warnings hints hinthash'})
1310		= @$self{qw'curstash warnings hints hinthash'} if $real_block;
1311    if ($real_block) {
1312	$kid = $op->first->sibling; # skip enter
1313	if (is_miniwhile($kid)) {
1314	    my $top = $kid->first;
1315	    my $name = $top->name;
1316	    if ($name eq "and") {
1317		$name = "while";
1318	    } elsif ($name eq "or") {
1319		$name = "until";
1320	    } else { # no conditional -> while 1 or until 0
1321		return $self->deparse($top->first, 1) . " while 1";
1322	    }
1323	    my $cond = $top->first;
1324	    my $body = $cond->sibling->first; # skip lineseq
1325	    $cond = $self->deparse($cond, 1);
1326	    $body = $self->deparse($body, 1);
1327	    return "$body $name $cond";
1328	}
1329    } else {
1330	$kid = $op->first;
1331    }
1332    for (; !null($kid); $kid = $kid->sibling) {
1333	push @kids, $kid;
1334    }
1335    if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1336	my $body = $self->lineseq($op, 0, @kids);
1337	return is_lexical_subs(@kids) ? $body : "do {\n\t$body\n\b}";
1338    } else {
1339	my $lineseq = $self->lineseq($op, $cx, @kids);
1340	return (length ($lineseq) ? "$lineseq;" : "");
1341    }
1342}
1343
1344sub pp_scope { scopeop(0, @_); }
1345sub pp_lineseq { scopeop(0, @_); }
1346sub pp_leave { scopeop(1, @_); }
1347
1348# This is a special case of scopeop and lineseq, for the case of the
1349# main_root. The difference is that we print the output statements as
1350# soon as we get them, for the sake of impatient users.
1351sub deparse_root {
1352    my $self = shift;
1353    my($op) = @_;
1354    local(@$self{qw'curstash warnings hints hinthash'})
1355      = @$self{qw'curstash warnings hints hinthash'};
1356    my @kids;
1357    return if null $op->first; # Can happen, e.g., for Bytecode without -k
1358    for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1359	push @kids, $kid;
1360    }
1361    $self->walk_lineseq($op, \@kids,
1362			sub { print $self->indent($_[0].';');
1363			      print "\n" unless $_[1] == $#kids;
1364			  });
1365}
1366
1367sub walk_lineseq {
1368    my ($self, $op, $kids, $callback) = @_;
1369    my @kids = @$kids;
1370    for (my $i = 0; $i < @kids; $i++) {
1371	my $expr = "";
1372	if (is_state $kids[$i]) {
1373	    $expr = $self->deparse($kids[$i++], 0);
1374	    if ($i > $#kids) {
1375		$callback->($expr, $i);
1376		last;
1377	    }
1378	}
1379	if (is_for_loop($kids[$i])) {
1380	    $callback->($expr . $self->for_loop($kids[$i], 0),
1381		$i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1382	    next;
1383	}
1384	$expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1385	$expr =~ s/;\n?\z//;
1386	$callback->($expr, $i);
1387    }
1388}
1389
1390# The BEGIN {} is used here because otherwise this code isn't executed
1391# when you run B::Deparse on itself.
1392my %globalnames;
1393BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1394	    "ENV", "ARGV", "ARGVOUT", "_"); }
1395
1396sub gv_name {
1397    my $self = shift;
1398    my $gv = shift;
1399    my $raw = shift;
1400Carp::confess() unless ref($gv) eq "B::GV";
1401    my $stash = $gv->STASH->NAME;
1402    my $name = $raw ? $gv->NAME : $gv->SAFENAME;
1403    if ($stash eq 'main' && $name =~ /^::/) {
1404	$stash = '::';
1405    }
1406    elsif (($stash eq 'main'
1407	    && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1408	or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1409	    && ($stash eq 'main' || $name !~ /::/))
1410	  )
1411    {
1412	$stash = "";
1413    } else {
1414	$stash = $stash . "::";
1415    }
1416    if (!$raw and $name =~ /^(\^..|{)/) {
1417        $name = "{$name}";       # ${^WARNING_BITS}, etc and ${
1418    }
1419    return $stash . $name;
1420}
1421
1422# Return the name to use for a stash variable.
1423# If a lexical with the same name is in scope, or
1424# if strictures are enabled, it may need to be
1425# fully-qualified.
1426sub stash_variable {
1427    my ($self, $prefix, $name, $cx) = @_;
1428
1429    return "$prefix$name" if $name =~ /::/;
1430
1431    unless ($prefix eq '$' || $prefix eq '@' || #'
1432	    $prefix eq '%' || $prefix eq '$#') {
1433	return "$prefix$name";
1434    }
1435
1436    if ($name =~ /^[^\w+-]$/) {
1437      if (defined $cx && $cx == 26) {
1438	if ($prefix eq '@') {
1439	    return "$prefix\{$name}";
1440	}
1441	elsif ($name eq '#') { return '${#}' } #  "${#}a" vs "$#a"
1442      }
1443      if ($prefix eq '$#') {
1444	return "\$#{$name}";
1445      }
1446    }
1447
1448    return $prefix . $self->maybe_qualify($prefix, $name);
1449}
1450
1451# Return just the name, without the prefix.  It may be returned as a quoted
1452# string.  The second return value is a boolean indicating that.
1453sub stash_variable_name {
1454    my($self, $prefix, $gv) = @_;
1455    my $name = $self->gv_name($gv, 1);
1456    $name = $self->maybe_qualify($prefix,$name);
1457    if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1458	$name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1459	$name =~ /^(\^..|{)/ and $name = "{$name}";
1460	return $name, 0; # not quoted
1461    }
1462    else {
1463	single_delim("q", "'", $name), 1;
1464    }
1465}
1466
1467sub maybe_qualify {
1468    my ($self,$prefix,$name) = @_;
1469    my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1470    return $name if !$prefix || $name =~ /::/;
1471    return $self->{'curstash'}.'::'. $name
1472	if
1473	    $name =~ /^(?!\d)\w/         # alphabetic
1474	 && $v    !~ /^\$[ab]\z/	 # not $a or $b
1475	 && !$globalnames{$name}         # not a global name
1476	 && $self->{hints} & $strict_bits{vars}  # strict vars
1477	 && !$self->lex_in_scope($v,1)   # no "our"
1478      or $self->lex_in_scope($v);        # conflicts with "my" variable
1479    return $name;
1480}
1481
1482sub lex_in_scope {
1483    my ($self, $name, $our) = @_;
1484    substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1485    $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1486
1487    return 0 if !defined($self->{'curcop'});
1488    my $seq = $self->{'curcop'}->cop_seq;
1489    return 0 if !exists $self->{'curcvlex'}{$name};
1490    for my $a (@{$self->{'curcvlex'}{$name}}) {
1491	my ($st, $en) = @$a;
1492	return 1 if $seq > $st && $seq <= $en;
1493    }
1494    return 0;
1495}
1496
1497sub populate_curcvlex {
1498    my $self = shift;
1499    for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1500	my $padlist = $cv->PADLIST;
1501	# an undef CV still in lexical chain
1502	next if class($padlist) eq "SPECIAL";
1503	my @padlist = $padlist->ARRAY;
1504	my @ns = $padlist[0]->ARRAY;
1505
1506	for (my $i=0; $i<@ns; ++$i) {
1507	    next if class($ns[$i]) eq "SPECIAL";
1508	    if (class($ns[$i]) eq "PV") {
1509		# Probably that pesky lexical @_
1510		next;
1511	    }
1512            my $name = $ns[$i]->PVX;
1513	    my ($seq_st, $seq_en) =
1514		($ns[$i]->FLAGS & SVf_FAKE)
1515		    ? (0, 999999)
1516		    : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1517
1518	    push @{$self->{'curcvlex'}{
1519			($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1520		  }}, [$seq_st, $seq_en];
1521	}
1522    }
1523}
1524
1525sub find_scope_st { ((find_scope(@_))[0]); }
1526sub find_scope_en { ((find_scope(@_))[1]); }
1527
1528# Recurses down the tree, looking for pad variable introductions and COPs
1529sub find_scope {
1530    my ($self, $op, $scope_st, $scope_en) = @_;
1531    carp("Undefined op in find_scope") if !defined $op;
1532    return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1533
1534    my @queue = ($op);
1535    while(my $op = shift @queue ) {
1536	for (my $o=$op->first; $$o; $o=$o->sibling) {
1537	    if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1538		my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1539		my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1540		$scope_st = $s if !defined($scope_st) || $s < $scope_st;
1541		$scope_en = $e if !defined($scope_en) || $e > $scope_en;
1542		return ($scope_st, $scope_en);
1543	    }
1544	    elsif (is_state($o)) {
1545		my $c = $o->cop_seq;
1546		$scope_st = $c if !defined($scope_st) || $c < $scope_st;
1547		$scope_en = $c if !defined($scope_en) || $c > $scope_en;
1548		return ($scope_st, $scope_en);
1549	    }
1550	    elsif ($o->flags & OPf_KIDS) {
1551		unshift (@queue, $o);
1552	    }
1553	}
1554    }
1555
1556    return ($scope_st, $scope_en);
1557}
1558
1559# Returns a list of subs which should be inserted before the COP
1560sub cop_subs {
1561    my ($self, $op, $out_seq) = @_;
1562    my $seq = $op->cop_seq;
1563    # If we have nephews, then our sequence number indicates
1564    # the cop_seq of the end of some sort of scope.
1565    if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1566	and my $nseq = $self->find_scope_st($op->sibling) ) {
1567	$seq = $nseq;
1568    }
1569    $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1570    return $self->seq_subs($seq);
1571}
1572
1573sub seq_subs {
1574    my ($self, $seq) = @_;
1575    my @text;
1576#push @text, "# ($seq)\n";
1577
1578    return "" if !defined $seq;
1579    while (scalar(@{$self->{'subs_todo'}})
1580	   and $seq > $self->{'subs_todo'}[0][0]) {
1581	push @text, $self->next_todo;
1582    }
1583    return @text;
1584}
1585
1586sub _features_from_bundle {
1587    my ($hints, $hh) = @_;
1588    foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
1589	$hh->{$feature::feature{$_}} = 1;
1590    }
1591    return $hh;
1592}
1593
1594# Notice how subs and formats are inserted between statements here;
1595# also $[ assignments and pragmas.
1596sub pp_nextstate {
1597    my $self = shift;
1598    my($op, $cx) = @_;
1599    $self->{'curcop'} = $op;
1600    my @text;
1601    push @text, $self->cop_subs($op);
1602    my $stash = $op->stashpv;
1603    if ($stash ne $self->{'curstash'}) {
1604	push @text, "package $stash;\n";
1605	$self->{'curstash'} = $stash;
1606    }
1607
1608    if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1609	push @text, '$[ = '. $op->arybase .";\n";
1610	$self->{'arybase'} = $op->arybase;
1611    }
1612
1613    my $warnings = $op->warnings;
1614    my $warning_bits;
1615    if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1616	$warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1617    }
1618    elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1619        $warning_bits = $warnings::NONE;
1620    }
1621    elsif ($warnings->isa("B::SPECIAL")) {
1622	$warning_bits = undef;
1623    }
1624    else {
1625	$warning_bits = $warnings->PV & WARN_MASK;
1626    }
1627
1628    if (defined ($warning_bits) and
1629       !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1630	push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1631	$self->{'warnings'} = $warning_bits;
1632    }
1633
1634    my $hints = $] < 5.008009 ? $op->private : $op->hints;
1635    my $old_hints = $self->{'hints'};
1636    if ($self->{'hints'} != $hints) {
1637	push @text, declare_hints($self->{'hints'}, $hints);
1638	$self->{'hints'} = $hints;
1639    }
1640
1641    my $newhh;
1642    if ($] > 5.009) {
1643	$newhh = $op->hints_hash->HASH;
1644    }
1645
1646    if ($] >= 5.015006) {
1647	# feature bundle hints
1648	my $from = $old_hints & $feature::hint_mask;
1649	my $to   = $    hints & $feature::hint_mask;
1650	if ($from != $to) {
1651	    if ($to == $feature::hint_mask) {
1652		if ($self->{'hinthash'}) {
1653		    delete $self->{'hinthash'}{$_}
1654			for grep /^feature_/, keys %{$self->{'hinthash'}};
1655		}
1656		else { $self->{'hinthash'} = {} }
1657		$self->{'hinthash'}
1658		    = _features_from_bundle($from, $self->{'hinthash'});
1659	    }
1660	    else {
1661		my $bundle =
1662		    $feature::hint_bundles[$to >> $feature::hint_shift];
1663		$bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1664		push @text, "no feature;\n",
1665			    "use feature ':$bundle';\n";
1666	    }
1667	}
1668    }
1669
1670    if ($] > 5.009) {
1671	push @text, declare_hinthash(
1672	    $self->{'hinthash'}, $newhh,
1673	    $self->{indent_size}, $self->{hints},
1674	);
1675	$self->{'hinthash'} = $newhh;
1676    }
1677
1678    # This should go after of any branches that add statements, to
1679    # increase the chances that it refers to the same line it did in
1680    # the original program.
1681    if ($self->{'linenums'}) {
1682	push @text, "\f#line " . $op->line .
1683	  ' "' . $op->file, qq'"\n';
1684    }
1685
1686    push @text, $op->label . ": " if $op->label;
1687
1688    return join("", @text);
1689}
1690
1691sub declare_warnings {
1692    my ($from, $to) = @_;
1693    if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1694	return "use warnings;\n";
1695    }
1696    elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1697	return "no warnings;\n";
1698    }
1699    return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1700}
1701
1702sub declare_hints {
1703    my ($from, $to) = @_;
1704    my $use = $to   & ~$from;
1705    my $no  = $from & ~$to;
1706    my $decls = "";
1707    for my $pragma (hint_pragmas($use)) {
1708	$decls .= "use $pragma;\n";
1709    }
1710    for my $pragma (hint_pragmas($no)) {
1711        $decls .= "no $pragma;\n";
1712    }
1713    return $decls;
1714}
1715
1716# Internal implementation hints that the core sets automatically, so don't need
1717# (or want) to be passed back to the user
1718my %ignored_hints = (
1719    'open<' => 1,
1720    'open>' => 1,
1721    ':'     => 1,
1722    'strict/refs' => 1,
1723    'strict/subs' => 1,
1724    'strict/vars' => 1,
1725);
1726
1727my %rev_feature;
1728
1729sub declare_hinthash {
1730    my ($from, $to, $indent, $hints) = @_;
1731    my $doing_features =
1732	($hints & $feature::hint_mask) == $feature::hint_mask;
1733    my @decls;
1734    my @features;
1735    my @unfeatures; # bugs?
1736    for my $key (sort keys %$to) {
1737	next if $ignored_hints{$key};
1738	my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1739	next if $is_feature and not $doing_features;
1740	if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1741	    push(@features, $key), next if $is_feature;
1742	    push @decls,
1743		qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1744	      . (
1745		   defined $to->{$key}
1746			? single_delim("q", "'", $to->{$key})
1747			: 'undef'
1748		)
1749	      . qq(;);
1750	}
1751    }
1752    for my $key (sort keys %$from) {
1753	next if $ignored_hints{$key};
1754	my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1755	next if $is_feature and not $doing_features;
1756	if (!exists $to->{$key}) {
1757	    push(@unfeatures, $key), next if $is_feature;
1758	    push @decls, qq(delete \$^H{'$key'};);
1759	}
1760    }
1761    my @ret;
1762    if (@features || @unfeatures) {
1763	if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1764    }
1765    if (@features) {
1766	push @ret, "use feature "
1767		 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1768    }
1769    if (@unfeatures) {
1770	push @ret, "no feature "
1771		 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1772		 . ";\n";
1773    }
1774    @decls and
1775	push @ret,
1776	     join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1777    return @ret;
1778}
1779
1780sub hint_pragmas {
1781    my ($bits) = @_;
1782    my (@pragmas, @strict);
1783    push @pragmas, "integer" if $bits & 0x1;
1784    for (sort keys %strict_bits) {
1785	push @strict, "'$_'" if $bits & $strict_bits{$_};
1786    }
1787    if (@strict == keys %strict_bits) {
1788	push @pragmas, "strict";
1789    }
1790    elsif (@strict) {
1791	push @pragmas, "strict " . join ', ', @strict;
1792    }
1793    push @pragmas, "bytes" if $bits & 0x8;
1794    return @pragmas;
1795}
1796
1797sub pp_dbstate { pp_nextstate(@_) }
1798sub pp_setstate { pp_nextstate(@_) }
1799
1800sub pp_unstack { return "" } # see also leaveloop
1801
1802my %feature_keywords = (
1803  # keyword => 'feature',
1804    state   => 'state',
1805    say     => 'say',
1806    given   => 'switch',
1807    when    => 'switch',
1808    default => 'switch',
1809    break   => 'switch',
1810    evalbytes=>'evalbytes',
1811    __SUB__ => '__SUB__',
1812   fc       => 'fc',
1813);
1814
1815# keywords that are strong and also have a prototype
1816#
1817my %strong_proto_keywords = map { $_ => 1 } qw(
1818    pos
1819    prototype
1820    scalar
1821    study
1822    undef
1823);
1824
1825sub keyword {
1826    my $self = shift;
1827    my $name = shift;
1828    return $name if $name =~ /^CORE::/; # just in case
1829    if (exists $feature_keywords{$name}) {
1830	my $hh;
1831	my $hints = $self->{hints} & $feature::hint_mask;
1832	if ($hints && $hints != $feature::hint_mask) {
1833	    $hh = _features_from_bundle($hints);
1834	}
1835	elsif ($hints) { $hh = $self->{'hinthash'} }
1836	return "CORE::$name"
1837	 if !$hh
1838	 || !$hh->{"feature_$feature_keywords{$name}"}
1839    }
1840    if ($strong_proto_keywords{$name}
1841        || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1842	    && !defined eval{prototype "CORE::$name"})
1843    ) { return $name }
1844    if (
1845	exists $self->{subs_declared}{$name}
1846	 or
1847	exists &{"$self->{curstash}::$name"}
1848    ) {
1849	return "CORE::$name"
1850    }
1851    return $name;
1852}
1853
1854sub baseop {
1855    my $self = shift;
1856    my($op, $cx, $name) = @_;
1857    return $self->keyword($name);
1858}
1859
1860sub pp_stub {
1861    my $self = shift;
1862    my($op, $cx, $name) = @_;
1863    if ($cx >= 1) {
1864	return "()";
1865    }
1866    else {
1867	return "();";
1868    }
1869}
1870sub pp_wantarray { baseop(@_, "wantarray") }
1871sub pp_fork { baseop(@_, "fork") }
1872sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1873sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1874sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1875sub pp_tms { baseop(@_, "times") }
1876sub pp_ghostent { baseop(@_, "gethostent") }
1877sub pp_gnetent { baseop(@_, "getnetent") }
1878sub pp_gprotoent { baseop(@_, "getprotoent") }
1879sub pp_gservent { baseop(@_, "getservent") }
1880sub pp_ehostent { baseop(@_, "endhostent") }
1881sub pp_enetent { baseop(@_, "endnetent") }
1882sub pp_eprotoent { baseop(@_, "endprotoent") }
1883sub pp_eservent { baseop(@_, "endservent") }
1884sub pp_gpwent { baseop(@_, "getpwent") }
1885sub pp_spwent { baseop(@_, "setpwent") }
1886sub pp_epwent { baseop(@_, "endpwent") }
1887sub pp_ggrent { baseop(@_, "getgrent") }
1888sub pp_sgrent { baseop(@_, "setgrent") }
1889sub pp_egrent { baseop(@_, "endgrent") }
1890sub pp_getlogin { baseop(@_, "getlogin") }
1891
1892sub POSTFIX () { 1 }
1893
1894# I couldn't think of a good short name, but this is the category of
1895# symbolic unary operators with interesting precedence
1896
1897sub pfixop {
1898    my $self = shift;
1899    my($op, $cx, $name, $prec, $flags) = (@_, 0);
1900    my $kid = $op->first;
1901    $kid = $self->deparse($kid, $prec);
1902    return $self->maybe_parens(($flags & POSTFIX)
1903				 ? "$kid$name"
1904				   # avoid confusion with filetests
1905				 : $name eq '-'
1906				   && $kid =~ /^[a-zA-Z](?!\w)/
1907					? "$name($kid)"
1908					: "$name$kid",
1909			       $cx, $prec);
1910}
1911
1912sub pp_preinc { pfixop(@_, "++", 23) }
1913sub pp_predec { pfixop(@_, "--", 23) }
1914sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1915sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1916sub pp_i_preinc { pfixop(@_, "++", 23) }
1917sub pp_i_predec { pfixop(@_, "--", 23) }
1918sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1919sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1920sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1921
1922sub pp_negate { maybe_targmy(@_, \&real_negate) }
1923sub real_negate {
1924    my $self = shift;
1925    my($op, $cx) = @_;
1926    if ($op->first->name =~ /^(i_)?negate$/) {
1927	# avoid --$x
1928	$self->pfixop($op, $cx, "-", 21.5);
1929    } else {
1930	$self->pfixop($op, $cx, "-", 21);
1931    }
1932}
1933sub pp_i_negate { pp_negate(@_) }
1934
1935sub pp_not {
1936    my $self = shift;
1937    my($op, $cx) = @_;
1938    if ($cx <= 4) {
1939	$self->listop($op, $cx, "not", $op->first);
1940    } else {
1941	$self->pfixop($op, $cx, "!", 21);
1942    }
1943}
1944
1945sub unop {
1946    my $self = shift;
1947    my($op, $cx, $name, $nollafr) = @_;
1948    my $kid;
1949    if ($op->flags & OPf_KIDS) {
1950	$kid = $op->first;
1951 	if (not $name) {
1952 	    # this deals with 'boolkeys' right now
1953 	    return $self->deparse($kid,$cx);
1954 	}
1955	my $builtinname = $name;
1956	$builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1957	if (defined prototype($builtinname)
1958	   && prototype($builtinname) =~ /^;?\*/
1959	   && $kid->name eq "rv2gv") {
1960	    $kid = $kid->first;
1961	}
1962
1963	if ($nollafr) {
1964	    ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1965	    return $self->maybe_parens(
1966			$self->keyword($name) . " $kid", $cx, 16
1967		   );
1968	}
1969	return $self->maybe_parens_unop($name, $kid, $cx);
1970    } else {
1971	return $self->maybe_parens(
1972	    $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1973	    $cx, 16,
1974	);
1975    }
1976}
1977
1978sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1979sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1980sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1981sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1982sub pp_defined { unop(@_, "defined") }
1983sub pp_undef { unop(@_, "undef") }
1984sub pp_study { unop(@_, "study") }
1985sub pp_ref { unop(@_, "ref") }
1986sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1987
1988sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1989sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1990sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1991sub pp_srand { unop(@_, "srand") }
1992sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1993sub pp_log { maybe_targmy(@_, \&unop, "log") }
1994sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1995sub pp_int { maybe_targmy(@_, \&unop, "int") }
1996sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1997sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1998sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1999
2000sub pp_length { maybe_targmy(@_, \&unop, "length") }
2001sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2002sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
2003
2004sub pp_each { unop(@_, "each") }
2005sub pp_values { unop(@_, "values") }
2006sub pp_keys { unop(@_, "keys") }
2007{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
2008sub pp_boolkeys {
2009    # no name because its an optimisation op that has no keyword
2010    unop(@_,"");
2011}
2012sub pp_aeach { unop(@_, "each") }
2013sub pp_avalues { unop(@_, "values") }
2014sub pp_akeys { unop(@_, "keys") }
2015sub pp_pop { unop(@_, "pop") }
2016sub pp_shift { unop(@_, "shift") }
2017
2018sub pp_caller { unop(@_, "caller") }
2019sub pp_reset { unop(@_, "reset") }
2020sub pp_exit { unop(@_, "exit") }
2021sub pp_prototype { unop(@_, "prototype") }
2022
2023sub pp_close { unop(@_, "close") }
2024sub pp_fileno { unop(@_, "fileno") }
2025sub pp_umask { unop(@_, "umask") }
2026sub pp_untie { unop(@_, "untie") }
2027sub pp_tied { unop(@_, "tied") }
2028sub pp_dbmclose { unop(@_, "dbmclose") }
2029sub pp_getc { unop(@_, "getc") }
2030sub pp_eof { unop(@_, "eof") }
2031sub pp_tell { unop(@_, "tell") }
2032sub pp_getsockname { unop(@_, "getsockname") }
2033sub pp_getpeername { unop(@_, "getpeername") }
2034
2035sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
2036sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
2037sub pp_readlink { unop(@_, "readlink") }
2038sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
2039sub pp_readdir { unop(@_, "readdir") }
2040sub pp_telldir { unop(@_, "telldir") }
2041sub pp_rewinddir { unop(@_, "rewinddir") }
2042sub pp_closedir { unop(@_, "closedir") }
2043sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
2044sub pp_localtime { unop(@_, "localtime") }
2045sub pp_gmtime { unop(@_, "gmtime") }
2046sub pp_alarm { unop(@_, "alarm") }
2047sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
2048
2049sub pp_dofile {
2050    my $code = unop(@_, "do", 1); # llafr does not apply
2051    if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
2052    $code;
2053}
2054sub pp_entereval {
2055    unop(
2056      @_,
2057      $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
2058    )
2059}
2060
2061sub pp_ghbyname { unop(@_, "gethostbyname") }
2062sub pp_gnbyname { unop(@_, "getnetbyname") }
2063sub pp_gpbyname { unop(@_, "getprotobyname") }
2064sub pp_shostent { unop(@_, "sethostent") }
2065sub pp_snetent { unop(@_, "setnetent") }
2066sub pp_sprotoent { unop(@_, "setprotoent") }
2067sub pp_sservent { unop(@_, "setservent") }
2068sub pp_gpwnam { unop(@_, "getpwnam") }
2069sub pp_gpwuid { unop(@_, "getpwuid") }
2070sub pp_ggrnam { unop(@_, "getgrnam") }
2071sub pp_ggrgid { unop(@_, "getgrgid") }
2072
2073sub pp_lock { unop(@_, "lock") }
2074
2075sub pp_continue { unop(@_, "continue"); }
2076sub pp_break { unop(@_, "break"); }
2077
2078sub givwhen {
2079    my $self = shift;
2080    my($op, $cx, $givwhen) = @_;
2081
2082    my $enterop = $op->first;
2083    my ($head, $block);
2084    if ($enterop->flags & OPf_SPECIAL) {
2085	$head = $self->keyword("default");
2086	$block = $self->deparse($enterop->first, 0);
2087    }
2088    else {
2089	my $cond = $enterop->first;
2090	my $cond_str = $self->deparse($cond, 1);
2091	$head = "$givwhen ($cond_str)";
2092	$block = $self->deparse($cond->sibling, 0);
2093    }
2094
2095    return "$head {\n".
2096	"\t$block\n".
2097	"\b}\cK";
2098}
2099
2100sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2101sub pp_leavewhen  { givwhen(@_, $_[0]->keyword("when")); }
2102
2103sub pp_exists {
2104    my $self = shift;
2105    my($op, $cx) = @_;
2106    my $arg;
2107    if ($op->private & OPpEXISTS_SUB) {
2108	# Checking for the existence of a subroutine
2109	return $self->maybe_parens_func("exists",
2110				$self->pp_rv2cv($op->first, 16), $cx, 16);
2111    }
2112    if ($op->flags & OPf_SPECIAL) {
2113	# Array element, not hash element
2114	return $self->maybe_parens_func("exists",
2115				$self->pp_aelem($op->first, 16), $cx, 16);
2116    }
2117    return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
2118				    $cx, 16);
2119}
2120
2121sub pp_delete {
2122    my $self = shift;
2123    my($op, $cx) = @_;
2124    my $arg;
2125    if ($op->private & OPpSLICE) {
2126	if ($op->flags & OPf_SPECIAL) {
2127	    # Deleting from an array, not a hash
2128	    return $self->maybe_parens_func("delete",
2129					$self->pp_aslice($op->first, 16),
2130					$cx, 16);
2131	}
2132	return $self->maybe_parens_func("delete",
2133					$self->pp_hslice($op->first, 16),
2134					$cx, 16);
2135    } else {
2136	if ($op->flags & OPf_SPECIAL) {
2137	    # Deleting from an array, not a hash
2138	    return $self->maybe_parens_func("delete",
2139					$self->pp_aelem($op->first, 16),
2140					$cx, 16);
2141	}
2142	return $self->maybe_parens_func("delete",
2143					$self->pp_helem($op->first, 16),
2144					$cx, 16);
2145    }
2146}
2147
2148sub pp_require {
2149    my $self = shift;
2150    my($op, $cx) = @_;
2151    my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2152    if (class($op) eq "UNOP" and $op->first->name eq "const"
2153	and $op->first->private & OPpCONST_BARE)
2154    {
2155	my $name = $self->const_sv($op->first)->PV;
2156	$name =~ s[/][::]g;
2157	$name =~ s/\.pm//g;
2158	return $self->maybe_parens("$opname $name", $cx, 16);
2159    } else {
2160	$self->unop(
2161	    $op, $cx,
2162	    $op->first->name eq 'const'
2163	     && $op->first->private & OPpCONST_NOVER
2164		 ? "no"
2165		 : $opname,
2166	    1, # llafr does not apply
2167	);
2168    }
2169}
2170
2171sub pp_scalar {
2172    my $self = shift;
2173    my($op, $cx) = @_;
2174    my $kid = $op->first;
2175    if (not null $kid->sibling) {
2176	# XXX Was a here-doc
2177	return $self->dquote($op);
2178    }
2179    $self->unop(@_, "scalar");
2180}
2181
2182
2183sub padval {
2184    my $self = shift;
2185    my $targ = shift;
2186    return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2187}
2188
2189sub anon_hash_or_list {
2190    my $self = shift;
2191    my($op, $cx) = @_;
2192
2193    my($pre, $post) = @{{"anonlist" => ["[","]"],
2194			 "anonhash" => ["{","}"]}->{$op->name}};
2195    my($expr, @exprs);
2196    $op = $op->first->sibling; # skip pushmark
2197    for (; !null($op); $op = $op->sibling) {
2198	$expr = $self->deparse($op, 6);
2199	push @exprs, $expr;
2200    }
2201    if ($pre eq "{" and $cx < 1) {
2202	# Disambiguate that it's not a block
2203	$pre = "+{";
2204    }
2205    return $pre . join(", ", @exprs) . $post;
2206}
2207
2208sub pp_anonlist {
2209    my $self = shift;
2210    my ($op, $cx) = @_;
2211    if ($op->flags & OPf_SPECIAL) {
2212	return $self->anon_hash_or_list($op, $cx);
2213    }
2214    warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2215    return 'XXX';
2216}
2217
2218*pp_anonhash = \&pp_anonlist;
2219
2220sub pp_refgen {
2221    my $self = shift;
2222    my($op, $cx) = @_;
2223    my $kid = $op->first;
2224    if ($kid->name eq "null") {
2225	$kid = $kid->first;
2226	if (!null($kid->sibling) and
2227		 $kid->sibling->name eq "anoncode") {
2228            return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
2229	} elsif ($kid->name eq "pushmark") {
2230            my $sib_name = $kid->sibling->name;
2231            if ($sib_name =~ /^(pad|rv2)[ah]v$/
2232                and not $kid->sibling->flags & OPf_REF)
2233            {
2234                # The @a in \(@a) isn't in ref context, but only when the
2235                # parens are there.
2236		return "\\(" . $self->pp_list($op->first) . ")";
2237            } elsif ($sib_name eq 'entersub') {
2238                my $text = $self->deparse($kid->sibling, 1);
2239                # Always show parens for \(&func()), but only with -p otherwise
2240                $text = "($text)" if $self->{'parens'}
2241                                 or $kid->sibling->private & OPpENTERSUB_AMPER;
2242                return "\\$text";
2243            }
2244        }
2245    }
2246    $self->pfixop($op, $cx, "\\", 20);
2247}
2248
2249sub e_anoncode {
2250    my ($self, $info) = @_;
2251    my $text = $self->deparse_sub($info->{code});
2252    return "sub " . $text;
2253}
2254
2255sub pp_srefgen { pp_refgen(@_) }
2256
2257sub pp_readline {
2258    my $self = shift;
2259    my($op, $cx) = @_;
2260    my $kid = $op->first;
2261    $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
2262    return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2263    return $self->unop($op, $cx, "readline");
2264}
2265
2266sub pp_rcatline {
2267    my $self = shift;
2268    my($op) = @_;
2269    return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2270}
2271
2272# Unary operators that can occur as pseudo-listops inside double quotes
2273sub dq_unop {
2274    my $self = shift;
2275    my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2276    my $kid;
2277    if ($op->flags & OPf_KIDS) {
2278       $kid = $op->first;
2279       # If there's more than one kid, the first is an ex-pushmark.
2280       $kid = $kid->sibling if not null $kid->sibling;
2281       return $self->maybe_parens_unop($name, $kid, $cx);
2282    } else {
2283       return $name .  ($op->flags & OPf_SPECIAL ? "()" : "");
2284    }
2285}
2286
2287sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2288sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2289sub pp_uc { dq_unop(@_, "uc") }
2290sub pp_lc { dq_unop(@_, "lc") }
2291sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2292sub pp_fc { dq_unop(@_, "fc") }
2293
2294sub loopex {
2295    my $self = shift;
2296    my ($op, $cx, $name) = @_;
2297    if (class($op) eq "PVOP") {
2298	$name .= " " . $op->pv;
2299    } elsif (class($op) eq "OP") {
2300	# no-op
2301    } elsif (class($op) eq "UNOP") {
2302	(my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
2303	$name .= " $kid";
2304    }
2305    return $self->maybe_parens($name, $cx, 7);
2306}
2307
2308sub pp_last { loopex(@_, "last") }
2309sub pp_next { loopex(@_, "next") }
2310sub pp_redo { loopex(@_, "redo") }
2311sub pp_goto { loopex(@_, "goto") }
2312sub pp_dump { loopex(@_, "CORE::dump") }
2313
2314sub ftst {
2315    my $self = shift;
2316    my($op, $cx, $name) = @_;
2317    if (class($op) eq "UNOP") {
2318	# Genuine '-X' filetests are exempt from the LLAFR, but not
2319	# l?stat()
2320	if ($name =~ /^-/) {
2321	    (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2322	    return $self->maybe_parens("$name $kid", $cx, 16);
2323	}
2324	return $self->maybe_parens_unop($name, $op->first, $cx);
2325    } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2326	return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2327    } else { # I don't think baseop filetests ever survive ck_ftst, but...
2328	return $name;
2329    }
2330}
2331
2332sub pp_lstat    { ftst(@_, "lstat") }
2333sub pp_stat     { ftst(@_, "stat") }
2334sub pp_ftrread  { ftst(@_, "-R") }
2335sub pp_ftrwrite { ftst(@_, "-W") }
2336sub pp_ftrexec  { ftst(@_, "-X") }
2337sub pp_fteread  { ftst(@_, "-r") }
2338sub pp_ftewrite { ftst(@_, "-w") }
2339sub pp_fteexec  { ftst(@_, "-x") }
2340sub pp_ftis     { ftst(@_, "-e") }
2341sub pp_fteowned { ftst(@_, "-O") }
2342sub pp_ftrowned { ftst(@_, "-o") }
2343sub pp_ftzero   { ftst(@_, "-z") }
2344sub pp_ftsize   { ftst(@_, "-s") }
2345sub pp_ftmtime  { ftst(@_, "-M") }
2346sub pp_ftatime  { ftst(@_, "-A") }
2347sub pp_ftctime  { ftst(@_, "-C") }
2348sub pp_ftsock   { ftst(@_, "-S") }
2349sub pp_ftchr    { ftst(@_, "-c") }
2350sub pp_ftblk    { ftst(@_, "-b") }
2351sub pp_ftfile   { ftst(@_, "-f") }
2352sub pp_ftdir    { ftst(@_, "-d") }
2353sub pp_ftpipe   { ftst(@_, "-p") }
2354sub pp_ftlink   { ftst(@_, "-l") }
2355sub pp_ftsuid   { ftst(@_, "-u") }
2356sub pp_ftsgid   { ftst(@_, "-g") }
2357sub pp_ftsvtx   { ftst(@_, "-k") }
2358sub pp_fttty    { ftst(@_, "-t") }
2359sub pp_fttext   { ftst(@_, "-T") }
2360sub pp_ftbinary { ftst(@_, "-B") }
2361
2362sub SWAP_CHILDREN () { 1 }
2363sub ASSIGN () { 2 } # has OP= variant
2364sub LIST_CONTEXT () { 4 } # Assignment is in list context
2365
2366my(%left, %right);
2367
2368sub assoc_class {
2369    my $op = shift;
2370    my $name = $op->name;
2371    if ($name eq "concat" and $op->first->name eq "concat") {
2372	# avoid spurious '=' -- see comment in pp_concat
2373	return "concat";
2374    }
2375    if ($name eq "null" and class($op) eq "UNOP"
2376	and $op->first->name =~ /^(and|x?or)$/
2377	and null $op->first->sibling)
2378    {
2379	# Like all conditional constructs, OP_ANDs and OP_ORs are topped
2380	# with a null that's used as the common end point of the two
2381	# flows of control. For precedence purposes, ignore it.
2382	# (COND_EXPRs have these too, but we don't bother with
2383	# their associativity).
2384	return assoc_class($op->first);
2385    }
2386    return $name . ($op->flags & OPf_STACKED ? "=" : "");
2387}
2388
2389# Left associative operators, like '+', for which
2390# $a + $b + $c is equivalent to ($a + $b) + $c
2391
2392BEGIN {
2393    %left = ('multiply' => 19, 'i_multiply' => 19,
2394	     'divide' => 19, 'i_divide' => 19,
2395	     'modulo' => 19, 'i_modulo' => 19,
2396	     'repeat' => 19,
2397	     'add' => 18, 'i_add' => 18,
2398	     'subtract' => 18, 'i_subtract' => 18,
2399	     'concat' => 18,
2400	     'left_shift' => 17, 'right_shift' => 17,
2401	     'bit_and' => 13,
2402	     'bit_or' => 12, 'bit_xor' => 12,
2403	     'and' => 3,
2404	     'or' => 2, 'xor' => 2,
2405	    );
2406}
2407
2408sub deparse_binop_left {
2409    my $self = shift;
2410    my($op, $left, $prec) = @_;
2411    if ($left{assoc_class($op)} && $left{assoc_class($left)}
2412	and $left{assoc_class($op)} == $left{assoc_class($left)})
2413    {
2414	return $self->deparse($left, $prec - .00001);
2415    } else {
2416	return $self->deparse($left, $prec);
2417    }
2418}
2419
2420# Right associative operators, like '=', for which
2421# $a = $b = $c is equivalent to $a = ($b = $c)
2422
2423BEGIN {
2424    %right = ('pow' => 22,
2425	      'sassign=' => 7, 'aassign=' => 7,
2426	      'multiply=' => 7, 'i_multiply=' => 7,
2427	      'divide=' => 7, 'i_divide=' => 7,
2428	      'modulo=' => 7, 'i_modulo=' => 7,
2429	      'repeat=' => 7,
2430	      'add=' => 7, 'i_add=' => 7,
2431	      'subtract=' => 7, 'i_subtract=' => 7,
2432	      'concat=' => 7,
2433	      'left_shift=' => 7, 'right_shift=' => 7,
2434	      'bit_and=' => 7,
2435	      'bit_or=' => 7, 'bit_xor=' => 7,
2436	      'andassign' => 7,
2437	      'orassign' => 7,
2438	     );
2439}
2440
2441sub deparse_binop_right {
2442    my $self = shift;
2443    my($op, $right, $prec) = @_;
2444    if ($right{assoc_class($op)} && $right{assoc_class($right)}
2445	and $right{assoc_class($op)} == $right{assoc_class($right)})
2446    {
2447	return $self->deparse($right, $prec - .00001);
2448    } else {
2449	return $self->deparse($right, $prec);
2450    }
2451}
2452
2453sub binop {
2454    my $self = shift;
2455    my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2456    my $left = $op->first;
2457    my $right = $op->last;
2458    my $eq = "";
2459    if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2460	$eq = "=";
2461	$prec = 7;
2462    }
2463    if ($flags & SWAP_CHILDREN) {
2464	($left, $right) = ($right, $left);
2465    }
2466    $left = $self->deparse_binop_left($op, $left, $prec);
2467    $left = "($left)" if $flags & LIST_CONTEXT
2468		&& $left !~ /^(my|our|local|)[\@\(]/;
2469    $right = $self->deparse_binop_right($op, $right, $prec);
2470    return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2471}
2472
2473sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2474sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2475sub pp_subtract { maybe_targmy(@_, \&binop, "-",18,  ASSIGN) }
2476sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2477sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2478sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2479sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2480sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2481sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2482sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2483sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2484
2485sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2486sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2487sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2488sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2489sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2490
2491sub pp_eq { binop(@_, "==", 14) }
2492sub pp_ne { binop(@_, "!=", 14) }
2493sub pp_lt { binop(@_, "<", 15) }
2494sub pp_gt { binop(@_, ">", 15) }
2495sub pp_ge { binop(@_, ">=", 15) }
2496sub pp_le { binop(@_, "<=", 15) }
2497sub pp_ncmp { binop(@_, "<=>", 14) }
2498sub pp_i_eq { binop(@_, "==", 14) }
2499sub pp_i_ne { binop(@_, "!=", 14) }
2500sub pp_i_lt { binop(@_, "<", 15) }
2501sub pp_i_gt { binop(@_, ">", 15) }
2502sub pp_i_ge { binop(@_, ">=", 15) }
2503sub pp_i_le { binop(@_, "<=", 15) }
2504sub pp_i_ncmp { binop(@_, "<=>", 14) }
2505
2506sub pp_seq { binop(@_, "eq", 14) }
2507sub pp_sne { binop(@_, "ne", 14) }
2508sub pp_slt { binop(@_, "lt", 15) }
2509sub pp_sgt { binop(@_, "gt", 15) }
2510sub pp_sge { binop(@_, "ge", 15) }
2511sub pp_sle { binop(@_, "le", 15) }
2512sub pp_scmp { binop(@_, "cmp", 14) }
2513
2514sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2515sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2516
2517sub pp_smartmatch {
2518    my ($self, $op, $cx) = @_;
2519    if ($op->flags & OPf_SPECIAL) {
2520	return $self->deparse($op->last, $cx);
2521    }
2522    else {
2523	binop(@_, "~~", 14);
2524    }
2525}
2526
2527# '.' is special because concats-of-concats are optimized to save copying
2528# by making all but the first concat stacked. The effect is as if the
2529# programmer had written '($a . $b) .= $c', except legal.
2530sub pp_concat { maybe_targmy(@_, \&real_concat) }
2531sub real_concat {
2532    my $self = shift;
2533    my($op, $cx) = @_;
2534    my $left = $op->first;
2535    my $right = $op->last;
2536    my $eq = "";
2537    my $prec = 18;
2538    if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2539	$eq = "=";
2540	$prec = 7;
2541    }
2542    $left = $self->deparse_binop_left($op, $left, $prec);
2543    $right = $self->deparse_binop_right($op, $right, $prec);
2544    return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2545}
2546
2547# 'x' is weird when the left arg is a list
2548sub pp_repeat {
2549    my $self = shift;
2550    my($op, $cx) = @_;
2551    my $left = $op->first;
2552    my $right = $op->last;
2553    my $eq = "";
2554    my $prec = 19;
2555    if ($op->flags & OPf_STACKED) {
2556	$eq = "=";
2557	$prec = 7;
2558    }
2559    if (null($right)) { # list repeat; count is inside left-side ex-list
2560	my $kid = $left->first->sibling; # skip pushmark
2561	my @exprs;
2562	for (; !null($kid->sibling); $kid = $kid->sibling) {
2563	    push @exprs, $self->deparse($kid, 6);
2564	}
2565	$right = $kid;
2566	$left = "(" . join(", ", @exprs). ")";
2567    } else {
2568	$left = $self->deparse_binop_left($op, $left, $prec);
2569    }
2570    $right = $self->deparse_binop_right($op, $right, $prec);
2571    return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2572}
2573
2574sub range {
2575    my $self = shift;
2576    my ($op, $cx, $type) = @_;
2577    my $left = $op->first;
2578    my $right = $left->sibling;
2579    $left = $self->deparse($left, 9);
2580    $right = $self->deparse($right, 9);
2581    return $self->maybe_parens("$left $type $right", $cx, 9);
2582}
2583
2584sub pp_flop {
2585    my $self = shift;
2586    my($op, $cx) = @_;
2587    my $flip = $op->first;
2588    my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2589    return $self->range($flip->first, $cx, $type);
2590}
2591
2592# one-line while/until is handled in pp_leave
2593
2594sub logop {
2595    my $self = shift;
2596    my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2597    my $left = $op->first;
2598    my $right = $op->first->sibling;
2599    if ($cx < 1 and is_scope($right) and $blockname
2600	and $self->{'expand'} < 7)
2601    { # if ($a) {$b}
2602	$left = $self->deparse($left, 1);
2603	$right = $self->deparse($right, 0);
2604	return "$blockname ($left) {\n\t$right\n\b}\cK";
2605    } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2606	     and $self->{'expand'} < 7) { # $b if $a
2607	$right = $self->deparse($right, 1);
2608	$left = $self->deparse($left, 1);
2609	return "$right $blockname $left";
2610    } elsif ($cx > $lowprec and $highop) { # $a && $b
2611	$left = $self->deparse_binop_left($op, $left, $highprec);
2612	$right = $self->deparse_binop_right($op, $right, $highprec);
2613	return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2614    } else { # $a and $b
2615	$left = $self->deparse_binop_left($op, $left, $lowprec);
2616	$right = $self->deparse_binop_right($op, $right, $lowprec);
2617	return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2618    }
2619}
2620
2621sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2622sub pp_or  { logop(@_, "or",  2, "||", 10, "unless") }
2623sub pp_dor { logop(@_, "//", 10) }
2624
2625# xor is syntactically a logop, but it's really a binop (contrary to
2626# old versions of opcode.pl). Syntax is what matters here.
2627sub pp_xor { logop(@_, "xor", 2, "",   0,  "") }
2628
2629sub logassignop {
2630    my $self = shift;
2631    my ($op, $cx, $opname) = @_;
2632    my $left = $op->first;
2633    my $right = $op->first->sibling->first; # skip sassign
2634    $left = $self->deparse($left, 7);
2635    $right = $self->deparse($right, 7);
2636    return $self->maybe_parens("$left $opname $right", $cx, 7);
2637}
2638
2639sub pp_andassign { logassignop(@_, "&&=") }
2640sub pp_orassign  { logassignop(@_, "||=") }
2641sub pp_dorassign { logassignop(@_, "//=") }
2642
2643sub rv2gv_or_string {
2644    my($self,$op) = @_;
2645    if ($op->name eq "gv") { # could be open("open") or open("###")
2646	my($name,$quoted) =
2647	    $self->stash_variable_name("", $self->gv_or_padgv($op));
2648	$quoted ? $name : "*$name";
2649    }
2650    else {
2651	$self->deparse($op, 6);
2652    }
2653}
2654
2655sub listop {
2656    my $self = shift;
2657    my($op, $cx, $name, $kid, $nollafr) = @_;
2658    my(@exprs);
2659    my $parens = ($cx >= 5) || $self->{'parens'};
2660    $kid ||= $op->first->sibling;
2661    # If there are no arguments, add final parentheses (or parenthesize the
2662    # whole thing if the llafr does not apply) to account for cases like
2663    # (return)+1 or setpgrp()+1.  When the llafr does not apply, we use a
2664    # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2665    if (null $kid) {
2666	return $nollafr
2667		? $self->maybe_parens($self->keyword($name), $cx, 7)
2668		: $self->keyword($name) . '()' x (7 < $cx);
2669    }
2670    my $first;
2671    my $fullname = $self->keyword($name);
2672    my $proto = prototype("CORE::$name");
2673    if (
2674	 (     (defined $proto && $proto =~ /^;?\*/)
2675	    || $name eq 'select' # select(F) doesn't have a proto
2676	 )
2677	 && $kid->name eq "rv2gv"
2678	 && !($kid->private & OPpLVAL_INTRO)
2679    ) {
2680	$first = $self->rv2gv_or_string($kid->first);
2681    }
2682    else {
2683	$first = $self->deparse($kid, 6);
2684    }
2685    if ($name eq "chmod" && $first =~ /^\d+$/) {
2686	$first = sprintf("%#o", $first);
2687    }
2688    $first = "+$first"
2689	if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
2690    push @exprs, $first;
2691    $kid = $kid->sibling;
2692    if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2693	 && !($kid->private & OPpLVAL_INTRO)) {
2694	push @exprs, $first = $self->rv2gv_or_string($kid->first);
2695	$kid = $kid->sibling;
2696    }
2697    for (; !null($kid); $kid = $kid->sibling) {
2698	push @exprs, $self->deparse($kid, 6);
2699    }
2700    if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2701	return "$exprs[0] = $fullname"
2702	         . ($parens ? "($exprs[0])" : " $exprs[0]");
2703    }
2704    if ($name =~ /^(system|exec)$/
2705	&& ($op->flags & OPf_STACKED)
2706	&& @exprs > 1)
2707    {
2708	# handle the "system prog a1,a2,.." form
2709	my $prog = shift @exprs;
2710	$exprs[0] = "$prog $exprs[0]";
2711    }
2712
2713    if ($parens && $nollafr) {
2714	return "($fullname " . join(", ", @exprs) . ")";
2715    } elsif ($parens) {
2716	return "$fullname(" . join(", ", @exprs) . ")";
2717    } else {
2718	return "$fullname " . join(", ", @exprs);
2719    }
2720}
2721
2722sub pp_bless { listop(@_, "bless") }
2723sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2724sub pp_substr {
2725    my ($self,$op,$cx) = @_;
2726    if ($op->private & OPpSUBSTR_REPL_FIRST) {
2727	return
2728	   listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2729	 . " = "
2730	 . $self->deparse($op->first->sibling, 7);
2731    }
2732    maybe_local(@_, listop(@_, "substr"))
2733}
2734sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2735sub pp_index { maybe_targmy(@_, \&listop, "index") }
2736sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2737sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2738sub pp_formline { listop(@_, "formline") } # see also deparse_format
2739sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2740sub pp_unpack { listop(@_, "unpack") }
2741sub pp_pack { listop(@_, "pack") }
2742sub pp_join { maybe_targmy(@_, \&listop, "join") }
2743sub pp_splice { listop(@_, "splice") }
2744sub pp_push { maybe_targmy(@_, \&listop, "push") }
2745sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2746sub pp_reverse { listop(@_, "reverse") }
2747sub pp_warn { listop(@_, "warn") }
2748sub pp_die { listop(@_, "die") }
2749sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
2750sub pp_open { listop(@_, "open") }
2751sub pp_pipe_op { listop(@_, "pipe") }
2752sub pp_tie { listop(@_, "tie") }
2753sub pp_binmode { listop(@_, "binmode") }
2754sub pp_dbmopen { listop(@_, "dbmopen") }
2755sub pp_sselect { listop(@_, "select") }
2756sub pp_select { listop(@_, "select") }
2757sub pp_read { listop(@_, "read") }
2758sub pp_sysopen { listop(@_, "sysopen") }
2759sub pp_sysseek { listop(@_, "sysseek") }
2760sub pp_sysread { listop(@_, "sysread") }
2761sub pp_syswrite { listop(@_, "syswrite") }
2762sub pp_send { listop(@_, "send") }
2763sub pp_recv { listop(@_, "recv") }
2764sub pp_seek { listop(@_, "seek") }
2765sub pp_fcntl { listop(@_, "fcntl") }
2766sub pp_ioctl { listop(@_, "ioctl") }
2767sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2768sub pp_socket { listop(@_, "socket") }
2769sub pp_sockpair { listop(@_, "socketpair") }
2770sub pp_bind { listop(@_, "bind") }
2771sub pp_connect { listop(@_, "connect") }
2772sub pp_listen { listop(@_, "listen") }
2773sub pp_accept { listop(@_, "accept") }
2774sub pp_shutdown { listop(@_, "shutdown") }
2775sub pp_gsockopt { listop(@_, "getsockopt") }
2776sub pp_ssockopt { listop(@_, "setsockopt") }
2777sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2778sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2779sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2780sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2781sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2782sub pp_link { maybe_targmy(@_, \&listop, "link") }
2783sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2784sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2785sub pp_open_dir { listop(@_, "opendir") }
2786sub pp_seekdir { listop(@_, "seekdir") }
2787sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2788sub pp_system { maybe_targmy(@_, \&listop, "system") }
2789sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2790sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2791sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2792sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2793sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2794sub pp_shmget { listop(@_, "shmget") }
2795sub pp_shmctl { listop(@_, "shmctl") }
2796sub pp_shmread { listop(@_, "shmread") }
2797sub pp_shmwrite { listop(@_, "shmwrite") }
2798sub pp_msgget { listop(@_, "msgget") }
2799sub pp_msgctl { listop(@_, "msgctl") }
2800sub pp_msgsnd { listop(@_, "msgsnd") }
2801sub pp_msgrcv { listop(@_, "msgrcv") }
2802sub pp_semget { listop(@_, "semget") }
2803sub pp_semctl { listop(@_, "semctl") }
2804sub pp_semop { listop(@_, "semop") }
2805sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2806sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2807sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2808sub pp_gsbyname { listop(@_, "getservbyname") }
2809sub pp_gsbyport { listop(@_, "getservbyport") }
2810sub pp_syscall { listop(@_, "syscall") }
2811
2812sub pp_glob {
2813    my $self = shift;
2814    my($op, $cx) = @_;
2815    my $kid = $op->first->sibling;  # skip pushmark
2816    my $keyword =
2817	$op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
2818    my $text;
2819    if ($keyword =~ /^CORE::/
2820	or $kid->name ne 'const'
2821	or ($text = $self->dq($kid))
2822	     =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2823        or $text =~ /[<>]/) {
2824	$text = $self->deparse($kid);
2825	return $cx >= 5 || $self->{'parens'}
2826	    ? "$keyword($text)"
2827	    : "$keyword $text";
2828    } else {
2829	return '<' . $text . '>';
2830    }
2831}
2832
2833# Truncate is special because OPf_SPECIAL makes a bareword first arg
2834# be a filehandle. This could probably be better fixed in the core
2835# by moving the GV lookup into ck_truc.
2836
2837sub pp_truncate {
2838    my $self = shift;
2839    my($op, $cx) = @_;
2840    my(@exprs);
2841    my $parens = ($cx >= 5) || $self->{'parens'};
2842    my $kid = $op->first->sibling;
2843    my $fh;
2844    if ($op->flags & OPf_SPECIAL) {
2845	# $kid is an OP_CONST
2846	$fh = $self->const_sv($kid)->PV;
2847    } else {
2848	$fh = $self->deparse($kid, 6);
2849        $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2850    }
2851    my $len = $self->deparse($kid->sibling, 6);
2852    my $name = $self->keyword('truncate');
2853    if ($parens) {
2854	return "$name($fh, $len)";
2855    } else {
2856	return "$name $fh, $len";
2857    }
2858}
2859
2860sub indirop {
2861    my $self = shift;
2862    my($op, $cx, $name) = @_;
2863    my($expr, @exprs);
2864    my $firstkid = my $kid = $op->first->sibling;
2865    my $indir = "";
2866    if ($op->flags & OPf_STACKED) {
2867	$indir = $kid;
2868	$indir = $indir->first; # skip rv2gv
2869	if (is_scope($indir)) {
2870	    $indir = "{" . $self->deparse($indir, 0) . "}";
2871	    $indir = "{;}" if $indir eq "{}";
2872	} elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2873	    $indir = $self->const_sv($indir)->PV;
2874	} else {
2875	    $indir = $self->deparse($indir, 24);
2876	}
2877	$indir = $indir . " ";
2878	$kid = $kid->sibling;
2879    }
2880    if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2881	$indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2882						  : '{$a <=> $b} ';
2883    }
2884    elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2885	$indir = '{$b cmp $a} ';
2886    }
2887    for (; !null($kid); $kid = $kid->sibling) {
2888	$expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
2889	push @exprs, $expr;
2890    }
2891    my $name2;
2892    if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2893	$name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2894    }
2895    else { $name2 = $self->keyword($name) }
2896    if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2897	return "$exprs[0] = $name2 $indir $exprs[0]";
2898    }
2899
2900    my $args = $indir . join(", ", @exprs);
2901    if ($indir ne "" && $name eq "sort") {
2902	# We don't want to say "sort(f 1, 2, 3)", since perl -w will
2903	# give bareword warnings in that case. Therefore if context
2904	# requires, we'll put parens around the outside "(sort f 1, 2,
2905	# 3)". Unfortunately, we'll currently think the parens are
2906	# necessary more often that they really are, because we don't
2907	# distinguish which side of an assignment we're on.
2908	if ($cx >= 5) {
2909	    return "($name2 $args)";
2910	} else {
2911	    return "$name2 $args";
2912	}
2913    } elsif (
2914	!$indir && $name eq "sort"
2915      && !null($op->first->sibling)
2916      && $op->first->sibling->name eq 'entersub'
2917    ) {
2918	# We cannot say sort foo(bar), as foo will be interpreted as a
2919	# comparison routine.  We have to say sort(...) in that case.
2920	return "$name2($args)";
2921    } else {
2922	return $self->maybe_parens_func($name2, $args, $cx, 5);
2923    }
2924
2925}
2926
2927sub pp_prtf { indirop(@_, "printf") }
2928sub pp_print { indirop(@_, "print") }
2929sub pp_say  { indirop(@_, "say") }
2930sub pp_sort { indirop(@_, "sort") }
2931
2932sub mapop {
2933    my $self = shift;
2934    my($op, $cx, $name) = @_;
2935    my($expr, @exprs);
2936    my $kid = $op->first; # this is the (map|grep)start
2937    $kid = $kid->first->sibling; # skip a pushmark
2938    my $code = $kid->first; # skip a null
2939    if (is_scope $code) {
2940	$code = "{" . $self->deparse($code, 0) . "} ";
2941    } else {
2942	$code = $self->deparse($code, 24);
2943	$code .= ", " if !null($kid->sibling);
2944    }
2945    $kid = $kid->sibling;
2946    for (; !null($kid); $kid = $kid->sibling) {
2947	$expr = $self->deparse($kid, 6);
2948	push @exprs, $expr if defined $expr;
2949    }
2950    return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2951}
2952
2953sub pp_mapwhile { mapop(@_, "map") }
2954sub pp_grepwhile { mapop(@_, "grep") }
2955sub pp_mapstart { baseop(@_, "map") }
2956sub pp_grepstart { baseop(@_, "grep") }
2957
2958sub pp_list {
2959    my $self = shift;
2960    my($op, $cx) = @_;
2961    my($expr, @exprs);
2962    my $kid = $op->first->sibling; # skip pushmark
2963    return '' if class($kid) eq 'NULL';
2964    my $lop;
2965    my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2966    for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2967	# This assumes that no other private flags equal 128, and that
2968	# OPs that store things other than flags in their op_private,
2969	# like OP_AELEMFAST, won't be immediate children of a list.
2970	#
2971	# OP_ENTERSUB and OP_SPLIT can break this logic, so check for them.
2972	# I suspect that open and exit can too.
2973	# XXX This really needs to be rewritten to accept only those ops
2974	#     known to take the OPpLVAL_INTRO flag.
2975
2976	if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2977		or $lop->name eq "undef")
2978	    or $lop->name =~ /^(?:entersub|exit|open|split)\z/)
2979	{
2980	    $local = ""; # or not
2981	    last;
2982	}
2983	if ($lop->name =~ /^pad[ash]v$/) {
2984	    if ($lop->private & OPpPAD_STATE) { # state()
2985		($local = "", last) if $local =~ /^(?:local|our|my)$/;
2986		$local = "state";
2987	    } else { # my()
2988		($local = "", last) if $local =~ /^(?:local|our|state)$/;
2989		$local = "my";
2990	    }
2991	} elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2992			&& $lop->private & OPpOUR_INTRO
2993		or $lop->name eq "null" && $lop->first->name eq "gvsv"
2994			&& $lop->first->private & OPpOUR_INTRO) { # our()
2995	    ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2996	    $local = "our";
2997	} elsif ($lop->name ne "undef"
2998		# specifically avoid the "reverse sort" optimisation,
2999		# where "reverse" is nullified
3000		&& !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
3001	{
3002	    # local()
3003	    ($local = "", last) if $local =~ /^(?:my|our|state)$/;
3004	    $local = "local";
3005	}
3006    }
3007    $local = "" if $local eq "either"; # no point if it's all undefs
3008    return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
3009    for (; !null($kid); $kid = $kid->sibling) {
3010	if ($local) {
3011	    if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
3012		$lop = $kid->first;
3013	    } else {
3014		$lop = $kid;
3015	    }
3016	    $self->{'avoid_local'}{$$lop}++;
3017	    $expr = $self->deparse($kid, 6);
3018	    delete $self->{'avoid_local'}{$$lop};
3019	} else {
3020	    $expr = $self->deparse($kid, 6);
3021	}
3022	push @exprs, $expr;
3023    }
3024    if ($local) {
3025	return "$local(" . join(", ", @exprs) . ")";
3026    } else {
3027	return $self->maybe_parens( join(", ", @exprs), $cx, 6);
3028    }
3029}
3030
3031sub is_ifelse_cont {
3032    my $op = shift;
3033    return ($op->name eq "null" and class($op) eq "UNOP"
3034	    and $op->first->name =~ /^(and|cond_expr)$/
3035	    and is_scope($op->first->first->sibling));
3036}
3037
3038sub pp_cond_expr {
3039    my $self = shift;
3040    my($op, $cx) = @_;
3041    my $cond = $op->first;
3042    my $true = $cond->sibling;
3043    my $false = $true->sibling;
3044    my $cuddle = $self->{'cuddle'};
3045    unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
3046	    (is_scope($false) || is_ifelse_cont($false))
3047	    and $self->{'expand'} < 7) {
3048	$cond = $self->deparse($cond, 8);
3049	$true = $self->deparse($true, 6);
3050	$false = $self->deparse($false, 8);
3051	return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
3052    }
3053
3054    $cond = $self->deparse($cond, 1);
3055    $true = $self->deparse($true, 0);
3056    my $head = "if ($cond) {\n\t$true\n\b}";
3057    my @elsifs;
3058    while (!null($false) and is_ifelse_cont($false)) {
3059	my $newop = $false->first;
3060	my $newcond = $newop->first;
3061	my $newtrue = $newcond->sibling;
3062	$false = $newtrue->sibling; # last in chain is OP_AND => no else
3063	if ($newcond->name eq "lineseq")
3064	{
3065	    # lineseq to ensure correct line numbers in elsif()
3066	    # Bug #37302 fixed by change #33710.
3067	    $newcond = $newcond->first->sibling;
3068	}
3069	$newcond = $self->deparse($newcond, 1);
3070	$newtrue = $self->deparse($newtrue, 0);
3071	push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
3072    }
3073    if (!null($false)) {
3074	$false = $cuddle . "else {\n\t" .
3075	  $self->deparse($false, 0) . "\n\b}\cK";
3076    } else {
3077	$false = "\cK";
3078    }
3079    return $head . join($cuddle, "", @elsifs) . $false;
3080}
3081
3082sub pp_once {
3083    my ($self, $op, $cx) = @_;
3084    my $cond = $op->first;
3085    my $true = $cond->sibling;
3086
3087    return $self->deparse($true, $cx);
3088}
3089
3090sub loop_common {
3091    my $self = shift;
3092    my($op, $cx, $init) = @_;
3093    my $enter = $op->first;
3094    my $kid = $enter->sibling;
3095    local(@$self{qw'curstash warnings hints hinthash'})
3096		= @$self{qw'curstash warnings hints hinthash'};
3097    my $head = "";
3098    my $bare = 0;
3099    my $body;
3100    my $cond = undef;
3101    if ($kid->name eq "lineseq") { # bare or infinite loop
3102	if ($kid->last->name eq "unstack") { # infinite
3103	    $head = "while (1) "; # Can't use for(;;) if there's a continue
3104	    $cond = "";
3105	} else {
3106	    $bare = 1;
3107	}
3108	$body = $kid;
3109    } elsif ($enter->name eq "enteriter") { # foreach
3110	my $ary = $enter->first->sibling; # first was pushmark
3111	my $var = $ary->sibling;
3112	if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
3113	    # "reverse" was optimised away
3114	    $ary = listop($self, $ary->first->sibling, 1, 'reverse');
3115	} elsif ($enter->flags & OPf_STACKED
3116	    and not null $ary->first->sibling->sibling)
3117	{
3118	    $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
3119	      $self->deparse($ary->first->sibling->sibling, 9);
3120	} else {
3121	    $ary = $self->deparse($ary, 1);
3122	}
3123	if (null $var) {
3124	    if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
3125		# thread special var, under 5005threads
3126		$var = $self->pp_threadsv($enter, 1);
3127	    } else { # regular my() variable
3128		$var = $self->pp_padsv($enter, 1, 1);
3129	    }
3130	} elsif ($var->name eq "rv2gv") {
3131	    $var = $self->pp_rv2sv($var, 1);
3132	    if ($enter->private & OPpOUR_INTRO) {
3133		# our declarations don't have package names
3134		$var =~ s/^(.).*::/$1/;
3135		$var = "our $var";
3136	    }
3137	} elsif ($var->name eq "gv") {
3138	    $var = "\$" . $self->deparse($var, 1);
3139	}
3140	$body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
3141	if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
3142	    confess unless $var eq '$_';
3143	    $body = $body->first;
3144	    return $self->deparse($body, 2) . " foreach ($ary)";
3145	}
3146	$head = "foreach $var ($ary) ";
3147    } elsif ($kid->name eq "null") { # while/until
3148	$kid = $kid->first;
3149	my $name = {"and" => "while", "or" => "until"}->{$kid->name};
3150	$cond = $self->deparse($kid->first, 1);
3151	$head = "$name ($cond) ";
3152	$body = $kid->first->sibling;
3153    } elsif ($kid->name eq "stub") { # bare and empty
3154	return "{;}"; # {} could be a hashref
3155    }
3156    # If there isn't a continue block, then the next pointer for the loop
3157    # will point to the unstack, which is kid's last child, except
3158    # in a bare loop, when it will point to the leaveloop. When neither of
3159    # these conditions hold, then the second-to-last child is the continue
3160    # block (or the last in a bare loop).
3161    my $cont_start = $enter->nextop;
3162    my $cont;
3163    if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3164	if ($bare) {
3165	    $cont = $body->last;
3166	} else {
3167	    $cont = $body->first;
3168	    while (!null($cont->sibling->sibling)) {
3169		$cont = $cont->sibling;
3170	    }
3171	}
3172	my $state = $body->first;
3173	my $cuddle = $self->{'cuddle'};
3174	my @states;
3175	for (; $$state != $$cont; $state = $state->sibling) {
3176	    push @states, $state;
3177	}
3178	$body = $self->lineseq(undef, 0, @states);
3179	if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3180	    $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3181	    $cont = "\cK";
3182	} else {
3183	    $cont = $cuddle . "continue {\n\t" .
3184	      $self->deparse($cont, 0) . "\n\b}\cK";
3185	}
3186    } else {
3187	return "" if !defined $body;
3188	if (length $init) {
3189	    $head = "for ($init; $cond;) ";
3190	}
3191	$cont = "\cK";
3192	$body = $self->deparse($body, 0);
3193    }
3194    $body =~ s/;?$/;\n/;
3195
3196    return $head . "{\n\t" . $body . "\b}" . $cont;
3197}
3198
3199sub pp_leaveloop { shift->loop_common(@_, "") }
3200
3201sub for_loop {
3202    my $self = shift;
3203    my($op, $cx) = @_;
3204    my $init = $self->deparse($op, 1);
3205    my $s = $op->sibling;
3206    my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3207    return $self->loop_common($ll, $cx, $init);
3208}
3209
3210sub pp_leavetry {
3211    my $self = shift;
3212    return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3213}
3214
3215sub _op_is_or_was {
3216  my ($op, $expect_type) = @_;
3217  my $type = $op->type;
3218  return($type == $expect_type
3219         || ($type == OP_NULL && $op->targ == $expect_type));
3220}
3221
3222sub pp_null {
3223    my $self = shift;
3224    my($op, $cx) = @_;
3225    if (class($op) eq "OP") {
3226	# old value is lost
3227	return $self->{'ex_const'} if $op->targ == OP_CONST;
3228    } elsif ($op->first->name eq 'pushmark'
3229             or $op->first->name eq 'null'
3230                && $op->first->targ == OP_PUSHMARK
3231                && _op_is_or_was($op, OP_LIST)) {
3232	return $self->pp_list($op, $cx);
3233    } elsif ($op->first->name eq "enter") {
3234	return $self->pp_leave($op, $cx);
3235    } elsif ($op->first->name eq "leave") {
3236	return $self->pp_leave($op->first, $cx);
3237    } elsif ($op->first->name eq "scope") {
3238	return $self->pp_scope($op->first, $cx);
3239    } elsif ($op->targ == OP_STRINGIFY) {
3240	return $self->dquote($op, $cx);
3241    } elsif ($op->targ == OP_GLOB) {
3242	return $self->pp_glob(
3243	         $op->first    # entersub
3244	            ->first    # ex-list
3245	            ->first    # pushmark
3246	            ->sibling, # glob
3247	         $cx
3248	       );
3249    } elsif (!null($op->first->sibling) and
3250	     $op->first->sibling->name eq "readline" and
3251	     $op->first->sibling->flags & OPf_STACKED) {
3252	return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3253				   . $self->deparse($op->first->sibling, 7),
3254				   $cx, 7);
3255    } elsif (!null($op->first->sibling) and
3256	     $op->first->sibling->name eq "trans" and
3257	     $op->first->sibling->flags & OPf_STACKED) {
3258	return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3259				   . $self->deparse($op->first->sibling, 20),
3260				   $cx, 20);
3261    } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3262	return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
3263    } elsif (!null($op->first->sibling) and
3264	     $op->first->sibling->name eq "null" and
3265	     class($op->first->sibling) eq "UNOP" and
3266	     $op->first->sibling->first->flags & OPf_STACKED and
3267	     $op->first->sibling->first->name eq "rcatline") {
3268	return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3269				   . $self->deparse($op->first->sibling, 18),
3270				   $cx, 18);
3271    } else {
3272	return $self->deparse($op->first, $cx);
3273    }
3274}
3275
3276sub padname {
3277    my $self = shift;
3278    my $targ = shift;
3279    return $self->padname_sv($targ)->PVX;
3280}
3281
3282sub padany {
3283    my $self = shift;
3284    my $op = shift;
3285    return substr($self->padname($op->targ), 1); # skip $/@/%
3286}
3287
3288sub pp_padsv {
3289    my $self = shift;
3290    my($op, $cx, $forbid_parens) = @_;
3291    return $self->maybe_my($op, $cx, $self->padname($op->targ),
3292			   $forbid_parens);
3293}
3294
3295sub pp_padav { pp_padsv(@_) }
3296sub pp_padhv { pp_padsv(@_) }
3297
3298my @threadsv_names = B::threadsv_names;
3299sub pp_threadsv {
3300    my $self = shift;
3301    my($op, $cx) = @_;
3302    return $self->maybe_local($op, $cx, "\$" .  $threadsv_names[$op->targ]);
3303}
3304
3305sub gv_or_padgv {
3306    my $self = shift;
3307    my $op = shift;
3308    if (class($op) eq "PADOP") {
3309	return $self->padval($op->padix);
3310    } else { # class($op) eq "SVOP"
3311	return $op->gv;
3312    }
3313}
3314
3315sub pp_gvsv {
3316    my $self = shift;
3317    my($op, $cx) = @_;
3318    my $gv = $self->gv_or_padgv($op);
3319    return $self->maybe_local($op, $cx, $self->stash_variable("\$",
3320				 $self->gv_name($gv), $cx));
3321}
3322
3323sub pp_gv {
3324    my $self = shift;
3325    my($op, $cx) = @_;
3326    my $gv = $self->gv_or_padgv($op);
3327    return $self->gv_name($gv);
3328}
3329
3330sub pp_aelemfast_lex {
3331    my $self = shift;
3332    my($op, $cx) = @_;
3333    my $name = $self->padname($op->targ);
3334    $name =~ s/^@/\$/;
3335    my $i = $op->private;
3336    $i -= 256 if $i > 127;
3337    return $name . "[" .  ($i + $self->{'arybase'}) . "]";
3338}
3339
3340sub pp_aelemfast {
3341    my $self = shift;
3342    my($op, $cx) = @_;
3343    # optimised PADAV, pre 5.15
3344    return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
3345
3346    my $gv = $self->gv_or_padgv($op);
3347    my($name,$quoted) = $self->stash_variable_name('@',$gv);
3348    $name = $quoted ? "$name->" : '$' . $name;
3349    my $i = $op->private;
3350    $i -= 256 if $i > 127;
3351    return $name . "[" .  ($i + $self->{'arybase'}) . "]";
3352}
3353
3354sub rv2x {
3355    my $self = shift;
3356    my($op, $cx, $type) = @_;
3357
3358    if (class($op) eq 'NULL' || !$op->can("first")) {
3359	carp("Unexpected op in pp_rv2x");
3360	return 'XXX';
3361    }
3362    my $kid = $op->first;
3363    if ($kid->name eq "gv") {
3364	return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
3365    } elsif (is_scalar $kid) {
3366	my $str = $self->deparse($kid, 0);
3367	if ($str =~ /^\$([^\w\d])\z/) {
3368	    # "$$+" isn't a legal way to write the scalar dereference
3369	    # of $+, since the lexer can't tell you aren't trying to
3370	    # do something like "$$ + 1" to get one more than your
3371	    # PID. Either "${$+}" or "$${+}" are workable
3372	    # disambiguations, but if the programmer did the former,
3373	    # they'd be in the "else" clause below rather than here.
3374	    # It's not clear if this should somehow be unified with
3375	    # the code in dq and re_dq that also adds lexer
3376	    # disambiguation braces.
3377	    $str = '$' . "{$1}"; #'
3378	}
3379	return $type . $str;
3380    } else {
3381	return $type . "{" . $self->deparse($kid, 0) . "}";
3382    }
3383}
3384
3385sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3386sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3387sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3388
3389# skip rv2av
3390sub pp_av2arylen {
3391    my $self = shift;
3392    my($op, $cx) = @_;
3393    if ($op->first->name eq "padav") {
3394	return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3395    } else {
3396	return $self->maybe_local($op, $cx,
3397				  $self->rv2x($op->first, $cx, '$#'));
3398    }
3399}
3400
3401# skip down to the old, ex-rv2cv
3402sub pp_rv2cv {
3403    my ($self, $op, $cx) = @_;
3404    if (!null($op->first) && $op->first->name eq 'null' &&
3405	$op->first->targ == OP_LIST)
3406    {
3407	return $self->rv2x($op->first->first->sibling, $cx, "&")
3408    }
3409    else {
3410	return $self->rv2x($op, $cx, "")
3411    }
3412}
3413
3414sub list_const {
3415    my $self = shift;
3416    my($cx, @list) = @_;
3417    my @a = map $self->const($_, 6), @list;
3418    if (@a == 0) {
3419	return "()";
3420    } elsif (@a == 1) {
3421	return $a[0];
3422    } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3423	# collapse (-1,0,1,2) into (-1..2)
3424	my ($s, $e) = @a[0,-1];
3425	my $i = $s;
3426	return $self->maybe_parens("$s..$e", $cx, 9)
3427	  unless grep $i++ != $_, @a;
3428    }
3429    return $self->maybe_parens(join(", ", @a), $cx, 6);
3430}
3431
3432sub pp_rv2av {
3433    my $self = shift;
3434    my($op, $cx) = @_;
3435    my $kid = $op->first;
3436    if ($kid->name eq "const") { # constant list
3437	my $av = $self->const_sv($kid);
3438	return $self->list_const($cx, $av->ARRAY);
3439    } else {
3440	return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3441    }
3442 }
3443
3444sub is_subscriptable {
3445    my $op = shift;
3446    if ($op->name =~ /^[ahg]elem/) {
3447	return 1;
3448    } elsif ($op->name eq "entersub") {
3449	my $kid = $op->first;
3450	return 0 unless null $kid->sibling;
3451	$kid = $kid->first;
3452	$kid = $kid->sibling until null $kid->sibling;
3453	return 0 if is_scope($kid);
3454	$kid = $kid->first;
3455	return 0 if $kid->name eq "gv" || $kid->name eq "padcv";
3456	return 0 if is_scalar($kid);
3457	return is_subscriptable($kid);
3458    } else {
3459	return 0;
3460    }
3461}
3462
3463sub elem_or_slice_array_name
3464{
3465    my $self = shift;
3466    my ($array, $left, $padname, $allow_arrow) = @_;
3467
3468    if ($array->name eq $padname) {
3469	return $self->padany($array);
3470    } elsif (is_scope($array)) { # ${expr}[0]
3471	return "{" . $self->deparse($array, 0) . "}";
3472    } elsif ($array->name eq "gv") {
3473	($array, my $quoted) =
3474	    $self->stash_variable_name(
3475		$left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3476	    );
3477	if (!$allow_arrow && $quoted) {
3478	    # This cannot happen.
3479	    die "Invalid variable name $array for slice";
3480	}
3481	return $quoted ? "$array->" : $array;
3482    } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3483	return $self->deparse($array, 24);
3484    } else {
3485	return undef;
3486    }
3487}
3488
3489sub elem_or_slice_single_index
3490{
3491    my $self = shift;
3492    my ($idx) = @_;
3493
3494    $idx = $self->deparse($idx, 1);
3495
3496    # Outer parens in an array index will confuse perl
3497    # if we're interpolating in a regular expression, i.e.
3498    # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3499    #
3500    # If $self->{parens}, then an initial '(' will
3501    # definitely be paired with a final ')'. If
3502    # !$self->{parens}, the misleading parens won't
3503    # have been added in the first place.
3504    #
3505    # [You might think that we could get "(...)...(...)"
3506    # where the initial and final parens do not match
3507    # each other. But we can't, because the above would
3508    # only happen if there's an infix binop between the
3509    # two pairs of parens, and *that* means that the whole
3510    # expression would be parenthesized as well.]
3511    #
3512    $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3513
3514    # Hash-element braces will autoquote a bareword inside themselves.
3515    # We need to make sure that C<$hash{warn()}> doesn't come out as
3516    # C<$hash{warn}>, which has a quite different meaning. Currently
3517    # B::Deparse will always quote strings, even if the string was a
3518    # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3519    # for constant strings.) So we can cheat slightly here - if we see
3520    # a bareword, we know that it is supposed to be a function call.
3521    #
3522    $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3523
3524    return $idx;
3525}
3526
3527sub elem {
3528    my $self = shift;
3529    my ($op, $cx, $left, $right, $padname) = @_;
3530    my($array, $idx) = ($op->first, $op->first->sibling);
3531
3532    $idx = $self->elem_or_slice_single_index($idx);
3533
3534    unless ($array->name eq $padname) { # Maybe this has been fixed
3535	$array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3536    }
3537    if (my $array_name=$self->elem_or_slice_array_name
3538	    ($array, $left, $padname, 1)) {
3539	return ($array_name =~ /->\z/
3540		    ? $array_name
3541		    : $array_name eq '#' ? '${#}' : "\$" . $array_name)
3542	      . $left . $idx . $right;
3543    } else {
3544	# $x[20][3]{hi} or expr->[20]
3545	my $arrow = is_subscriptable($array) ? "" : "->";
3546	return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3547    }
3548
3549}
3550
3551sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3552sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3553
3554sub pp_gelem {
3555    my $self = shift;
3556    my($op, $cx) = @_;
3557    my($glob, $part) = ($op->first, $op->last);
3558    $glob = $glob->first; # skip rv2gv
3559    $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3560    my $scope = is_scope($glob);
3561    $glob = $self->deparse($glob, 0);
3562    $part = $self->deparse($part, 1);
3563    return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3564}
3565
3566sub slice {
3567    my $self = shift;
3568    my ($op, $cx, $left, $right, $regname, $padname) = @_;
3569    my $last;
3570    my(@elems, $kid, $array, $list);
3571    if (class($op) eq "LISTOP") {
3572	$last = $op->last;
3573    } else { # ex-hslice inside delete()
3574	for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3575	$last = $kid;
3576    }
3577    $array = $last;
3578    $array = $array->first
3579	if $array->name eq $regname or $array->name eq "null";
3580    $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3581    $kid = $op->first->sibling; # skip pushmark
3582    if ($kid->name eq "list") {
3583	$kid = $kid->first->sibling; # skip list, pushmark
3584	for (; !null $kid; $kid = $kid->sibling) {
3585	    push @elems, $self->deparse($kid, 6);
3586	}
3587	$list = join(", ", @elems);
3588    } else {
3589	$list = $self->elem_or_slice_single_index($kid);
3590    }
3591    my $lead = '@';
3592    $lead = '%' if $op->name =~ /^kv/i;
3593    return $lead . $array . $left . $list . $right;
3594}
3595
3596sub pp_aslice   { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3597sub pp_kvaslice {                 slice(@_, "[", "]", "rv2av", "padav")  }
3598sub pp_hslice   { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3599sub pp_kvhslice {                 slice(@_, "{", "}", "rv2hv", "padhv")  }
3600
3601sub pp_lslice {
3602    my $self = shift;
3603    my($op, $cx) = @_;
3604    my $idx = $op->first;
3605    my $list = $op->last;
3606    my(@elems, $kid);
3607    $list = $self->deparse($list, 1);
3608    $idx = $self->deparse($idx, 1);
3609    return "($list)" . "[$idx]";
3610}
3611
3612sub want_scalar {
3613    my $op = shift;
3614    return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3615}
3616
3617sub want_list {
3618    my $op = shift;
3619    return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3620}
3621
3622sub _method {
3623    my $self = shift;
3624    my($op, $cx) = @_;
3625    my $kid = $op->first->sibling; # skip pushmark
3626    my($meth, $obj, @exprs);
3627    if ($kid->name eq "list" and want_list $kid) {
3628	# When an indirect object isn't a bareword but the args are in
3629	# parens, the parens aren't part of the method syntax (the LLAFR
3630	# doesn't apply), but they make a list with OPf_PARENS set that
3631	# doesn't get flattened by the append_elem that adds the method,
3632	# making a (object, arg1, arg2, ...) list where the object
3633	# usually is. This can be distinguished from
3634	# '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3635	# object) because in the later the list is in scalar context
3636	# as the left side of -> always is, while in the former
3637	# the list is in list context as method arguments always are.
3638	# (Good thing there aren't method prototypes!)
3639	$meth = $kid->sibling;
3640	$kid = $kid->first->sibling; # skip pushmark
3641	$obj = $kid;
3642	$kid = $kid->sibling;
3643	for (; not null $kid; $kid = $kid->sibling) {
3644	    push @exprs, $kid;
3645	}
3646    } else {
3647	$obj = $kid;
3648	$kid = $kid->sibling;
3649	for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3650	      $kid = $kid->sibling) {
3651	    push @exprs, $kid
3652	}
3653	$meth = $kid;
3654    }
3655
3656    if ($meth->name eq "method_named") {
3657	$meth = $self->const_sv($meth)->PV;
3658    } else {
3659	$meth = $meth->first;
3660	if ($meth->name eq "const") {
3661	    # As of 5.005_58, this case is probably obsoleted by the
3662	    # method_named case above
3663	    $meth = $self->const_sv($meth)->PV; # needs to be bare
3664	}
3665    }
3666
3667    return { method => $meth, variable_method => ref($meth),
3668             object => $obj, args => \@exprs  },
3669	   $cx;
3670}
3671
3672# compat function only
3673sub method {
3674    my $self = shift;
3675    my $info = $self->_method(@_);
3676    return $self->e_method( $self->_method(@_) );
3677}
3678
3679sub e_method {
3680    my ($self, $info, $cx) = @_;
3681    my $obj = $self->deparse($info->{object}, 24);
3682
3683    my $meth = $info->{method};
3684    $meth = $self->deparse($meth, 1) if $info->{variable_method};
3685    my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3686    if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
3687	# method { $object }
3688	# This must be deparsed this way to preserve list context
3689	# of $object.
3690	my $need_paren = $cx >= 6;
3691	return '(' x $need_paren
3692	     . $meth . substr($obj,2) # chop off the "do"
3693	     . " $args"
3694	     . ')' x $need_paren;
3695    }
3696    my $kid = $obj . "->" . $meth;
3697    if (length $args) {
3698	return $kid . "(" . $args . ")"; # parens mandatory
3699    } else {
3700	return $kid;
3701    }
3702}
3703
3704# returns "&" if the prototype doesn't match the args,
3705# or ("", $args_after_prototype_demunging) if it does.
3706sub check_proto {
3707    my $self = shift;
3708    return "&" if $self->{'noproto'};
3709    my($proto, @args) = @_;
3710    my($arg, $real);
3711    my $doneok = 0;
3712    my @reals;
3713    # An unbackslashed @ or % gobbles up the rest of the args
3714    1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3715    $proto =~ s/^\s*//;
3716    while ($proto) {
3717	$proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)\s*//;
3718	my $chr = $1;
3719	if ($chr eq "") {
3720	    return "&" if @args;
3721	} elsif ($chr eq ";") {
3722	    $doneok = 1;
3723	} elsif ($chr eq "@" or $chr eq "%") {
3724	    push @reals, map($self->deparse($_, 6), @args);
3725	    @args = ();
3726	} else {
3727	    $arg = shift @args;
3728	    last unless $arg;
3729	    if ($chr eq "\$" || $chr eq "_") {
3730		if (want_scalar $arg) {
3731		    push @reals, $self->deparse($arg, 6);
3732		} else {
3733		    return "&";
3734		}
3735	    } elsif ($chr eq "&") {
3736		if ($arg->name =~ /^(s?refgen|undef)$/) {
3737		    push @reals, $self->deparse($arg, 6);
3738		} else {
3739		    return "&";
3740		}
3741	    } elsif ($chr eq "*") {
3742		if ($arg->name =~ /^s?refgen$/
3743		    and $arg->first->first->name eq "rv2gv")
3744		  {
3745		      $real = $arg->first->first; # skip refgen, null
3746		      if ($real->first->name eq "gv") {
3747			  push @reals, $self->deparse($real, 6);
3748		      } else {
3749			  push @reals, $self->deparse($real->first, 6);
3750		      }
3751		  } else {
3752		      return "&";
3753		  }
3754	    } elsif (substr($chr, 0, 1) eq "\\") {
3755		$chr =~ tr/\\[]//d;
3756		if ($arg->name =~ /^s?refgen$/ and
3757		    !null($real = $arg->first) and
3758		    ($chr =~ /\$/ && is_scalar($real->first)
3759		     or ($chr =~ /@/
3760			 && class($real->first->sibling) ne 'NULL'
3761			 && $real->first->sibling->name
3762			 =~ /^(rv2|pad)av$/)
3763		     or ($chr =~ /%/
3764			 && class($real->first->sibling) ne 'NULL'
3765			 && $real->first->sibling->name
3766			 =~ /^(rv2|pad)hv$/)
3767		     #or ($chr =~ /&/ # This doesn't work
3768		     #   && $real->first->name eq "rv2cv")
3769		     or ($chr =~ /\*/
3770			 && $real->first->name eq "rv2gv")))
3771		  {
3772		      push @reals, $self->deparse($real, 6);
3773		  } else {
3774		      return "&";
3775		  }
3776	    }
3777       }
3778    }
3779    return "&" if $proto and !$doneok; # too few args and no ';'
3780    return "&" if @args;               # too many args
3781    return ("", join ", ", @reals);
3782}
3783
3784sub pp_entersub {
3785    my $self = shift;
3786    my($op, $cx) = @_;
3787    return $self->e_method($self->_method($op, $cx))
3788        unless null $op->first->sibling;
3789    my $prefix = "";
3790    my $amper = "";
3791    my($kid, @exprs);
3792    if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3793	$prefix = "do ";
3794    } elsif ($op->private & OPpENTERSUB_AMPER) {
3795	$amper = "&";
3796    }
3797    $kid = $op->first;
3798    $kid = $kid->first->sibling; # skip ex-list, pushmark
3799    for (; not null $kid->sibling; $kid = $kid->sibling) {
3800	push @exprs, $kid;
3801    }
3802    my $simple = 0;
3803    my $proto = undef;
3804    if (is_scope($kid)) {
3805	$amper = "&";
3806	$kid = "{" . $self->deparse($kid, 0) . "}";
3807    } elsif ($kid->first->name eq "gv") {
3808	my $gv = $self->gv_or_padgv($kid->first);
3809	if (class($gv->CV) ne "SPECIAL") {
3810	    $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3811	}
3812	$simple = 1; # only calls of named functions can be prototyped
3813	$kid = $self->deparse($kid, 24);
3814	if (!$amper) {
3815	    if ($kid eq 'main::') {
3816		$kid = '::';
3817	    } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3818		$kid = single_delim("q", "'", $kid) . '->';
3819	    }
3820	}
3821    } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3822	$amper = "&";
3823	$kid = $self->deparse($kid, 24);
3824    } else {
3825	$prefix = "";
3826	my $arrow = is_subscriptable($kid->first) || $kid->first->name eq "padcv" ? "" : "->";
3827	$kid = $self->deparse($kid, 24) . $arrow;
3828    }
3829
3830    # Doesn't matter how many prototypes there are, if
3831    # they haven't happened yet!
3832    my $declared;
3833    {
3834	no strict 'refs';
3835	no warnings 'uninitialized';
3836	$declared = exists $self->{'subs_declared'}{$kid}
3837	    || (
3838		 defined &{ ${$self->{'curstash'}."::"}{$kid} }
3839		 && !exists
3840		     $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3841		 && defined prototype $self->{'curstash'}."::".$kid
3842	       );
3843	if (!$declared && defined($proto)) {
3844	    # Avoid "too early to check prototype" warning
3845	    ($amper, $proto) = ('&');
3846	}
3847    }
3848
3849    my $args;
3850    if ($declared and defined $proto and not $amper) {
3851	($amper, $args) = $self->check_proto($proto, @exprs);
3852	if ($amper eq "&") {
3853	    $args = join(", ", map($self->deparse($_, 6), @exprs));
3854	}
3855    } else {
3856	$args = join(", ", map($self->deparse($_, 6), @exprs));
3857    }
3858    if ($prefix or $amper) {
3859	if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
3860	if ($op->flags & OPf_STACKED) {
3861	    return $prefix . $amper . $kid . "(" . $args . ")";
3862	} else {
3863	    return $prefix . $amper. $kid;
3864	}
3865    } else {
3866	# It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3867	# so it must have been translated from a keyword call. Translate
3868	# it back.
3869	$kid =~ s/^CORE::GLOBAL:://;
3870
3871	my $dproto = defined($proto) ? $proto : "undefined";
3872        if (!$declared) {
3873	    return "$kid(" . $args . ")";
3874	} elsif ($dproto =~ /^\s*\z/) {
3875	    return $kid;
3876	} elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3877	    # is_scalar is an excessively conservative test here:
3878	    # really, we should be comparing to the precedence of the
3879	    # top operator of $exprs[0] (ala unop()), but that would
3880	    # take some major code restructuring to do right.
3881	    return $self->maybe_parens_func($kid, $args, $cx, 16);
3882	} elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3883	    return $self->maybe_parens_func($kid, $args, $cx, 5);
3884	} else {
3885	    return "$kid(" . $args . ")";
3886	}
3887    }
3888}
3889
3890sub pp_enterwrite { unop(@_, "write") }
3891
3892# escape things that cause interpolation in double quotes,
3893# but not character escapes
3894sub uninterp {
3895    my($str) = @_;
3896    $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3897    return $str;
3898}
3899
3900{
3901my $bal;
3902BEGIN {
3903    use re "eval";
3904    # Matches any string which is balanced with respect to {braces}
3905    $bal = qr(
3906      (?:
3907	[^\\{}]
3908      | \\\\
3909      | \\[{}]
3910      | \{(??{$bal})\}
3911      )*
3912    )x;
3913}
3914
3915# the same, but treat $|, $), $( and $ at the end of the string differently
3916sub re_uninterp {
3917    my($str) = @_;
3918
3919    $str =~ s/
3920	  ( ^|\G                  # $1
3921          | [^\\]
3922          )
3923
3924          (                       # $2
3925            (?:\\\\)*
3926          )
3927
3928          (                       # $3
3929            (\(\?\??\{$bal\}\))   # $4
3930          | [\$\@]
3931            (?!\||\)|\(|$)
3932          | \\[uUlLQE]
3933          )
3934
3935	/defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3936
3937    return $str;
3938}
3939
3940# This is for regular expressions with the /x modifier
3941# We have to leave comments unmangled.
3942sub re_uninterp_extended {
3943    my($str) = @_;
3944
3945    $str =~ s/
3946	  ( ^|\G                  # $1
3947          | [^\\]
3948          )
3949
3950          (                       # $2
3951            (?:\\\\)*
3952          )
3953
3954          (                       # $3
3955            ( \(\?\??\{$bal\}\)   # $4  (skip over (?{}) and (??{}) blocks)
3956            | \#[^\n]*            #     (skip over comments)
3957            )
3958          | [\$\@]
3959            (?!\||\)|\(|$|\s)
3960          | \\[uUlLQE]
3961          )
3962
3963	/defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3964
3965    return $str;
3966}
3967}
3968
3969my %unctrl = # portable to EBCDIC
3970    (
3971     "\c@" => '\c@',	# unused
3972     "\cA" => '\cA',
3973     "\cB" => '\cB',
3974     "\cC" => '\cC',
3975     "\cD" => '\cD',
3976     "\cE" => '\cE',
3977     "\cF" => '\cF',
3978     "\cG" => '\cG',
3979     "\cH" => '\cH',
3980     "\cI" => '\cI',
3981     "\cJ" => '\cJ',
3982     "\cK" => '\cK',
3983     "\cL" => '\cL',
3984     "\cM" => '\cM',
3985     "\cN" => '\cN',
3986     "\cO" => '\cO',
3987     "\cP" => '\cP',
3988     "\cQ" => '\cQ',
3989     "\cR" => '\cR',
3990     "\cS" => '\cS',
3991     "\cT" => '\cT',
3992     "\cU" => '\cU',
3993     "\cV" => '\cV',
3994     "\cW" => '\cW',
3995     "\cX" => '\cX',
3996     "\cY" => '\cY',
3997     "\cZ" => '\cZ',
3998     "\c[" => '\c[',	# unused
3999     "\c\\" => '\c\\',	# unused
4000     "\c]" => '\c]',	# unused
4001     "\c_" => '\c_',	# unused
4002    );
4003
4004# character escapes, but not delimiters that might need to be escaped
4005sub escape_str { # ASCII, UTF8
4006    my($str) = @_;
4007    $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
4008    $str =~ s/\a/\\a/g;
4009#    $str =~ s/\cH/\\b/g; # \b means something different in a regex
4010    $str =~ s/\t/\\t/g;
4011    $str =~ s/\n/\\n/g;
4012    $str =~ s/\e/\\e/g;
4013    $str =~ s/\f/\\f/g;
4014    $str =~ s/\r/\\r/g;
4015    $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
4016    $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
4017    return $str;
4018}
4019
4020# For regexes with the /x modifier.
4021# Leave whitespace unmangled.
4022sub escape_extended_re {
4023    my($str) = @_;
4024    $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
4025    $str =~ s/([[:^print:]])/
4026	($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
4027    $str =~ s/\n/\n\f/g;
4028    return $str;
4029}
4030
4031# Don't do this for regexen
4032sub unback {
4033    my($str) = @_;
4034    $str =~ s/\\/\\\\/g;
4035    return $str;
4036}
4037
4038# Remove backslashes which precede literal control characters,
4039# to avoid creating ambiguity when we escape the latter.
4040sub re_unback {
4041    my($str) = @_;
4042
4043    # the insane complexity here is due to the behaviour of "\c\"
4044    $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
4045    return $str;
4046}
4047
4048sub balanced_delim {
4049    my($str) = @_;
4050    my @str = split //, $str;
4051    my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
4052    for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
4053	($open, $close) = @$ar;
4054	$fail = 0; $cnt = 0; $last_bs = 0;
4055	for $c (@str) {
4056	    if ($c eq $open) {
4057		$fail = 1 if $last_bs;
4058		$cnt++;
4059	    } elsif ($c eq $close) {
4060		$fail = 1 if $last_bs;
4061		$cnt--;
4062		if ($cnt < 0) {
4063		    # qq()() isn't ")("
4064		    $fail = 1;
4065		    last;
4066		}
4067	    }
4068	    $last_bs = $c eq '\\';
4069	}
4070	$fail = 1 if $cnt != 0;
4071	return ($open, "$open$str$close") if not $fail;
4072    }
4073    return ("", $str);
4074}
4075
4076sub single_delim {
4077    my($q, $default, $str) = @_;
4078    return "$default$str$default" if $default and index($str, $default) == -1;
4079    if ($q ne 'qr') {
4080	(my $succeed, $str) = balanced_delim($str);
4081	return "$q$str" if $succeed;
4082    }
4083    for my $delim ('/', '"', '#') {
4084	return "$q$delim" . $str . $delim if index($str, $delim) == -1;
4085    }
4086    if ($default) {
4087	$str =~ s/$default/\\$default/g;
4088	return "$default$str$default";
4089    } else {
4090	$str =~ s[/][\\/]g;
4091	return "$q/$str/";
4092    }
4093}
4094
4095my $max_prec;
4096BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
4097
4098# Split a floating point number into an integer mantissa and a binary
4099# exponent. Assumes you've already made sure the number isn't zero or
4100# some weird infinity or NaN.
4101sub split_float {
4102    my($f) = @_;
4103    my $exponent = 0;
4104    if ($f == int($f)) {
4105	while ($f % 2 == 0) {
4106	    $f /= 2;
4107	    $exponent++;
4108	}
4109    } else {
4110	while ($f != int($f)) {
4111	    $f *= 2;
4112	    $exponent--;
4113	}
4114    }
4115    my $mantissa = sprintf("%.0f", $f);
4116    return ($mantissa, $exponent);
4117}
4118
4119sub const {
4120    my $self = shift;
4121    my($sv, $cx) = @_;
4122    if ($self->{'use_dumper'}) {
4123	return $self->const_dumper($sv, $cx);
4124    }
4125    if (class($sv) eq "SPECIAL") {
4126	# sv_undef, sv_yes, sv_no
4127	return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
4128    }
4129    if (class($sv) eq "NULL") {
4130       return 'undef';
4131    }
4132    # convert a version object into the "v1.2.3" string in its V magic
4133    if ($sv->FLAGS & SVs_RMG) {
4134	for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4135	    return $mg->PTR if $mg->TYPE eq 'V';
4136	}
4137    }
4138
4139    if ($sv->FLAGS & SVf_IOK) {
4140	my $str = $sv->int_value;
4141	$str = $self->maybe_parens($str, $cx, 21) if $str < 0;
4142	return $str;
4143    } elsif ($sv->FLAGS & SVf_NOK) {
4144	my $nv = $sv->NV;
4145	if ($nv == 0) {
4146	    if (pack("F", $nv) eq pack("F", 0)) {
4147		# positive zero
4148		return "0";
4149	    } else {
4150		# negative zero
4151		return $self->maybe_parens("-.0", $cx, 21);
4152	    }
4153	} elsif (1/$nv == 0) {
4154	    if ($nv > 0) {
4155		# positive infinity
4156		return $self->maybe_parens("9**9**9", $cx, 22);
4157	    } else {
4158		# negative infinity
4159		return $self->maybe_parens("-9**9**9", $cx, 21);
4160	    }
4161	} elsif ($nv != $nv) {
4162	    # NaN
4163	    if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
4164		# the normal kind
4165		return "sin(9**9**9)";
4166	    } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
4167		# the inverted kind
4168		return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
4169	    } else {
4170		# some other kind
4171		my $hex = unpack("h*", pack("F", $nv));
4172		return qq'unpack("F", pack("h*", "$hex"))';
4173	    }
4174	}
4175	# first, try the default stringification
4176	my $str = "$nv";
4177	if ($str != $nv) {
4178	    # failing that, try using more precision
4179	    $str = sprintf("%.${max_prec}g", $nv);
4180#	    if (pack("F", $str) ne pack("F", $nv)) {
4181	    if ($str != $nv) {
4182		# not representable in decimal with whatever sprintf()
4183		# and atof() Perl is using here.
4184		my($mant, $exp) = split_float($nv);
4185		return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
4186	    }
4187	}
4188	$str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
4189	return $str;
4190    } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
4191	my $ref = $sv->RV;
4192	if (class($ref) eq "AV") {
4193	    return "[" . $self->list_const(2, $ref->ARRAY) . "]";
4194	} elsif (class($ref) eq "HV") {
4195	    my %hash = $ref->ARRAY;
4196	    my @elts;
4197	    for my $k (sort keys %hash) {
4198		push @elts, "$k => " . $self->const($hash{$k}, 6);
4199	    }
4200	    return "{" . join(", ", @elts) . "}";
4201	} elsif (class($ref) eq "CV") {
4202	    BEGIN {
4203		if ($] > 5.0150051) {
4204		    require overloading;
4205		    unimport overloading;
4206		}
4207	    }
4208	    if ($] > 5.0150051 && $self->{curcv} &&
4209		 $self->{curcv}->object_2svref == $ref->object_2svref) {
4210		return $self->keyword("__SUB__");
4211	    }
4212	    return "sub " . $self->deparse_sub($ref);
4213	}
4214	if ($ref->FLAGS & SVs_SMG) {
4215	    for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4216		if ($mg->TYPE eq 'r') {
4217		    my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
4218		    return single_delim("qr", "", $re);
4219		}
4220	    }
4221	}
4222
4223	my $const = $self->const($ref, 20);
4224	if ($self->{in_subst_repl} && $const =~ /^[0-9]/) {
4225	    $const = "($const)";
4226	}
4227	return $self->maybe_parens("\\$const", $cx, 20);
4228    } elsif ($sv->FLAGS & SVf_POK) {
4229	my $str = $sv->PV;
4230	if ($str =~ /[[:^print:]]/) {
4231	    return single_delim("qq", '"', uninterp escape_str unback $str);
4232	} else {
4233	    return single_delim("q", "'", unback $str);
4234	}
4235    } else {
4236	return "undef";
4237    }
4238}
4239
4240sub const_dumper {
4241    my $self = shift;
4242    my($sv, $cx) = @_;
4243    my $ref = $sv->object_2svref();
4244    my $dumper = Data::Dumper->new([$$ref], ['$v']);
4245    $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
4246    my $str = $dumper->Dump();
4247    if ($str =~ /^\$v/) {
4248	return '${my ' . $str . ' \$v}';
4249    } else {
4250	return $str;
4251    }
4252}
4253
4254sub const_sv {
4255    my $self = shift;
4256    my $op = shift;
4257    my $sv = $op->sv;
4258    # the constant could be in the pad (under useithreads)
4259    $sv = $self->padval($op->targ) unless $$sv;
4260    return $sv;
4261}
4262
4263sub pp_const {
4264    my $self = shift;
4265    my($op, $cx) = @_;
4266    if ($op->private & OPpCONST_ARYBASE) {
4267        return '$[';
4268    }
4269#    if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
4270#	return $self->const_sv($op)->PV;
4271#    }
4272    my $sv = $self->const_sv($op);
4273    return $self->const($sv, $cx);
4274}
4275
4276sub dq {
4277    my $self = shift;
4278    my $op = shift;
4279    my $type = $op->name;
4280    if ($type eq "const") {
4281	return '$[' if $op->private & OPpCONST_ARYBASE;
4282	return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
4283    } elsif ($type eq "concat") {
4284	my $first = $self->dq($op->first);
4285	my $last  = $self->dq($op->last);
4286
4287	# Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
4288	($last =~ /^[A-Z\\\^\[\]_?]/ &&
4289	    $first =~ s/([\$@])\^$/${1}{^}/)  # "${^}W" etc
4290	    || ($last =~ /^[:'{\[\w_]/ && #'
4291		$first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4292
4293	return $first . $last;
4294    } elsif ($type eq "uc") {
4295	return '\U' . $self->dq($op->first->sibling) . '\E';
4296    } elsif ($type eq "lc") {
4297	return '\L' . $self->dq($op->first->sibling) . '\E';
4298    } elsif ($type eq "ucfirst") {
4299	return '\u' . $self->dq($op->first->sibling);
4300    } elsif ($type eq "lcfirst") {
4301	return '\l' . $self->dq($op->first->sibling);
4302    } elsif ($type eq "quotemeta") {
4303	return '\Q' . $self->dq($op->first->sibling) . '\E';
4304    } elsif ($type eq "fc") {
4305	return '\F' . $self->dq($op->first->sibling) . '\E';
4306    } elsif ($type eq "join") {
4307	return $self->deparse($op->last, 26); # was join($", @ary)
4308    } else {
4309	return $self->deparse($op, 26);
4310    }
4311}
4312
4313sub pp_backtick {
4314    my $self = shift;
4315    my($op, $cx) = @_;
4316    # skip pushmark if it exists (readpipe() vs ``)
4317    my $child = $op->first->sibling->isa('B::NULL')
4318	? $op->first : $op->first->sibling;
4319    if ($self->pure_string($child)) {
4320	return single_delim("qx", '`', $self->dq($child, 1));
4321    }
4322    unop($self, @_, "readpipe");
4323}
4324
4325sub dquote {
4326    my $self = shift;
4327    my($op, $cx) = @_;
4328    my $kid = $op->first->sibling; # skip ex-stringify, pushmark
4329    return $self->deparse($kid, $cx) if $self->{'unquote'};
4330    $self->maybe_targmy($kid, $cx,
4331			sub {single_delim("qq", '"', $self->dq($_[1]))});
4332}
4333
4334# OP_STRINGIFY is a listop, but it only ever has one arg
4335sub pp_stringify { maybe_targmy(@_, \&dquote) }
4336
4337# tr/// and s/// (and tr[][], tr[]//, tr###, etc)
4338# note that tr(from)/to/ is OK, but not tr/from/(to)
4339sub double_delim {
4340    my($from, $to) = @_;
4341    my($succeed, $delim);
4342    if ($from !~ m[/] and $to !~ m[/]) {
4343	return "/$from/$to/";
4344    } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
4345	if (($succeed, $to) = balanced_delim($to) and $succeed) {
4346	    return "$from$to";
4347	} else {
4348	    for $delim ('/', '"', '#') { # note no "'" -- s''' is special
4349		return "$from$delim$to$delim" if index($to, $delim) == -1;
4350	    }
4351	    $to =~ s[/][\\/]g;
4352	    return "$from/$to/";
4353	}
4354    } else {
4355	for $delim ('/', '"', '#') { # note no '
4356	    return "$delim$from$delim$to$delim"
4357		if index($to . $from, $delim) == -1;
4358	}
4359	$from =~ s[/][\\/]g;
4360	$to =~ s[/][\\/]g;
4361	return "/$from/$to/";
4362    }
4363}
4364
4365# Only used by tr///, so backslashes hyphens
4366sub pchr { # ASCII
4367    my($n) = @_;
4368    if ($n == ord '\\') {
4369	return '\\\\';
4370    } elsif ($n == ord "-") {
4371	return "\\-";
4372    } elsif ($n >= ord(' ') and $n <= ord('~')) {
4373	return chr($n);
4374    } elsif ($n == ord "\a") {
4375	return '\\a';
4376    } elsif ($n == ord "\b") {
4377	return '\\b';
4378    } elsif ($n == ord "\t") {
4379	return '\\t';
4380    } elsif ($n == ord "\n") {
4381	return '\\n';
4382    } elsif ($n == ord "\e") {
4383	return '\\e';
4384    } elsif ($n == ord "\f") {
4385	return '\\f';
4386    } elsif ($n == ord "\r") {
4387	return '\\r';
4388    } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
4389	return '\\c' . chr(ord("@") + $n);
4390    } else {
4391#	return '\x' . sprintf("%02x", $n);
4392	return '\\' . sprintf("%03o", $n);
4393    }
4394}
4395
4396sub collapse {
4397    my(@chars) = @_;
4398    my($str, $c, $tr) = ("");
4399    for ($c = 0; $c < @chars; $c++) {
4400	$tr = $chars[$c];
4401	$str .= pchr($tr);
4402	if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
4403	    $chars[$c + 2] == $tr + 2)
4404	{
4405	    for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
4406	      {}
4407	    $str .= "-";
4408	    $str .= pchr($chars[$c]);
4409	}
4410    }
4411    return $str;
4412}
4413
4414sub tr_decode_byte {
4415    my($table, $flags) = @_;
4416    my(@table) = unpack("s*", $table);
4417    splice @table, 0x100, 1;   # Number of subsequent elements
4418    my($c, $tr, @from, @to, @delfrom, $delhyphen);
4419    if ($table[ord "-"] != -1 and
4420	$table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4421    {
4422	$tr = $table[ord "-"];
4423	$table[ord "-"] = -1;
4424	if ($tr >= 0) {
4425	    @from = ord("-");
4426	    @to = $tr;
4427	} else { # -2 ==> delete
4428	    $delhyphen = 1;
4429	}
4430    }
4431    for ($c = 0; $c < @table; $c++) {
4432	$tr = $table[$c];
4433	if ($tr >= 0) {
4434	    push @from, $c; push @to, $tr;
4435	} elsif ($tr == -2) {
4436	    push @delfrom, $c;
4437	}
4438    }
4439    @from = (@from, @delfrom);
4440    if ($flags & OPpTRANS_COMPLEMENT) {
4441	my @newfrom = ();
4442	my %from;
4443	@from{@from} = (1) x @from;
4444	for ($c = 0; $c < 256; $c++) {
4445	    push @newfrom, $c unless $from{$c};
4446	}
4447	@from = @newfrom;
4448    }
4449    unless ($flags & OPpTRANS_DELETE || !@to) {
4450	pop @to while $#to and $to[$#to] == $to[$#to -1];
4451    }
4452    my($from, $to);
4453    $from = collapse(@from);
4454    $to = collapse(@to);
4455    $from .= "-" if $delhyphen;
4456    return ($from, $to);
4457}
4458
4459sub tr_chr {
4460    my $x = shift;
4461    if ($x == ord "-") {
4462	return "\\-";
4463    } elsif ($x == ord "\\") {
4464	return "\\\\";
4465    } else {
4466	return chr $x;
4467    }
4468}
4469
4470# XXX This doesn't yet handle all cases correctly either
4471
4472sub tr_decode_utf8 {
4473    my($swash_hv, $flags) = @_;
4474    my %swash = $swash_hv->ARRAY;
4475    my $final = undef;
4476    $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4477    my $none = $swash{"NONE"}->IV;
4478    my $extra = $none + 1;
4479    my(@from, @delfrom, @to);
4480    my $line;
4481    foreach $line (split /\n/, $swash{'LIST'}->PV) {
4482	my($min, $max, $result) = split(/\t/, $line);
4483	$min = hex $min;
4484	if (length $max) {
4485	    $max = hex $max;
4486	} else {
4487	    $max = $min;
4488	}
4489	$result = hex $result;
4490	if ($result == $extra) {
4491	    push @delfrom, [$min, $max];
4492	} else {
4493	    push @from, [$min, $max];
4494	    push @to, [$result, $result + $max - $min];
4495	}
4496    }
4497    for my $i (0 .. $#from) {
4498	if ($from[$i][0] == ord '-') {
4499	    unshift @from, splice(@from, $i, 1);
4500	    unshift @to, splice(@to, $i, 1);
4501	    last;
4502	} elsif ($from[$i][1] == ord '-') {
4503	    $from[$i][1]--;
4504	    $to[$i][1]--;
4505	    unshift @from, ord '-';
4506	    unshift @to, ord '-';
4507	    last;
4508	}
4509    }
4510    for my $i (0 .. $#delfrom) {
4511	if ($delfrom[$i][0] == ord '-') {
4512	    push @delfrom, splice(@delfrom, $i, 1);
4513	    last;
4514	} elsif ($delfrom[$i][1] == ord '-') {
4515	    $delfrom[$i][1]--;
4516	    push @delfrom, ord '-';
4517	    last;
4518	}
4519    }
4520    if (defined $final and $to[$#to][1] != $final) {
4521	push @to, [$final, $final];
4522    }
4523    push @from, @delfrom;
4524    if ($flags & OPpTRANS_COMPLEMENT) {
4525	my @newfrom;
4526	my $next = 0;
4527	for my $i (0 .. $#from) {
4528	    push @newfrom, [$next, $from[$i][0] - 1];
4529	    $next = $from[$i][1] + 1;
4530	}
4531	@from = ();
4532	for my $range (@newfrom) {
4533	    if ($range->[0] <= $range->[1]) {
4534		push @from, $range;
4535	    }
4536	}
4537    }
4538    my($from, $to, $diff);
4539    for my $chunk (@from) {
4540	$diff = $chunk->[1] - $chunk->[0];
4541	if ($diff > 1) {
4542	    $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4543	} elsif ($diff == 1) {
4544	    $from .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
4545	} else {
4546	    $from .= tr_chr($chunk->[0]);
4547	}
4548    }
4549    for my $chunk (@to) {
4550	$diff = $chunk->[1] - $chunk->[0];
4551	if ($diff > 1) {
4552	    $to .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4553	} elsif ($diff == 1) {
4554	    $to .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
4555	} else {
4556	    $to .= tr_chr($chunk->[0]);
4557	}
4558    }
4559    #$final = sprintf("%04x", $final) if defined $final;
4560    #$none = sprintf("%04x", $none) if defined $none;
4561    #$extra = sprintf("%04x", $extra) if defined $extra;
4562    #print STDERR "final: $final\n none: $none\nextra: $extra\n";
4563    #print STDERR $swash{'LIST'}->PV;
4564    return (escape_str($from), escape_str($to));
4565}
4566
4567sub pp_trans {
4568    my $self = shift;
4569    my($op, $cx) = @_;
4570    my($from, $to);
4571    my $class = class($op);
4572    my $priv_flags = $op->private;
4573    if ($class eq "PVOP") {
4574	($from, $to) = tr_decode_byte($op->pv, $priv_flags);
4575    } elsif ($class eq "PADOP") {
4576	($from, $to)
4577	  = tr_decode_utf8($self->padval($op->padix)->RV, $priv_flags);
4578    } else { # class($op) eq "SVOP"
4579	($from, $to) = tr_decode_utf8($op->sv->RV, $priv_flags);
4580    }
4581    my $flags = "";
4582    $flags .= "c" if $priv_flags & OPpTRANS_COMPLEMENT;
4583    $flags .= "d" if $priv_flags & OPpTRANS_DELETE;
4584    $to = "" if $from eq $to and $flags eq "";
4585    $flags .= "s" if $priv_flags & OPpTRANS_SQUASH;
4586    return "tr" . double_delim($from, $to) . $flags;
4587}
4588
4589sub pp_transr { &pp_trans . 'r' }
4590
4591sub re_dq_disambiguate {
4592    my ($first, $last) = @_;
4593    # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
4594    ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4595	$first =~ s/([\$@])\^$/${1}{^}/)  # "${^}W" etc
4596	|| ($last =~ /^[{\[\w_]/ &&
4597	    $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4598    return $first . $last;
4599}
4600
4601# Like dq(), but different
4602sub re_dq {
4603    my $self = shift;
4604    my ($op, $extended) = @_;
4605
4606    my $type = $op->name;
4607    if ($type eq "const") {
4608	return '$[' if $op->private & OPpCONST_ARYBASE;
4609	my $unbacked = re_unback($self->const_sv($op)->as_string);
4610	return re_uninterp_extended(escape_extended_re($unbacked))
4611	    if $extended;
4612	return re_uninterp(escape_str($unbacked));
4613    } elsif ($type eq "concat") {
4614	my $first = $self->re_dq($op->first, $extended);
4615	my $last  = $self->re_dq($op->last,  $extended);
4616	return re_dq_disambiguate($first, $last);
4617    } elsif ($type eq "uc") {
4618	return '\U' . $self->re_dq($op->first->sibling, $extended) . '\E';
4619    } elsif ($type eq "lc") {
4620	return '\L' . $self->re_dq($op->first->sibling, $extended) . '\E';
4621    } elsif ($type eq "ucfirst") {
4622	return '\u' . $self->re_dq($op->first->sibling, $extended);
4623    } elsif ($type eq "lcfirst") {
4624	return '\l' . $self->re_dq($op->first->sibling, $extended);
4625    } elsif ($type eq "quotemeta") {
4626	return '\Q' . $self->re_dq($op->first->sibling, $extended) . '\E';
4627    } elsif ($type eq "fc") {
4628	return '\F' . $self->re_dq($op->first->sibling, $extended) . '\E';
4629    } elsif ($type eq "join") {
4630	return $self->deparse($op->last, 26); # was join($", @ary)
4631    } else {
4632	my $ret = $self->deparse($op, 26);
4633	$ret =~ s/^\$([(|)])\z/\${$1}/; # $( $| $) need braces
4634	return $ret;
4635    }
4636}
4637
4638sub pure_string {
4639    my ($self, $op) = @_;
4640    return 0 if null $op;
4641    my $type = $op->name;
4642
4643    if ($type eq 'const' || $type eq 'av2arylen') {
4644	return 1;
4645    }
4646    elsif ($type =~ /^(?:[ul]c(first)?|fc)$/ || $type eq 'quotemeta') {
4647	return $self->pure_string($op->first->sibling);
4648    }
4649    elsif ($type eq 'join') {
4650	my $join_op = $op->first->sibling;  # Skip pushmark
4651	return 0 unless $join_op->name eq 'null' && $join_op->targ == OP_RV2SV;
4652
4653	my $gvop = $join_op->first;
4654	return 0 unless $gvop->name eq 'gvsv';
4655        return 0 unless '"' eq $self->gv_name($self->gv_or_padgv($gvop));
4656
4657	return 0 unless ${$join_op->sibling} eq ${$op->last};
4658	return 0 unless $op->last->name =~ /^(?:[ah]slice|(?:rv2|pad)av)$/;
4659    }
4660    elsif ($type eq 'concat') {
4661	return $self->pure_string($op->first)
4662            && $self->pure_string($op->last);
4663    }
4664    elsif (is_scalar($op) || $type =~ /^[ah]elem$/) {
4665	return 1;
4666    }
4667    elsif ($type eq "null" and $op->can('first') and not null $op->first and
4668	  ($op->first->name eq "null" and $op->first->can('first')
4669	   and not null $op->first->first and
4670	   $op->first->first->name eq "aelemfast"
4671          or
4672	   $op->first->name =~ /^aelemfast(?:_lex)?\z/
4673	  )) {
4674	return 1;
4675    }
4676    else {
4677	return 0;
4678    }
4679
4680    return 1;
4681}
4682
4683sub regcomp {
4684    my $self = shift;
4685    my($op, $cx, $extended) = @_;
4686    my $kid = $op->first;
4687    $kid = $kid->first if $kid->name eq "regcmaybe";
4688    $kid = $kid->first if $kid->name eq "regcreset";
4689    if ($kid->name eq "null" and !null($kid->first)
4690	and $kid->first->name eq 'pushmark')
4691    {
4692	my $str = '';
4693	$kid = $kid->first->sibling;
4694	while (!null($kid)) {
4695	    my $first = $str;
4696	    my $last = $self->re_dq($kid, $extended);
4697	    $str = re_dq_disambiguate($first, $last);
4698	    $kid = $kid->sibling;
4699	}
4700	return $str, 1;
4701    }
4702
4703    return ($self->re_dq($kid, $extended), 1) if $self->pure_string($kid);
4704    return ($self->deparse($kid, $cx), 0);
4705}
4706
4707sub pp_regcomp {
4708    my ($self, $op, $cx) = @_;
4709    return (($self->regcomp($op, $cx, 0))[0]);
4710}
4711
4712sub re_flags {
4713    my ($self, $op) = @_;
4714    my $flags = '';
4715    my $pmflags = $op->pmflags;
4716    $flags .= "g" if $pmflags & PMf_GLOBAL;
4717    $flags .= "i" if $pmflags & PMf_FOLD;
4718    $flags .= "m" if $pmflags & PMf_MULTILINE;
4719    $flags .= "o" if $pmflags & PMf_KEEP;
4720    $flags .= "s" if $pmflags & PMf_SINGLELINE;
4721    $flags .= "x" if $pmflags & PMf_EXTENDED;
4722    $flags .= "p" if $pmflags & RXf_PMf_KEEPCOPY;
4723    if (my $charset = $pmflags & RXf_PMf_CHARSET) {
4724	# Hardcoding this is fragile, but B does not yet export the
4725	# constants we need.
4726	$flags .= qw(d l u a aa)[$charset >> 5]
4727    }
4728    # The /d flag is indicated by 0; only show it if necessary.
4729    elsif ($self->{hinthash} and
4730	     $self->{hinthash}{reflags_charset}
4731	    || $self->{hinthash}{feature_unicode}
4732	or $self->{hints} & $feature::hint_mask
4733	  && ($self->{hints} & $feature::hint_mask)
4734	       != $feature::hint_mask
4735	  && do {
4736		$self->{hints} & $feature::hint_uni8bit;
4737	     }
4738  ) {
4739	$flags .= 'd';
4740    }
4741    $flags;
4742}
4743
4744# osmic acid -- see osmium tetroxide
4745
4746my %matchwords;
4747map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs',
4748    'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic',
4749    'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi');
4750
4751sub matchop {
4752    my $self = shift;
4753    my($op, $cx, $name, $delim) = @_;
4754    my $kid = $op->first;
4755    my ($binop, $var, $re) = ("", "", "");
4756    if ($op->flags & OPf_STACKED) {
4757	$binop = 1;
4758	$var = $self->deparse($kid, 20);
4759	$kid = $kid->sibling;
4760    }
4761    my $quote = 1;
4762    my $pmflags = $op->pmflags;
4763    my $extended = ($pmflags & PMf_EXTENDED);
4764    my $rhs_bound_to_defsv;
4765    if (null $kid) {
4766	my $unbacked = re_unback($op->precomp);
4767	if ($extended) {
4768	    $re = re_uninterp_extended(escape_extended_re($unbacked));
4769	} else {
4770	    $re = re_uninterp(escape_str(re_unback($op->precomp)));
4771	}
4772    } elsif ($kid->name ne 'regcomp') {
4773	carp("found ".$kid->name." where regcomp expected");
4774    } else {
4775	($re, $quote) = $self->regcomp($kid, 21, $extended);
4776	my $matchop = $kid->first;
4777	if ($matchop->name eq 'regcrest') {
4778	    $matchop = $matchop->first;
4779	}
4780	if ($matchop->name =~ /^(?:match|transr?|subst)\z/
4781	   && $matchop->flags & OPf_SPECIAL) {
4782	    $rhs_bound_to_defsv = 1;
4783	}
4784    }
4785    my $flags = "";
4786    $flags .= "c" if $pmflags & PMf_CONTINUE;
4787    $flags .= $self->re_flags($op);
4788    $flags = join '', sort split //, $flags;
4789    $flags = $matchwords{$flags} if $matchwords{$flags};
4790    if ($pmflags & PMf_ONCE) { # only one kind of delimiter works here
4791	$re =~ s/\?/\\?/g;
4792	$re = "?$re?";
4793    } elsif ($quote) {
4794	$re = single_delim($name, $delim, $re);
4795    }
4796    $re = $re . $flags if $quote;
4797    if ($binop) {
4798	return
4799	 $self->maybe_parens(
4800	  $rhs_bound_to_defsv
4801	   ? "$var =~ (\$_ =~ $re)"
4802	   : "$var =~ $re",
4803	  $cx, 20
4804	 );
4805    } else {
4806	return $re;
4807    }
4808}
4809
4810sub pp_match { matchop(@_, "m", "/") }
4811sub pp_pushre { matchop(@_, "m", "/") }
4812sub pp_qr { matchop(@_, "qr", "") }
4813
4814sub pp_runcv { unop(@_, "__SUB__"); }
4815
4816sub pp_split {
4817    my $self = shift;
4818    my($op, $cx) = @_;
4819    my($kid, @exprs, $ary, $expr);
4820    $kid = $op->first;
4821
4822    # For our kid (an OP_PUSHRE), pmreplroot is never actually the
4823    # root of a replacement; it's either empty, or abused to point to
4824    # the GV for an array we split into (an optimization to save
4825    # assignment overhead). Depending on whether we're using ithreads,
4826    # this OP* holds either a GV* or a PADOFFSET. Luckily, B.xs
4827    # figures out for us which it is.
4828    my $replroot = $kid->pmreplroot;
4829    my $gv = 0;
4830    if (ref($replroot) eq "B::GV") {
4831	$gv = $replroot;
4832    } elsif (!ref($replroot) and $replroot > 0) {
4833	$gv = $self->padval($replroot);
4834    }
4835    $ary = $self->stash_variable('@', $self->gv_name($gv), $cx) if $gv;
4836
4837    for (; !null($kid); $kid = $kid->sibling) {
4838	push @exprs, $self->deparse($kid, 6);
4839    }
4840
4841    # handle special case of split(), and split(' ') that compiles to /\s+/
4842    # Under 5.10, the reflags may be undef if the split regexp isn't a constant
4843    # Under 5.17.5-5.17.9, the special flag is on split itself.
4844    $kid = $op->first;
4845    if ( $op->flags & OPf_SPECIAL
4846         or (
4847            $kid->flags & OPf_SPECIAL
4848            and ( $] < 5.009 ? $kid->pmflags & PMf_SKIPWHITE()
4849                             : ($kid->reflags || 0) & RXf_SKIPWHITE()
4850            )
4851         )
4852    ) {
4853	$exprs[0] = "' '";
4854    }
4855
4856    $expr = "split(" . join(", ", @exprs) . ")";
4857    if ($ary) {
4858	return $self->maybe_parens("$ary = $expr", $cx, 7);
4859    } else {
4860	return $expr;
4861    }
4862}
4863
4864# oxime -- any of various compounds obtained chiefly by the action of
4865# hydroxylamine on aldehydes and ketones and characterized by the
4866# bivalent grouping C=NOH [Webster's Tenth]
4867
4868my %substwords;
4869map($substwords{join "", sort split //, $_} = $_, 'ego', 'egoism', 'em',
4870    'es', 'ex', 'exes', 'gee', 'go', 'goes', 'ie', 'ism', 'iso', 'me',
4871    'meese', 'meso', 'mig', 'mix', 'os', 'ox', 'oxime', 'see', 'seem',
4872    'seg', 'sex', 'sig', 'six', 'smog', 'sog', 'some', 'xi', 'rogue',
4873    'sir', 'rise', 'smore', 'more', 'seer', 'rome', 'gore', 'grim', 'grime',
4874    'or', 'rose', 'rosie');
4875
4876sub pp_subst {
4877    my $self = shift;
4878    my($op, $cx) = @_;
4879    my $kid = $op->first;
4880    my($binop, $var, $re, $repl) = ("", "", "", "");
4881    if ($op->flags & OPf_STACKED) {
4882	$binop = 1;
4883	$var = $self->deparse($kid, 20);
4884	$kid = $kid->sibling;
4885    }
4886    my $flags = "";
4887    my $pmflags = $op->pmflags;
4888    if (null($op->pmreplroot)) {
4889	$repl = $kid;
4890	$kid = $kid->sibling;
4891    } else {
4892	$repl = $op->pmreplroot->first; # skip substcont
4893    }
4894    while ($repl->name eq "entereval") {
4895	    $repl = $repl->first;
4896	    $flags .= "e";
4897    }
4898    {
4899	local $self->{in_subst_repl} = 1;
4900	if ($pmflags & PMf_EVAL) {
4901	    $repl = $self->deparse($repl->first, 0);
4902	} else {
4903	    $repl = $self->dq($repl);
4904	}
4905    }
4906    my $extended = ($pmflags & PMf_EXTENDED);
4907    if (null $kid) {
4908	my $unbacked = re_unback($op->precomp);
4909	if ($extended) {
4910	    $re = re_uninterp_extended(escape_extended_re($unbacked));
4911	}
4912	else {
4913	    $re = re_uninterp(escape_str($unbacked));
4914	}
4915    } else {
4916	($re) = $self->regcomp($kid, 1, $extended);
4917    }
4918    $flags .= "r" if $pmflags & PMf_NONDESTRUCT;
4919    $flags .= "e" if $pmflags & PMf_EVAL;
4920    $flags .= $self->re_flags($op);
4921    $flags = join '', sort split //, $flags;
4922    $flags = $substwords{$flags} if $substwords{$flags};
4923    if ($binop) {
4924	return $self->maybe_parens("$var =~ s"
4925				   . double_delim($re, $repl) . $flags,
4926				   $cx, 20);
4927    } else {
4928	return "s". double_delim($re, $repl) . $flags;
4929    }
4930}
4931
4932sub is_lexical_subs {
4933    my (@ops) = shift;
4934    for my $op (@ops) {
4935        return 0 if $op->name !~ /\A(?:introcv|clonecv)\z/;
4936    }
4937    return 1;
4938}
4939
4940sub pp_introcv {
4941    my $self = shift;
4942    my($op, $cx) = @_;
4943    # For now, deparsing doesn't worry about the distinction between introcv
4944    # and clonecv, so pretend this op doesn't exist:
4945    return '';
4946}
4947
4948sub pp_clonecv {
4949    my $self = shift;
4950    my($op, $cx) = @_;
4951    my $sv = $self->padname_sv($op->targ);
4952    my $name = substr $sv->PVX, 1; # skip &/$/@/%, like $self->padany
4953    return "my sub $name";
4954}
4955
4956sub pp_padcv {
4957    my $self = shift;
4958    my($op, $cx) = @_;
4959    return $self->padany($op);
4960}
4961
49621;
4963__END__
4964
4965=head1 NAME
4966
4967B::Deparse - Perl compiler backend to produce perl code
4968
4969=head1 SYNOPSIS
4970
4971B<perl> B<-MO=Deparse>[B<,-d>][B<,-f>I<FILE>][B<,-p>][B<,-q>][B<,-l>]
4972        [B<,-s>I<LETTERS>][B<,-x>I<LEVEL>] I<prog.pl>
4973
4974=head1 DESCRIPTION
4975
4976B::Deparse is a backend module for the Perl compiler that generates
4977perl source code, based on the internal compiled structure that perl
4978itself creates after parsing a program.  The output of B::Deparse won't
4979be exactly the same as the original source, since perl doesn't keep
4980track of comments or whitespace, and there isn't a one-to-one
4981correspondence between perl's syntactical constructions and their
4982compiled form, but it will often be close.  When you use the B<-p>
4983option, the output also includes parentheses even when they are not
4984required by precedence, which can make it easy to see if perl is
4985parsing your expressions the way you intended.
4986
4987While B::Deparse goes to some lengths to try to figure out what your
4988original program was doing, some parts of the language can still trip
4989it up; it still fails even on some parts of Perl's own test suite.  If
4990you encounter a failure other than the most common ones described in
4991the BUGS section below, you can help contribute to B::Deparse's
4992ongoing development by submitting a bug report with a small
4993example.
4994
4995=head1 OPTIONS
4996
4997As with all compiler backend options, these must follow directly after
4998the '-MO=Deparse', separated by a comma but not any white space.
4999
5000=over 4
5001
5002=item B<-d>
5003
5004Output data values (when they appear as constants) using Data::Dumper.
5005Without this option, B::Deparse will use some simple routines of its
5006own for the same purpose.  Currently, Data::Dumper is better for some
5007kinds of data (such as complex structures with sharing and
5008self-reference) while the built-in routines are better for others
5009(such as odd floating-point values).
5010
5011=item B<-f>I<FILE>
5012
5013Normally, B::Deparse deparses the main code of a program, and all the subs
5014defined in the same file.  To include subs defined in
5015other files, pass the B<-f> option with the filename.
5016You can pass the B<-f> option several times, to
5017include more than one secondary file.  (Most of the time you don't want to
5018use it at all.)  You can also use this option to include subs which are
5019defined in the scope of a B<#line> directive with two parameters.
5020
5021=item B<-l>
5022
5023Add '#line' declarations to the output based on the line and file
5024locations of the original code.
5025
5026=item B<-p>
5027
5028Print extra parentheses.  Without this option, B::Deparse includes
5029parentheses in its output only when they are needed, based on the
5030structure of your program.  With B<-p>, it uses parentheses (almost)
5031whenever they would be legal.  This can be useful if you are used to
5032LISP, or if you want to see how perl parses your input.  If you say
5033
5034    if ($var & 0x7f == 65) {print "Gimme an A!"}
5035    print ($which ? $a : $b), "\n";
5036    $name = $ENV{USER} or "Bob";
5037
5038C<B::Deparse,-p> will print
5039
5040    if (($var & 0)) {
5041        print('Gimme an A!')
5042    };
5043    (print(($which ? $a : $b)), '???');
5044    (($name = $ENV{'USER'}) or '???')
5045
5046which probably isn't what you intended (the C<'???'> is a sign that
5047perl optimized away a constant value).
5048
5049=item B<-P>
5050
5051Disable prototype checking.  With this option, all function calls are
5052deparsed as if no prototype was defined for them.  In other words,
5053
5054    perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x'
5055
5056will print
5057
5058    sub foo (\@) {
5059	1;
5060    }
5061    &foo(\@x);
5062
5063making clear how the parameters are actually passed to C<foo>.
5064
5065=item B<-q>
5066
5067Expand double-quoted strings into the corresponding combinations of
5068concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join.  For
5069instance, print
5070
5071    print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";
5072
5073as
5074
5075    print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
5076          . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');
5077
5078Note that the expanded form represents the way perl handles such
5079constructions internally -- this option actually turns off the reverse
5080translation that B::Deparse usually does.  On the other hand, note that
5081C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value
5082of $y into a string before doing the assignment.
5083
5084=item B<-s>I<LETTERS>
5085
5086Tweak the style of B::Deparse's output.  The letters should follow
5087directly after the 's', with no space or punctuation.  The following
5088options are available:
5089
5090=over 4
5091
5092=item B<C>
5093
5094Cuddle C<elsif>, C<else>, and C<continue> blocks.  For example, print
5095
5096    if (...) {
5097         ...
5098    } else {
5099         ...
5100    }
5101
5102instead of
5103
5104    if (...) {
5105         ...
5106    }
5107    else {
5108         ...
5109    }
5110
5111The default is not to cuddle.
5112
5113=item B<i>I<NUMBER>
5114
5115Indent lines by multiples of I<NUMBER> columns.  The default is 4 columns.
5116
5117=item B<T>
5118
5119Use tabs for each 8 columns of indent.  The default is to use only spaces.
5120For instance, if the style options are B<-si4T>, a line that's indented
51213 times will be preceded by one tab and four spaces; if the options were
5122B<-si8T>, the same line would be preceded by three tabs.
5123
5124=item B<v>I<STRING>B<.>
5125
5126Print I<STRING> for the value of a constant that can't be determined
5127because it was optimized away (mnemonic: this happens when a constant
5128is used in B<v>oid context).  The end of the string is marked by a period.
5129The string should be a valid perl expression, generally a constant.
5130Note that unless it's a number, it probably needs to be quoted, and on
5131a command line quotes need to be protected from the shell.  Some
5132conventional values include 0, 1, 42, '', 'foo', and
5133'Useless use of constant omitted' (which may need to be
5134B<-sv"'Useless use of constant omitted'.">
5135or something similar depending on your shell).  The default is '???'.
5136If you're using B::Deparse on a module or other file that's require'd,
5137you shouldn't use a value that evaluates to false, since the customary
5138true constant at the end of a module will be in void context when the
5139file is compiled as a main program.
5140
5141=back
5142
5143=item B<-x>I<LEVEL>
5144
5145Expand conventional syntax constructions into equivalent ones that expose
5146their internal operation.  I<LEVEL> should be a digit, with higher values
5147meaning more expansion.  As with B<-q>, this actually involves turning off
5148special cases in B::Deparse's normal operations.
5149
5150If I<LEVEL> is at least 3, C<for> loops will be translated into equivalent
5151while loops with continue blocks; for instance
5152
5153    for ($i = 0; $i < 10; ++$i) {
5154        print $i;
5155    }
5156
5157turns into
5158
5159    $i = 0;
5160    while ($i < 10) {
5161        print $i;
5162    } continue {
5163        ++$i
5164    }
5165
5166Note that in a few cases this translation can't be perfectly carried back
5167into the source code -- if the loop's initializer declares a my variable,
5168for instance, it won't have the correct scope outside of the loop.
5169
5170If I<LEVEL> is at least 5, C<use> declarations will be translated into
5171C<BEGIN> blocks containing calls to C<require> and C<import>; for
5172instance,
5173
5174    use strict 'refs';
5175
5176turns into
5177
5178    sub BEGIN {
5179        require strict;
5180        do {
5181            'strict'->import('refs')
5182        };
5183    }
5184
5185If I<LEVEL> is at least 7, C<if> statements will be translated into
5186equivalent expressions using C<&&>, C<?:> and C<do {}>; for instance
5187
5188    print 'hi' if $nice;
5189    if ($nice) {
5190        print 'hi';
5191    }
5192    if ($nice) {
5193        print 'hi';
5194    } else {
5195        print 'bye';
5196    }
5197
5198turns into
5199
5200    $nice and print 'hi';
5201    $nice and do { print 'hi' };
5202    $nice ? do { print 'hi' } : do { print 'bye' };
5203
5204Long sequences of elsifs will turn into nested ternary operators, which
5205B::Deparse doesn't know how to indent nicely.
5206
5207=back
5208
5209=head1 USING B::Deparse AS A MODULE
5210
5211=head2 Synopsis
5212
5213    use B::Deparse;
5214    $deparse = B::Deparse->new("-p", "-sC");
5215    $body = $deparse->coderef2text(\&func);
5216    eval "sub func $body"; # the inverse operation
5217
5218=head2 Description
5219
5220B::Deparse can also be used on a sub-by-sub basis from other perl
5221programs.
5222
5223=head2 new
5224
5225    $deparse = B::Deparse->new(OPTIONS)
5226
5227Create an object to store the state of a deparsing operation and any
5228options.  The options are the same as those that can be given on the
5229command line (see L</OPTIONS>); options that are separated by commas
5230after B<-MO=Deparse> should be given as separate strings.
5231
5232=head2 ambient_pragmas
5233
5234    $deparse->ambient_pragmas(strict => 'all', '$[' => $[);
5235
5236The compilation of a subroutine can be affected by a few compiler
5237directives, B<pragmas>.  These are:
5238
5239=over 4
5240
5241=item *
5242
5243use strict;
5244
5245=item *
5246
5247use warnings;
5248
5249=item *
5250
5251Assigning to the special variable $[
5252
5253=item *
5254
5255use integer;
5256
5257=item *
5258
5259use bytes;
5260
5261=item *
5262
5263use utf8;
5264
5265=item *
5266
5267use re;
5268
5269=back
5270
5271Ordinarily, if you use B::Deparse on a subroutine which has
5272been compiled in the presence of one or more of these pragmas,
5273the output will include statements to turn on the appropriate
5274directives.  So if you then compile the code returned by coderef2text,
5275it will behave the same way as the subroutine which you deparsed.
5276
5277However, you may know that you intend to use the results in a
5278particular context, where some pragmas are already in scope.  In
5279this case, you use the B<ambient_pragmas> method to describe the
5280assumptions you wish to make.
5281
5282Not all of the options currently have any useful effect.  See
5283L</BUGS> for more details.
5284
5285The parameters it accepts are:
5286
5287=over 4
5288
5289=item strict
5290
5291Takes a string, possibly containing several values separated
5292by whitespace.  The special values "all" and "none" mean what you'd
5293expect.
5294
5295    $deparse->ambient_pragmas(strict => 'subs refs');
5296
5297=item $[
5298
5299Takes a number, the value of the array base $[.
5300Cannot be non-zero on Perl 5.15.3 or later.
5301
5302=item bytes
5303
5304=item utf8
5305
5306=item integer
5307
5308If the value is true, then the appropriate pragma is assumed to
5309be in the ambient scope, otherwise not.
5310
5311=item re
5312
5313Takes a string, possibly containing a whitespace-separated list of
5314values.  The values "all" and "none" are special.  It's also permissible
5315to pass an array reference here.
5316
5317    $deparser->ambient_pragmas(re => 'eval');
5318
5319
5320=item warnings
5321
5322Takes a string, possibly containing a whitespace-separated list of
5323values.  The values "all" and "none" are special, again.  It's also
5324permissible to pass an array reference here.
5325
5326    $deparser->ambient_pragmas(warnings => [qw[void io]]);
5327
5328If one of the values is the string "FATAL", then all the warnings
5329in that list will be considered fatal, just as with the B<warnings>
5330pragma itself.  Should you need to specify that some warnings are
5331fatal, and others are merely enabled, you can pass the B<warnings>
5332parameter twice:
5333
5334    $deparser->ambient_pragmas(
5335	warnings => 'all',
5336	warnings => [FATAL => qw/void io/],
5337    );
5338
5339See L<warnings> for more information about lexical warnings.
5340
5341=item hint_bits
5342
5343=item warning_bits
5344
5345These two parameters are used to specify the ambient pragmas in
5346the format used by the special variables $^H and ${^WARNING_BITS}.
5347
5348They exist principally so that you can write code like:
5349
5350    { my ($hint_bits, $warning_bits);
5351    BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
5352    $deparser->ambient_pragmas (
5353	hint_bits    => $hint_bits,
5354	warning_bits => $warning_bits,
5355	'$['         => 0 + $[
5356    ); }
5357
5358which specifies that the ambient pragmas are exactly those which
5359are in scope at the point of calling.
5360
5361=item %^H
5362
5363This parameter is used to specify the ambient pragmas which are
5364stored in the special hash %^H.
5365
5366=back
5367
5368=head2 coderef2text
5369
5370    $body = $deparse->coderef2text(\&func)
5371    $body = $deparse->coderef2text(sub ($$) { ... })
5372
5373Return source code for the body of a subroutine (a block, optionally
5374preceded by a prototype in parens), given a reference to the
5375sub.  Because a subroutine can have no names, or more than one name,
5376this method doesn't return a complete subroutine definition -- if you
5377want to eval the result, you should prepend "sub subname ", or "sub "
5378for an anonymous function constructor.  Unless the sub was defined in
5379the main:: package, the code will include a package declaration.
5380
5381=head1 BUGS
5382
5383=over 4
5384
5385=item *
5386
5387The only pragmas to be completely supported are: C<use warnings>,
5388C<use strict>, C<use bytes>, C<use integer>
5389and C<use feature>.  (C<$[>, which
5390behaves like a pragma, is also supported.)
5391
5392Excepting those listed above, we're currently unable to guarantee that
5393B::Deparse will produce a pragma at the correct point in the program.
5394(Specifically, pragmas at the beginning of a block often appear right
5395before the start of the block instead.)
5396Since the effects of pragmas are often lexically scoped, this can mean
5397that the pragma holds sway over a different portion of the program
5398than in the input file.
5399
5400=item *
5401
5402In fact, the above is a specific instance of a more general problem:
5403we can't guarantee to produce BEGIN blocks or C<use> declarations in
5404exactly the right place.  So if you use a module which affects compilation
5405(such as by over-riding keywords, overloading constants or whatever)
5406then the output code might not work as intended.
5407
5408This is the most serious outstanding problem, and will require some help
5409from the Perl core to fix.
5410
5411=item *
5412
5413Some constants don't print correctly either with or without B<-d>.
5414For instance, neither B::Deparse nor Data::Dumper know how to print
5415dual-valued scalars correctly, as in:
5416
5417    use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y;
5418
5419    use constant H => { "#" => 1 }; H->{"#"};
5420
5421=item *
5422
5423An input file that uses source filtering probably won't be deparsed into
5424runnable code, because it will still include the B<use> declaration
5425for the source filtering module, even though the code that is
5426produced is already ordinary Perl which shouldn't be filtered again.
5427
5428=item *
5429
5430Optimised away statements are rendered as
5431'???'.  This includes statements that
5432have a compile-time side-effect, such as the obscure
5433
5434    my $x if 0;
5435
5436which is not, consequently, deparsed correctly.
5437
5438    foreach my $i (@_) { 0 }
5439  =>
5440    foreach my $i (@_) { '???' }
5441
5442=item *
5443
5444Lexical (my) variables declared in scopes external to a subroutine
5445appear in code2ref output text as package variables.  This is a tricky
5446problem, as perl has no native facility for referring to a lexical variable
5447defined within a different scope, although L<PadWalker> is a good start.
5448
5449=item *
5450
5451There are probably many more bugs on non-ASCII platforms (EBCDIC).
5452
5453=item *
5454
5455Lexical C<my> subroutines are not deparsed properly at the moment.  They are
5456emitted as pure declarations, without their body; and the declaration may
5457appear in the wrong place (before any lexicals the body closes over, or
5458before the C<use feature> declaration that permits use of this feature).
5459
5460We expect to resolve this before the lexical-subroutine feature is no longer
5461considered experimental.
5462
5463=item *
5464
5465Lexical C<state> subroutines are not deparsed at all at the moment.
5466
5467We expect to resolve this before the lexical-subroutine feature is no longer
5468considered experimental.
5469
5470=back
5471
5472=head1 AUTHOR
5473
5474Stephen McCamant <smcc@CSUA.Berkeley.EDU>, based on an earlier version
5475by Malcolm Beattie <mbeattie@sable.ox.ac.uk>, with contributions from
5476Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell,
5477Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael
5478Garcia-Suarez.
5479
5480=cut
5481