2 # Copyright (c) 1998, 1999, 2000 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.
6 # This is based on the module of the same name by Malcolm Beattie,
7 # but essentially none of his code remains.
10 use Carp 'cluck', 'croak';
11 use B qw(class main_root main_start main_cv svref_2object opnumber cstring
12 OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
13 OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL
14 OPpLVAL_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
15 OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
16 OPpCONST_ARYBASE OPpEXISTS_SUB
17 SVf_IOK SVf_NOK SVf_ROK SVf_POK
18 CVf_METHOD CVf_LOCKED CVf_LVALUE
19 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE PMf_SKIPWHITE
20 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
25 # Changes between 0.50 and 0.51:
26 # - fixed nulled leave with live enter in sort { }
27 # - fixed reference constants (\"str")
28 # - handle empty programs gracefully
29 # - handle infinte loops (for (;;) {}, while (1) {})
30 # - differentiate between `for my $x ...' and `my $x; for $x ...'
31 # - various minor cleanups
32 # - moved globals into an object
33 # - added `-u', like B::C
34 # - package declarations using cop_stash
35 # - subs, formats and code sorted by cop_seq
36 # Changes between 0.51 and 0.52:
37 # - added pp_threadsv (special variables under USE_THREADS)
38 # - added documentation
39 # Changes between 0.52 and 0.53:
40 # - many changes adding precedence contexts and associativity
41 # - added `-p' and `-s' output style options
42 # - various other minor fixes
43 # Changes between 0.53 and 0.54:
44 # - added support for new `for (1..100)' optimization,
46 # Changes between 0.54 and 0.55:
47 # - added support for new qr// construct
48 # - added support for new pp_regcreset OP
49 # Changes between 0.55 and 0.56:
50 # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
51 # - fixed $# on non-lexicals broken in last big rewrite
52 # - added temporary fix for change in opcode of OP_STRINGIFY
53 # - fixed problem in 0.54's for() patch in `for (@ary)'
54 # - fixed precedence in conditional of ?:
55 # - tweaked list paren elimination in `my($x) = @_'
56 # - made continue-block detection trickier wrt. null ops
57 # - fixed various prototype problems in pp_entersub
58 # - added support for sub prototypes that never get GVs
59 # - added unquoting for special filehandle first arg in truncate
60 # - print doubled rv2gv (a bug) as `*{*GV}' instead of illegal `**GV'
61 # - added semicolons at the ends of blocks
62 # - added -l `#line' declaration option -- fixes cmd/subval.t 27,28
63 # Changes between 0.56 and 0.561:
64 # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
65 # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
66 # Changes between 0.561 and 0.57:
67 # - stylistic changes to symbolic constant stuff
68 # - handled scope in s///e replacement code
69 # - added unquote option for expanding "" into concats, etc.
70 # - split method and proto parts of pp_entersub into separate functions
71 # - various minor cleanups
73 # - added parens in \&foo (patch by Albert Dvornik)
74 # Changes between 0.57 and 0.58:
75 # - fixed `0' statements that weren't being printed
76 # - added methods for use from other programs
77 # (based on patches from James Duncan and Hugo van der Sanden)
78 # - added -si and -sT to control indenting (also based on a patch from Hugo)
79 # - added -sv to print something else instead of '???'
80 # - preliminary version of utf8 tr/// handling
82 # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
83 # - added support for Hugo's new OP_SETSTATE (like nextstate)
84 # Changes between 0.58 and 0.59
85 # - added support for Chip's OP_METHOD_NAMED
86 # - added support for Ilya's OPpTARGET_MY optimization
87 # - elided arrows before `()' subscripts when possible
88 # Changes between 0.59 and 0.60
89 # - support for method attribues was added
90 # - some warnings fixed
91 # - separate recognition of constant subs
92 # - rewrote continue block handling, now recoginizing for loops
93 # - added more control of expanding control structures
96 # - finish tr/// changes
97 # - add option for even more parens (generalize \&foo change)
98 # - left/right context
99 # - treat top-level block specially for incremental output
100 # - copy comments (look at real text with $^P?)
101 # - avoid semis in one-statement blocks
102 # - associativity of &&=, ||=, ?:
103 # - ',' => '=>' (auto-unquote?)
104 # - break long lines ("\r" as discretionary break?)
105 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
106 # - more style options: brace style, hex vs. octal, quotes, ...
107 # - print big ints as hex/octal instead of decimal (heuristic?)
108 # - handle `my $x if 0'?
109 # - coordinate with Data::Dumper (both directions? see previous)
110 # - version using op_next instead of op_first/sibling?
111 # - avoid string copies (pass arrays, one big join?)
114 # Tests that will always fail:
115 # comp/redef.t -- all (redefinition happens at compile time)
117 # Object fields (were globals):
120 # (local($a), local($b)) and local($a, $b) have the same internal
121 # representation but the short form looks better. We notice we can
122 # use a large-scale local when checking the list, but need to prevent
123 # individual locals too. This hash holds the addresses of OPs that
124 # have already had their local-ness accounted for. The same thing
128 # CV for current sub (or main program) being deparsed
131 # Cached hash of lexical variables for curcv: keys are names,
132 # each value is an array of pairs, indicating the cop_seq of scopes
133 # in which a var of that name is valid.
136 # COP for statement being deparsed
139 # name of the current package for deparsed code
142 # array of [cop_seq, CV, is_format?] for subs and formats we still
146 # as above, but [name, prototype] for subs that never got a GV
148 # subs_done, forms_done:
149 # keys are addresses of GVs for subs and formats we've already
150 # deparsed (or at least put into subs_todo)
153 # keys are names of subs for which we've printed declarations.
154 # That means we can omit parentheses from the arguments.
159 # cuddle: ` ' or `\n', depending on -sC
164 # A little explanation of how precedence contexts and associativity
167 # deparse() calls each per-op subroutine with an argument $cx (short
168 # for context, but not the same as the cx* in the perl core), which is
169 # a number describing the op's parents in terms of precedence, whether
170 # they're inside an expression or at statement level, etc. (see
171 # chart below). When ops with children call deparse on them, they pass
172 # along their precedence. Fractional values are used to implement
173 # associativity (`($x + $y) + $z' => `$x + $y + $y') and related
174 # parentheses hacks. The major disadvantage of this scheme is that
175 # it doesn't know about right sides and left sides, so say if you
176 # assign a listop to a variable, it can't tell it's allowed to leave
177 # the parens off the listop.
180 # 26 [TODO] inside interpolation context ("")
181 # 25 left terms and list operators (leftward)
185 # 21 right ! ~ \ and unary + and -
190 # 16 nonassoc named unary operators
191 # 15 nonassoc < > <= >= lt gt le ge
192 # 14 nonassoc == != <=> eq ne cmp
199 # 7 right = += -= *= etc.
201 # 5 nonassoc list operators (rightward)
205 # 1 statement modifiers
208 # Nonprinting characters with special meaning:
209 # \cS - steal parens (see maybe_parens_unop)
210 # \n - newline and indent
211 # \t - increase indent
212 # \b - decrease indent (`outdent')
213 # \f - flush left (no indent)
214 # \cK - kill following semicolon, if any
218 return class($op) eq "NULL";
223 my($cv, $is_form) = @_;
224 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
226 if (!null($cv->START) and is_state($cv->START)) {
227 $seq = $cv->START->cop_seq;
231 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
236 my $ent = shift @{$self->{'subs_todo'}};
239 my $name = $self->gv_name($gv);
241 return "format $name =\n"
242 . $self->deparse_format($ent->[1]). "\n";
244 $self->{'subs_declared'}{$name} = 1;
245 if ($name eq "BEGIN") {
246 my $use_dec = $self->begin_is_use($cv);
247 if (defined ($use_dec)) {
248 return () if 0 == length($use_dec);
253 if ($self->{'linenums'}) {
254 my $line = $gv->LINE;
255 my $file = $gv->FILE;
256 $l = "\n\f#line $line \"$file\"\n";
258 return "${l}sub $name " . $self->deparse_sub($cv);
262 # Return a "use" declaration for this BEGIN block, if appropriate
264 my ($self, $cv) = @_;
265 my $root = $cv->ROOT;
267 #B::walkoptree($cv->ROOT, "debug");
268 my $lineseq = $root->first;
269 return if $lineseq->name ne "lineseq";
271 my $req_op = $lineseq->first->sibling;
272 return if $req_op->name ne "require";
275 if ($req_op->first->private & OPpCONST_BARE) {
276 # Actually it should always be a bareword
277 $module = $self->const_sv($req_op->first)->PV;
278 $module =~ s[/][::]g;
282 $module = const($self->const_sv($req_op->first));
286 my $version_op = $req_op->sibling;
287 return if class($version_op) eq "NULL";
288 if ($version_op->name eq "lineseq") {
289 # We have a version parameter; skip nextstate & pushmark
290 my $constop = $version_op->first->next->next;
292 return unless $self->const_sv($constop)->PV eq $module;
293 $constop = $constop->sibling;
295 $version = $self->const_sv($constop)->int_value;
296 $constop = $constop->sibling;
297 return if $constop->name ne "method_named";
298 return if $self->const_sv($constop)->PV ne "VERSION";
301 $lineseq = $version_op->sibling;
302 return if $lineseq->name ne "lineseq";
303 my $entersub = $lineseq->first->sibling;
304 if ($entersub->name eq "stub") {
305 return "use $module $version ();\n" if defined $version;
306 return "use $module ();\n";
308 return if $entersub->name ne "entersub";
310 # See if there are import arguments
313 my $constop = $entersub->first->sibling; # Skip over pushmark
314 return unless $self->const_sv($constop)->PV eq $module;
316 # Pull out the arguments
317 for ($constop=$constop->sibling; $constop->name eq "const";
318 $constop = $constop->sibling) {
319 $args .= ", " if length($args);
320 $args .= $self->deparse($constop, 6);
324 my $method_named = $constop;
325 return if $method_named->name ne "method_named";
326 my $method_name = $self->const_sv($method_named)->PV;
328 if ($method_name eq "unimport") {
332 # Certain pragmas are dealt with using hint bits,
333 # so we ignore them here
334 if ($module eq 'strict' || $module eq 'integer'
335 || $module eq 'bytes' || $module eq 'warnings') {
339 if (defined $version && length $args) {
340 return "$use $module $version ($args);\n";
341 } elsif (defined $version) {
342 return "$use $module $version;\n";
343 } elsif (length $args) {
344 return "$use $module ($args);\n";
346 return "$use $module;\n";
351 my ($self, $pack) = @_;
353 if (!defined $pack) {
358 $pack =~ s/(::)?$/::/;
362 my %stash = svref_2object($stash)->ARRAY;
363 while (my ($key, $val) = each %stash) {
364 next if $key eq 'main::'; # avoid infinite recursion
365 my $class = class($val);
366 if ($class eq "PV") {
367 # Just a prototype. As an ugly but fairly effective way
368 # to find out if it belongs here is to see if the AUTOLOAD
369 # (if any) for the stash was defined in one of our files.
370 my $A = $stash{"AUTOLOAD"};
371 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
372 && class($A->CV) eq "CV") {
374 next unless $AF eq $0 || exists $self->{'files'}{$AF};
376 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
377 } elsif ($class eq "IV") {
378 # Just a name. As above.
379 my $A = $stash{"AUTOLOAD"};
380 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
381 && class($A->CV) eq "CV") {
383 next unless $AF eq $0 || exists $self->{'files'}{$AF};
385 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
386 } elsif ($class eq "GV") {
387 if (class(my $cv = $val->CV) ne "SPECIAL") {
388 next if $self->{'subs_done'}{$$val}++;
389 next if $$val != ${$cv->GV}; # Ignore imposters
392 if (class(my $cv = $val->FORM) ne "SPECIAL") {
393 next if $self->{'forms_done'}{$$val}++;
394 next if $$val != ${$cv->GV}; # Ignore imposters
397 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
398 $self->stash_subs($pack . $key);
408 foreach $ar (@{$self->{'protos_todo'}}) {
409 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
410 push @ret, "sub " . $ar->[0] . "$proto;\n";
412 delete $self->{'protos_todo'};
420 while (length($opt = substr($opts, 0, 1))) {
422 $self->{'cuddle'} = " ";
423 $opts = substr($opts, 1);
424 } elsif ($opt eq "i") {
425 $opts =~ s/^i(\d+)//;
426 $self->{'indent_size'} = $1;
427 } elsif ($opt eq "T") {
428 $self->{'use_tabs'} = 1;
429 $opts = substr($opts, 1);
430 } elsif ($opt eq "v") {
431 $opts =~ s/^v([^.]*)(.|$)//;
432 $self->{'ex_const'} = $1;
439 my $self = bless {}, $class;
440 $self->{'subs_todo'} = [];
441 $self->{'files'} = {};
442 $self->{'curstash'} = "main";
443 $self->{'curcop'} = undef;
444 $self->{'cuddle'} = "\n";
445 $self->{'indent_size'} = 4;
446 $self->{'use_tabs'} = 0;
447 $self->{'expand'} = 0;
448 $self->{'unquote'} = 0;
449 $self->{'linenums'} = 0;
450 $self->{'parens'} = 0;
451 $self->{'ex_const'} = "'???'";
453 $self->{'ambient_arybase'} = 0;
454 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
455 $self->{'ambient_hints'} = 0;
458 while (my $arg = shift @_) {
459 if ($arg =~ /^-f(.*)/) {
460 $self->{'files'}{$1} = 1;
461 } elsif ($arg eq "-p") {
462 $self->{'parens'} = 1;
463 } elsif ($arg eq "-l") {
464 $self->{'linenums'} = 1;
465 } elsif ($arg eq "-q") {
466 $self->{'unquote'} = 1;
467 } elsif (substr($arg, 0, 2) eq "-s") {
468 $self->style_opts(substr $arg, 2);
469 } elsif ($arg =~ /^-x(\d)$/) {
470 $self->{'expand'} = $1;
477 # Mask out the bits that C<use vars> uses
478 $warnings::Bits{all} | $warnings::DeadBits{all};
481 # Initialise the contextual information, either from
482 # defaults provided with the ambient_pragmas method,
483 # or from perl's own defaults otherwise.
487 $self->{'arybase'} = $self->{'ambient_arybase'};
488 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
489 ? $self->{'ambient_warnings'} & WARN_MASK
491 $self->{'hints'} = $self->{'ambient_hints'} & 0xFF;
493 # also a convenient place to clear out subs_declared
494 delete $self->{'subs_declared'};
500 my $self = B::Deparse->new(@args);
501 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
502 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
503 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
504 for my $block (@BEGINs, @INITs, @ENDs) {
505 $self->todo($block, 0);
508 $self->{'curcv'} = main_cv;
509 $self->{'curcvlex'} = undef;
510 print $self->print_protos;
511 @{$self->{'subs_todo'}} =
512 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
513 print $self->indent($self->deparse(main_root, 0)), "\n"
514 unless null main_root;
516 while (scalar(@{$self->{'subs_todo'}})) {
517 push @text, $self->next_todo;
519 print $self->indent(join("", @text)), "\n" if @text;
521 # Print __DATA__ section, if necessary
523 if (defined *{$self->{'curstash'}."::DATA"}{IO}) {
525 print readline(*{$self->{'curstash'}."::DATA"});
533 croak "Usage: ->coderef2text(CODEREF)" unless ref($sub) eq "CODE";
536 return $self->indent($self->deparse_sub(svref_2object($sub)));
539 sub ambient_pragmas {
541 my ($arybase, $hint_bits, $warning_bits) = (0, 0);
547 if ($name eq 'strict') {
550 if ($val eq 'none') {
551 $hint_bits &= ~strict::bits(qw/refs subs vars/);
557 @names = qw/refs subs vars/;
563 @names = split' ', $val;
565 $hint_bits |= strict::bits(@names);
568 elsif ($name eq '$[') {
572 elsif ($name eq 'integer'
574 || $name eq 'utf8') {
577 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
580 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
584 elsif ($name eq 're') {
586 if ($val eq 'none') {
587 $hint_bits &= ~re::bits(qw/taint eval asciirange/);
593 @names = qw/taint eval asciirange/;
599 @names = split' ',$val;
601 $hint_bits |= re::bits(@names);
604 elsif ($name eq 'warnings') {
605 if ($val eq 'none') {
606 $warning_bits = "\0"x12;
615 @names = split/\s+/, $val;
618 $warning_bits = "\0"x12 if !defined ($warning_bits);
619 $warning_bits |= warnings::bits(@names);
622 elsif ($name eq 'warning_bits') {
623 $warning_bits = $val;
626 elsif ($name eq 'hint_bits') {
631 croak "Unknown pragma type: $name";
635 croak "The ambient_pragmas method expects an even number of args";
638 $self->{'ambient_arybase'} = $arybase;
639 $self->{'ambient_warnings'} = $warning_bits;
640 $self->{'ambient_hints'} = $hint_bits;
647 Carp::confess("Null op in deparse") if !defined($op)
648 || class($op) eq "NULL";
649 my $meth = "pp_" . $op->name;
650 return $self->$meth($op, $cx);
656 my @lines = split(/\n/, $txt);
661 my $cmd = substr($line, 0, 1);
662 if ($cmd eq "\t" or $cmd eq "\b") {
663 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
664 if ($self->{'use_tabs'}) {
665 $leader = "\t" x ($level / 8) . " " x ($level % 8);
667 $leader = " " x $level;
669 $line = substr($line, 1);
671 if (substr($line, 0, 1) eq "\f") {
672 $line = substr($line, 1); # no indent
674 $line = $leader . $line;
678 return join("\n", @lines);
685 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
686 local $self->{'curcop'} = $self->{'curcop'};
687 if ($cv->FLAGS & SVf_POK) {
688 $proto = "(". $cv->PV . ") ";
690 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
692 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
693 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
694 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
697 local($self->{'curcv'}) = $cv;
698 local($self->{'curcvlex'});
699 local(@$self{qw'curstash warnings hints'})
700 = @$self{qw'curstash warnings hints'};
701 if (not null $cv->ROOT) {
703 return $proto . "{\n\t" .
704 $self->deparse($cv->ROOT->first, 0) . "\n\b}\n";
706 my $sv = $cv->const_sv;
708 # uh-oh. inlinable sub... format it differently
709 return $proto . "{ " . const($sv) . " }\n";
710 } else { # XSUB? (or just a declaration)
719 local($self->{'curcv'}) = $form;
720 local($self->{'curcvlex'});
721 local(@$self{qw'curstash warnings hints'})
722 = @$self{'curstash warnings hints'};
723 my $op = $form->ROOT;
725 $op = $op->first->first; # skip leavewrite, lineseq
726 while (not null $op) {
727 $op = $op->sibling; # skip nextstate
729 $kid = $op->first->sibling; # skip pushmark
730 push @text, "\f".$self->const_sv($kid)->PV;
731 $kid = $kid->sibling;
732 for (; not null $kid; $kid = $kid->sibling) {
733 push @exprs, $self->deparse($kid, 0);
735 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
738 return join("", @text) . "\f.";
743 return $op->name eq "leave" || $op->name eq "scope"
744 || $op->name eq "lineseq"
745 || ($op->name eq "null" && class($op) eq "UNOP"
746 && (is_scope($op->first) || $op->first->name eq "enter"));
750 my $name = $_[0]->name;
751 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
754 sub is_miniwhile { # check for one-line loop (`foo() while $y--')
756 return (!null($op) and null($op->sibling)
757 and $op->name eq "null" and class($op) eq "UNOP"
758 and (($op->first->name =~ /^(and|or)$/
759 and $op->first->first->sibling->name eq "lineseq")
760 or ($op->first->name eq "lineseq"
761 and not null $op->first->first->sibling
762 and $op->first->first->sibling->name eq "unstack")
768 return ($op->name eq "rv2sv" or
769 $op->name eq "padsv" or
770 $op->name eq "gv" or # only in array/hash constructs
771 $op->flags & OPf_KIDS && !null($op->first)
772 && $op->first->name eq "gvsv");
777 my($text, $cx, $prec) = @_;
778 if ($prec < $cx # unary ops nest just fine
779 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
780 or $self->{'parens'})
783 # In a unop, let parent reuse our parens; see maybe_parens_unop
784 $text = "\cS" . $text if $cx == 16;
791 # same as above, but get around the `if it looks like a function' rule
792 sub maybe_parens_unop {
794 my($name, $kid, $cx) = @_;
795 if ($cx > 16 or $self->{'parens'}) {
796 $kid = $self->deparse($kid, 1);
797 if ($name eq "umask" && $kid =~ /^\d+$/) {
798 $kid = sprintf("%#o", $kid);
800 return "$name($kid)";
802 $kid = $self->deparse($kid, 16);
803 if ($name eq "umask" && $kid =~ /^\d+$/) {
804 $kid = sprintf("%#o", $kid);
806 if (substr($kid, 0, 1) eq "\cS") {
808 return $name . substr($kid, 1);
809 } elsif (substr($kid, 0, 1) eq "(") {
810 # avoid looks-like-a-function trap with extra parens
811 # (`+' can lead to ambiguities)
812 return "$name(" . $kid . ")";
819 sub maybe_parens_func {
821 my($func, $text, $cx, $prec) = @_;
822 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
823 return "$func($text)";
825 return "$func $text";
831 my($op, $cx, $text) = @_;
832 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
833 if (want_scalar($op)) {
834 return "local $text";
836 return $self->maybe_parens_func("local", $text, $cx, 16);
845 my($op, $cx, $func, @args) = @_;
846 if ($op->private & OPpTARGET_MY) {
847 my $var = $self->padname($op->targ);
848 my $val = $func->($self, $op, 7, @args);
849 return $self->maybe_parens("$var = $val", $cx, 7);
851 return $func->($self, $op, $cx, @args);
858 return (($self->{'curcv'}->PADLIST->ARRAY)[0]->ARRAY)[$targ];
863 my($op, $cx, $text) = @_;
864 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
865 if (want_scalar($op)) {
868 return $self->maybe_parens_func("my", $text, $cx, 16);
875 # The following OPs don't have functions:
877 # pp_padany -- does not exist after parsing
878 # pp_rcatline -- does not exist
880 sub pp_enter { # see also leave
881 cluck "unexpected OP_ENTER";
885 sub pp_pushmark { # see also list
886 cluck "unexpected OP_PUSHMARK";
890 sub pp_leavesub { # see also deparse_sub
891 cluck "unexpected OP_LEAVESUB";
895 sub pp_leavewrite { # see also deparse_format
896 cluck "unexpected OP_LEAVEWRITE";
900 sub pp_method { # see also entersub
901 cluck "unexpected OP_METHOD";
905 sub pp_regcmaybe { # see also regcomp
906 cluck "unexpected OP_REGCMAYBE";
910 sub pp_regcreset { # see also regcomp
911 cluck "unexpected OP_REGCRESET";
915 sub pp_substcont { # see also subst
916 cluck "unexpected OP_SUBSTCONT";
920 sub pp_grepstart { # see also grepwhile
921 cluck "unexpected OP_GREPSTART";
925 sub pp_mapstart { # see also mapwhile
926 cluck "unexpected OP_MAPSTART";
930 sub pp_flip { # see also flop
931 cluck "unexpected OP_FLIP";
935 sub pp_iter { # see also leaveloop
936 cluck "unexpected OP_ITER";
940 sub pp_enteriter { # see also leaveloop
941 cluck "unexpected OP_ENTERITER";
945 sub pp_enterloop { # see also leaveloop
946 cluck "unexpected OP_ENTERLOOP";
950 sub pp_leaveeval { # see also entereval
951 cluck "unexpected OP_LEAVEEVAL";
955 sub pp_entertry { # see also leavetry
956 cluck "unexpected OP_ENTERTRY";
964 for (my $i = 0; $i < @ops; $i++) {
966 if (is_state $ops[$i]) {
967 $expr = $self->deparse($ops[$i], 0);
974 if (!is_state $ops[$i] and $ops[$i+1] and !null($ops[$i+1]) and
975 $ops[$i+1]->name eq "leaveloop" and $self->{'expand'} < 3)
977 push @exprs, $expr . $self->for_loop($ops[$i], 0);
981 $expr .= $self->deparse($ops[$i], 0);
985 return join(";\n", grep {length} @exprs);
989 my($real_block, $self, $op, $cx) = @_;
993 local(@$self{qw'curstash warnings hints'})
994 = @$self{qw'curstash warnings hints'} if $real_block;
996 $kid = $op->first->sibling; # skip enter
997 if (is_miniwhile($kid)) {
998 my $top = $kid->first;
999 my $name = $top->name;
1000 if ($name eq "and") {
1002 } elsif ($name eq "or") {
1004 } else { # no conditional -> while 1 or until 0
1005 return $self->deparse($top->first, 1) . " while 1";
1007 my $cond = $top->first;
1008 my $body = $cond->sibling->first; # skip lineseq
1009 $cond = $self->deparse($cond, 1);
1010 $body = $self->deparse($body, 1);
1011 return "$body $name $cond";
1016 for (; !null($kid); $kid = $kid->sibling) {
1019 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1020 return "do { " . $self->lineseq(@kids) . " }";
1022 my $lineseq = $self->lineseq(@kids);
1023 return (length ($lineseq) ? "$lineseq;" : "");
1028 my $caller = (caller(2))[3];
1029 if ($caller eq "B::Deparse::deparse") {
1030 return (caller(3))[3];
1038 my ($self, $op, $cx) = @_;
1039 my $body = scopeop(0, @_);
1040 return $body if $cx > 0 || invoker() ne "B::Deparse::lineseq";
1041 return "do {\n\t$body\n\b};";
1043 sub pp_lineseq { scopeop(0, @_); }
1044 sub pp_leave { scopeop(1, @_); }
1046 # The BEGIN {} is used here because otherwise this code isn't executed
1047 # when you run B::Deparse on itself.
1049 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1050 "ENV", "ARGV", "ARGVOUT", "_"); }
1055 Carp::confess() if $gv->isa("B::CV");
1056 my $stash = $gv->STASH->NAME;
1057 my $name = $gv->SAFENAME;
1058 if ($stash eq $self->{'curstash'} or $globalnames{$name}
1059 or $name =~ /^[^A-Za-z_]/)
1063 $stash = $stash . "::";
1065 if ($name =~ /^\^../) {
1066 $name = "{$name}"; # ${^WARNING_BITS} etc
1068 return $stash . $name;
1071 # Return the name to use for a stash variable.
1072 # If a lexical with the same name is in scope, it may need to be
1074 sub stash_variable {
1075 my ($self, $prefix, $name) = @_;
1077 return "$prefix$name" if $name =~ /::/;
1079 unless ($prefix eq '$' || $prefix eq '@' ||
1080 $prefix eq '%' || $prefix eq '$#') {
1081 return "$prefix$name";
1084 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1085 return $prefix .$self->{'curstash'}.'::'. $name if $self->lex_in_scope($v);
1086 return "$prefix$name";
1090 my ($self, $name) = @_;
1091 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1093 my $seq = $self->{'curcop'}->cop_seq;
1094 return 0 if !exists $self->{'curcvlex'}{$name};
1095 for my $a (@{$self->{'curcvlex'}{$name}}) {
1096 my ($st, $en) = @$a;
1097 return 1 if $seq > $st && $seq <= $en;
1102 sub populate_curcvlex {
1104 for (my $cv = $self->{'curcv'}; $$cv; $cv = $cv->OUTSIDE) {
1105 my @padlist = $cv->PADLIST->ARRAY;
1106 my @ns = $padlist[0]->ARRAY;
1108 for (my $i=0; $i<@ns; ++$i) {
1109 next if class($ns[$i]) eq "SPECIAL";
1110 if (class($ns[$i]) eq "PV") {
1111 # Probably that pesky lexical @_
1114 my $name = $ns[$i]->PVX;
1115 my $seq_st = $ns[$i]->NVX;
1116 my $seq_en = int($ns[$i]->IVX);
1118 push @{$self->{'curcvlex'}{$name}}, [$seq_st, $seq_en];
1123 # Recurses down the tree, looking for a COP
1125 my ($self, $op) = @_;
1126 if ($op->flags & OPf_KIDS) {
1127 for (my $o=$op->first; $$o; $o=$o->sibling) {
1128 return $o if is_state($o);
1129 my $r = $self->find_cop($o);
1130 return $r if defined $r;
1136 # Returns a list of subs which should be inserted before the COP
1138 my ($self, $op, $out_seq) = @_;
1139 my $seq = $op->cop_seq;
1140 # If we have nephews, then our sequence number indicates
1141 # the cop_seq of the end of some sort of scope.
1142 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1143 and my $ncop = $self->find_cop($op->sibling)) {
1144 $seq = $ncop->cop_seq;
1146 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1147 return $self->seq_subs($seq);
1151 my ($self, $seq) = @_;
1153 #push @text, "# ($seq)\n";
1155 while (scalar(@{$self->{'subs_todo'}})
1156 and $seq > $self->{'subs_todo'}[0][0]) {
1157 push @text, $self->next_todo;
1162 # Notice how subs and formats are inserted between statements here;
1163 # also $[ assignments and pragmas.
1167 $self->{'curcop'} = $op;
1169 #push @text, "# ", $op->cop_seq, "\n";
1170 push @text, $self->cop_subs($op);
1171 push @text, $op->label . ": " if $op->label;
1172 my $stash = $op->stashpv;
1173 if ($stash ne $self->{'curstash'}) {
1174 push @text, "package $stash;\n";
1175 $self->{'curstash'} = $stash;
1177 if ($self->{'linenums'}) {
1178 push @text, "\f#line " . $op->line .
1179 ' "' . $op->file, qq'"\n';
1182 if ($self->{'arybase'} != $op->arybase) {
1183 push @text, '$[ = '. $op->arybase .";\n";
1184 $self->{'arybase'} = $op->arybase;
1187 my $warnings = $op->warnings;
1189 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1190 $warning_bits = $warnings::Bits{"all"};
1192 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1193 $warning_bits = "\0"x12;
1195 elsif ($warnings->isa("B::SPECIAL")) {
1196 $warning_bits = undef;
1199 $warning_bits = $warnings->PV & WARN_MASK;
1202 if (defined ($warning_bits) and
1203 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1204 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1205 $self->{'warnings'} = $warning_bits;
1208 if ($self->{'hints'} != $op->private) {
1209 push @text, declare_hints($self->{'hints'}, $op->private);
1210 $self->{'hints'} = $op->private;
1213 return join("", @text);
1216 sub declare_warnings {
1217 my ($from, $to) = @_;
1218 if ($to eq warnings::bits("all")) {
1219 return "use warnings;\n";
1221 elsif ($to eq "\0"x12) {
1222 return "no warnings;\n";
1224 return "BEGIN {\${^WARNING_BITS} = ".cstring($to)."}\n";
1228 my ($from, $to) = @_;
1229 my $use = $to & ~$from;
1230 my $no = $from & ~$to;
1232 for my $pragma (hint_pragmas($use)) {
1233 $decls .= "use $pragma;\n";
1235 for my $pragma (hint_pragmas($no)) {
1236 $decls .= "no $pragma;\n";
1244 push @pragmas, "integer" if $bits & 0x1;
1245 push @pragmas, "strict 'refs'" if $bits & 0x2;
1246 push @pragmas, "bytes" if $bits & 0x8;
1250 sub pp_dbstate { pp_nextstate(@_) }
1251 sub pp_setstate { pp_nextstate(@_) }
1253 sub pp_unstack { return "" } # see also leaveloop
1257 my($op, $cx, $name) = @_;
1263 my($op, $cx, $name) = @_;
1271 sub pp_wantarray { baseop(@_, "wantarray") }
1272 sub pp_fork { baseop(@_, "fork") }
1273 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1274 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1275 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1276 sub pp_tms { baseop(@_, "times") }
1277 sub pp_ghostent { baseop(@_, "gethostent") }
1278 sub pp_gnetent { baseop(@_, "getnetent") }
1279 sub pp_gprotoent { baseop(@_, "getprotoent") }
1280 sub pp_gservent { baseop(@_, "getservent") }
1281 sub pp_ehostent { baseop(@_, "endhostent") }
1282 sub pp_enetent { baseop(@_, "endnetent") }
1283 sub pp_eprotoent { baseop(@_, "endprotoent") }
1284 sub pp_eservent { baseop(@_, "endservent") }
1285 sub pp_gpwent { baseop(@_, "getpwent") }
1286 sub pp_spwent { baseop(@_, "setpwent") }
1287 sub pp_epwent { baseop(@_, "endpwent") }
1288 sub pp_ggrent { baseop(@_, "getgrent") }
1289 sub pp_sgrent { baseop(@_, "setgrent") }
1290 sub pp_egrent { baseop(@_, "endgrent") }
1291 sub pp_getlogin { baseop(@_, "getlogin") }
1293 sub POSTFIX () { 1 }
1295 # I couldn't think of a good short name, but this is the category of
1296 # symbolic unary operators with interesting precedence
1300 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1301 my $kid = $op->first;
1302 $kid = $self->deparse($kid, $prec);
1303 return $self->maybe_parens(($flags & POSTFIX) ? "$kid$name" : "$name$kid",
1307 sub pp_preinc { pfixop(@_, "++", 23) }
1308 sub pp_predec { pfixop(@_, "--", 23) }
1309 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1310 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1311 sub pp_i_preinc { pfixop(@_, "++", 23) }
1312 sub pp_i_predec { pfixop(@_, "--", 23) }
1313 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1314 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1315 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1317 sub pp_negate { maybe_targmy(@_, \&real_negate) }
1321 if ($op->first->name =~ /^(i_)?negate$/) {
1323 $self->pfixop($op, $cx, "-", 21.5);
1325 $self->pfixop($op, $cx, "-", 21);
1328 sub pp_i_negate { pp_negate(@_) }
1334 $self->pfixop($op, $cx, "not ", 4);
1336 $self->pfixop($op, $cx, "!", 21);
1342 my($op, $cx, $name) = @_;
1344 if ($op->flags & OPf_KIDS) {
1346 if (defined prototype("CORE::$name")
1347 && prototype("CORE::$name") =~ /^;?\*/
1348 && $kid->name eq "rv2gv") {
1352 return $self->maybe_parens_unop($name, $kid, $cx);
1354 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
1358 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1359 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1360 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1361 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1362 sub pp_defined { unop(@_, "defined") }
1363 sub pp_undef { unop(@_, "undef") }
1364 sub pp_study { unop(@_, "study") }
1365 sub pp_ref { unop(@_, "ref") }
1366 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1368 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1369 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1370 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1371 sub pp_srand { unop(@_, "srand") }
1372 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1373 sub pp_log { maybe_targmy(@_, \&unop, "log") }
1374 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1375 sub pp_int { maybe_targmy(@_, \&unop, "int") }
1376 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1377 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1378 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1380 sub pp_length { maybe_targmy(@_, \&unop, "length") }
1381 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1382 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1384 sub pp_each { unop(@_, "each") }
1385 sub pp_values { unop(@_, "values") }
1386 sub pp_keys { unop(@_, "keys") }
1387 sub pp_pop { unop(@_, "pop") }
1388 sub pp_shift { unop(@_, "shift") }
1390 sub pp_caller { unop(@_, "caller") }
1391 sub pp_reset { unop(@_, "reset") }
1392 sub pp_exit { unop(@_, "exit") }
1393 sub pp_prototype { unop(@_, "prototype") }
1395 sub pp_close { unop(@_, "close") }
1396 sub pp_fileno { unop(@_, "fileno") }
1397 sub pp_umask { unop(@_, "umask") }
1398 sub pp_untie { unop(@_, "untie") }
1399 sub pp_tied { unop(@_, "tied") }
1400 sub pp_dbmclose { unop(@_, "dbmclose") }
1401 sub pp_getc { unop(@_, "getc") }
1402 sub pp_eof { unop(@_, "eof") }
1403 sub pp_tell { unop(@_, "tell") }
1404 sub pp_getsockname { unop(@_, "getsockname") }
1405 sub pp_getpeername { unop(@_, "getpeername") }
1407 sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1408 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1409 sub pp_readlink { unop(@_, "readlink") }
1410 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1411 sub pp_readdir { unop(@_, "readdir") }
1412 sub pp_telldir { unop(@_, "telldir") }
1413 sub pp_rewinddir { unop(@_, "rewinddir") }
1414 sub pp_closedir { unop(@_, "closedir") }
1415 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1416 sub pp_localtime { unop(@_, "localtime") }
1417 sub pp_gmtime { unop(@_, "gmtime") }
1418 sub pp_alarm { unop(@_, "alarm") }
1419 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1421 sub pp_dofile { unop(@_, "do") }
1422 sub pp_entereval { unop(@_, "eval") }
1424 sub pp_ghbyname { unop(@_, "gethostbyname") }
1425 sub pp_gnbyname { unop(@_, "getnetbyname") }
1426 sub pp_gpbyname { unop(@_, "getprotobyname") }
1427 sub pp_shostent { unop(@_, "sethostent") }
1428 sub pp_snetent { unop(@_, "setnetent") }
1429 sub pp_sprotoent { unop(@_, "setprotoent") }
1430 sub pp_sservent { unop(@_, "setservent") }
1431 sub pp_gpwnam { unop(@_, "getpwnam") }
1432 sub pp_gpwuid { unop(@_, "getpwuid") }
1433 sub pp_ggrnam { unop(@_, "getgrnam") }
1434 sub pp_ggrgid { unop(@_, "getgrgid") }
1436 sub pp_lock { unop(@_, "lock") }
1442 if ($op->private & OPpEXISTS_SUB) {
1443 # Checking for the existence of a subroutine
1444 return $self->maybe_parens_func("exists",
1445 $self->pp_rv2cv($op->first, 16), $cx, 16);
1447 if ($op->flags & OPf_SPECIAL) {
1448 # Array element, not hash element
1449 return $self->maybe_parens_func("exists",
1450 $self->pp_aelem($op->first, 16), $cx, 16);
1452 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1460 if ($op->private & OPpSLICE) {
1461 if ($op->flags & OPf_SPECIAL) {
1462 # Deleting from an array, not a hash
1463 return $self->maybe_parens_func("delete",
1464 $self->pp_aslice($op->first, 16),
1467 return $self->maybe_parens_func("delete",
1468 $self->pp_hslice($op->first, 16),
1471 if ($op->flags & OPf_SPECIAL) {
1472 # Deleting from an array, not a hash
1473 return $self->maybe_parens_func("delete",
1474 $self->pp_aelem($op->first, 16),
1477 return $self->maybe_parens_func("delete",
1478 $self->pp_helem($op->first, 16),
1486 if (class($op) eq "UNOP" and $op->first->name eq "const"
1487 and $op->first->private & OPpCONST_BARE)
1489 my $name = $self->const_sv($op->first)->PV;
1492 return "require $name";
1494 $self->unop($op, $cx, "require");
1501 my $kid = $op->first;
1502 if (not null $kid->sibling) {
1503 # XXX Was a here-doc
1504 return $self->dquote($op);
1506 $self->unop(@_, "scalar");
1513 #cluck "curcv was undef" unless $self->{curcv};
1514 return (($self->{'curcv'}->PADLIST->ARRAY)[1]->ARRAY)[$targ];
1520 my $kid = $op->first;
1521 if ($kid->name eq "null") {
1523 if ($kid->name eq "anonlist" || $kid->name eq "anonhash") {
1524 my($pre, $post) = @{{"anonlist" => ["[","]"],
1525 "anonhash" => ["{","}"]}->{$kid->name}};
1527 $kid = $kid->first->sibling; # skip pushmark
1528 for (; !null($kid); $kid = $kid->sibling) {
1529 $expr = $self->deparse($kid, 6);
1532 return $pre . join(", ", @exprs) . $post;
1533 } elsif (!null($kid->sibling) and
1534 $kid->sibling->name eq "anoncode") {
1536 $self->deparse_sub($self->padval($kid->sibling->targ));
1537 } elsif ($kid->name eq "pushmark") {
1538 my $sib_name = $kid->sibling->name;
1539 if ($sib_name =~ /^(pad|rv2)[ah]v$/
1540 and not $kid->sibling->flags & OPf_REF)
1542 # The @a in \(@a) isn't in ref context, but only when the
1544 return "\\(" . $self->deparse($kid->sibling, 1) . ")";
1545 } elsif ($sib_name eq 'entersub') {
1546 my $text = $self->deparse($kid->sibling, 1);
1547 # Always show parens for \(&func()), but only with -p otherwise
1548 $text = "($text)" if $self->{'parens'}
1549 or $kid->sibling->private & OPpENTERSUB_AMPER;
1554 $self->pfixop($op, $cx, "\\", 20);
1557 sub pp_srefgen { pp_refgen(@_) }
1562 my $kid = $op->first;
1563 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
1564 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
1565 return $self->unop($op, $cx, "readline");
1568 # Unary operators that can occur as pseudo-listops inside double quotes
1571 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
1573 if ($op->flags & OPf_KIDS) {
1575 # If there's more than one kid, the first is an ex-pushmark.
1576 $kid = $kid->sibling if not null $kid->sibling;
1577 return $self->maybe_parens_unop($name, $kid, $cx);
1579 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
1583 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
1584 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
1585 sub pp_uc { dq_unop(@_, "uc") }
1586 sub pp_lc { dq_unop(@_, "lc") }
1587 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
1591 my ($op, $cx, $name) = @_;
1592 if (class($op) eq "PVOP") {
1593 return "$name " . $op->pv;
1594 } elsif (class($op) eq "OP") {
1596 } elsif (class($op) eq "UNOP") {
1597 # Note -- loop exits are actually exempt from the
1598 # looks-like-a-func rule, but a few extra parens won't hurt
1599 return $self->maybe_parens_unop($name, $op->first, $cx);
1603 sub pp_last { loopex(@_, "last") }
1604 sub pp_next { loopex(@_, "next") }
1605 sub pp_redo { loopex(@_, "redo") }
1606 sub pp_goto { loopex(@_, "goto") }
1607 sub pp_dump { loopex(@_, "dump") }
1611 my($op, $cx, $name) = @_;
1612 if (class($op) eq "UNOP") {
1613 # Genuine `-X' filetests are exempt from the LLAFR, but not
1614 # l?stat(); for the sake of clarity, give'em all parens
1615 return $self->maybe_parens_unop($name, $op->first, $cx);
1616 } elsif (class($op) eq "SVOP") {
1617 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
1618 } else { # I don't think baseop filetests ever survive ck_ftst, but...
1623 sub pp_lstat { ftst(@_, "lstat") }
1624 sub pp_stat { ftst(@_, "stat") }
1625 sub pp_ftrread { ftst(@_, "-R") }
1626 sub pp_ftrwrite { ftst(@_, "-W") }
1627 sub pp_ftrexec { ftst(@_, "-X") }
1628 sub pp_fteread { ftst(@_, "-r") }
1629 sub pp_ftewrite { ftst(@_, "-w") }
1630 sub pp_fteexec { ftst(@_, "-x") }
1631 sub pp_ftis { ftst(@_, "-e") }
1632 sub pp_fteowned { ftst(@_, "-O") }
1633 sub pp_ftrowned { ftst(@_, "-o") }
1634 sub pp_ftzero { ftst(@_, "-z") }
1635 sub pp_ftsize { ftst(@_, "-s") }
1636 sub pp_ftmtime { ftst(@_, "-M") }
1637 sub pp_ftatime { ftst(@_, "-A") }
1638 sub pp_ftctime { ftst(@_, "-C") }
1639 sub pp_ftsock { ftst(@_, "-S") }
1640 sub pp_ftchr { ftst(@_, "-c") }
1641 sub pp_ftblk { ftst(@_, "-b") }
1642 sub pp_ftfile { ftst(@_, "-f") }
1643 sub pp_ftdir { ftst(@_, "-d") }
1644 sub pp_ftpipe { ftst(@_, "-p") }
1645 sub pp_ftlink { ftst(@_, "-l") }
1646 sub pp_ftsuid { ftst(@_, "-u") }
1647 sub pp_ftsgid { ftst(@_, "-g") }
1648 sub pp_ftsvtx { ftst(@_, "-k") }
1649 sub pp_fttty { ftst(@_, "-t") }
1650 sub pp_fttext { ftst(@_, "-T") }
1651 sub pp_ftbinary { ftst(@_, "-B") }
1653 sub SWAP_CHILDREN () { 1 }
1654 sub ASSIGN () { 2 } # has OP= variant
1655 sub LIST_CONTEXT () { 4 } # Assignment is in list context
1661 my $name = $op->name;
1662 if ($name eq "concat" and $op->first->name eq "concat") {
1663 # avoid spurious `=' -- see comment in pp_concat
1666 if ($name eq "null" and class($op) eq "UNOP"
1667 and $op->first->name =~ /^(and|x?or)$/
1668 and null $op->first->sibling)
1670 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
1671 # with a null that's used as the common end point of the two
1672 # flows of control. For precedence purposes, ignore it.
1673 # (COND_EXPRs have these too, but we don't bother with
1674 # their associativity).
1675 return assoc_class($op->first);
1677 return $name . ($op->flags & OPf_STACKED ? "=" : "");
1680 # Left associative operators, like `+', for which
1681 # $a + $b + $c is equivalent to ($a + $b) + $c
1684 %left = ('multiply' => 19, 'i_multiply' => 19,
1685 'divide' => 19, 'i_divide' => 19,
1686 'modulo' => 19, 'i_modulo' => 19,
1688 'add' => 18, 'i_add' => 18,
1689 'subtract' => 18, 'i_subtract' => 18,
1691 'left_shift' => 17, 'right_shift' => 17,
1693 'bit_or' => 12, 'bit_xor' => 12,
1695 'or' => 2, 'xor' => 2,
1699 sub deparse_binop_left {
1701 my($op, $left, $prec) = @_;
1702 if ($left{assoc_class($op)} && $left{assoc_class($left)}
1703 and $left{assoc_class($op)} == $left{assoc_class($left)})
1705 return $self->deparse($left, $prec - .00001);
1707 return $self->deparse($left, $prec);
1711 # Right associative operators, like `=', for which
1712 # $a = $b = $c is equivalent to $a = ($b = $c)
1715 %right = ('pow' => 22,
1716 'sassign=' => 7, 'aassign=' => 7,
1717 'multiply=' => 7, 'i_multiply=' => 7,
1718 'divide=' => 7, 'i_divide=' => 7,
1719 'modulo=' => 7, 'i_modulo=' => 7,
1721 'add=' => 7, 'i_add=' => 7,
1722 'subtract=' => 7, 'i_subtract=' => 7,
1724 'left_shift=' => 7, 'right_shift=' => 7,
1726 'bit_or=' => 7, 'bit_xor=' => 7,
1732 sub deparse_binop_right {
1734 my($op, $right, $prec) = @_;
1735 if ($right{assoc_class($op)} && $right{assoc_class($right)}
1736 and $right{assoc_class($op)} == $right{assoc_class($right)})
1738 return $self->deparse($right, $prec - .00001);
1740 return $self->deparse($right, $prec);
1746 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
1747 my $left = $op->first;
1748 my $right = $op->last;
1750 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
1754 if ($flags & SWAP_CHILDREN) {
1755 ($left, $right) = ($right, $left);
1757 $left = $self->deparse_binop_left($op, $left, $prec);
1758 $left = "($left)" if $flags & LIST_CONTEXT && $left =~ /^\$/;
1759 $right = $self->deparse_binop_right($op, $right, $prec);
1760 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
1763 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
1764 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
1765 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
1766 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
1767 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
1768 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
1769 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
1770 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
1771 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
1772 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
1773 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
1775 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
1776 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
1777 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
1778 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
1779 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
1781 sub pp_eq { binop(@_, "==", 14) }
1782 sub pp_ne { binop(@_, "!=", 14) }
1783 sub pp_lt { binop(@_, "<", 15) }
1784 sub pp_gt { binop(@_, ">", 15) }
1785 sub pp_ge { binop(@_, ">=", 15) }
1786 sub pp_le { binop(@_, "<=", 15) }
1787 sub pp_ncmp { binop(@_, "<=>", 14) }
1788 sub pp_i_eq { binop(@_, "==", 14) }
1789 sub pp_i_ne { binop(@_, "!=", 14) }
1790 sub pp_i_lt { binop(@_, "<", 15) }
1791 sub pp_i_gt { binop(@_, ">", 15) }
1792 sub pp_i_ge { binop(@_, ">=", 15) }
1793 sub pp_i_le { binop(@_, "<=", 15) }
1794 sub pp_i_ncmp { binop(@_, "<=>", 14) }
1796 sub pp_seq { binop(@_, "eq", 14) }
1797 sub pp_sne { binop(@_, "ne", 14) }
1798 sub pp_slt { binop(@_, "lt", 15) }
1799 sub pp_sgt { binop(@_, "gt", 15) }
1800 sub pp_sge { binop(@_, "ge", 15) }
1801 sub pp_sle { binop(@_, "le", 15) }
1802 sub pp_scmp { binop(@_, "cmp", 14) }
1804 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
1805 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
1807 # `.' is special because concats-of-concats are optimized to save copying
1808 # by making all but the first concat stacked. The effect is as if the
1809 # programmer had written `($a . $b) .= $c', except legal.
1810 sub pp_concat { maybe_targmy(@_, \&real_concat) }
1814 my $left = $op->first;
1815 my $right = $op->last;
1818 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
1822 $left = $self->deparse_binop_left($op, $left, $prec);
1823 $right = $self->deparse_binop_right($op, $right, $prec);
1824 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
1827 # `x' is weird when the left arg is a list
1831 my $left = $op->first;
1832 my $right = $op->last;
1835 if ($op->flags & OPf_STACKED) {
1839 if (null($right)) { # list repeat; count is inside left-side ex-list
1840 my $kid = $left->first->sibling; # skip pushmark
1842 for (; !null($kid->sibling); $kid = $kid->sibling) {
1843 push @exprs, $self->deparse($kid, 6);
1846 $left = "(" . join(", ", @exprs). ")";
1848 $left = $self->deparse_binop_left($op, $left, $prec);
1850 $right = $self->deparse_binop_right($op, $right, $prec);
1851 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
1856 my ($op, $cx, $type) = @_;
1857 my $left = $op->first;
1858 my $right = $left->sibling;
1859 $left = $self->deparse($left, 9);
1860 $right = $self->deparse($right, 9);
1861 return $self->maybe_parens("$left $type $right", $cx, 9);
1867 my $flip = $op->first;
1868 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
1869 return $self->range($flip->first, $cx, $type);
1872 # one-line while/until is handled in pp_leave
1876 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
1877 my $left = $op->first;
1878 my $right = $op->first->sibling;
1879 if ($cx == 0 and is_scope($right) and $blockname
1880 and $self->{'expand'} < 7)
1882 $left = $self->deparse($left, 1);
1883 $right = $self->deparse($right, 0);
1884 return "$blockname ($left) {\n\t$right\n\b}\cK";
1885 } elsif ($cx == 0 and $blockname and not $self->{'parens'}
1886 and $self->{'expand'} < 7) { # $b if $a
1887 $right = $self->deparse($right, 1);
1888 $left = $self->deparse($left, 1);
1889 return "$right $blockname $left";
1890 } elsif ($cx > $lowprec and $highop) { # $a && $b
1891 $left = $self->deparse_binop_left($op, $left, $highprec);
1892 $right = $self->deparse_binop_right($op, $right, $highprec);
1893 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
1894 } else { # $a and $b
1895 $left = $self->deparse_binop_left($op, $left, $lowprec);
1896 $right = $self->deparse_binop_right($op, $right, $lowprec);
1897 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
1901 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
1902 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
1904 # xor is syntactically a logop, but it's really a binop (contrary to
1905 # old versions of opcode.pl). Syntax is what matters here.
1906 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
1910 my ($op, $cx, $opname) = @_;
1911 my $left = $op->first;
1912 my $right = $op->first->sibling->first; # skip sassign
1913 $left = $self->deparse($left, 7);
1914 $right = $self->deparse($right, 7);
1915 return $self->maybe_parens("$left $opname $right", $cx, 7);
1918 sub pp_andassign { logassignop(@_, "&&=") }
1919 sub pp_orassign { logassignop(@_, "||=") }
1923 my($op, $cx, $name) = @_;
1925 my $parens = ($cx >= 5) || $self->{'parens'};
1926 my $kid = $op->first->sibling;
1927 return $name if null $kid;
1929 if (defined prototype("CORE::$name")
1930 && prototype("CORE::$name") =~ /^;?\*/
1931 && $kid->name eq "rv2gv") {
1932 $first = $self->deparse($kid->first, 6);
1935 $first = $self->deparse($kid, 6);
1937 if ($name eq "chmod" && $first =~ /^\d+$/) {
1938 $first = sprintf("%#o", $first);
1940 $first = "+$first" if not $parens and substr($first, 0, 1) eq "(";
1941 push @exprs, $first;
1942 $kid = $kid->sibling;
1943 for (; !null($kid); $kid = $kid->sibling) {
1944 push @exprs, $self->deparse($kid, 6);
1947 return "$name(" . join(", ", @exprs) . ")";
1949 return "$name " . join(", ", @exprs);
1953 sub pp_bless { listop(@_, "bless") }
1954 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
1955 sub pp_substr { maybe_local(@_, listop(@_, "substr")) }
1956 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
1957 sub pp_index { maybe_targmy(@_, \&listop, "index") }
1958 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
1959 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
1960 sub pp_formline { listop(@_, "formline") } # see also deparse_format
1961 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
1962 sub pp_unpack { listop(@_, "unpack") }
1963 sub pp_pack { listop(@_, "pack") }
1964 sub pp_join { maybe_targmy(@_, \&listop, "join") }
1965 sub pp_splice { listop(@_, "splice") }
1966 sub pp_push { maybe_targmy(@_, \&listop, "push") }
1967 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
1968 sub pp_reverse { listop(@_, "reverse") }
1969 sub pp_warn { listop(@_, "warn") }
1970 sub pp_die { listop(@_, "die") }
1971 # Actually, return is exempt from the LLAFR (see examples in this very
1972 # module!), but for consistency's sake, ignore that fact
1973 sub pp_return { listop(@_, "return") }
1974 sub pp_open { listop(@_, "open") }
1975 sub pp_pipe_op { listop(@_, "pipe") }
1976 sub pp_tie { listop(@_, "tie") }
1977 sub pp_binmode { listop(@_, "binmode") }
1978 sub pp_dbmopen { listop(@_, "dbmopen") }
1979 sub pp_sselect { listop(@_, "select") }
1980 sub pp_select { listop(@_, "select") }
1981 sub pp_read { listop(@_, "read") }
1982 sub pp_sysopen { listop(@_, "sysopen") }
1983 sub pp_sysseek { listop(@_, "sysseek") }
1984 sub pp_sysread { listop(@_, "sysread") }
1985 sub pp_syswrite { listop(@_, "syswrite") }
1986 sub pp_send { listop(@_, "send") }
1987 sub pp_recv { listop(@_, "recv") }
1988 sub pp_seek { listop(@_, "seek") }
1989 sub pp_fcntl { listop(@_, "fcntl") }
1990 sub pp_ioctl { listop(@_, "ioctl") }
1991 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
1992 sub pp_socket { listop(@_, "socket") }
1993 sub pp_sockpair { listop(@_, "sockpair") }
1994 sub pp_bind { listop(@_, "bind") }
1995 sub pp_connect { listop(@_, "connect") }
1996 sub pp_listen { listop(@_, "listen") }
1997 sub pp_accept { listop(@_, "accept") }
1998 sub pp_shutdown { listop(@_, "shutdown") }
1999 sub pp_gsockopt { listop(@_, "getsockopt") }
2000 sub pp_ssockopt { listop(@_, "setsockopt") }
2001 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2002 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2003 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2004 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2005 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2006 sub pp_link { maybe_targmy(@_, \&listop, "link") }
2007 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2008 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2009 sub pp_open_dir { listop(@_, "opendir") }
2010 sub pp_seekdir { listop(@_, "seekdir") }
2011 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2012 sub pp_system { maybe_targmy(@_, \&listop, "system") }
2013 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2014 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2015 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2016 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2017 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2018 sub pp_shmget { listop(@_, "shmget") }
2019 sub pp_shmctl { listop(@_, "shmctl") }
2020 sub pp_shmread { listop(@_, "shmread") }
2021 sub pp_shmwrite { listop(@_, "shmwrite") }
2022 sub pp_msgget { listop(@_, "msgget") }
2023 sub pp_msgctl { listop(@_, "msgctl") }
2024 sub pp_msgsnd { listop(@_, "msgsnd") }
2025 sub pp_msgrcv { listop(@_, "msgrcv") }
2026 sub pp_semget { listop(@_, "semget") }
2027 sub pp_semctl { listop(@_, "semctl") }
2028 sub pp_semop { listop(@_, "semop") }
2029 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2030 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2031 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2032 sub pp_gsbyname { listop(@_, "getservbyname") }
2033 sub pp_gsbyport { listop(@_, "getservbyport") }
2034 sub pp_syscall { listop(@_, "syscall") }
2039 my $text = $self->dq($op->first->sibling); # skip pushmark
2040 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2041 or $text =~ /[<>]/) {
2042 return 'glob(' . single_delim('qq', '"', $text) . ')';
2044 return '<' . $text . '>';
2048 # Truncate is special because OPf_SPECIAL makes a bareword first arg
2049 # be a filehandle. This could probably be better fixed in the core
2050 # by moving the GV lookup into ck_truc.
2056 my $parens = ($cx >= 5) || $self->{'parens'};
2057 my $kid = $op->first->sibling;
2059 if ($op->flags & OPf_SPECIAL) {
2060 # $kid is an OP_CONST
2061 $fh = $self->const_sv($kid)->PV;
2063 $fh = $self->deparse($kid, 6);
2064 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2066 my $len = $self->deparse($kid->sibling, 6);
2068 return "truncate($fh, $len)";
2070 return "truncate $fh, $len";
2076 my($op, $cx, $name) = @_;
2078 my $kid = $op->first->sibling;
2080 if ($op->flags & OPf_STACKED) {
2082 $indir = $indir->first; # skip rv2gv
2083 if (is_scope($indir)) {
2084 $indir = "{" . $self->deparse($indir, 0) . "}";
2086 $indir = $self->deparse($indir, 24);
2088 $indir = $indir . " ";
2089 $kid = $kid->sibling;
2091 for (; !null($kid); $kid = $kid->sibling) {
2092 $expr = $self->deparse($kid, 6);
2095 return $self->maybe_parens_func($name, $indir . join(", ", @exprs),
2099 sub pp_prtf { indirop(@_, "printf") }
2100 sub pp_print { indirop(@_, "print") }
2101 sub pp_sort { indirop(@_, "sort") }
2105 my($op, $cx, $name) = @_;
2107 my $kid = $op->first; # this is the (map|grep)start
2108 $kid = $kid->first->sibling; # skip a pushmark
2109 my $code = $kid->first; # skip a null
2110 if (is_scope $code) {
2111 $code = "{" . $self->deparse($code, 0) . "} ";
2113 $code = $self->deparse($code, 24) . ", ";
2115 $kid = $kid->sibling;
2116 for (; !null($kid); $kid = $kid->sibling) {
2117 $expr = $self->deparse($kid, 6);
2118 push @exprs, $expr if $expr;
2120 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2123 sub pp_mapwhile { mapop(@_, "map") }
2124 sub pp_grepwhile { mapop(@_, "grep") }
2130 my $kid = $op->first->sibling; # skip pushmark
2132 my $local = "either"; # could be local(...) or my(...)
2133 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2134 # This assumes that no other private flags equal 128, and that
2135 # OPs that store things other than flags in their op_private,
2136 # like OP_AELEMFAST, won't be immediate children of a list.
2137 unless ($lop->private & OPpLVAL_INTRO or $lop->name eq "undef")
2139 $local = ""; # or not
2142 if ($lop->name =~ /^pad[ash]v$/) { # my()
2143 ($local = "", last) if $local eq "local";
2145 } elsif ($lop->name ne "undef") { # local()
2146 ($local = "", last) if $local eq "my";
2150 $local = "" if $local eq "either"; # no point if it's all undefs
2151 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2152 for (; !null($kid); $kid = $kid->sibling) {
2154 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2159 $self->{'avoid_local'}{$$lop}++;
2160 $expr = $self->deparse($kid, 6);
2161 delete $self->{'avoid_local'}{$$lop};
2163 $expr = $self->deparse($kid, 6);
2168 return "$local(" . join(", ", @exprs) . ")";
2170 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2174 sub is_ifelse_cont {
2176 return ($op->name eq "null" and class($op) eq "UNOP"
2177 and $op->first->name =~ /^(and|cond_expr)$/
2178 and is_scope($op->first->first->sibling));
2184 my $cond = $op->first;
2185 my $true = $cond->sibling;
2186 my $false = $true->sibling;
2187 my $cuddle = $self->{'cuddle'};
2188 unless ($cx == 0 and (is_scope($true) and $true->name ne "null") and
2189 (is_scope($false) || is_ifelse_cont($false))
2190 and $self->{'expand'} < 7) {
2191 $cond = $self->deparse($cond, 8);
2192 $true = $self->deparse($true, 8);
2193 $false = $self->deparse($false, 8);
2194 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2197 $cond = $self->deparse($cond, 1);
2198 $true = $self->deparse($true, 0);
2199 my $head = "if ($cond) {\n\t$true\n\b}";
2201 while (!null($false) and is_ifelse_cont($false)) {
2202 my $newop = $false->first;
2203 my $newcond = $newop->first;
2204 my $newtrue = $newcond->sibling;
2205 $false = $newtrue->sibling; # last in chain is OP_AND => no else
2206 $newcond = $self->deparse($newcond, 1);
2207 $newtrue = $self->deparse($newtrue, 0);
2208 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2210 if (!null($false)) {
2211 $false = $cuddle . "else {\n\t" .
2212 $self->deparse($false, 0) . "\n\b}\cK";
2216 return $head . join($cuddle, "", @elsifs) . $false;
2221 my($op, $cx, $init) = @_;
2222 my $enter = $op->first;
2223 my $kid = $enter->sibling;
2224 local(@$self{qw'curstash warnings hints'})
2225 = @$self{qw'curstash warnings hints'};
2230 my $out_seq = $self->{'curcop'}->cop_seq;;
2231 if ($kid->name eq "lineseq") { # bare or infinite loop
2232 if (is_state $kid->last) { # infinite
2233 $head = "while (1) "; # Can't use for(;;) if there's a continue
2239 } elsif ($enter->name eq "enteriter") { # foreach
2240 my $ary = $enter->first->sibling; # first was pushmark
2241 my $var = $ary->sibling;
2242 if ($enter->flags & OPf_STACKED
2243 and not null $ary->first->sibling->sibling)
2245 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2246 $self->deparse($ary->first->sibling->sibling, 9);
2248 $ary = $self->deparse($ary, 1);
2251 if ($enter->flags & OPf_SPECIAL) { # thread special var
2252 $var = $self->pp_threadsv($enter, 1);
2253 } else { # regular my() variable
2254 $var = $self->pp_padsv($enter, 1);
2255 if ($self->padname_sv($enter->targ)->IVX ==
2256 $kid->first->first->sibling->last->cop_seq)
2258 # If the scope of this variable closes at the last
2259 # statement of the loop, it must have been
2261 $var = "my " . $var;
2264 } elsif ($var->name eq "rv2gv") {
2265 $var = $self->pp_rv2sv($var, 1);
2266 } elsif ($var->name eq "gv") {
2267 $var = "\$" . $self->deparse($var, 1);
2269 $head = "foreach $var ($ary) ";
2270 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
2271 } elsif ($kid->name eq "null") { # while/until
2273 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2274 $cond = $self->deparse($kid->first, 1);
2275 $head = "$name ($cond) ";
2276 $body = $kid->first->sibling;
2277 } elsif ($kid->name eq "stub") { # bare and empty
2278 return "{;}"; # {} could be a hashref
2280 # If there isn't a continue block, then the next pointer for the loop
2281 # will point to the unstack, which is kid's penultimate child, except
2282 # in a bare loop, when it will point to the leaveloop. When neither of
2283 # these conditions hold, then the third-to-last child in the continue
2284 # block (or the last in a bare loop).
2285 my $cont_start = $enter->nextop;
2287 if ($$cont_start != $$op and $ {$cont_start->sibling} != $ {$body->last}) {
2289 $cont = $body->last;
2291 $cont = $body->first;
2292 while (!null($cont->sibling->sibling->sibling)) {
2293 $cont = $cont->sibling;
2296 my $state = $body->first;
2297 my $cuddle = $self->{'cuddle'};
2299 for (; $$state != $$cont; $state = $state->sibling) {
2300 push @states, $state;
2302 $body = $self->lineseq(@states);
2303 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
2304 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
2307 $cont = $cuddle . "continue {\n\t" .
2308 $self->deparse($cont, 0) . "\n\b}\cK";
2311 return "" if !defined $body;
2313 $body = $self->deparse($body, 0);
2317 # If we have say C<{my $x=2; sub x{$x}}>, the sub must go inside
2318 # the loop. So we insert any subs which are due here.
2319 $body .= join"", $self->seq_subs($out_seq);
2321 return $head . "{\n\t" . $body . "\b}" . $cont;
2324 sub pp_leaveloop { loop_common(@_, "") }
2329 my $init = $self->deparse($op, 1);
2330 return $self->loop_common($op->sibling, $cx, $init);
2335 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
2338 BEGIN { eval "sub OP_CONST () {" . opnumber("const") . "}" }
2339 BEGIN { eval "sub OP_STRINGIFY () {" . opnumber("stringify") . "}" }
2344 if (class($op) eq "OP") {
2346 return $self->{'ex_const'} if $op->targ == OP_CONST;
2347 } elsif ($op->first->name eq "pushmark") {
2348 return $self->pp_list($op, $cx);
2349 } elsif ($op->first->name eq "enter") {
2350 return $self->pp_leave($op, $cx);
2351 } elsif ($op->targ == OP_STRINGIFY) {
2352 return $self->dquote($op, $cx);
2353 } elsif (!null($op->first->sibling) and
2354 $op->first->sibling->name eq "readline" and
2355 $op->first->sibling->flags & OPf_STACKED) {
2356 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
2357 . $self->deparse($op->first->sibling, 7),
2359 } elsif (!null($op->first->sibling) and
2360 $op->first->sibling->name eq "trans" and
2361 $op->first->sibling->flags & OPf_STACKED) {
2362 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
2363 . $self->deparse($op->first->sibling, 20),
2365 } elsif ($op->flags & OPf_SPECIAL && $cx == 0 && !$op->targ) {
2366 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
2368 return $self->deparse($op->first, $cx);
2375 return $self->padname_sv($targ)->PVX;
2381 return substr($self->padname($op->targ), 1); # skip $/@/%
2387 return $self->maybe_my($op, $cx, $self->padname($op->targ));
2390 sub pp_padav { pp_padsv(@_) }
2391 sub pp_padhv { pp_padsv(@_) }
2396 @threadsv_names = ("_", "1", "2", "3", "4", "5", "6", "7", "8", "9",
2397 "&", "`", "'", "+", "/", ".", ",", "\\", '"', ";",
2398 "^", "-", "%", "=", "|", "~", ":", "^A", "^E",
2405 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
2411 if (class($op) eq "PADOP") {
2412 return $self->padval($op->padix);
2413 } else { # class($op) eq "SVOP"
2421 my $gv = $self->gv_or_padgv($op);
2422 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
2423 $self->gv_name($gv)));
2429 my $gv = $self->gv_or_padgv($op);
2430 return $self->gv_name($gv);
2436 my $gv = $self->gv_or_padgv($op);
2437 return "\$" . $self->gv_name($gv) . "[" .
2438 ($op->private + $self->{'arybase'}) . "]";
2443 my($op, $cx, $type) = @_;
2444 my $kid = $op->first;
2445 my $str = $self->deparse($kid, 0);
2446 return $self->stash_variable($type, $str) if is_scalar($kid);
2447 return $type ."{$str}";
2450 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
2451 sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
2452 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
2458 if ($op->first->name eq "padav") {
2459 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
2461 return $self->maybe_local($op, $cx,
2462 $self->rv2x($op->first, $cx, '$#'));
2466 # skip down to the old, ex-rv2cv
2467 sub pp_rv2cv { $_[0]->rv2x($_[1]->first->first->sibling, $_[2], "&") }
2472 my $kid = $op->first;
2473 if ($kid->name eq "const") { # constant list
2474 my $av = $self->const_sv($kid);
2475 return "(" . join(", ", map(const($_), $av->ARRAY)) . ")";
2477 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
2481 sub is_subscriptable {
2483 if ($op->name =~ /^[ahg]elem/) {
2485 } elsif ($op->name eq "entersub") {
2486 my $kid = $op->first;
2487 return 0 unless null $kid->sibling;
2489 $kid = $kid->sibling until null $kid->sibling;
2490 return 0 if is_scope($kid);
2492 return 0 if $kid->name eq "gv";
2493 return 0 if is_scalar($kid);
2494 return is_subscriptable($kid);
2502 my ($op, $cx, $left, $right, $padname) = @_;
2503 my($array, $idx) = ($op->first, $op->first->sibling);
2504 unless ($array->name eq $padname) { # Maybe this has been fixed
2505 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
2507 if ($array->name eq $padname) {
2508 $array = $self->padany($array);
2509 } elsif (is_scope($array)) { # ${expr}[0]
2510 $array = "{" . $self->deparse($array, 0) . "}";
2511 } elsif (is_scalar $array) { # $x[0], $$x[0], ...
2512 $array = $self->deparse($array, 24);
2514 # $x[20][3]{hi} or expr->[20]
2515 my $arrow = is_subscriptable($array) ? "" : "->";
2516 return $self->deparse($array, 24) . $arrow .
2517 $left . $self->deparse($idx, 1) . $right;
2519 $idx = $self->deparse($idx, 1);
2521 # Outer parens in an array index will confuse perl
2522 # if we're interpolating in a regular expression, i.e.
2523 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
2525 # If $self->{parens}, then an initial '(' will
2526 # definitely be paired with a final ')'. If
2527 # !$self->{parens}, the misleading parens won't
2528 # have been added in the first place.
2530 # [You might think that we could get "(...)...(...)"
2531 # where the initial and final parens do not match
2532 # each other. But we can't, because the above would
2533 # only happen if there's an infix binop between the
2534 # two pairs of parens, and *that* means that the whole
2535 # expression would be parenthesized as well.]
2537 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
2539 return "\$" . $array . $left . $idx . $right;
2542 sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
2543 sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
2548 my($glob, $part) = ($op->first, $op->last);
2549 $glob = $glob->first; # skip rv2gv
2550 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
2551 my $scope = is_scope($glob);
2552 $glob = $self->deparse($glob, 0);
2553 $part = $self->deparse($part, 1);
2554 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
2559 my ($op, $cx, $left, $right, $regname, $padname) = @_;
2561 my(@elems, $kid, $array, $list);
2562 if (class($op) eq "LISTOP") {
2564 } else { # ex-hslice inside delete()
2565 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
2569 $array = $array->first
2570 if $array->name eq $regname or $array->name eq "null";
2571 if (is_scope($array)) {
2572 $array = "{" . $self->deparse($array, 0) . "}";
2573 } elsif ($array->name eq $padname) {
2574 $array = $self->padany($array);
2576 $array = $self->deparse($array, 24);
2578 $kid = $op->first->sibling; # skip pushmark
2579 if ($kid->name eq "list") {
2580 $kid = $kid->first->sibling; # skip list, pushmark
2581 for (; !null $kid; $kid = $kid->sibling) {
2582 push @elems, $self->deparse($kid, 6);
2584 $list = join(", ", @elems);
2586 $list = $self->deparse($kid, 1);
2588 return "\@" . $array . $left . $list . $right;
2591 sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
2592 sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
2597 my $idx = $op->first;
2598 my $list = $op->last;
2600 $list = $self->deparse($list, 1);
2601 $idx = $self->deparse($idx, 1);
2602 return "($list)" . "[$idx]";
2607 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
2612 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
2618 my $kid = $op->first->sibling; # skip pushmark
2619 my($meth, $obj, @exprs);
2620 if ($kid->name eq "list" and want_list $kid) {
2621 # When an indirect object isn't a bareword but the args are in
2622 # parens, the parens aren't part of the method syntax (the LLAFR
2623 # doesn't apply), but they make a list with OPf_PARENS set that
2624 # doesn't get flattened by the append_elem that adds the method,
2625 # making a (object, arg1, arg2, ...) list where the object
2626 # usually is. This can be distinguished from
2627 # `($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
2628 # object) because in the later the list is in scalar context
2629 # as the left side of -> always is, while in the former
2630 # the list is in list context as method arguments always are.
2631 # (Good thing there aren't method prototypes!)
2632 $meth = $kid->sibling;
2633 $kid = $kid->first->sibling; # skip pushmark
2635 $kid = $kid->sibling;
2636 for (; not null $kid; $kid = $kid->sibling) {
2637 push @exprs, $self->deparse($kid, 6);
2641 $kid = $kid->sibling;
2642 for (; not null $kid->sibling; $kid = $kid->sibling) {
2643 push @exprs, $self->deparse($kid, 6);
2647 $obj = $self->deparse($obj, 24);
2648 if ($meth->name eq "method_named") {
2649 $meth = $self->const_sv($meth)->PV;
2651 $meth = $meth->first;
2652 if ($meth->name eq "const") {
2653 # As of 5.005_58, this case is probably obsoleted by the
2654 # method_named case above
2655 $meth = $self->const_sv($meth)->PV; # needs to be bare
2657 $meth = $self->deparse($meth, 1);
2660 my $args = join(", ", @exprs);
2661 $kid = $obj . "->" . $meth;
2663 return $kid . "(" . $args . ")"; # parens mandatory
2669 # returns "&" if the prototype doesn't match the args,
2670 # or ("", $args_after_prototype_demunging) if it does.
2673 my($proto, @args) = @_;
2677 # An unbackslashed @ or % gobbles up the rest of the args
2678 $proto =~ s/([^\\]|^)([@%])(.*)$/$1$2/;
2680 $proto =~ s/^ *([\\]?[\$\@&%*]|;)//;
2683 return "&" if @args;
2684 } elsif ($chr eq ";") {
2686 } elsif ($chr eq "@" or $chr eq "%") {
2687 push @reals, map($self->deparse($_, 6), @args);
2693 if (want_scalar $arg) {
2694 push @reals, $self->deparse($arg, 6);
2698 } elsif ($chr eq "&") {
2699 if ($arg->name =~ /^(s?refgen|undef)$/) {
2700 push @reals, $self->deparse($arg, 6);
2704 } elsif ($chr eq "*") {
2705 if ($arg->name =~ /^s?refgen$/
2706 and $arg->first->first->name eq "rv2gv")
2708 $real = $arg->first->first; # skip refgen, null
2709 if ($real->first->name eq "gv") {
2710 push @reals, $self->deparse($real, 6);
2712 push @reals, $self->deparse($real->first, 6);
2717 } elsif (substr($chr, 0, 1) eq "\\") {
2718 $chr = substr($chr, 1);
2719 if ($arg->name =~ /^s?refgen$/ and
2720 !null($real = $arg->first) and
2721 ($chr eq "\$" && is_scalar($real->first)
2723 && $real->first->sibling->name
2726 && $real->first->sibling->name
2728 #or ($chr eq "&" # This doesn't work
2729 # && $real->first->name eq "rv2cv")
2731 && $real->first->name eq "rv2gv")))
2733 push @reals, $self->deparse($real, 6);
2740 return "&" if $proto and !$doneok; # too few args and no `;'
2741 return "&" if @args; # too many args
2742 return ("", join ", ", @reals);
2748 return $self->method($op, $cx) unless null $op->first->sibling;
2752 if ($op->flags & OPf_SPECIAL) {
2754 } elsif ($op->private & OPpENTERSUB_AMPER) {
2758 $kid = $kid->first->sibling; # skip ex-list, pushmark
2759 for (; not null $kid->sibling; $kid = $kid->sibling) {
2764 if (is_scope($kid)) {
2766 $kid = "{" . $self->deparse($kid, 0) . "}";
2767 } elsif ($kid->first->name eq "gv") {
2768 my $gv = $self->gv_or_padgv($kid->first);
2769 if (class($gv->CV) ne "SPECIAL") {
2770 $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
2772 $simple = 1; # only calls of named functions can be prototyped
2773 $kid = $self->deparse($kid, 24);
2774 } elsif (is_scalar $kid->first) {
2776 $kid = $self->deparse($kid, 24);
2779 my $arrow = is_subscriptable($kid->first) ? "" : "->";
2780 $kid = $self->deparse($kid, 24) . $arrow;
2783 # Doesn't matter how many prototypes there are, if
2784 # they haven't happened yet!
2785 my $declared = exists $self->{'subs_declared'}{$kid};
2786 if (!$declared && defined($proto)) {
2787 # Avoid "too early to check prototype" warning
2788 ($amper, $proto) = ('&');
2792 if ($declared and defined $proto and not $amper) {
2793 ($amper, $args) = $self->check_proto($proto, @exprs);
2794 if ($amper eq "&") {
2795 $args = join(", ", map($self->deparse($_, 6), @exprs));
2798 $args = join(", ", map($self->deparse($_, 6), @exprs));
2800 if ($prefix or $amper) {
2801 if ($op->flags & OPf_STACKED) {
2802 return $prefix . $amper . $kid . "(" . $args . ")";
2804 return $prefix . $amper. $kid;
2807 # glob() invocations can be translated into calls of
2808 # CORE::GLOBAL::glob with an second parameter, a number.
2810 if ($kid eq "CORE::GLOBAL::glob") {
2812 $args =~ s/\s*,[^,]+$//;
2815 # It's a syntax error to call CORE::GLOBAL::foo without a prefix,
2816 # so it must have been translated from a keyword call. Translate
2818 $kid =~ s/^CORE::GLOBAL:://;
2821 return "$kid(" . $args . ")";
2822 } elsif (defined $proto and $proto eq "") {
2824 } elsif (defined $proto and $proto eq "\$") {
2825 return $self->maybe_parens_func($kid, $args, $cx, 16);
2826 } elsif (defined($proto) && $proto or $simple) {
2827 return $self->maybe_parens_func($kid, $args, $cx, 5);
2829 return "$kid(" . $args . ")";
2834 sub pp_enterwrite { unop(@_, "write") }
2836 # escape things that cause interpolation in double quotes,
2837 # but not character escapes
2840 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
2844 # the same, but treat $|, $), $( and $ at the end of the string differently
2847 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@](?!\||\)|\(|$)|\\[uUlLQE])/$1$2\\$3/g;
2851 # character escapes, but not delimiters that might need to be escaped
2852 sub escape_str { # ASCII, UTF8
2854 $str =~ s/(.)/ord($1)>255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
2856 # $str =~ s/\cH/\\b/g; # \b means someting different in a regex
2862 $str =~ s/([\cA-\cZ])/'\\c' . chr(ord('@') + ord($1))/ge;
2863 $str =~ s/([\0\033-\037\177-\377])/'\\' . sprintf("%03o", ord($1))/ge;
2867 # Don't do this for regexen
2870 $str =~ s/\\/\\\\/g;
2874 # Remove backslashes which precede literal control characters,
2875 # to avoid creating ambiguity when we escape the latter.
2879 # the insane complexity here is due to the behaviour of "\c\"
2880 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[\0-\031\177-\377])/$1$2/g;
2884 sub balanced_delim {
2886 my @str = split //, $str;
2887 my($ar, $open, $close, $fail, $c, $cnt);
2888 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
2889 ($open, $close) = @$ar;
2890 $fail = 0; $cnt = 0;
2894 } elsif ($c eq $close) {
2903 $fail = 1 if $cnt != 0;
2904 return ($open, "$open$str$close") if not $fail;
2910 my($q, $default, $str) = @_;
2911 return "$default$str$default" if $default and index($str, $default) == -1;
2912 my($succeed, $delim);
2913 ($succeed, $str) = balanced_delim($str);
2914 return "$q$str" if $succeed;
2915 for $delim ('/', '"', '#') {
2916 return "$q$delim" . $str . $delim if index($str, $delim) == -1;
2919 $str =~ s/$default/\\$default/g;
2920 return "$default$str$default";
2929 if (class($sv) eq "SPECIAL") {
2930 return ('undef', '1', '0')[$$sv-1]; # sv_undef, sv_yes, sv_no
2931 } elsif (class($sv) eq "NULL") {
2933 } elsif ($sv->FLAGS & SVf_IOK) {
2934 return $sv->int_value;
2935 } elsif ($sv->FLAGS & SVf_NOK) {
2937 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
2938 return "\\(" . const($sv->RV) . ")"; # constant folded
2941 if ($str =~ /[^ -~]/) { # ASCII for non-printing
2942 return single_delim("qq", '"', uninterp escape_str unback $str);
2944 return single_delim("q", "'", unback $str);
2953 # the constant could be in the pad (under useithreads)
2954 $sv = $self->padval($op->targ) unless $$sv;
2961 if ($op->private & OPpCONST_ARYBASE) {
2964 # if ($op->private & OPpCONST_BARE) { # trouble with `=>' autoquoting
2965 # return $self->const_sv($op)->PV;
2967 my $sv = $self->const_sv($op);
2968 # return const($sv);
2970 return $c =~ /^-\d/ ? $self->maybe_parens($c, $cx, 21) : $c;
2976 my $type = $op->name;
2977 if ($type eq "const") {
2978 return '$[' if $op->private & OPpCONST_ARYBASE;
2979 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
2980 } elsif ($type eq "concat") {
2981 my $first = $self->dq($op->first);
2982 my $last = $self->dq($op->last);
2983 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
2984 if ($last =~ /^[A-Z\\\^\[\]_?]/) {
2985 $first =~ s/([\$@])\^$/${1}{^}/; # "${^}W" etc
2987 elsif ($last =~ /^[{\[\w]/) {
2988 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/;
2990 return $first . $last;
2991 } elsif ($type eq "uc") {
2992 return '\U' . $self->dq($op->first->sibling) . '\E';
2993 } elsif ($type eq "lc") {
2994 return '\L' . $self->dq($op->first->sibling) . '\E';
2995 } elsif ($type eq "ucfirst") {
2996 return '\u' . $self->dq($op->first->sibling);
2997 } elsif ($type eq "lcfirst") {
2998 return '\l' . $self->dq($op->first->sibling);
2999 } elsif ($type eq "quotemeta") {
3000 return '\Q' . $self->dq($op->first->sibling) . '\E';
3001 } elsif ($type eq "join") {
3002 return $self->deparse($op->last, 26); # was join($", @ary)
3004 return $self->deparse($op, 26);
3012 return single_delim("qx", '`', $self->dq($op->first->sibling));
3018 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
3019 return $self->deparse($kid, $cx) if $self->{'unquote'};
3020 $self->maybe_targmy($kid, $cx,
3021 sub {single_delim("qq", '"', $self->dq($_[1]))});
3024 # OP_STRINGIFY is a listop, but it only ever has one arg
3025 sub pp_stringify { maybe_targmy(@_, \&dquote) }
3027 # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
3028 # note that tr(from)/to/ is OK, but not tr/from/(to)
3030 my($from, $to) = @_;
3031 my($succeed, $delim);
3032 if ($from !~ m[/] and $to !~ m[/]) {
3033 return "/$from/$to/";
3034 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
3035 if (($succeed, $to) = balanced_delim($to) and $succeed) {
3038 for $delim ('/', '"', '#') { # note no `'' -- s''' is special
3039 return "$from$delim$to$delim" if index($to, $delim) == -1;
3042 return "$from/$to/";
3045 for $delim ('/', '"', '#') { # note no '
3046 return "$delim$from$delim$to$delim"
3047 if index($to . $from, $delim) == -1;
3049 $from =~ s[/][\\/]g;
3051 return "/$from/$to/";
3057 if ($n == ord '\\') {
3059 } elsif ($n >= ord(' ') and $n <= ord('~')) {
3061 } elsif ($n == ord "\a") {
3063 } elsif ($n == ord "\b") {
3065 } elsif ($n == ord "\t") {
3067 } elsif ($n == ord "\n") {
3069 } elsif ($n == ord "\e") {
3071 } elsif ($n == ord "\f") {
3073 } elsif ($n == ord "\r") {
3075 } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
3076 return '\\c' . chr(ord("@") + $n);
3078 # return '\x' . sprintf("%02x", $n);
3079 return '\\' . sprintf("%03o", $n);
3085 my($str, $c, $tr) = ("");
3086 for ($c = 0; $c < @chars; $c++) {
3089 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
3090 $chars[$c + 2] == $tr + 2)
3092 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
3095 $str .= pchr($chars[$c]);
3101 # XXX This has trouble with hyphens in the replacement (tr/bac/-AC/),
3104 sub tr_decode_byte {
3105 my($table, $flags) = @_;
3106 my(@table) = unpack("s256", $table);
3107 my($c, $tr, @from, @to, @delfrom, $delhyphen);
3108 if ($table[ord "-"] != -1 and
3109 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
3111 $tr = $table[ord "-"];
3112 $table[ord "-"] = -1;
3116 } else { # -2 ==> delete
3120 for ($c = 0; $c < 256; $c++) {
3123 push @from, $c; push @to, $tr;
3124 } elsif ($tr == -2) {
3128 @from = (@from, @delfrom);
3129 if ($flags & OPpTRANS_COMPLEMENT) {
3132 @from{@from} = (1) x @from;
3133 for ($c = 0; $c < 256; $c++) {
3134 push @newfrom, $c unless $from{$c};
3138 unless ($flags & OPpTRANS_DELETE || !@to) {
3139 pop @to while $#to and $to[$#to] == $to[$#to -1];
3142 $from = collapse(@from);
3143 $to = collapse(@to);
3144 $from .= "-" if $delhyphen;
3145 return ($from, $to);
3150 if ($x == ord "-") {
3157 # XXX This doesn't yet handle all cases correctly either
3159 sub tr_decode_utf8 {
3160 my($swash_hv, $flags) = @_;
3161 my %swash = $swash_hv->ARRAY;
3163 $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
3164 my $none = $swash{"NONE"}->IV;
3165 my $extra = $none + 1;
3166 my(@from, @delfrom, @to);
3168 foreach $line (split /\n/, $swash{'LIST'}->PV) {
3169 my($min, $max, $result) = split(/\t/, $line);
3176 $result = hex $result;
3177 if ($result == $extra) {
3178 push @delfrom, [$min, $max];
3180 push @from, [$min, $max];
3181 push @to, [$result, $result + $max - $min];
3184 for my $i (0 .. $#from) {
3185 if ($from[$i][0] == ord '-') {
3186 unshift @from, splice(@from, $i, 1);
3187 unshift @to, splice(@to, $i, 1);
3189 } elsif ($from[$i][1] == ord '-') {
3192 unshift @from, ord '-';
3193 unshift @to, ord '-';
3197 for my $i (0 .. $#delfrom) {
3198 if ($delfrom[$i][0] == ord '-') {
3199 push @delfrom, splice(@delfrom, $i, 1);
3201 } elsif ($delfrom[$i][1] == ord '-') {
3203 push @delfrom, ord '-';
3207 if (defined $final and $to[$#to][1] != $final) {
3208 push @to, [$final, $final];
3210 push @from, @delfrom;
3211 if ($flags & OPpTRANS_COMPLEMENT) {
3214 for my $i (0 .. $#from) {
3215 push @newfrom, [$next, $from[$i][0] - 1];
3216 $next = $from[$i][1] + 1;
3219 for my $range (@newfrom) {
3220 if ($range->[0] <= $range->[1]) {
3225 my($from, $to, $diff);
3226 for my $chunk (@from) {
3227 $diff = $chunk->[1] - $chunk->[0];
3229 $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
3230 } elsif ($diff == 1) {
3231 $from .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
3233 $from .= tr_chr($chunk->[0]);
3236 for my $chunk (@to) {
3237 $diff = $chunk->[1] - $chunk->[0];
3239 $to .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
3240 } elsif ($diff == 1) {
3241 $to .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
3243 $to .= tr_chr($chunk->[0]);
3246 #$final = sprintf("%04x", $final) if defined $final;
3247 #$none = sprintf("%04x", $none) if defined $none;
3248 #$extra = sprintf("%04x", $extra) if defined $extra;
3249 #print STDERR "final: $final\n none: $none\nextra: $extra\n";
3250 #print STDERR $swash{'LIST'}->PV;
3251 return (escape_str($from), escape_str($to));
3258 if (class($op) eq "PVOP") {
3259 ($from, $to) = tr_decode_byte($op->pv, $op->private);
3260 } else { # class($op) eq "SVOP"
3261 ($from, $to) = tr_decode_utf8($op->sv->RV, $op->private);
3264 $flags .= "c" if $op->private & OPpTRANS_COMPLEMENT;
3265 $flags .= "d" if $op->private & OPpTRANS_DELETE;
3266 $to = "" if $from eq $to and $flags eq "";
3267 $flags .= "s" if $op->private & OPpTRANS_SQUASH;
3268 return "tr" . double_delim($from, $to) . $flags;
3271 # Like dq(), but different
3275 my $type = $op->name;
3276 if ($type eq "const") {
3277 return '$[' if $op->private & OPpCONST_ARYBASE;
3278 return re_uninterp(escape_str(re_unback($self->const_sv($op)->as_string)));
3279 } elsif ($type eq "concat") {
3280 my $first = $self->re_dq($op->first);
3281 my $last = $self->re_dq($op->last);
3282 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
3283 if ($last =~ /^[A-Z\\\^\[\]_?]/) {
3284 $first =~ s/([\$@])\^$/${1}{^}/;
3286 elsif ($last =~ /^[{\[\w]/) {
3287 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/;
3289 return $first . $last;
3290 } elsif ($type eq "uc") {
3291 return '\U' . $self->re_dq($op->first->sibling) . '\E';
3292 } elsif ($type eq "lc") {
3293 return '\L' . $self->re_dq($op->first->sibling) . '\E';
3294 } elsif ($type eq "ucfirst") {
3295 return '\u' . $self->re_dq($op->first->sibling);
3296 } elsif ($type eq "lcfirst") {
3297 return '\l' . $self->re_dq($op->first->sibling);
3298 } elsif ($type eq "quotemeta") {
3299 return '\Q' . $self->re_dq($op->first->sibling) . '\E';
3300 } elsif ($type eq "join") {
3301 return $self->deparse($op->last, 26); # was join($", @ary)
3303 return $self->deparse($op, 26);
3310 my $kid = $op->first;
3311 $kid = $kid->first if $kid->name eq "regcmaybe";
3312 $kid = $kid->first if $kid->name eq "regcreset";
3313 return $self->re_dq($kid);
3316 # osmic acid -- see osmium tetroxide
3319 map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs',
3320 'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic',
3321 'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi');
3325 my($op, $cx, $name, $delim) = @_;
3326 my $kid = $op->first;
3327 my ($binop, $var, $re) = ("", "", "");
3328 if ($op->flags & OPf_STACKED) {
3330 $var = $self->deparse($kid, 20);
3331 $kid = $kid->sibling;
3334 $re = re_uninterp(escape_str(re_unback($op->precomp)));
3336 $re = $self->deparse($kid, 1);
3339 $flags .= "c" if $op->pmflags & PMf_CONTINUE;
3340 $flags .= "g" if $op->pmflags & PMf_GLOBAL;
3341 $flags .= "i" if $op->pmflags & PMf_FOLD;
3342 $flags .= "m" if $op->pmflags & PMf_MULTILINE;
3343 $flags .= "o" if $op->pmflags & PMf_KEEP;
3344 $flags .= "s" if $op->pmflags & PMf_SINGLELINE;
3345 $flags .= "x" if $op->pmflags & PMf_EXTENDED;
3346 $flags = $matchwords{$flags} if $matchwords{$flags};
3347 if ($op->pmflags & PMf_ONCE) { # only one kind of delimiter works here
3351 $re = single_delim($name, $delim, $re);
3355 return $self->maybe_parens("$var =~ $re", $cx, 20);
3361 sub pp_match { matchop(@_, "m", "/") }
3362 sub pp_pushre { matchop(@_, "m", "/") }
3363 sub pp_qr { matchop(@_, "qr", "") }
3368 my($kid, @exprs, $ary, $expr);
3370 if ($ {$kid->pmreplroot}) {
3371 $ary = '@' . $self->gv_name($kid->pmreplroot);
3373 for (; !null($kid); $kid = $kid->sibling) {
3374 push @exprs, $self->deparse($kid, 6);
3377 # handle special case of split(), and split(" ") that compiles to /\s+/
3379 if ($kid->flags & OPf_SPECIAL
3380 && $exprs[0] eq '/\\s+/'
3381 && $kid->pmflags & PMf_SKIPWHITE ) {
3385 $expr = "split(" . join(", ", @exprs) . ")";
3387 return $self->maybe_parens("$ary = $expr", $cx, 7);
3393 # oxime -- any of various compounds obtained chiefly by the action of
3394 # hydroxylamine on aldehydes and ketones and characterized by the
3395 # bivalent grouping C=NOH [Webster's Tenth]
3398 map($substwords{join "", sort split //, $_} = $_, 'ego', 'egoism', 'em',
3399 'es', 'ex', 'exes', 'gee', 'go', 'goes', 'ie', 'ism', 'iso', 'me',
3400 'meese', 'meso', 'mig', 'mix', 'os', 'ox', 'oxime', 'see', 'seem',
3401 'seg', 'sex', 'sig', 'six', 'smog', 'sog', 'some', 'xi');
3406 my $kid = $op->first;
3407 my($binop, $var, $re, $repl) = ("", "", "", "");
3408 if ($op->flags & OPf_STACKED) {
3410 $var = $self->deparse($kid, 20);
3411 $kid = $kid->sibling;
3414 if (null($op->pmreplroot)) {
3415 $repl = $self->dq($kid);
3416 $kid = $kid->sibling;
3418 $repl = $op->pmreplroot->first; # skip substcont
3419 while ($repl->name eq "entereval") {
3420 $repl = $repl->first;
3423 if ($op->pmflags & PMf_EVAL) {
3424 $repl = $self->deparse($repl, 0);
3426 $repl = $self->dq($repl);
3430 $re = re_uninterp(escape_str(re_unback($op->precomp)));
3432 $re = $self->deparse($kid, 1);
3434 $flags .= "e" if $op->pmflags & PMf_EVAL;
3435 $flags .= "g" if $op->pmflags & PMf_GLOBAL;
3436 $flags .= "i" if $op->pmflags & PMf_FOLD;
3437 $flags .= "m" if $op->pmflags & PMf_MULTILINE;
3438 $flags .= "o" if $op->pmflags & PMf_KEEP;
3439 $flags .= "s" if $op->pmflags & PMf_SINGLELINE;
3440 $flags .= "x" if $op->pmflags & PMf_EXTENDED;
3441 $flags = $substwords{$flags} if $substwords{$flags};
3443 return $self->maybe_parens("$var =~ s"
3444 . double_delim($re, $repl) . $flags,
3447 return "s". double_delim($re, $repl) . $flags;
3456 B::Deparse - Perl compiler backend to produce perl code
3460 B<perl> B<-MO=Deparse>[B<,-u>I<PACKAGE>][B<,-p>][B<,-q>][B<,-l>]
3461 [B<,-s>I<LETTERS>][B<,-x>I<LEVEL>] I<prog.pl>
3465 B::Deparse is a backend module for the Perl compiler that generates
3466 perl source code, based on the internal compiled structure that perl
3467 itself creates after parsing a program. The output of B::Deparse won't
3468 be exactly the same as the original source, since perl doesn't keep
3469 track of comments or whitespace, and there isn't a one-to-one
3470 correspondence between perl's syntactical constructions and their
3471 compiled form, but it will often be close. When you use the B<-p>
3472 option, the output also includes parentheses even when they are not
3473 required by precedence, which can make it easy to see if perl is
3474 parsing your expressions the way you intended.
3476 Please note that this module is mainly new and untested code and is
3477 still under development, so it may change in the future.
3481 As with all compiler backend options, these must follow directly after
3482 the '-MO=Deparse', separated by a comma but not any white space.
3488 Add '#line' declarations to the output based on the line and file
3489 locations of the original code.
3493 Print extra parentheses. Without this option, B::Deparse includes
3494 parentheses in its output only when they are needed, based on the
3495 structure of your program. With B<-p>, it uses parentheses (almost)
3496 whenever they would be legal. This can be useful if you are used to
3497 LISP, or if you want to see how perl parses your input. If you say
3499 if ($var & 0x7f == 65) {print "Gimme an A!"}
3500 print ($which ? $a : $b), "\n";
3501 $name = $ENV{USER} or "Bob";
3503 C<B::Deparse,-p> will print
3506 print('Gimme an A!')
3508 (print(($which ? $a : $b)), '???');
3509 (($name = $ENV{'USER'}) or '???')
3511 which probably isn't what you intended (the C<'???'> is a sign that
3512 perl optimized away a constant value).
3516 Expand double-quoted strings into the corresponding combinations of
3517 concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For
3520 print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";
3524 print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
3525 . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');
3527 Note that the expanded form represents the way perl handles such
3528 constructions internally -- this option actually turns off the reverse
3529 translation that B::Deparse usually does. On the other hand, note that
3530 C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value
3531 of $y into a string before doing the assignment.
3535 Normally, B::Deparse deparses the main code of a program, and all the subs
3536 defined in the same file. To include subs defined in other files, pass the
3537 B<-f> option with the filename. You can pass the B<-f> option several times, to
3538 include more than one secondary file. (Most of the time you don't want to
3539 use it at all.) You can also use this option to include subs which are
3540 defined in the scope of a B<#line> directive with two parameters.
3542 =item B<-s>I<LETTERS>
3544 Tweak the style of B::Deparse's output. The letters should follow
3545 directly after the 's', with no space or punctuation. The following
3546 options are available:
3552 Cuddle C<elsif>, C<else>, and C<continue> blocks. For example, print
3569 The default is not to cuddle.
3573 Indent lines by multiples of I<NUMBER> columns. The default is 4 columns.
3577 Use tabs for each 8 columns of indent. The default is to use only spaces.
3578 For instance, if the style options are B<-si4T>, a line that's indented
3579 3 times will be preceded by one tab and four spaces; if the options were
3580 B<-si8T>, the same line would be preceded by three tabs.
3582 =item B<v>I<STRING>B<.>
3584 Print I<STRING> for the value of a constant that can't be determined
3585 because it was optimized away (mnemonic: this happens when a constant
3586 is used in B<v>oid context). The end of the string is marked by a period.
3587 The string should be a valid perl expression, generally a constant.
3588 Note that unless it's a number, it probably needs to be quoted, and on
3589 a command line quotes need to be protected from the shell. Some
3590 conventional values include 0, 1, 42, '', 'foo', and
3591 'Useless use of constant omitted' (which may need to be
3592 B<-sv"'Useless use of constant omitted'.">
3593 or something similar depending on your shell). The default is '???'.
3594 If you're using B::Deparse on a module or other file that's require'd,
3595 you shouldn't use a value that evaluates to false, since the customary
3596 true constant at the end of a module will be in void context when the
3597 file is compiled as a main program.
3603 Expand conventional syntax constructions into equivalent ones that expose
3604 their internal operation. I<LEVEL> should be a digit, with higher values
3605 meaning more expansion. As with B<-q>, this actually involves turning off
3606 special cases in B::Deparse's normal operations.
3608 If I<LEVEL> is at least 3, for loops will be translated into equivalent
3609 while loops with continue blocks; for instance
3611 for ($i = 0; $i < 10; ++$i) {
3624 Note that in a few cases this translation can't be perfectly carried back
3625 into the source code -- if the loop's initializer declares a my variable,
3626 for instance, it won't have the correct scope outside of the loop.
3628 If I<LEVEL> is at least 7, if statements will be translated into equivalent
3629 expressions using C<&&>, C<?:> and C<do {}>; for instance
3631 print 'hi' if $nice;
3643 $nice and print 'hi';
3644 $nice and do { print 'hi' };
3645 $nice ? do { print 'hi' } : do { print 'bye' };
3647 Long sequences of elsifs will turn into nested ternary operators, which
3648 B::Deparse doesn't know how to indent nicely.
3652 =head1 USING B::Deparse AS A MODULE
3657 $deparse = B::Deparse->new("-p", "-sC");
3658 $body = $deparse->coderef2text(\&func);
3659 eval "sub func $body"; # the inverse operation
3663 B::Deparse can also be used on a sub-by-sub basis from other perl
3668 $deparse = B::Deparse->new(OPTIONS)
3670 Create an object to store the state of a deparsing operation and any
3671 options. The options are the same as those that can be given on the
3672 command line (see L</OPTIONS>); options that are separated by commas
3673 after B<-MO=Deparse> should be given as separate strings. Some
3674 options, like B<-u>, don't make sense for a single subroutine, so
3677 =head2 ambient_pragmas
3679 $deparse->ambient_pragmas(strict => 'all', '$[' => $[);
3681 The compilation of a subroutine can be affected by a few compiler
3682 directives, B<pragmas>. These are:
3696 Assigning to the special variable $[
3716 Ordinarily, if you use B::Deparse on a subroutine which has
3717 been compiled in the presence of one or more of these pragmas,
3718 the output will include statements to turn on the appropriate
3719 directives. So if you then compile the code returned by coderef2text,
3720 it will behave the same way as the subroutine which you deparsed.
3722 However, you may know that you intend to use the results in a
3723 particular context, where some pragmas are already in scope. In
3724 this case, you use the B<ambient_pragmas> method to describe the
3725 assumptions you wish to make.
3727 The parameters it accepts are:
3733 Takes a string, possibly containing several values separated
3734 by whitespace. The special values "all" and "none" mean what you'd
3737 $deparse->ambient_pragmas(strict => 'subs refs');
3741 Takes a number, the value of the array base $[.
3749 If the value is true, then the appropriate pragma is assumed to
3750 be in the ambient scope, otherwise not.
3754 Takes a string, possibly containing a whitespace-separated list of
3755 values. The values "all" and "none" are special. It's also permissible
3756 to pass an array reference here.
3758 $deparser->ambient_pragmas(re => 'eval');
3763 Takes a string, possibly containing a whitespace-separated list of
3764 values. The values "all" and "none" are special, again. It's also
3765 permissible to pass an array reference here.
3767 $deparser->ambient_pragmas(warnings => [qw[void io]]);
3769 If one of the values is the string "FATAL", then all the warnings
3770 in that list will be considered fatal, just as with the B<warnings>
3771 pragma itself. Should you need to specify that some warnings are
3772 fatal, and others are merely enabled, you can pass the B<warnings>
3775 $deparser->ambient_pragmas(
3777 warnings => [FATAL => qw/void io/],
3780 See L<perllexwarn> for more information about lexical warnings.
3786 These two parameters are used to specify the ambient pragmas in
3787 the format used by the special variables $^H and ${^WARNING_BITS}.
3789 They exist principally so that you can write code like:
3791 { my ($hint_bits, $warning_bits);
3792 BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
3793 $deparser->ambient_pragmas (
3794 hint_bits => $hint_bits,
3795 warning_bits => $warning_bits,
3799 which specifies that the ambient pragmas are exactly those which
3800 are in scope at the point of calling.
3806 $body = $deparse->coderef2text(\&func)
3807 $body = $deparse->coderef2text(sub ($$) { ... })
3809 Return source code for the body of a subroutine (a block, optionally
3810 preceded by a prototype in parens), given a reference to the
3811 sub. Because a subroutine can have no names, or more than one name,
3812 this method doesn't return a complete subroutine definition -- if you
3813 want to eval the result, you should prepend "sub subname ", or "sub "
3814 for an anonymous function constructor. Unless the sub was defined in
3815 the main:: package, the code will include a package declaration.
3819 See the 'to do' list at the beginning of the module file.
3823 Stephen McCamant <smcc@CSUA.Berkeley.EDU>, based on an earlier
3824 version by Malcolm Beattie <mbeattie@sable.ox.ac.uk>, with
3825 contributions from Gisle Aas, James Duncan, Albert Dvornik, Hugo van
3826 der Sanden, Gurusamy Sarathy, and Nick Ing-Simmons.