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